blob: bdf8d810fb667127098fbbdd3171d545e172eac4 [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 Lattner6806f562003-08-01 22:15:03 +000013#include "Support/Debug.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000014#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000015#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000016#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000017#include <algorithm>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000018
Chris Lattner08db7192002-11-06 06:20:27 +000019namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000020 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
21 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000022};
23
Chris Lattnerb1060432002-11-07 05:20:53 +000024namespace DS { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000025 extern TargetData TD;
26}
Chris Lattnerb1060432002-11-07 05:20:53 +000027using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000028
Chris Lattner731b2d72003-02-13 19:09:00 +000029DSNode *DSNodeHandle::HandleForwarding() const {
30 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
31
32 // Handle node forwarding here!
33 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
34 Offset += N->ForwardNH.getOffset();
35
36 if (--N->NumReferrers == 0) {
37 // Removing the last referrer to the node, sever the forwarding link
38 N->stopForwarding();
39 }
40
41 N = Next;
42 N->NumReferrers++;
43 if (N->Size <= Offset) {
44 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
45 Offset = 0;
46 }
47 return N;
48}
49
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000050//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000051// DSNode Implementation
52//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000053
Chris Lattnerbd92b732003-06-19 21:15:11 +000054DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000055 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000056 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000057 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000058 G->getNodes().push_back(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000059}
60
Chris Lattner0d9bab82002-07-18 00:12:30 +000061// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner72d29a42003-02-11 23:11:51 +000062DSNode::DSNode(const DSNode &N, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000063 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner58f98d02003-07-02 04:38:49 +000064 Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner72d29a42003-02-11 23:11:51 +000065 G->getNodes().push_back(this);
Chris Lattner0d9bab82002-07-18 00:12:30 +000066}
67
Chris Lattner72d29a42003-02-11 23:11:51 +000068void DSNode::assertOK() const {
69 assert((Ty != Type::VoidTy ||
70 Ty == Type::VoidTy && (Size == 0 ||
71 (NodeType & DSNode::Array))) &&
72 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +000073
74 assert(ParentGraph && "Node has no parent?");
75 const DSGraph::ScalarMapTy &SM = ParentGraph->getScalarMap();
76 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
77 assert(SM.find(Globals[i]) != SM.end());
78 assert(SM.find(Globals[i])->second.getNode() == this);
79 }
Chris Lattner72d29a42003-02-11 23:11:51 +000080}
81
82/// forwardNode - Mark this node as being obsolete, and all references to it
83/// should be forwarded to the specified node and offset.
84///
85void DSNode::forwardNode(DSNode *To, unsigned Offset) {
86 assert(this != To && "Cannot forward a node to itself!");
87 assert(ForwardNH.isNull() && "Already forwarding from this node!");
88 if (To->Size <= 1) Offset = 0;
89 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
90 "Forwarded offset is wrong!");
91 ForwardNH.setNode(To);
92 ForwardNH.setOffset(Offset);
93 NodeType = DEAD;
94 Size = 0;
95 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000096}
97
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000098// addGlobal - Add an entry for a global value to the Globals list. This also
99// marks the node with the 'G' flag if it does not already have it.
100//
101void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000102 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000103 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000104 std::lower_bound(Globals.begin(), Globals.end(), GV);
105
106 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000107 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000108 Globals.insert(I, GV);
109 NodeType |= GlobalNode;
110 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000111}
112
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000113/// foldNodeCompletely - If we determine that this node has some funny
114/// behavior happening to it that we cannot represent, we fold it down to a
115/// single, completely pessimistic, node. This node is represented as a
116/// single byte with a single TypeEntry of "void".
117///
118void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000119 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000120
Chris Lattner08db7192002-11-06 06:20:27 +0000121 ++NumFolds;
122
Chris Lattner72d29a42003-02-11 23:11:51 +0000123 // Create the node we are going to forward to...
Chris Lattner70793862003-07-02 23:57:05 +0000124 DSNode *DestNode = new DSNode(0, ParentGraph);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000125 DestNode->NodeType = NodeType|DSNode::Array;
Chris Lattner72d29a42003-02-11 23:11:51 +0000126 DestNode->Ty = Type::VoidTy;
127 DestNode->Size = 1;
128 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000129
Chris Lattner72d29a42003-02-11 23:11:51 +0000130 // Start forwarding to the destination node...
131 forwardNode(DestNode, 0);
132
133 if (Links.size()) {
134 DestNode->Links.push_back(Links[0]);
135 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000136
Chris Lattner72d29a42003-02-11 23:11:51 +0000137 // If we have links, merge all of our outgoing links together...
138 for (unsigned i = Links.size()-1; i != 0; --i)
139 NH.getNode()->Links[0].mergeWith(Links[i]);
140 Links.clear();
141 } else {
142 DestNode->Links.resize(1);
143 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000144}
Chris Lattner076c1f92002-11-07 06:31:54 +0000145
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000146/// isNodeCompletelyFolded - Return true if this node has been completely
147/// folded down to something that can never be expanded, effectively losing
148/// all of the field sensitivity that may be present in the node.
149///
150bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000151 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000152}
153
154
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000155namespace {
156 /// TypeElementWalker Class - Used for implementation of physical subtyping...
157 ///
158 class TypeElementWalker {
159 struct StackState {
160 const Type *Ty;
161 unsigned Offset;
162 unsigned Idx;
163 StackState(const Type *T, unsigned Off = 0)
164 : Ty(T), Offset(Off), Idx(0) {}
165 };
166
167 std::vector<StackState> Stack;
168 public:
169 TypeElementWalker(const Type *T) {
170 Stack.push_back(T);
171 StepToLeaf();
172 }
173
174 bool isDone() const { return Stack.empty(); }
175 const Type *getCurrentType() const { return Stack.back().Ty; }
176 unsigned getCurrentOffset() const { return Stack.back().Offset; }
177
178 void StepToNextType() {
179 PopStackAndAdvance();
180 StepToLeaf();
181 }
182
183 private:
184 /// PopStackAndAdvance - Pop the current element off of the stack and
185 /// advance the underlying element to the next contained member.
186 void PopStackAndAdvance() {
187 assert(!Stack.empty() && "Cannot pop an empty stack!");
188 Stack.pop_back();
189 while (!Stack.empty()) {
190 StackState &SS = Stack.back();
191 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
192 ++SS.Idx;
193 if (SS.Idx != ST->getElementTypes().size()) {
194 const StructLayout *SL = TD.getStructLayout(ST);
195 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
196 return;
197 }
198 Stack.pop_back(); // At the end of the structure
199 } else {
200 const ArrayType *AT = cast<ArrayType>(SS.Ty);
201 ++SS.Idx;
202 if (SS.Idx != AT->getNumElements()) {
203 SS.Offset += TD.getTypeSize(AT->getElementType());
204 return;
205 }
206 Stack.pop_back(); // At the end of the array
207 }
208 }
209 }
210
211 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
212 /// on the type stack.
213 void StepToLeaf() {
214 if (Stack.empty()) return;
215 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
216 StackState &SS = Stack.back();
217 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
218 if (ST->getElementTypes().empty()) {
219 assert(SS.Idx == 0);
220 PopStackAndAdvance();
221 } else {
222 // Step into the structure...
223 assert(SS.Idx < ST->getElementTypes().size());
224 const StructLayout *SL = TD.getStructLayout(ST);
225 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
226 SS.Offset+SL->MemberOffsets[SS.Idx]));
227 }
228 } else {
229 const ArrayType *AT = cast<ArrayType>(SS.Ty);
230 if (AT->getNumElements() == 0) {
231 assert(SS.Idx == 0);
232 PopStackAndAdvance();
233 } else {
234 // Step into the array...
235 assert(SS.Idx < AT->getNumElements());
236 Stack.push_back(StackState(AT->getElementType(),
237 SS.Offset+SS.Idx*
238 TD.getTypeSize(AT->getElementType())));
239 }
240 }
241 }
242 }
243 };
244}
245
246/// ElementTypesAreCompatible - Check to see if the specified types are
247/// "physically" compatible. If so, return true, else return false. We only
248/// have to check the fields in T1: T2 may be larger than T1.
249///
250static bool ElementTypesAreCompatible(const Type *T1, const Type *T2) {
251 TypeElementWalker T1W(T1), T2W(T2);
252
253 while (!T1W.isDone() && !T2W.isDone()) {
254 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
255 return false;
256
257 const Type *T1 = T1W.getCurrentType();
258 const Type *T2 = T2W.getCurrentType();
259 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
260 return false;
261
262 T1W.StepToNextType();
263 T2W.StepToNextType();
264 }
265
266 return T1W.isDone();
267}
268
269
Chris Lattner08db7192002-11-06 06:20:27 +0000270/// mergeTypeInfo - This method merges the specified type into the current node
271/// at the specified offset. This may update the current node's type record if
272/// this gives more information to the node, it may do nothing to the node if
273/// this information is already known, or it may merge the node completely (and
274/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000275///
Chris Lattner08db7192002-11-06 06:20:27 +0000276/// This method returns true if the node is completely folded, otherwise false.
277///
Chris Lattner088b6392003-03-03 17:13:31 +0000278bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
279 bool FoldIfIncompatible) {
Chris Lattner08db7192002-11-06 06:20:27 +0000280 // Check to make sure the Size member is up-to-date. Size can be one of the
281 // following:
282 // Size = 0, Ty = Void: Nothing is known about this node.
283 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
284 // Size = 1, Ty = Void, Array = 1: The node is collapsed
285 // Otherwise, sizeof(Ty) = Size
286 //
Chris Lattner18552922002-11-18 21:44:46 +0000287 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
288 (Size == 0 && !Ty->isSized() && !isArray()) ||
289 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
290 (Size == 0 && !Ty->isSized() && !isArray()) ||
291 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000292 "Size member of DSNode doesn't match the type structure!");
293 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000294
Chris Lattner18552922002-11-18 21:44:46 +0000295 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000296 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000297
Chris Lattner08db7192002-11-06 06:20:27 +0000298 // Return true immediately if the node is completely folded.
299 if (isNodeCompletelyFolded()) return true;
300
Chris Lattner23f83dc2002-11-08 22:49:57 +0000301 // If this is an array type, eliminate the outside arrays because they won't
302 // be used anyway. This greatly reduces the size of large static arrays used
303 // as global variables, for example.
304 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000305 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000306 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
307 // FIXME: we might want to keep small arrays, but must be careful about
308 // things like: [2 x [10000 x int*]]
309 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000310 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000311 }
312
Chris Lattner08db7192002-11-06 06:20:27 +0000313 // Figure out how big the new type we're merging in is...
314 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
315
316 // Otherwise check to see if we can fold this type into the current node. If
317 // we can't, we fold the node completely, if we can, we potentially update our
318 // internal state.
319 //
Chris Lattner18552922002-11-18 21:44:46 +0000320 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000321 // If this is the first type that this node has seen, just accept it without
322 // question....
323 assert(Offset == 0 && "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000324 assert(!isArray() && "This shouldn't happen!");
325 Ty = NewTy;
326 NodeType &= ~Array;
327 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000328 Size = NewTySize;
329
330 // Calculate the number of outgoing links from this node.
331 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
332 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000333 }
Chris Lattner08db7192002-11-06 06:20:27 +0000334
335 // Handle node expansion case here...
336 if (Offset+NewTySize > Size) {
337 // It is illegal to grow this node if we have treated it as an array of
338 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000339 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000340 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000341 return true;
342 }
343
344 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000345 std::cerr << "UNIMP: Trying to merge a growth type into "
346 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000347 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000348 return true;
349 }
350
351 // Okay, the situation is nice and simple, we are trying to merge a type in
352 // at offset 0 that is bigger than our current type. Implement this by
353 // switching to the new type and then merge in the smaller one, which should
354 // hit the other code path here. If the other code path decides it's not
355 // ok, it will collapse the node as appropriate.
356 //
Chris Lattner18552922002-11-18 21:44:46 +0000357 const Type *OldTy = Ty;
358 Ty = NewTy;
359 NodeType &= ~Array;
360 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000361 Size = NewTySize;
362
363 // Must grow links to be the appropriate size...
364 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
365
366 // Merge in the old type now... which is guaranteed to be smaller than the
367 // "current" type.
368 return mergeTypeInfo(OldTy, 0);
369 }
370
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000371 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000372 "Cannot merge something into a part of our type that doesn't exist!");
373
Chris Lattner18552922002-11-18 21:44:46 +0000374 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000375 // type that starts at offset Offset.
376 //
377 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000378 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000379 while (O < Offset) {
380 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
381
382 switch (SubType->getPrimitiveID()) {
383 case Type::StructTyID: {
384 const StructType *STy = cast<StructType>(SubType);
385 const StructLayout &SL = *TD.getStructLayout(STy);
386
387 unsigned i = 0, e = SL.MemberOffsets.size();
388 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
389 /* empty */;
390
391 // The offset we are looking for must be in the i'th element...
392 SubType = STy->getElementTypes()[i];
393 O += SL.MemberOffsets[i];
394 break;
395 }
396 case Type::ArrayTyID: {
397 SubType = cast<ArrayType>(SubType)->getElementType();
398 unsigned ElSize = TD.getTypeSize(SubType);
399 unsigned Remainder = (Offset-O) % ElSize;
400 O = Offset-Remainder;
401 break;
402 }
403 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000404 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000405 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000406 }
407 }
408
409 assert(O == Offset && "Could not achieve the correct offset!");
410
411 // If we found our type exactly, early exit
412 if (SubType == NewTy) return false;
413
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000414 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
415
416 // Ok, we are getting desperate now. Check for physical subtyping, where we
417 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000418 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000419 SubTypeSize && SubTypeSize < 256 &&
420 ElementTypesAreCompatible(NewTy, SubType))
421 return false;
422
Chris Lattner08db7192002-11-06 06:20:27 +0000423 // Okay, so we found the leader type at the offset requested. Search the list
424 // of types that starts at this offset. If SubType is currently an array or
425 // structure, the type desired may actually be the first element of the
426 // composite type...
427 //
Chris Lattner18552922002-11-18 21:44:46 +0000428 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000429 while (SubType != NewTy) {
430 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000431 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000432 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000433 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000434 case Type::StructTyID: {
435 const StructType *STy = cast<StructType>(SubType);
436 const StructLayout &SL = *TD.getStructLayout(STy);
437 if (SL.MemberOffsets.size() > 1)
438 NextPadSize = SL.MemberOffsets[1];
439 else
440 NextPadSize = SubTypeSize;
441 NextSubType = STy->getElementTypes()[0];
442 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000443 break;
Chris Lattner18552922002-11-18 21:44:46 +0000444 }
Chris Lattner08db7192002-11-06 06:20:27 +0000445 case Type::ArrayTyID:
446 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000447 NextSubTypeSize = TD.getTypeSize(NextSubType);
448 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000449 break;
450 default: ;
451 // fall out
452 }
453
454 if (NextSubType == 0)
455 break; // In the default case, break out of the loop
456
Chris Lattner18552922002-11-18 21:44:46 +0000457 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000458 break; // Don't allow shrinking to a smaller type than NewTySize
459 SubType = NextSubType;
460 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000461 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000462 }
463
464 // If we found the type exactly, return it...
465 if (SubType == NewTy)
466 return false;
467
468 // Check to see if we have a compatible, but different type...
469 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000470 // Check to see if this type is obviously convertible... int -> uint f.e.
471 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000472 return false;
473
474 // Check to see if we have a pointer & integer mismatch going on here,
475 // loading a pointer as a long, for example.
476 //
477 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
478 NewTy->isInteger() && isa<PointerType>(SubType))
479 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000480 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
481 // We are accessing the field, plus some structure padding. Ignore the
482 // structure padding.
483 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000484 }
485
Chris Lattner58f98d02003-07-02 04:38:49 +0000486 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000487 if (getParentGraph()->getReturnNodes().size())
488 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000489 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
490 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
491 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
492 << "SubType: ";
493 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000494
Chris Lattner088b6392003-03-03 17:13:31 +0000495 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000496 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000497}
498
Chris Lattner08db7192002-11-06 06:20:27 +0000499
500
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000501// addEdgeTo - Add an edge from the current node to the specified node. This
502// can cause merging of nodes in the graph.
503//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000504void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000505 if (NH.getNode() == 0) return; // Nothing to do
506
Chris Lattner08db7192002-11-06 06:20:27 +0000507 DSNodeHandle &ExistingEdge = getLink(Offset);
508 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000509 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000510 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000511 } else { // No merging to perform...
512 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000513 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000514}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000515
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000516
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000517// MergeSortedVectors - Efficiently merge a vector into another vector where
518// duplicates are not allowed and both are sorted. This assumes that 'T's are
519// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000520//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000521static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
522 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000523 // By far, the most common cases will be the simple ones. In these cases,
524 // avoid having to allocate a temporary vector...
525 //
526 if (Src.empty()) { // Nothing to merge in...
527 return;
528 } else if (Dest.empty()) { // Just copy the result in...
529 Dest = Src;
530 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000531 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000532 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000533 std::lower_bound(Dest.begin(), Dest.end(), V);
534 if (I == Dest.end() || *I != Src[0]) // If not already contained...
535 Dest.insert(I, Src[0]);
536 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000537 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000538 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000539 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000540 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
541 if (I == Dest.end() || *I != Tmp) // If not already contained...
542 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000543
544 } else {
545 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000546 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000547
548 // Make space for all of the type entries now...
549 Dest.resize(Dest.size()+Src.size());
550
551 // Merge the two sorted ranges together... into Dest.
552 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
553
554 // Now erase any duplicate entries that may have accumulated into the
555 // vectors (because they were in both of the input sets)
556 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
557 }
558}
559
560
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000561// MergeNodes() - Helper function for DSNode::mergeWith().
562// This function does the hard work of merging two nodes, CurNodeH
563// and NH after filtering out trivial cases and making sure that
564// CurNodeH.offset >= NH.offset.
565//
566// ***WARNING***
567// Since merging may cause either node to go away, we must always
568// use the node-handles to refer to the nodes. These node handles are
569// automatically updated during merging, so will always provide access
570// to the correct node after a merge.
571//
572void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
573 assert(CurNodeH.getOffset() >= NH.getOffset() &&
574 "This should have been enforced in the caller.");
575
576 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
577 // respect to NH.Offset) is now zero. NOffset is the distance from the base
578 // of our object that N starts from.
579 //
580 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
581 unsigned NSize = NH.getNode()->getSize();
582
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000583 // If the two nodes are of different size, and the smaller node has the array
584 // bit set, collapse!
585 if (NSize != CurNodeH.getNode()->getSize()) {
586 if (NSize < CurNodeH.getNode()->getSize()) {
587 if (NH.getNode()->isArray())
588 NH.getNode()->foldNodeCompletely();
589 } else if (CurNodeH.getNode()->isArray()) {
590 NH.getNode()->foldNodeCompletely();
591 }
592 }
593
594 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000595 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000596 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000597 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000598
599 // If we are merging a node with a completely folded node, then both nodes are
600 // now completely folded.
601 //
602 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
603 if (!NH.getNode()->isNodeCompletelyFolded()) {
604 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000605 assert(NH.getNode() && NH.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 } else if (NH.getNode()->isNodeCompletelyFolded()) {
612 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000613 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
614 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000615 NOffset = NH.getOffset();
616 NSize = NH.getNode()->getSize();
617 assert(NOffset == 0 && NSize == 1);
618 }
619
Chris Lattner72d29a42003-02-11 23:11:51 +0000620 DSNode *N = NH.getNode();
621 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000622 assert(!CurNodeH.getNode()->isDeadNode());
623
624 // Merge the NodeType information...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000625 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000626
Chris Lattner72d29a42003-02-11 23:11:51 +0000627 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000628 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000629 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000630
Chris Lattner72d29a42003-02-11 23:11:51 +0000631 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
632 //
633 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
634 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000635 if (Link.getNode()) {
636 // Compute the offset into the current node at which to
637 // merge this link. In the common case, this is a linear
638 // relation to the offset in the original node (with
639 // wrapping), but if the current node gets collapsed due to
640 // recursive merging, we must make sure to merge in all remaining
641 // links at offset zero.
642 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000643 DSNode *CN = CurNodeH.getNode();
644 if (CN->Size != 1)
645 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
646 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000647 }
648 }
649
650 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000651 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000652
653 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000654 if (!N->Globals.empty()) {
655 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000656
657 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000658 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000659 }
660}
661
662
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000663// mergeWith - Merge this node and the specified node, moving all links to and
664// from the argument node into the current node, deleting the node argument.
665// Offset indicates what offset the specified node is to be merged into the
666// current node.
667//
668// The specified node may be a null pointer (in which case, nothing happens).
669//
670void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
671 DSNode *N = NH.getNode();
672 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000673 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000674
Chris Lattnerbd92b732003-06-19 21:15:11 +0000675 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000676 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
677
Chris Lattner02606632002-11-04 06:48:26 +0000678 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000679 // We cannot merge two pieces of the same node together, collapse the node
680 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000681 DEBUG(std::cerr << "Attempting to merge two chunks of"
682 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000683 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000684 return;
685 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000686
Chris Lattner5190ce82002-11-12 07:20:45 +0000687 // If both nodes are not at offset 0, make sure that we are merging the node
688 // at an later offset into the node with the zero offset.
689 //
690 if (Offset < NH.getOffset()) {
691 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
692 return;
693 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
694 // If the offsets are the same, merge the smaller node into the bigger node
695 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
696 return;
697 }
698
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000699 // Ok, now we can merge the two nodes. Use a static helper that works with
700 // two node handles, since "this" may get merged away at intermediate steps.
701 DSNodeHandle CurNodeH(this, Offset);
702 DSNodeHandle NHCopy(NH);
703 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000704}
705
Chris Lattner9de906c2002-10-20 22:11:44 +0000706//===----------------------------------------------------------------------===//
707// DSCallSite Implementation
708//===----------------------------------------------------------------------===//
709
Vikram S. Adve26b98262002-10-20 21:41:02 +0000710// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000711Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000712 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000713}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000714
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000715
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000716//===----------------------------------------------------------------------===//
717// DSGraph Implementation
718//===----------------------------------------------------------------------===//
719
Chris Lattnera9d65662003-06-30 05:57:30 +0000720/// getFunctionNames - Return a space separated list of the name of the
721/// functions in this graph (if any)
722std::string DSGraph::getFunctionNames() const {
723 switch (getReturnNodes().size()) {
724 case 0: return "Globals graph";
725 case 1: return getReturnNodes().begin()->first->getName();
726 default:
727 std::string Return;
728 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
729 I != getReturnNodes().end(); ++I)
730 Return += I->first->getName() + " ";
731 Return.erase(Return.end()-1, Return.end()); // Remove last space character
732 return Return;
733 }
734}
735
736
Chris Lattner5a540632003-06-30 03:15:25 +0000737DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000738 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000739 NodeMapTy NodeMap;
740 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000741 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattner0d9bab82002-07-18 00:12:30 +0000742}
743
Chris Lattner5a540632003-06-30 03:15:25 +0000744DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
745 : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000746 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000747 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000748 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattnereff0da92002-10-21 15:32:34 +0000749}
750
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000751DSGraph::~DSGraph() {
752 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000753 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000754 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000755 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +0000756 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000757
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000758 // Drop all intra-node references, so that assertions don't fail...
759 std::for_each(Nodes.begin(), Nodes.end(),
760 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000761
762 // Delete all of the nodes themselves...
763 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
764}
765
Chris Lattner0d9bab82002-07-18 00:12:30 +0000766// dump - Allow inspection of graph in a debugger.
767void DSGraph::dump() const { print(std::cerr); }
768
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000769
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000770/// remapLinks - Change all of the Links in the current node according to the
771/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000772///
Chris Lattner8d327672003-06-30 03:36:09 +0000773void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000774 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
775 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
776 Links[i].setNode(H.getNode());
777 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
778 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000779}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000780
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000781
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000782/// cloneReachableNodes - Clone all reachable nodes from *Node into the
783/// current graph. This is a recursive function. The map OldNodeMap is a
784/// map from the original nodes to their clones.
785///
786void DSGraph::cloneReachableNodes(const DSNode* Node,
787 unsigned BitsToClear,
788 NodeMapTy& OldNodeMap,
789 NodeMapTy& CompletedNodeMap) {
790 if (CompletedNodeMap.find(Node) != CompletedNodeMap.end())
791 return;
792
793 DSNodeHandle& NH = OldNodeMap[Node];
794 if (NH.getNode() != NULL)
795 return;
796
797 // else Node has not yet been cloned: clone it and clear the specified bits
798 NH = new DSNode(*Node, this); // enters in OldNodeMap
799 NH.getNode()->maskNodeTypes(~BitsToClear);
800
801 // now recursively clone nodes pointed to by this node
802 for (unsigned i = 0, e = Node->getNumLinks(); i != e; ++i) {
803 const DSNodeHandle &Link = Node->getLink(i << DS::PointerShift);
804 if (const DSNode* nextNode = Link.getNode())
805 cloneReachableNodes(nextNode, BitsToClear, OldNodeMap, CompletedNodeMap);
806 }
807}
808
809void DSGraph::cloneReachableSubgraph(const DSGraph& G,
810 const hash_set<const DSNode*>& RootNodes,
811 NodeMapTy& OldNodeMap,
812 NodeMapTy& CompletedNodeMap,
813 unsigned CloneFlags) {
814 if (RootNodes.empty())
815 return;
816
817 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
818 assert(&G != this && "Cannot clone graph into itself!");
819 assert((*RootNodes.begin())->getParentGraph() == &G &&
820 "Root nodes do not belong to this graph!");
821
822 // Remove alloca or mod/ref bits as specified...
823 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
824 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
825 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
826 BitsToClear |= DSNode::DEAD; // Clear dead flag...
827
828 // Clone all nodes reachable from each root node, using a recursive helper
829 for (hash_set<const DSNode*>::const_iterator I = RootNodes.begin(),
830 E = RootNodes.end(); I != E; ++I)
831 cloneReachableNodes(*I, BitsToClear, OldNodeMap, CompletedNodeMap);
832
833 // Merge the map entries in OldNodeMap and CompletedNodeMap to remap links
834 NodeMapTy MergedMap(OldNodeMap);
835 MergedMap.insert(CompletedNodeMap.begin(), CompletedNodeMap.end());
836
837 // Rewrite the links in the newly created nodes (the nodes in OldNodeMap)
838 // to point into the current graph. MergedMap gives the full mapping.
839 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
840 I->second.getNode()->remapLinks(MergedMap);
841
842 // Now merge cloned global nodes with their copies in the current graph
843 // Just look through OldNodeMap to find such nodes!
844 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
845 if (I->first->isGlobalNode()) {
846 DSNodeHandle &GClone = I->second;
847 assert(GClone.getNode() != NULL && "NULL node in OldNodeMap?");
848 const std::vector<GlobalValue*> &Globals = I->first->getGlobals();
849 for (unsigned gi = 0, ge = Globals.size(); gi != ge; ++gi) {
850 DSNodeHandle &GH = ScalarMap[Globals[gi]];
851 GH.mergeWith(GClone);
852 }
853 }
854}
855
856
857/// updateFromGlobalGraph - This function rematerializes global nodes and
858/// nodes reachable from them from the globals graph into the current graph.
859/// It invokes cloneReachableSubgraph, using the globals in the current graph
860/// as the roots. It also uses the vector InlinedGlobals to avoid cloning and
861/// merging globals that are already up-to-date in the current graph. In
862/// practice, in the TD pass, this is likely to be a large fraction of the
863/// live global nodes in each function (since most live nodes are likely to
864/// have been brought up-to-date in at _some_ caller or callee).
865///
866void DSGraph::updateFromGlobalGraph() {
867
868 // Use a map to keep track of the mapping between nodes in the globals graph
869 // and this graph for up-to-date global nodes, which do not need to be cloned.
870 NodeMapTy CompletedMap;
871
872 // Put the live, non-up-to-date global nodes into a set and the up-to-date
873 // ones in the map above, mapping node in GlobalsGraph to the up-to-date node.
874 hash_set<const DSNode*> GlobalNodeSet;
875 for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
876 E = getScalarMap().end(); I != E; ++I)
877 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
878 DSNode* GNode = I->second.getNode();
879 assert(GNode && "No node for live global in current Graph?");
880 if (const DSNode* GGNode = GlobalsGraph->ScalarMap[GV].getNode())
881 if (InlinedGlobals.count(GV) == 0) // GNode is not up-to-date
882 GlobalNodeSet.insert(GGNode);
883 else { // GNode is up-to-date
884 CompletedMap[GGNode] = I->second;
885 assert(GGNode->getNumLinks() == GNode->getNumLinks() &&
886 "Links dont match in a node that is supposed to be up-to-date?"
887 "\nremapLinks() will not work if the links don't match!");
888 }
889 }
890
891 // Clone the subgraph reachable from the vector of nodes in GlobalNodes
892 // and merge the cloned global nodes with the corresponding ones, if any.
893 NodeMapTy OldNodeMap;
894 cloneReachableSubgraph(*GlobalsGraph, GlobalNodeSet, OldNodeMap,CompletedMap);
895
896 // Merging global nodes leaves behind unused nodes: get rid of them now.
897 OldNodeMap.clear(); // remove references before dead node cleanup
898 CompletedMap.clear(); // remove references before dead node cleanup
899 removeTriviallyDeadNodes();
900}
901
Chris Lattner5a540632003-06-30 03:15:25 +0000902/// cloneInto - Clone the specified DSGraph into the current graph. The
903/// translated ScalarMap for the old function is filled into the OldValMap
904/// member, and the translated ReturnNodes map is returned into ReturnNodes.
905///
906/// The CloneFlags member controls various aspects of the cloning process.
907///
908void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
909 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
910 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000911 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000912 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000913
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000914 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000915
916 // Duplicate all of the nodes, populating the node map...
917 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000918
919 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000920 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
921 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
922 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000923 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000924 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000925 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000926 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000927 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000928 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000929 }
930
Chris Lattner18552922002-11-18 21:44:46 +0000931#ifndef NDEBUG
932 Timer::addPeakMemoryMeasurement();
933#endif
934
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000935 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000936 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000937 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000938
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000939 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +0000940 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000941 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000942 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000943 DSNodeHandle &H = OldValMap[I->first];
944 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
945 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +0000946
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000947 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000948 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
949 ScalarMap[GV].mergeWith(H);
950 InlinedGlobals.insert(GV);
951 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000952 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000953
Chris Lattner679e8e12002-11-08 21:27:12 +0000954 if (!(CloneFlags & DontCloneCallNodes)) {
955 // Copy the function calls list...
956 unsigned FC = FunctionCalls.size(); // FirstCall
957 FunctionCalls.reserve(FC+G.FunctionCalls.size());
958 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
959 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000960 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000961
Chris Lattneracf491f2002-11-08 22:27:09 +0000962 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +0000963 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000964 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000965 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
966 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
967 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
968 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000969
Chris Lattner5a540632003-06-30 03:15:25 +0000970 // Map the return node pointers over...
971 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
972 E = G.getReturnNodes().end(); I != E; ++I) {
973 const DSNodeHandle &Ret = I->second;
974 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
975 OldReturnNodes.insert(std::make_pair(I->first,
976 DSNodeHandle(MappedRet.getNode(),
977 MappedRet.getOffset()+Ret.getOffset())));
978 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000979}
980
Chris Lattner076c1f92002-11-07 06:31:54 +0000981/// mergeInGraph - The method is used for merging graphs together. If the
982/// argument graph is not *this, it makes a clone of the specified graph, then
983/// merges the nodes specified in the call site with the formal arguments in the
984/// graph.
985///
Chris Lattner9f930552003-06-30 05:27:18 +0000986void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
987 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000988 ScalarMapTy OldValMap, *ScalarMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000989 DSNodeHandle RetVal;
Chris Lattner076c1f92002-11-07 06:31:54 +0000990
991 // If this is not a recursive call, clone the graph into this graph...
992 if (&Graph != this) {
993 // Clone the callee's graph into the current graph, keeping
994 // track of where scalars in the old graph _used_ to point,
995 // and of the new nodes matching nodes of the old graph.
Chris Lattner5a540632003-06-30 03:15:25 +0000996 NodeMapTy OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000997
998 // The clone call may invalidate any of the vectors in the data
999 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner5a540632003-06-30 03:15:25 +00001000 ReturnNodesTy OldRetNodes;
1001 cloneInto(Graph, OldValMap, OldRetNodes, OldNodeMap, CloneFlags);
Chris Lattner58f98d02003-07-02 04:38:49 +00001002
1003 // We need to map the arguments for the function to the cloned nodes old
1004 // argument values. Do this now.
Chris Lattner5a540632003-06-30 03:15:25 +00001005 RetVal = OldRetNodes[&F];
Chris Lattner076c1f92002-11-07 06:31:54 +00001006 ScalarMap = &OldValMap;
1007 } else {
Chris Lattner5a540632003-06-30 03:15:25 +00001008 RetVal = getReturnNodeFor(F);
Chris Lattner076c1f92002-11-07 06:31:54 +00001009 ScalarMap = &getScalarMap();
1010 }
1011
1012 // Merge the return value with the return value of the context...
1013 RetVal.mergeWith(CS.getRetVal());
1014
1015 // Resolve all of the function arguments...
Chris Lattner076c1f92002-11-07 06:31:54 +00001016 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +00001017
Chris Lattner076c1f92002-11-07 06:31:54 +00001018 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1019 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +00001020 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +00001021 ++AI;
1022#ifndef NDEBUG
1023 if (AI == F.aend())
1024 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1025#endif
Chris Lattner076c1f92002-11-07 06:31:54 +00001026 }
Chris Lattner5d274582003-02-06 00:15:08 +00001027 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +00001028
1029 // Add the link from the argument scalar to the provided value
Chris Lattner72d29a42003-02-11 23:11:51 +00001030 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
Chris Lattner076c1f92002-11-07 06:31:54 +00001031 DSNodeHandle &NH = (*ScalarMap)[AI];
1032 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1033 NH.mergeWith(CS.getPtrArg(i));
1034 }
1035}
1036
Chris Lattner58f98d02003-07-02 04:38:49 +00001037/// getCallSiteForArguments - Get the arguments and return value bindings for
1038/// the specified function in the current graph.
1039///
1040DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1041 std::vector<DSNodeHandle> Args;
1042
1043 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1044 if (isPointerType(I->getType()))
1045 Args.push_back(getScalarMap().find(I)->second);
1046
Chris Lattner808a7ae2003-09-20 16:34:13 +00001047 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001048}
1049
1050
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001051
Chris Lattner0d9bab82002-07-18 00:12:30 +00001052// markIncompleteNodes - Mark the specified node as having contents that are not
1053// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001054// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001055// must recursively traverse the data structure graph, marking all reachable
1056// nodes as incomplete.
1057//
1058static void markIncompleteNode(DSNode *N) {
1059 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001060 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001061
1062 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001063 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001064
Misha Brukman2f2d0652003-09-11 18:14:24 +00001065 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001066 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1067 if (DSNode *DSN = N->getLink(i).getNode())
1068 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001069}
1070
Chris Lattnere71ffc22002-11-11 03:36:55 +00001071static void markIncomplete(DSCallSite &Call) {
1072 // Then the return value is certainly incomplete!
1073 markIncompleteNode(Call.getRetVal().getNode());
1074
1075 // All objects pointed to by function arguments are incomplete!
1076 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1077 markIncompleteNode(Call.getPtrArg(i).getNode());
1078}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001079
1080// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1081// modified by other functions that have not been resolved yet. This marks
1082// nodes that are reachable through three sources of "unknownness":
1083//
1084// Global Variables, Function Calls, and Incoming Arguments
1085//
1086// For any node that may have unknown components (because something outside the
1087// scope of current analysis may have modified it), the 'Incomplete' flag is
1088// added to the NodeType.
1089//
Chris Lattner394471f2003-01-23 22:05:33 +00001090void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001091 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001092 if (Flags & DSGraph::MarkFormalArgs)
1093 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1094 FI != E; ++FI) {
1095 Function &F = *FI->first;
1096 if (F.getName() != "main")
1097 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1098 if (isPointerType(I->getType()) &&
1099 ScalarMap.find(I) != ScalarMap.end())
1100 markIncompleteNode(ScalarMap[I].getNode());
1101 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001102
1103 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001104 if (!shouldPrintAuxCalls())
1105 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1106 markIncomplete(FunctionCalls[i]);
1107 else
1108 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1109 markIncomplete(AuxFunctionCalls[i]);
1110
Chris Lattner0d9bab82002-07-18 00:12:30 +00001111
Chris Lattner93d7a212003-02-09 18:41:49 +00001112 // Mark all global nodes as incomplete...
1113 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1114 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +00001115 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +00001116 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001117}
1118
Chris Lattneraa8146f2002-11-10 06:59:55 +00001119static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1120 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001121 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001122 // No interesting info?
1123 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001124 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001125 Edge.setNode(0); // Kill the edge!
1126}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001127
Chris Lattneraa8146f2002-11-10 06:59:55 +00001128static inline bool nodeContainsExternalFunction(const DSNode *N) {
1129 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1130 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1131 if (Globals[i]->isExternal())
1132 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001133 return false;
1134}
1135
Chris Lattner5a540632003-06-30 03:15:25 +00001136static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Chris Lattner18f07a12003-07-01 16:28:11 +00001137
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001138 // Remove trivially identical function calls
1139 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001140 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1141
1142 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001143 DSNode *LastCalleeNode = 0;
1144 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001145 unsigned NumDuplicateCalls = 0;
1146 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001147 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001148 DSCallSite &CS = Calls[i];
1149
Chris Lattnere4258442002-11-11 21:35:38 +00001150 // If the Callee is a useless edge, this must be an unreachable call site,
1151 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001152 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001153 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +00001154 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +00001155 CS.swap(Calls.back());
1156 Calls.pop_back();
1157 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001158 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001159 // If the return value or any arguments point to a void node with no
1160 // information at all in it, and the call node is the only node to point
1161 // to it, remove the edge to the node (killing the node).
1162 //
1163 killIfUselessEdge(CS.getRetVal());
1164 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1165 killIfUselessEdge(CS.getPtrArg(a));
1166
1167 // If this call site calls the same function as the last call site, and if
1168 // the function pointer contains an external function, this node will
1169 // never be resolved. Merge the arguments of the call node because no
1170 // information will be lost.
1171 //
Chris Lattner923fc052003-02-05 21:59:58 +00001172 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1173 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001174 ++NumDuplicateCalls;
1175 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001176 if (LastCalleeNode)
1177 LastCalleeContainsExternalFunction =
1178 nodeContainsExternalFunction(LastCalleeNode);
1179 else
1180 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001181 }
1182
Chris Lattner58f98d02003-07-02 04:38:49 +00001183#if 1
Chris Lattnere4258442002-11-11 21:35:38 +00001184 if (LastCalleeContainsExternalFunction ||
1185 // This should be more than enough context sensitivity!
1186 // FIXME: Evaluate how many times this is tripped!
1187 NumDuplicateCalls > 20) {
1188 DSCallSite &OCS = Calls[i-1];
1189 OCS.mergeWith(CS);
1190
1191 // The node will now be eliminated as a duplicate!
1192 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1193 CS = OCS;
1194 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1195 OCS = CS;
1196 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001197#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001198 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001199 if (CS.isDirectCall()) {
1200 LastCalleeFunc = CS.getCalleeFunc();
1201 LastCalleeNode = 0;
1202 } else {
1203 LastCalleeNode = CS.getCalleeNode();
1204 LastCalleeFunc = 0;
1205 }
Chris Lattnere4258442002-11-11 21:35:38 +00001206 NumDuplicateCalls = 0;
1207 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001208 }
1209 }
1210
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001211 Calls.erase(std::unique(Calls.begin(), Calls.end()),
1212 Calls.end());
1213
Chris Lattner33312f72002-11-08 01:21:07 +00001214 // Track the number of call nodes merged away...
1215 NumCallNodesMerged += NumFns-Calls.size();
1216
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001217 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001218 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001219}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001220
Chris Lattneraa8146f2002-11-10 06:59:55 +00001221
Chris Lattnere2219762002-07-18 18:22:40 +00001222// removeTriviallyDeadNodes - After the graph has been constructed, this method
1223// removes all unreachable nodes that are created because they got merged with
1224// other nodes in the graph. These nodes will all be trivially unreachable, so
1225// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001226//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001227void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner5a540632003-06-30 03:15:25 +00001228 removeIdenticalCalls(FunctionCalls);
1229 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001230
Chris Lattnerbab8c282003-09-20 21:34:07 +00001231 // Loop over all of the nodes in the graph, calling getNode on each field.
1232 // This will cause all nodes to update their forwarding edges, causing
1233 // forwarded nodes to be delete-able.
1234 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1235 DSNode *N = Nodes[i];
1236 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1237 N->getLink(l*N->getPointerSize()).getNode();
1238 }
1239
1240 // Likewise, forward any edges from the scalar nodes...
1241 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1242 I != E; ++I)
1243 I->second.getNode();
1244
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001245 bool isGlobalsGraph = !GlobalsGraph;
1246
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001247 for (unsigned i = 0; i != Nodes.size(); ++i) {
1248 DSNode *Node = Nodes[i];
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001249
1250 // Do not remove *any* global nodes in the globals graph.
1251 // This is a special case because such nodes may not have I, M, R flags set.
1252 if (Node->isGlobalNode() && isGlobalsGraph)
1253 continue;
1254
Chris Lattner72d50a02003-06-28 21:58:28 +00001255 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001256 // This is a useless node if it has no mod/ref info (checked above),
1257 // outgoing edges (which it cannot, as it is not modified in this
1258 // context), and it has no incoming edges. If it is a global node it may
1259 // have all of these properties and still have incoming edges, due to the
1260 // scalar map, so we check those now.
1261 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001262 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001263 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001264
1265 // Loop through and make sure all of the globals are referring directly
1266 // to the node...
1267 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1268 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1269 assert(N == Node && "ScalarMap doesn't match globals list!");
1270 }
1271
Chris Lattnerbd92b732003-06-19 21:15:11 +00001272 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001273 if (Node->getNumReferrers() == Globals.size()) {
1274 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1275 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001276 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001277 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001278 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001279
1280#ifdef SANER_CODE_FOR_CHECKING_IF_ALL_REFERRERS_ARE_FROM_SCALARMAP
1281 //
1282 // *** It seems to me that we should be able to simply check if
1283 // *** there are fewer or equal #referrers as #globals and make
1284 // *** sure that all those referrers are in the scalar map?
1285 //
1286 if (Node->getNumReferrers() <= Node->getGlobals().size()) {
1287 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1288
1289#ifndef NDEBUG
1290 // Loop through and make sure all of the globals are referring directly
1291 // to the node...
1292 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1293 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1294 assert(N == Node && "ScalarMap doesn't match globals list!");
1295 }
1296#endif
1297
1298 // Make sure NumReferrers still agrees. The node is truly dead.
1299 assert(Node->getNumReferrers() == Globals.size());
1300 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1301 ScalarMap.erase(Globals[j]);
1302 Node->makeNodeDead();
1303 }
1304#endif
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001305 }
1306
Chris Lattnerbd92b732003-06-19 21:15:11 +00001307 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001308 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001309 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001310 Nodes[i--] = Nodes.back();
1311 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001312 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001313 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001314}
1315
1316
Chris Lattner5c7380e2003-01-29 21:10:20 +00001317/// markReachableNodes - This method recursively traverses the specified
1318/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1319/// to the set, which allows it to only traverse visited nodes once.
1320///
Chris Lattner41c04f72003-02-01 04:52:08 +00001321void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001322 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001323 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner41c04f72003-02-01 04:52:08 +00001324 if (ReachableNodes.count(this)) return; // Already marked reachable
1325 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +00001326
Chris Lattner5c7380e2003-01-29 21:10:20 +00001327 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1328 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1329}
1330
Chris Lattner41c04f72003-02-01 04:52:08 +00001331void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001332 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001333 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001334
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001335 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1336 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001337}
1338
Chris Lattnera1220af2003-02-01 06:17:02 +00001339// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1340// looking for a node that is marked alive. If an alive node is found, return
1341// true, otherwise return false. If an alive node is reachable, this node is
1342// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001343//
Chris Lattnera1220af2003-02-01 06:17:02 +00001344static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001345 hash_set<DSNode*> &Visited,
1346 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001347 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001348 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001349
Chris Lattner85cfe012003-07-03 02:03:53 +00001350 // If this is a global node, it will end up in the globals graph anyway, so we
1351 // don't need to worry about it.
1352 if (IgnoreGlobals && N->isGlobalNode()) return false;
1353
Chris Lattneraa8146f2002-11-10 06:59:55 +00001354 // If we know that this node is alive, return so!
1355 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001356
Chris Lattneraa8146f2002-11-10 06:59:55 +00001357 // Otherwise, we don't think the node is alive yet, check for infinite
1358 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001359 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001360 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001361
Chris Lattner08db7192002-11-06 06:20:27 +00001362 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001363 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1364 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001365 N->markReachableNodes(Alive);
1366 return true;
1367 }
1368 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001369}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001370
Chris Lattnera1220af2003-02-01 06:17:02 +00001371// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1372// alive nodes.
1373//
Chris Lattner41c04f72003-02-01 04:52:08 +00001374static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001375 hash_set<DSNode*> &Visited,
1376 bool IgnoreGlobals) {
1377 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1378 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001379 return true;
1380 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001381 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001382 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001383 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001384 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1385 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001386 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001387 return false;
1388}
1389
Chris Lattnere2219762002-07-18 18:22:40 +00001390// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1391// subgraphs that are unreachable. This often occurs because the data
1392// structure doesn't "escape" into it's caller, and thus should be eliminated
1393// from the caller's graph entirely. This is only appropriate to use when
1394// inlining graphs.
1395//
Chris Lattner394471f2003-01-23 22:05:33 +00001396void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner85cfe012003-07-03 02:03:53 +00001397 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1398
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001399 // Reduce the amount of work we have to do... remove dummy nodes left over by
1400 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001401 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001402
Misha Brukman2f2d0652003-09-11 18:14:24 +00001403 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001404
1405 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001406 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001407 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001408
Chris Lattneraa8146f2002-11-10 06:59:55 +00001409 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner8d327672003-06-30 03:36:09 +00001410 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001411 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001412 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001413 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001414 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1415 ++I;
1416 } else {
1417 // Check to see if this is a worthless node generated for non-pointer
1418 // values, such as integers. Consider an addition of long types: A+B.
1419 // Assuming we can track all uses of the value in this context, and it is
1420 // NOT used as a pointer, we can delete the node. We will be able to
1421 // detect this situation if the node pointed to ONLY has Unknown bit set
1422 // in the node. In this case, the node is not incomplete, does not point
1423 // to any other nodes (no mod/ref bits set), and is therefore
1424 // uninteresting for data structure analysis. If we run across one of
1425 // these, prune the scalar pointing to it.
1426 //
1427 DSNode *N = I->second.getNode();
Chris Lattner85cfe012003-07-03 02:03:53 +00001428 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first)){
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001429 ScalarMap.erase(I++);
1430 } else {
1431 I->second.getNode()->markReachableNodes(Alive);
1432 ++I;
1433 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001434 }
Chris Lattnere2219762002-07-18 18:22:40 +00001435
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001436 // The return value is alive as well...
Chris Lattner5a540632003-06-30 03:15:25 +00001437 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1438 I != E; ++I)
1439 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001440
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001441 // Mark any nodes reachable by primary calls as alive...
1442 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1443 FunctionCalls[i].markReachableNodes(Alive);
1444
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001445 // Copy and merge all information about globals to the GlobalsGraph
1446 // if this is not a final pass (where unreachable globals are removed)
1447 NodeMapTy GlobalNodeMap;
1448 hash_set<const DSNode*> GlobalNodeSet;
1449
1450 for (std::vector<std::pair<Value*, DSNode*> >::const_iterator
1451 I = GlobalNodes.begin(), E = GlobalNodes.end(); I != E; ++I)
1452 GlobalNodeSet.insert(I->second); // put global nodes into a set
1453
1454 // Now find globals and aux call nodes that are already live or reach a live
1455 // value (which makes them live in turn), and continue till no more are found.
1456 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001457 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001458 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001459 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1460 do {
1461 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001462 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001463 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001464 // unreachable globals in the list.
1465 //
1466 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001467 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1468 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1469 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1470 Flags & DSGraph::RemoveUnreachableGlobals)) {
1471 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1472 GlobalNodes.pop_back(); // erase efficiently
1473 Iterate = true;
1474 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001475
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001476 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1477 // call nodes that get resolved will be difficult to remove from that graph.
1478 // The final unresolved call nodes must be handled specially at the end of
1479 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001480 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1481 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001482 (AuxFunctionCalls[i].isIndirectCall()
1483 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1484 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001485 AuxFunctionCalls[i].markReachableNodes(Alive);
1486 AuxFCallsAlive[i] = true;
1487 Iterate = true;
1488 }
1489 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001490
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001491 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001492 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001493 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1494 if (AuxFCallsAlive[i])
1495 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001496
1497 // Copy and merge all global nodes and dead aux call nodes into the
1498 // GlobalsGraph, and all nodes reachable from those nodes
1499 //
1500 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1501
1502 // First, add the dead aux call nodes to the set of root nodes for cloning
1503 // -- return value at this call site, if any
1504 // -- actual arguments passed at this call site
1505 // -- callee node at this call site, if this is an indirect call
1506 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i) {
1507 if (const DSNode* RetNode = AuxFunctionCalls[i].getRetVal().getNode())
1508 GlobalNodeSet.insert(RetNode);
1509 for (unsigned j=0, N=AuxFunctionCalls[i].getNumPtrArgs(); j < N; ++j)
1510 if (const DSNode* ArgTarget=AuxFunctionCalls[i].getPtrArg(j).getNode())
1511 GlobalNodeSet.insert(ArgTarget);
1512 if (AuxFunctionCalls[i].isIndirectCall())
1513 GlobalNodeSet.insert(AuxFunctionCalls[i].getCalleeNode());
1514 }
1515
1516 // There are no "pre-completed" nodes so use any empty map for those.
1517 // Strip all alloca bits since the current function is only for the BU pass.
1518 // Strip all incomplete bits since they are short-lived properties and they
1519 // will be correctly computed when rematerializing nodes into the functions.
1520 //
1521 NodeMapTy CompletedMap;
1522 GlobalsGraph->cloneReachableSubgraph(*this, GlobalNodeSet,
1523 GlobalNodeMap, CompletedMap,
1524 (DSGraph::StripAllocaBit |
1525 DSGraph::StripIncompleteBit));
1526 }
1527
1528 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001529 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001530 assert(GlobalsGraph && "No globals graph available??");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001531
1532 // Copy the unreachable call nodes to the globals graph, updating
1533 // their target pointers using the GlobalNodeMap
1534 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1535 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1536 GlobalNodeMap));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001537 }
1538 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001539 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1540 AuxFunctionCalls.end());
1541
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001542 // We are finally done with the GlobalNodeMap so we can clear it and
1543 // then get rid of unused nodes in the GlobalsGraph produced by merging.
1544 GlobalNodeMap.clear();
1545 GlobalsGraph->removeTriviallyDeadNodes();
1546
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001547 // At this point, any nodes which are visited, but not alive, are nodes
1548 // which can be removed. Loop over all nodes, eliminating completely
1549 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001550 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001551 std::vector<DSNode*> DeadNodes;
1552 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001553 for (unsigned i = 0; i != Nodes.size(); ++i)
1554 if (!Alive.count(Nodes[i])) {
1555 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001556 Nodes[i--] = Nodes.back(); // move node to end of vector
1557 Nodes.pop_back(); // Erase node from alive list.
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001558 DeadNodes.push_back(N);
1559 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001560 } else {
1561 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001562 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001563
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001564 // Remove all unreachable globals from the ScalarMap.
1565 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1566 // In either case, the dead nodes will not be in the set Alive.
1567 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1568 assert(((Flags & DSGraph::RemoveUnreachableGlobals) ||
1569 !Alive.count(GlobalNodes[i].second)) && "huh? non-dead global");
1570 if (!Alive.count(GlobalNodes[i].second))
1571 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001572 }
1573
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001574 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001575 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1576 delete DeadNodes[i];
1577
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001578 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001579}
1580
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001581void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001582 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1583 Nodes[i]->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001584
Chris Lattner8d327672003-06-30 03:36:09 +00001585 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001586 E = ScalarMap.end(); I != E; ++I) {
1587 assert(I->second.getNode() && "Null node in scalarmap!");
1588 AssertNodeInGraph(I->second.getNode());
1589 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001590 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001591 "Global points to node, but node isn't global?");
1592 AssertNodeContainsGlobal(I->second.getNode(), GV);
1593 }
1594 }
1595 AssertCallNodesInGraph();
1596 AssertAuxCallNodesInGraph();
1597}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001598
Chris Lattner7ddb0132003-08-05 18:38:37 +00001599/// mergeInGlobalsGraph - This method is useful for clients to incorporate the
1600/// globals graph into the DS, BU or TD graph for a function. This code retains
1601/// all globals, i.e., does not delete unreachable globals after they are
1602/// inlined.
1603///
1604void DSGraph::mergeInGlobalsGraph() {
Sumant Kowshik108421a2003-08-05 17:04:41 +00001605 NodeMapTy GlobalNodeMap;
1606 ScalarMapTy OldValMap;
1607 ReturnNodesTy OldRetNodes;
Chris Lattner7ddb0132003-08-05 18:38:37 +00001608 cloneInto(*GlobalsGraph, OldValMap, OldRetNodes, GlobalNodeMap,
1609 DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes |
1610 DSGraph::DontCloneAuxCallNodes);
Sumant Kowshik108421a2003-08-05 17:04:41 +00001611
1612 // Now merge existing global nodes in the GlobalsGraph with their copies
1613 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1614 I != E; ++I)
1615 if (isa<GlobalValue>(I->first)) { // Found a global node
1616 DSNodeHandle &GH = I->second;
1617 DSNodeHandle &GGNodeH = GlobalsGraph->getScalarMap()[I->first];
1618 GH.mergeWith(GlobalNodeMap[GGNodeH.getNode()]);
1619 }
1620
1621 // Merging leaves behind unused nodes: get rid of them now.
1622 GlobalNodeMap.clear();
1623 OldValMap.clear();
1624 OldRetNodes.clear();
1625 removeTriviallyDeadNodes();
1626}