blob: a3fecec69ccb7edd69217ce8ef2f81d067e7f406 [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!");
Chris Lattner85cfe012003-07-03 02:03:53 +000072
73 assert(ParentGraph && "Node has no parent?");
74 const DSGraph::ScalarMapTy &SM = ParentGraph->getScalarMap();
75 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
76 assert(SM.find(Globals[i]) != SM.end());
77 assert(SM.find(Globals[i])->second.getNode() == this);
78 }
Chris Lattner72d29a42003-02-11 23:11:51 +000079}
80
81/// forwardNode - Mark this node as being obsolete, and all references to it
82/// should be forwarded to the specified node and offset.
83///
84void DSNode::forwardNode(DSNode *To, unsigned Offset) {
85 assert(this != To && "Cannot forward a node to itself!");
86 assert(ForwardNH.isNull() && "Already forwarding from this node!");
87 if (To->Size <= 1) Offset = 0;
88 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
89 "Forwarded offset is wrong!");
90 ForwardNH.setNode(To);
91 ForwardNH.setOffset(Offset);
92 NodeType = DEAD;
93 Size = 0;
94 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000095}
96
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000097// addGlobal - Add an entry for a global value to the Globals list. This also
98// marks the node with the 'G' flag if it does not already have it.
99//
100void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000101 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000102 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000103 std::lower_bound(Globals.begin(), Globals.end(), GV);
104
105 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000106 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000107 Globals.insert(I, GV);
108 NodeType |= GlobalNode;
109 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000110}
111
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000112/// foldNodeCompletely - If we determine that this node has some funny
113/// behavior happening to it that we cannot represent, we fold it down to a
114/// single, completely pessimistic, node. This node is represented as a
115/// single byte with a single TypeEntry of "void".
116///
117void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000118 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000119
Chris Lattner08db7192002-11-06 06:20:27 +0000120 ++NumFolds;
121
Chris Lattner72d29a42003-02-11 23:11:51 +0000122 // Create the node we are going to forward to...
Chris Lattner70793862003-07-02 23:57:05 +0000123 DSNode *DestNode = new DSNode(0, ParentGraph);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000124 DestNode->NodeType = NodeType|DSNode::Array;
Chris Lattner72d29a42003-02-11 23:11:51 +0000125 DestNode->Ty = Type::VoidTy;
126 DestNode->Size = 1;
127 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000128
Chris Lattner72d29a42003-02-11 23:11:51 +0000129 // Start forwarding to the destination node...
130 forwardNode(DestNode, 0);
131
132 if (Links.size()) {
133 DestNode->Links.push_back(Links[0]);
134 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000135
Chris Lattner72d29a42003-02-11 23:11:51 +0000136 // If we have links, merge all of our outgoing links together...
137 for (unsigned i = Links.size()-1; i != 0; --i)
138 NH.getNode()->Links[0].mergeWith(Links[i]);
139 Links.clear();
140 } else {
141 DestNode->Links.resize(1);
142 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000143}
Chris Lattner076c1f92002-11-07 06:31:54 +0000144
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000145/// isNodeCompletelyFolded - Return true if this node has been completely
146/// folded down to something that can never be expanded, effectively losing
147/// all of the field sensitivity that may be present in the node.
148///
149bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000150 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000151}
152
153
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000154namespace {
155 /// TypeElementWalker Class - Used for implementation of physical subtyping...
156 ///
157 class TypeElementWalker {
158 struct StackState {
159 const Type *Ty;
160 unsigned Offset;
161 unsigned Idx;
162 StackState(const Type *T, unsigned Off = 0)
163 : Ty(T), Offset(Off), Idx(0) {}
164 };
165
166 std::vector<StackState> Stack;
167 public:
168 TypeElementWalker(const Type *T) {
169 Stack.push_back(T);
170 StepToLeaf();
171 }
172
173 bool isDone() const { return Stack.empty(); }
174 const Type *getCurrentType() const { return Stack.back().Ty; }
175 unsigned getCurrentOffset() const { return Stack.back().Offset; }
176
177 void StepToNextType() {
178 PopStackAndAdvance();
179 StepToLeaf();
180 }
181
182 private:
183 /// PopStackAndAdvance - Pop the current element off of the stack and
184 /// advance the underlying element to the next contained member.
185 void PopStackAndAdvance() {
186 assert(!Stack.empty() && "Cannot pop an empty stack!");
187 Stack.pop_back();
188 while (!Stack.empty()) {
189 StackState &SS = Stack.back();
190 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
191 ++SS.Idx;
192 if (SS.Idx != ST->getElementTypes().size()) {
193 const StructLayout *SL = TD.getStructLayout(ST);
194 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
195 return;
196 }
197 Stack.pop_back(); // At the end of the structure
198 } else {
199 const ArrayType *AT = cast<ArrayType>(SS.Ty);
200 ++SS.Idx;
201 if (SS.Idx != AT->getNumElements()) {
202 SS.Offset += TD.getTypeSize(AT->getElementType());
203 return;
204 }
205 Stack.pop_back(); // At the end of the array
206 }
207 }
208 }
209
210 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
211 /// on the type stack.
212 void StepToLeaf() {
213 if (Stack.empty()) return;
214 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
215 StackState &SS = Stack.back();
216 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
217 if (ST->getElementTypes().empty()) {
218 assert(SS.Idx == 0);
219 PopStackAndAdvance();
220 } else {
221 // Step into the structure...
222 assert(SS.Idx < ST->getElementTypes().size());
223 const StructLayout *SL = TD.getStructLayout(ST);
224 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
225 SS.Offset+SL->MemberOffsets[SS.Idx]));
226 }
227 } else {
228 const ArrayType *AT = cast<ArrayType>(SS.Ty);
229 if (AT->getNumElements() == 0) {
230 assert(SS.Idx == 0);
231 PopStackAndAdvance();
232 } else {
233 // Step into the array...
234 assert(SS.Idx < AT->getNumElements());
235 Stack.push_back(StackState(AT->getElementType(),
236 SS.Offset+SS.Idx*
237 TD.getTypeSize(AT->getElementType())));
238 }
239 }
240 }
241 }
242 };
243}
244
245/// ElementTypesAreCompatible - Check to see if the specified types are
246/// "physically" compatible. If so, return true, else return false. We only
247/// have to check the fields in T1: T2 may be larger than T1.
248///
249static bool ElementTypesAreCompatible(const Type *T1, const Type *T2) {
250 TypeElementWalker T1W(T1), T2W(T2);
251
252 while (!T1W.isDone() && !T2W.isDone()) {
253 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
254 return false;
255
256 const Type *T1 = T1W.getCurrentType();
257 const Type *T2 = T2W.getCurrentType();
258 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
259 return false;
260
261 T1W.StepToNextType();
262 T2W.StepToNextType();
263 }
264
265 return T1W.isDone();
266}
267
268
Chris Lattner08db7192002-11-06 06:20:27 +0000269/// mergeTypeInfo - This method merges the specified type into the current node
270/// at the specified offset. This may update the current node's type record if
271/// this gives more information to the node, it may do nothing to the node if
272/// this information is already known, or it may merge the node completely (and
273/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000274///
Chris Lattner08db7192002-11-06 06:20:27 +0000275/// This method returns true if the node is completely folded, otherwise false.
276///
Chris Lattner088b6392003-03-03 17:13:31 +0000277bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
278 bool FoldIfIncompatible) {
Chris Lattner08db7192002-11-06 06:20:27 +0000279 // Check to make sure the Size member is up-to-date. Size can be one of the
280 // following:
281 // Size = 0, Ty = Void: Nothing is known about this node.
282 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
283 // Size = 1, Ty = Void, Array = 1: The node is collapsed
284 // Otherwise, sizeof(Ty) = Size
285 //
Chris Lattner18552922002-11-18 21:44:46 +0000286 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
287 (Size == 0 && !Ty->isSized() && !isArray()) ||
288 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
289 (Size == 0 && !Ty->isSized() && !isArray()) ||
290 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000291 "Size member of DSNode doesn't match the type structure!");
292 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000293
Chris Lattner18552922002-11-18 21:44:46 +0000294 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000295 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000296
Chris Lattner08db7192002-11-06 06:20:27 +0000297 // Return true immediately if the node is completely folded.
298 if (isNodeCompletelyFolded()) return true;
299
Chris Lattner23f83dc2002-11-08 22:49:57 +0000300 // If this is an array type, eliminate the outside arrays because they won't
301 // be used anyway. This greatly reduces the size of large static arrays used
302 // as global variables, for example.
303 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000304 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000305 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
306 // FIXME: we might want to keep small arrays, but must be careful about
307 // things like: [2 x [10000 x int*]]
308 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000309 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000310 }
311
Chris Lattner08db7192002-11-06 06:20:27 +0000312 // Figure out how big the new type we're merging in is...
313 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
314
315 // Otherwise check to see if we can fold this type into the current node. If
316 // we can't, we fold the node completely, if we can, we potentially update our
317 // internal state.
318 //
Chris Lattner18552922002-11-18 21:44:46 +0000319 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000320 // If this is the first type that this node has seen, just accept it without
321 // question....
322 assert(Offset == 0 && "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000323 assert(!isArray() && "This shouldn't happen!");
324 Ty = NewTy;
325 NodeType &= ~Array;
326 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000327 Size = NewTySize;
328
329 // Calculate the number of outgoing links from this node.
330 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
331 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000332 }
Chris Lattner08db7192002-11-06 06:20:27 +0000333
334 // Handle node expansion case here...
335 if (Offset+NewTySize > Size) {
336 // It is illegal to grow this node if we have treated it as an array of
337 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000338 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000339 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000340 return true;
341 }
342
343 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000344 std::cerr << "UNIMP: Trying to merge a growth type into "
345 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000346 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000347 return true;
348 }
349
350 // Okay, the situation is nice and simple, we are trying to merge a type in
351 // at offset 0 that is bigger than our current type. Implement this by
352 // switching to the new type and then merge in the smaller one, which should
353 // hit the other code path here. If the other code path decides it's not
354 // ok, it will collapse the node as appropriate.
355 //
Chris Lattner18552922002-11-18 21:44:46 +0000356 const Type *OldTy = Ty;
357 Ty = NewTy;
358 NodeType &= ~Array;
359 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000360 Size = NewTySize;
361
362 // Must grow links to be the appropriate size...
363 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
364
365 // Merge in the old type now... which is guaranteed to be smaller than the
366 // "current" type.
367 return mergeTypeInfo(OldTy, 0);
368 }
369
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000370 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000371 "Cannot merge something into a part of our type that doesn't exist!");
372
Chris Lattner18552922002-11-18 21:44:46 +0000373 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000374 // type that starts at offset Offset.
375 //
376 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000377 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000378 while (O < Offset) {
379 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
380
381 switch (SubType->getPrimitiveID()) {
382 case Type::StructTyID: {
383 const StructType *STy = cast<StructType>(SubType);
384 const StructLayout &SL = *TD.getStructLayout(STy);
385
386 unsigned i = 0, e = SL.MemberOffsets.size();
387 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
388 /* empty */;
389
390 // The offset we are looking for must be in the i'th element...
391 SubType = STy->getElementTypes()[i];
392 O += SL.MemberOffsets[i];
393 break;
394 }
395 case Type::ArrayTyID: {
396 SubType = cast<ArrayType>(SubType)->getElementType();
397 unsigned ElSize = TD.getTypeSize(SubType);
398 unsigned Remainder = (Offset-O) % ElSize;
399 O = Offset-Remainder;
400 break;
401 }
402 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000403 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000404 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000405 }
406 }
407
408 assert(O == Offset && "Could not achieve the correct offset!");
409
410 // If we found our type exactly, early exit
411 if (SubType == NewTy) return false;
412
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000413 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
414
415 // Ok, we are getting desperate now. Check for physical subtyping, where we
416 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000417 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000418 SubTypeSize && SubTypeSize < 256 &&
419 ElementTypesAreCompatible(NewTy, SubType))
420 return false;
421
Chris Lattner08db7192002-11-06 06:20:27 +0000422 // Okay, so we found the leader type at the offset requested. Search the list
423 // of types that starts at this offset. If SubType is currently an array or
424 // structure, the type desired may actually be the first element of the
425 // composite type...
426 //
Chris Lattner18552922002-11-18 21:44:46 +0000427 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000428 while (SubType != NewTy) {
429 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000430 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000431 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000432 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000433 case Type::StructTyID: {
434 const StructType *STy = cast<StructType>(SubType);
435 const StructLayout &SL = *TD.getStructLayout(STy);
436 if (SL.MemberOffsets.size() > 1)
437 NextPadSize = SL.MemberOffsets[1];
438 else
439 NextPadSize = SubTypeSize;
440 NextSubType = STy->getElementTypes()[0];
441 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000442 break;
Chris Lattner18552922002-11-18 21:44:46 +0000443 }
Chris Lattner08db7192002-11-06 06:20:27 +0000444 case Type::ArrayTyID:
445 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000446 NextSubTypeSize = TD.getTypeSize(NextSubType);
447 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000448 break;
449 default: ;
450 // fall out
451 }
452
453 if (NextSubType == 0)
454 break; // In the default case, break out of the loop
455
Chris Lattner18552922002-11-18 21:44:46 +0000456 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000457 break; // Don't allow shrinking to a smaller type than NewTySize
458 SubType = NextSubType;
459 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000460 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000461 }
462
463 // If we found the type exactly, return it...
464 if (SubType == NewTy)
465 return false;
466
467 // Check to see if we have a compatible, but different type...
468 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000469 // Check to see if this type is obviously convertible... int -> uint f.e.
470 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000471 return false;
472
473 // Check to see if we have a pointer & integer mismatch going on here,
474 // loading a pointer as a long, for example.
475 //
476 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
477 NewTy->isInteger() && isa<PointerType>(SubType))
478 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000479 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
480 // We are accessing the field, plus some structure padding. Ignore the
481 // structure padding.
482 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000483 }
484
Chris Lattner58f98d02003-07-02 04:38:49 +0000485 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000486 if (getParentGraph()->getReturnNodes().size())
487 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000488 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
489 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
490 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
491 << "SubType: ";
492 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000493
Chris Lattner088b6392003-03-03 17:13:31 +0000494 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000495 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000496}
497
Chris Lattner08db7192002-11-06 06:20:27 +0000498
499
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000500// addEdgeTo - Add an edge from the current node to the specified node. This
501// can cause merging of nodes in the graph.
502//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000503void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000504 if (NH.getNode() == 0) return; // Nothing to do
505
Chris Lattner08db7192002-11-06 06:20:27 +0000506 DSNodeHandle &ExistingEdge = getLink(Offset);
507 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000508 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000509 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000510 } else { // No merging to perform...
511 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000512 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000513}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000514
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000515
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000516// MergeSortedVectors - Efficiently merge a vector into another vector where
517// duplicates are not allowed and both are sorted. This assumes that 'T's are
518// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000519//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000520static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
521 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000522 // By far, the most common cases will be the simple ones. In these cases,
523 // avoid having to allocate a temporary vector...
524 //
525 if (Src.empty()) { // Nothing to merge in...
526 return;
527 } else if (Dest.empty()) { // Just copy the result in...
528 Dest = Src;
529 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000530 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000531 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000532 std::lower_bound(Dest.begin(), Dest.end(), V);
533 if (I == Dest.end() || *I != Src[0]) // If not already contained...
534 Dest.insert(I, Src[0]);
535 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000536 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000537 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000538 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000539 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
540 if (I == Dest.end() || *I != Tmp) // If not already contained...
541 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000542
543 } else {
544 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000545 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000546
547 // Make space for all of the type entries now...
548 Dest.resize(Dest.size()+Src.size());
549
550 // Merge the two sorted ranges together... into Dest.
551 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
552
553 // Now erase any duplicate entries that may have accumulated into the
554 // vectors (because they were in both of the input sets)
555 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
556 }
557}
558
559
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000560// MergeNodes() - Helper function for DSNode::mergeWith().
561// This function does the hard work of merging two nodes, CurNodeH
562// and NH after filtering out trivial cases and making sure that
563// CurNodeH.offset >= NH.offset.
564//
565// ***WARNING***
566// Since merging may cause either node to go away, we must always
567// use the node-handles to refer to the nodes. These node handles are
568// automatically updated during merging, so will always provide access
569// to the correct node after a merge.
570//
571void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
572 assert(CurNodeH.getOffset() >= NH.getOffset() &&
573 "This should have been enforced in the caller.");
574
575 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
576 // respect to NH.Offset) is now zero. NOffset is the distance from the base
577 // of our object that N starts from.
578 //
579 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
580 unsigned NSize = NH.getNode()->getSize();
581
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000582 // If the two nodes are of different size, and the smaller node has the array
583 // bit set, collapse!
584 if (NSize != CurNodeH.getNode()->getSize()) {
585 if (NSize < CurNodeH.getNode()->getSize()) {
586 if (NH.getNode()->isArray())
587 NH.getNode()->foldNodeCompletely();
588 } else if (CurNodeH.getNode()->isArray()) {
589 NH.getNode()->foldNodeCompletely();
590 }
591 }
592
593 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000594 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000595 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000596 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000597
598 // If we are merging a node with a completely folded node, then both nodes are
599 // now completely folded.
600 //
601 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
602 if (!NH.getNode()->isNodeCompletelyFolded()) {
603 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000604 assert(NH.getNode() && NH.getOffset() == 0 &&
605 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000606 NOffset = NH.getOffset();
607 NSize = NH.getNode()->getSize();
608 assert(NOffset == 0 && NSize == 1);
609 }
610 } else if (NH.getNode()->isNodeCompletelyFolded()) {
611 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000612 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
613 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000614 NOffset = NH.getOffset();
615 NSize = NH.getNode()->getSize();
616 assert(NOffset == 0 && NSize == 1);
617 }
618
Chris Lattner72d29a42003-02-11 23:11:51 +0000619 DSNode *N = NH.getNode();
620 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000621 assert(!CurNodeH.getNode()->isDeadNode());
622
623 // Merge the NodeType information...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000624 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000625
Chris Lattner72d29a42003-02-11 23:11:51 +0000626 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000627 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000628 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000629
Chris Lattner72d29a42003-02-11 23:11:51 +0000630 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
631 //
632 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
633 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000634 if (Link.getNode()) {
635 // Compute the offset into the current node at which to
636 // merge this link. In the common case, this is a linear
637 // relation to the offset in the original node (with
638 // wrapping), but if the current node gets collapsed due to
639 // recursive merging, we must make sure to merge in all remaining
640 // links at offset zero.
641 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000642 DSNode *CN = CurNodeH.getNode();
643 if (CN->Size != 1)
644 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
645 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000646 }
647 }
648
649 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000650 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000651
652 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000653 if (!N->Globals.empty()) {
654 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000655
656 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000657 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000658 }
659}
660
661
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000662// mergeWith - Merge this node and the specified node, moving all links to and
663// from the argument node into the current node, deleting the node argument.
664// Offset indicates what offset the specified node is to be merged into the
665// current node.
666//
667// The specified node may be a null pointer (in which case, nothing happens).
668//
669void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
670 DSNode *N = NH.getNode();
671 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000672 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000673
Chris Lattnerbd92b732003-06-19 21:15:11 +0000674 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000675 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
676
Chris Lattner02606632002-11-04 06:48:26 +0000677 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000678 // We cannot merge two pieces of the same node together, collapse the node
679 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000680 DEBUG(std::cerr << "Attempting to merge two chunks of"
681 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000682 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000683 return;
684 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000685
Chris Lattner5190ce82002-11-12 07:20:45 +0000686 // If both nodes are not at offset 0, make sure that we are merging the node
687 // at an later offset into the node with the zero offset.
688 //
689 if (Offset < NH.getOffset()) {
690 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
691 return;
692 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
693 // If the offsets are the same, merge the smaller node into the bigger node
694 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
695 return;
696 }
697
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000698 // Ok, now we can merge the two nodes. Use a static helper that works with
699 // two node handles, since "this" may get merged away at intermediate steps.
700 DSNodeHandle CurNodeH(this, Offset);
701 DSNodeHandle NHCopy(NH);
702 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000703}
704
Chris Lattner9de906c2002-10-20 22:11:44 +0000705//===----------------------------------------------------------------------===//
706// DSCallSite Implementation
707//===----------------------------------------------------------------------===//
708
Vikram S. Adve26b98262002-10-20 21:41:02 +0000709// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000710Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000711 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000712}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000713
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000714
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000715//===----------------------------------------------------------------------===//
716// DSGraph Implementation
717//===----------------------------------------------------------------------===//
718
Chris Lattnera9d65662003-06-30 05:57:30 +0000719/// getFunctionNames - Return a space separated list of the name of the
720/// functions in this graph (if any)
721std::string DSGraph::getFunctionNames() const {
722 switch (getReturnNodes().size()) {
723 case 0: return "Globals graph";
724 case 1: return getReturnNodes().begin()->first->getName();
725 default:
726 std::string Return;
727 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
728 I != getReturnNodes().end(); ++I)
729 Return += I->first->getName() + " ";
730 Return.erase(Return.end()-1, Return.end()); // Remove last space character
731 return Return;
732 }
733}
734
735
Chris Lattner5a540632003-06-30 03:15:25 +0000736DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000737 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000738 NodeMapTy NodeMap;
739 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000740 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattner0d9bab82002-07-18 00:12:30 +0000741}
742
Chris Lattner5a540632003-06-30 03:15:25 +0000743DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
744 : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000745 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000746 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000747 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattnereff0da92002-10-21 15:32:34 +0000748}
749
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000750DSGraph::~DSGraph() {
751 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000752 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000753 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000754 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +0000755 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000756
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000757 // Drop all intra-node references, so that assertions don't fail...
758 std::for_each(Nodes.begin(), Nodes.end(),
759 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000760
761 // Delete all of the nodes themselves...
762 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
763}
764
Chris Lattner0d9bab82002-07-18 00:12:30 +0000765// dump - Allow inspection of graph in a debugger.
766void DSGraph::dump() const { print(std::cerr); }
767
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000768
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000769/// remapLinks - Change all of the Links in the current node according to the
770/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000771///
Chris Lattner8d327672003-06-30 03:36:09 +0000772void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000773 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
774 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
775 Links[i].setNode(H.getNode());
776 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
777 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000778}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000779
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000780
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000781/// cloneReachableNodes - Clone all reachable nodes from *Node into the
782/// current graph. This is a recursive function. The map OldNodeMap is a
783/// map from the original nodes to their clones.
784///
785void DSGraph::cloneReachableNodes(const DSNode* Node,
786 unsigned BitsToClear,
787 NodeMapTy& OldNodeMap,
788 NodeMapTy& CompletedNodeMap) {
789 if (CompletedNodeMap.find(Node) != CompletedNodeMap.end())
790 return;
791
792 DSNodeHandle& NH = OldNodeMap[Node];
793 if (NH.getNode() != NULL)
794 return;
795
796 // else Node has not yet been cloned: clone it and clear the specified bits
797 NH = new DSNode(*Node, this); // enters in OldNodeMap
798 NH.getNode()->maskNodeTypes(~BitsToClear);
799
800 // now recursively clone nodes pointed to by this node
801 for (unsigned i = 0, e = Node->getNumLinks(); i != e; ++i) {
802 const DSNodeHandle &Link = Node->getLink(i << DS::PointerShift);
803 if (const DSNode* nextNode = Link.getNode())
804 cloneReachableNodes(nextNode, BitsToClear, OldNodeMap, CompletedNodeMap);
805 }
806}
807
808void DSGraph::cloneReachableSubgraph(const DSGraph& G,
809 const hash_set<const DSNode*>& RootNodes,
810 NodeMapTy& OldNodeMap,
811 NodeMapTy& CompletedNodeMap,
812 unsigned CloneFlags) {
813 if (RootNodes.empty())
814 return;
815
816 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
817 assert(&G != this && "Cannot clone graph into itself!");
818 assert((*RootNodes.begin())->getParentGraph() == &G &&
819 "Root nodes do not belong to this graph!");
820
821 // Remove alloca or mod/ref bits as specified...
822 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
823 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
824 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
825 BitsToClear |= DSNode::DEAD; // Clear dead flag...
826
827 // Clone all nodes reachable from each root node, using a recursive helper
828 for (hash_set<const DSNode*>::const_iterator I = RootNodes.begin(),
829 E = RootNodes.end(); I != E; ++I)
830 cloneReachableNodes(*I, BitsToClear, OldNodeMap, CompletedNodeMap);
831
832 // Merge the map entries in OldNodeMap and CompletedNodeMap to remap links
833 NodeMapTy MergedMap(OldNodeMap);
834 MergedMap.insert(CompletedNodeMap.begin(), CompletedNodeMap.end());
835
836 // Rewrite the links in the newly created nodes (the nodes in OldNodeMap)
837 // to point into the current graph. MergedMap gives the full mapping.
838 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
839 I->second.getNode()->remapLinks(MergedMap);
840
841 // Now merge cloned global nodes with their copies in the current graph
842 // Just look through OldNodeMap to find such nodes!
843 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
844 if (I->first->isGlobalNode()) {
845 DSNodeHandle &GClone = I->second;
846 assert(GClone.getNode() != NULL && "NULL node in OldNodeMap?");
847 const std::vector<GlobalValue*> &Globals = I->first->getGlobals();
848 for (unsigned gi = 0, ge = Globals.size(); gi != ge; ++gi) {
849 DSNodeHandle &GH = ScalarMap[Globals[gi]];
850 GH.mergeWith(GClone);
851 }
852 }
853}
854
855
856/// updateFromGlobalGraph - This function rematerializes global nodes and
857/// nodes reachable from them from the globals graph into the current graph.
858/// It invokes cloneReachableSubgraph, using the globals in the current graph
859/// as the roots. It also uses the vector InlinedGlobals to avoid cloning and
860/// merging globals that are already up-to-date in the current graph. In
861/// practice, in the TD pass, this is likely to be a large fraction of the
862/// live global nodes in each function (since most live nodes are likely to
863/// have been brought up-to-date in at _some_ caller or callee).
864///
865void DSGraph::updateFromGlobalGraph() {
866
867 // Use a map to keep track of the mapping between nodes in the globals graph
868 // and this graph for up-to-date global nodes, which do not need to be cloned.
869 NodeMapTy CompletedMap;
870
871 // Put the live, non-up-to-date global nodes into a set and the up-to-date
872 // ones in the map above, mapping node in GlobalsGraph to the up-to-date node.
873 hash_set<const DSNode*> GlobalNodeSet;
874 for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
875 E = getScalarMap().end(); I != E; ++I)
876 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
877 DSNode* GNode = I->second.getNode();
878 assert(GNode && "No node for live global in current Graph?");
879 if (const DSNode* GGNode = GlobalsGraph->ScalarMap[GV].getNode())
880 if (InlinedGlobals.count(GV) == 0) // GNode is not up-to-date
881 GlobalNodeSet.insert(GGNode);
882 else { // GNode is up-to-date
883 CompletedMap[GGNode] = I->second;
884 assert(GGNode->getNumLinks() == GNode->getNumLinks() &&
885 "Links dont match in a node that is supposed to be up-to-date?"
886 "\nremapLinks() will not work if the links don't match!");
887 }
888 }
889
890 // Clone the subgraph reachable from the vector of nodes in GlobalNodes
891 // and merge the cloned global nodes with the corresponding ones, if any.
892 NodeMapTy OldNodeMap;
893 cloneReachableSubgraph(*GlobalsGraph, GlobalNodeSet, OldNodeMap,CompletedMap);
894
895 // Merging global nodes leaves behind unused nodes: get rid of them now.
896 OldNodeMap.clear(); // remove references before dead node cleanup
897 CompletedMap.clear(); // remove references before dead node cleanup
898 removeTriviallyDeadNodes();
899}
900
Chris Lattner5a540632003-06-30 03:15:25 +0000901/// cloneInto - Clone the specified DSGraph into the current graph. The
902/// translated ScalarMap for the old function is filled into the OldValMap
903/// member, and the translated ReturnNodes map is returned into ReturnNodes.
904///
905/// The CloneFlags member controls various aspects of the cloning process.
906///
907void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
908 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
909 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000910 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000911 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000912
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000913 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000914
915 // Duplicate all of the nodes, populating the node map...
916 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000917
918 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000919 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
920 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
921 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000922 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000923 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000924 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000925 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000926 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000927 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000928 }
929
Chris Lattner18552922002-11-18 21:44:46 +0000930#ifndef NDEBUG
931 Timer::addPeakMemoryMeasurement();
932#endif
933
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000934 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000935 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000936 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000937
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000938 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +0000939 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000940 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000941 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000942 DSNodeHandle &H = OldValMap[I->first];
943 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
944 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +0000945
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000946 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000947 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
948 ScalarMap[GV].mergeWith(H);
949 InlinedGlobals.insert(GV);
950 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000951 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000952
Chris Lattner679e8e12002-11-08 21:27:12 +0000953 if (!(CloneFlags & DontCloneCallNodes)) {
954 // Copy the function calls list...
955 unsigned FC = FunctionCalls.size(); // FirstCall
956 FunctionCalls.reserve(FC+G.FunctionCalls.size());
957 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
958 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000959 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000960
Chris Lattneracf491f2002-11-08 22:27:09 +0000961 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000962 // Copy the auxillary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000963 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000964 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
965 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
966 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
967 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000968
Chris Lattner5a540632003-06-30 03:15:25 +0000969 // Map the return node pointers over...
970 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
971 E = G.getReturnNodes().end(); I != E; ++I) {
972 const DSNodeHandle &Ret = I->second;
973 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
974 OldReturnNodes.insert(std::make_pair(I->first,
975 DSNodeHandle(MappedRet.getNode(),
976 MappedRet.getOffset()+Ret.getOffset())));
977 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000978}
979
Chris Lattner076c1f92002-11-07 06:31:54 +0000980/// mergeInGraph - The method is used for merging graphs together. If the
981/// argument graph is not *this, it makes a clone of the specified graph, then
982/// merges the nodes specified in the call site with the formal arguments in the
983/// graph.
984///
Chris Lattner9f930552003-06-30 05:27:18 +0000985void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
986 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000987 ScalarMapTy OldValMap, *ScalarMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000988 DSNodeHandle RetVal;
Chris Lattner076c1f92002-11-07 06:31:54 +0000989
990 // If this is not a recursive call, clone the graph into this graph...
991 if (&Graph != this) {
992 // Clone the callee's graph into the current graph, keeping
993 // track of where scalars in the old graph _used_ to point,
994 // and of the new nodes matching nodes of the old graph.
Chris Lattner5a540632003-06-30 03:15:25 +0000995 NodeMapTy OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000996
997 // The clone call may invalidate any of the vectors in the data
998 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner5a540632003-06-30 03:15:25 +0000999 ReturnNodesTy OldRetNodes;
1000 cloneInto(Graph, OldValMap, OldRetNodes, OldNodeMap, CloneFlags);
Chris Lattner58f98d02003-07-02 04:38:49 +00001001
1002 // We need to map the arguments for the function to the cloned nodes old
1003 // argument values. Do this now.
Chris Lattner5a540632003-06-30 03:15:25 +00001004 RetVal = OldRetNodes[&F];
Chris Lattner076c1f92002-11-07 06:31:54 +00001005 ScalarMap = &OldValMap;
1006 } else {
Chris Lattner5a540632003-06-30 03:15:25 +00001007 RetVal = getReturnNodeFor(F);
Chris Lattner076c1f92002-11-07 06:31:54 +00001008 ScalarMap = &getScalarMap();
1009 }
1010
1011 // Merge the return value with the return value of the context...
1012 RetVal.mergeWith(CS.getRetVal());
1013
1014 // Resolve all of the function arguments...
Chris Lattner076c1f92002-11-07 06:31:54 +00001015 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +00001016
Chris Lattner076c1f92002-11-07 06:31:54 +00001017 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1018 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +00001019 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +00001020 ++AI;
1021#ifndef NDEBUG
1022 if (AI == F.aend())
1023 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1024#endif
Chris Lattner076c1f92002-11-07 06:31:54 +00001025 }
Chris Lattner5d274582003-02-06 00:15:08 +00001026 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +00001027
1028 // Add the link from the argument scalar to the provided value
Chris Lattner72d29a42003-02-11 23:11:51 +00001029 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
Chris Lattner076c1f92002-11-07 06:31:54 +00001030 DSNodeHandle &NH = (*ScalarMap)[AI];
1031 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1032 NH.mergeWith(CS.getPtrArg(i));
1033 }
1034}
1035
Chris Lattner58f98d02003-07-02 04:38:49 +00001036/// getCallSiteForArguments - Get the arguments and return value bindings for
1037/// the specified function in the current graph.
1038///
1039DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1040 std::vector<DSNodeHandle> Args;
1041
1042 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1043 if (isPointerType(I->getType()))
1044 Args.push_back(getScalarMap().find(I)->second);
1045
1046 return DSCallSite(*(CallInst*)0, getReturnNodeFor(F), &F, Args);
1047}
1048
1049
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001050
Chris Lattner0d9bab82002-07-18 00:12:30 +00001051// markIncompleteNodes - Mark the specified node as having contents that are not
1052// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001053// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001054// must recursively traverse the data structure graph, marking all reachable
1055// nodes as incomplete.
1056//
1057static void markIncompleteNode(DSNode *N) {
1058 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001059 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001060
1061 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001062 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001063
1064 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001065 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1066 if (DSNode *DSN = N->getLink(i).getNode())
1067 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001068}
1069
Chris Lattnere71ffc22002-11-11 03:36:55 +00001070static void markIncomplete(DSCallSite &Call) {
1071 // Then the return value is certainly incomplete!
1072 markIncompleteNode(Call.getRetVal().getNode());
1073
1074 // All objects pointed to by function arguments are incomplete!
1075 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1076 markIncompleteNode(Call.getPtrArg(i).getNode());
1077}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001078
1079// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1080// modified by other functions that have not been resolved yet. This marks
1081// nodes that are reachable through three sources of "unknownness":
1082//
1083// Global Variables, Function Calls, and Incoming Arguments
1084//
1085// For any node that may have unknown components (because something outside the
1086// scope of current analysis may have modified it), the 'Incomplete' flag is
1087// added to the NodeType.
1088//
Chris Lattner394471f2003-01-23 22:05:33 +00001089void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001090 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001091 if (Flags & DSGraph::MarkFormalArgs)
1092 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1093 FI != E; ++FI) {
1094 Function &F = *FI->first;
1095 if (F.getName() != "main")
1096 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1097 if (isPointerType(I->getType()) &&
1098 ScalarMap.find(I) != ScalarMap.end())
1099 markIncompleteNode(ScalarMap[I].getNode());
1100 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001101
1102 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001103 if (!shouldPrintAuxCalls())
1104 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1105 markIncomplete(FunctionCalls[i]);
1106 else
1107 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1108 markIncomplete(AuxFunctionCalls[i]);
1109
Chris Lattner0d9bab82002-07-18 00:12:30 +00001110
Chris Lattner93d7a212003-02-09 18:41:49 +00001111 // Mark all global nodes as incomplete...
1112 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1113 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +00001114 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +00001115 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001116}
1117
Chris Lattneraa8146f2002-11-10 06:59:55 +00001118static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1119 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001120 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001121 // No interesting info?
1122 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001123 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001124 Edge.setNode(0); // Kill the edge!
1125}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001126
Chris Lattneraa8146f2002-11-10 06:59:55 +00001127static inline bool nodeContainsExternalFunction(const DSNode *N) {
1128 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1129 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1130 if (Globals[i]->isExternal())
1131 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001132 return false;
1133}
1134
Chris Lattner5a540632003-06-30 03:15:25 +00001135static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Chris Lattner18f07a12003-07-01 16:28:11 +00001136
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001137 // Remove trivially identical function calls
1138 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001139 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1140
1141 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001142 DSNode *LastCalleeNode = 0;
1143 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001144 unsigned NumDuplicateCalls = 0;
1145 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001146 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001147 DSCallSite &CS = Calls[i];
1148
Chris Lattnere4258442002-11-11 21:35:38 +00001149 // If the Callee is a useless edge, this must be an unreachable call site,
1150 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001151 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001152 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +00001153 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +00001154 CS.swap(Calls.back());
1155 Calls.pop_back();
1156 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001157 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001158 // If the return value or any arguments point to a void node with no
1159 // information at all in it, and the call node is the only node to point
1160 // to it, remove the edge to the node (killing the node).
1161 //
1162 killIfUselessEdge(CS.getRetVal());
1163 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1164 killIfUselessEdge(CS.getPtrArg(a));
1165
1166 // If this call site calls the same function as the last call site, and if
1167 // the function pointer contains an external function, this node will
1168 // never be resolved. Merge the arguments of the call node because no
1169 // information will be lost.
1170 //
Chris Lattner923fc052003-02-05 21:59:58 +00001171 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1172 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001173 ++NumDuplicateCalls;
1174 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001175 if (LastCalleeNode)
1176 LastCalleeContainsExternalFunction =
1177 nodeContainsExternalFunction(LastCalleeNode);
1178 else
1179 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001180 }
1181
Chris Lattner58f98d02003-07-02 04:38:49 +00001182#if 1
Chris Lattnere4258442002-11-11 21:35:38 +00001183 if (LastCalleeContainsExternalFunction ||
1184 // This should be more than enough context sensitivity!
1185 // FIXME: Evaluate how many times this is tripped!
1186 NumDuplicateCalls > 20) {
1187 DSCallSite &OCS = Calls[i-1];
1188 OCS.mergeWith(CS);
1189
1190 // The node will now be eliminated as a duplicate!
1191 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1192 CS = OCS;
1193 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1194 OCS = CS;
1195 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001196#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001197 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001198 if (CS.isDirectCall()) {
1199 LastCalleeFunc = CS.getCalleeFunc();
1200 LastCalleeNode = 0;
1201 } else {
1202 LastCalleeNode = CS.getCalleeNode();
1203 LastCalleeFunc = 0;
1204 }
Chris Lattnere4258442002-11-11 21:35:38 +00001205 NumDuplicateCalls = 0;
1206 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001207 }
1208 }
1209
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001210 Calls.erase(std::unique(Calls.begin(), Calls.end()),
1211 Calls.end());
1212
Chris Lattner33312f72002-11-08 01:21:07 +00001213 // Track the number of call nodes merged away...
1214 NumCallNodesMerged += NumFns-Calls.size();
1215
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001216 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001217 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001218}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001219
Chris Lattneraa8146f2002-11-10 06:59:55 +00001220
Chris Lattnere2219762002-07-18 18:22:40 +00001221// removeTriviallyDeadNodes - After the graph has been constructed, this method
1222// removes all unreachable nodes that are created because they got merged with
1223// other nodes in the graph. These nodes will all be trivially unreachable, so
1224// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001225//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001226void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner5a540632003-06-30 03:15:25 +00001227 removeIdenticalCalls(FunctionCalls);
1228 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001229
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001230 bool isGlobalsGraph = !GlobalsGraph;
1231
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001232 for (unsigned i = 0; i != Nodes.size(); ++i) {
1233 DSNode *Node = Nodes[i];
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001234
1235 // Do not remove *any* global nodes in the globals graph.
1236 // This is a special case because such nodes may not have I, M, R flags set.
1237 if (Node->isGlobalNode() && isGlobalsGraph)
1238 continue;
1239
Chris Lattner72d50a02003-06-28 21:58:28 +00001240 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001241 // This is a useless node if it has no mod/ref info (checked above),
1242 // outgoing edges (which it cannot, as it is not modified in this
1243 // context), and it has no incoming edges. If it is a global node it may
1244 // have all of these properties and still have incoming edges, due to the
1245 // scalar map, so we check those now.
1246 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001247 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001248 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001249
1250 // Loop through and make sure all of the globals are referring directly
1251 // to the node...
1252 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1253 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1254 assert(N == Node && "ScalarMap doesn't match globals list!");
1255 }
1256
Chris Lattnerbd92b732003-06-19 21:15:11 +00001257 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001258 if (Node->getNumReferrers() == Globals.size()) {
1259 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1260 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001261 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001262 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001263 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001264
1265#ifdef SANER_CODE_FOR_CHECKING_IF_ALL_REFERRERS_ARE_FROM_SCALARMAP
1266 //
1267 // *** It seems to me that we should be able to simply check if
1268 // *** there are fewer or equal #referrers as #globals and make
1269 // *** sure that all those referrers are in the scalar map?
1270 //
1271 if (Node->getNumReferrers() <= Node->getGlobals().size()) {
1272 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1273
1274#ifndef NDEBUG
1275 // Loop through and make sure all of the globals are referring directly
1276 // to the node...
1277 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1278 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1279 assert(N == Node && "ScalarMap doesn't match globals list!");
1280 }
1281#endif
1282
1283 // Make sure NumReferrers still agrees. The node is truly dead.
1284 assert(Node->getNumReferrers() == Globals.size());
1285 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1286 ScalarMap.erase(Globals[j]);
1287 Node->makeNodeDead();
1288 }
1289#endif
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001290 }
1291
Chris Lattnerbd92b732003-06-19 21:15:11 +00001292 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001293 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001294 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001295 Nodes[i--] = Nodes.back();
1296 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001297 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001298 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001299}
1300
1301
Chris Lattner5c7380e2003-01-29 21:10:20 +00001302/// markReachableNodes - This method recursively traverses the specified
1303/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1304/// to the set, which allows it to only traverse visited nodes once.
1305///
Chris Lattner41c04f72003-02-01 04:52:08 +00001306void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001307 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001308 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner41c04f72003-02-01 04:52:08 +00001309 if (ReachableNodes.count(this)) return; // Already marked reachable
1310 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +00001311
Chris Lattner5c7380e2003-01-29 21:10:20 +00001312 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1313 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1314}
1315
Chris Lattner41c04f72003-02-01 04:52:08 +00001316void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001317 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001318 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001319
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001320 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1321 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001322}
1323
Chris Lattnera1220af2003-02-01 06:17:02 +00001324// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1325// looking for a node that is marked alive. If an alive node is found, return
1326// true, otherwise return false. If an alive node is reachable, this node is
1327// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001328//
Chris Lattnera1220af2003-02-01 06:17:02 +00001329static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001330 hash_set<DSNode*> &Visited,
1331 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001332 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001333 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001334
Chris Lattner85cfe012003-07-03 02:03:53 +00001335 // If this is a global node, it will end up in the globals graph anyway, so we
1336 // don't need to worry about it.
1337 if (IgnoreGlobals && N->isGlobalNode()) return false;
1338
Chris Lattneraa8146f2002-11-10 06:59:55 +00001339 // If we know that this node is alive, return so!
1340 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001341
Chris Lattneraa8146f2002-11-10 06:59:55 +00001342 // Otherwise, we don't think the node is alive yet, check for infinite
1343 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001344 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001345 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001346
Chris Lattner08db7192002-11-06 06:20:27 +00001347 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001348 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1349 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001350 N->markReachableNodes(Alive);
1351 return true;
1352 }
1353 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001354}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001355
Chris Lattnera1220af2003-02-01 06:17:02 +00001356// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1357// alive nodes.
1358//
Chris Lattner41c04f72003-02-01 04:52:08 +00001359static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001360 hash_set<DSNode*> &Visited,
1361 bool IgnoreGlobals) {
1362 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1363 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001364 return true;
1365 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001366 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001367 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001368 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001369 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1370 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001371 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001372 return false;
1373}
1374
Chris Lattnere2219762002-07-18 18:22:40 +00001375// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1376// subgraphs that are unreachable. This often occurs because the data
1377// structure doesn't "escape" into it's caller, and thus should be eliminated
1378// from the caller's graph entirely. This is only appropriate to use when
1379// inlining graphs.
1380//
Chris Lattner394471f2003-01-23 22:05:33 +00001381void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner85cfe012003-07-03 02:03:53 +00001382 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1383
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001384 // Reduce the amount of work we have to do... remove dummy nodes left over by
1385 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001386 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001387
Chris Lattnere2219762002-07-18 18:22:40 +00001388 // FIXME: Merge nontrivially identical call nodes...
1389
1390 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001391 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001392 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001393
Chris Lattneraa8146f2002-11-10 06:59:55 +00001394 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner8d327672003-06-30 03:36:09 +00001395 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001396 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001397 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001398 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001399 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1400 ++I;
1401 } else {
1402 // Check to see if this is a worthless node generated for non-pointer
1403 // values, such as integers. Consider an addition of long types: A+B.
1404 // Assuming we can track all uses of the value in this context, and it is
1405 // NOT used as a pointer, we can delete the node. We will be able to
1406 // detect this situation if the node pointed to ONLY has Unknown bit set
1407 // in the node. In this case, the node is not incomplete, does not point
1408 // to any other nodes (no mod/ref bits set), and is therefore
1409 // uninteresting for data structure analysis. If we run across one of
1410 // these, prune the scalar pointing to it.
1411 //
1412 DSNode *N = I->second.getNode();
Chris Lattner85cfe012003-07-03 02:03:53 +00001413 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first)){
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001414 ScalarMap.erase(I++);
1415 } else {
1416 I->second.getNode()->markReachableNodes(Alive);
1417 ++I;
1418 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001419 }
Chris Lattnere2219762002-07-18 18:22:40 +00001420
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001421 // The return value is alive as well...
Chris Lattner5a540632003-06-30 03:15:25 +00001422 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1423 I != E; ++I)
1424 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001425
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001426 // Mark any nodes reachable by primary calls as alive...
1427 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1428 FunctionCalls[i].markReachableNodes(Alive);
1429
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001430 // Copy and merge all information about globals to the GlobalsGraph
1431 // if this is not a final pass (where unreachable globals are removed)
1432 NodeMapTy GlobalNodeMap;
1433 hash_set<const DSNode*> GlobalNodeSet;
1434
1435 for (std::vector<std::pair<Value*, DSNode*> >::const_iterator
1436 I = GlobalNodes.begin(), E = GlobalNodes.end(); I != E; ++I)
1437 GlobalNodeSet.insert(I->second); // put global nodes into a set
1438
1439 // Now find globals and aux call nodes that are already live or reach a live
1440 // value (which makes them live in turn), and continue till no more are found.
1441 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001442 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001443 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001444 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1445 do {
1446 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001447 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001448 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001449 // unreachable globals in the list.
1450 //
1451 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001452 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1453 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1454 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1455 Flags & DSGraph::RemoveUnreachableGlobals)) {
1456 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1457 GlobalNodes.pop_back(); // erase efficiently
1458 Iterate = true;
1459 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001460
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001461 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1462 // call nodes that get resolved will be difficult to remove from that graph.
1463 // The final unresolved call nodes must be handled specially at the end of
1464 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001465 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1466 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001467 (AuxFunctionCalls[i].isIndirectCall()
1468 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1469 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001470 AuxFunctionCalls[i].markReachableNodes(Alive);
1471 AuxFCallsAlive[i] = true;
1472 Iterate = true;
1473 }
1474 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001475
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001476 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001477 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001478 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1479 if (AuxFCallsAlive[i])
1480 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001481
1482 // Copy and merge all global nodes and dead aux call nodes into the
1483 // GlobalsGraph, and all nodes reachable from those nodes
1484 //
1485 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1486
1487 // First, add the dead aux call nodes to the set of root nodes for cloning
1488 // -- return value at this call site, if any
1489 // -- actual arguments passed at this call site
1490 // -- callee node at this call site, if this is an indirect call
1491 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i) {
1492 if (const DSNode* RetNode = AuxFunctionCalls[i].getRetVal().getNode())
1493 GlobalNodeSet.insert(RetNode);
1494 for (unsigned j=0, N=AuxFunctionCalls[i].getNumPtrArgs(); j < N; ++j)
1495 if (const DSNode* ArgTarget=AuxFunctionCalls[i].getPtrArg(j).getNode())
1496 GlobalNodeSet.insert(ArgTarget);
1497 if (AuxFunctionCalls[i].isIndirectCall())
1498 GlobalNodeSet.insert(AuxFunctionCalls[i].getCalleeNode());
1499 }
1500
1501 // There are no "pre-completed" nodes so use any empty map for those.
1502 // Strip all alloca bits since the current function is only for the BU pass.
1503 // Strip all incomplete bits since they are short-lived properties and they
1504 // will be correctly computed when rematerializing nodes into the functions.
1505 //
1506 NodeMapTy CompletedMap;
1507 GlobalsGraph->cloneReachableSubgraph(*this, GlobalNodeSet,
1508 GlobalNodeMap, CompletedMap,
1509 (DSGraph::StripAllocaBit |
1510 DSGraph::StripIncompleteBit));
1511 }
1512
1513 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001514 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001515 assert(GlobalsGraph && "No globals graph available??");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001516
1517 // Copy the unreachable call nodes to the globals graph, updating
1518 // their target pointers using the GlobalNodeMap
1519 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1520 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1521 GlobalNodeMap));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001522 }
1523 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001524 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1525 AuxFunctionCalls.end());
1526
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001527 // We are finally done with the GlobalNodeMap so we can clear it and
1528 // then get rid of unused nodes in the GlobalsGraph produced by merging.
1529 GlobalNodeMap.clear();
1530 GlobalsGraph->removeTriviallyDeadNodes();
1531
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001532 // At this point, any nodes which are visited, but not alive, are nodes
1533 // which can be removed. Loop over all nodes, eliminating completely
1534 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001535 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001536 std::vector<DSNode*> DeadNodes;
1537 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001538 for (unsigned i = 0; i != Nodes.size(); ++i)
1539 if (!Alive.count(Nodes[i])) {
1540 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001541 Nodes[i--] = Nodes.back(); // move node to end of vector
1542 Nodes.pop_back(); // Erase node from alive list.
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001543 DeadNodes.push_back(N);
1544 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001545 } else {
1546 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001547 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001548
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001549 // Remove all unreachable globals from the ScalarMap.
1550 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1551 // In either case, the dead nodes will not be in the set Alive.
1552 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1553 assert(((Flags & DSGraph::RemoveUnreachableGlobals) ||
1554 !Alive.count(GlobalNodes[i].second)) && "huh? non-dead global");
1555 if (!Alive.count(GlobalNodes[i].second))
1556 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001557 }
1558
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001559 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001560 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1561 delete DeadNodes[i];
1562
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001563 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001564}
1565
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001566void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001567 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1568 Nodes[i]->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001569
Chris Lattner8d327672003-06-30 03:36:09 +00001570 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001571 E = ScalarMap.end(); I != E; ++I) {
1572 assert(I->second.getNode() && "Null node in scalarmap!");
1573 AssertNodeInGraph(I->second.getNode());
1574 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001575 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001576 "Global points to node, but node isn't global?");
1577 AssertNodeContainsGlobal(I->second.getNode(), GV);
1578 }
1579 }
1580 AssertCallNodesInGraph();
1581 AssertAuxCallNodesInGraph();
1582}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001583