blob: 772c0c7a6a0056cdd0d3c6aec7cfd4421459d266 [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);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000740}
741
Chris Lattner5a540632003-06-30 03:15:25 +0000742DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
743 : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000744 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000745 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000746}
747
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000748DSGraph::~DSGraph() {
749 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000750 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000751 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +0000752 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000753
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000754 // Drop all intra-node references, so that assertions don't fail...
755 std::for_each(Nodes.begin(), Nodes.end(),
756 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000757
758 // Delete all of the nodes themselves...
759 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
760}
761
Chris Lattner0d9bab82002-07-18 00:12:30 +0000762// dump - Allow inspection of graph in a debugger.
763void DSGraph::dump() const { print(std::cerr); }
764
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000765
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000766/// remapLinks - Change all of the Links in the current node according to the
767/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000768///
Chris Lattner8d327672003-06-30 03:36:09 +0000769void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000770 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
771 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
772 Links[i].setNode(H.getNode());
773 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
774 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000775}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000776
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000777
Chris Lattner5a540632003-06-30 03:15:25 +0000778/// cloneInto - Clone the specified DSGraph into the current graph. The
779/// translated ScalarMap for the old function is filled into the OldValMap
780/// member, and the translated ReturnNodes map is returned into ReturnNodes.
781///
782/// The CloneFlags member controls various aspects of the cloning process.
783///
784void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
785 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
786 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000787 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000788 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000789
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000790 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000791
792 // Duplicate all of the nodes, populating the node map...
793 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000794
795 // Remove alloca or mod/ref bits as specified...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000796 unsigned BitsToClear =((CloneFlags & StripAllocaBit) ? DSNode::AllocaNode : 0)
797 | ((CloneFlags & StripModRefBits) ? (DSNode::Modified | DSNode::Read) : 0);
798 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000799 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000800 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000801 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000802 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000803 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000804 }
805
Chris Lattner18552922002-11-18 21:44:46 +0000806#ifndef NDEBUG
807 Timer::addPeakMemoryMeasurement();
808#endif
809
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000810 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000811 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000812 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000813
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000814 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +0000815 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000816 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000817 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000818 DSNodeHandle &H = OldValMap[I->first];
819 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
820 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +0000821
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000822 // If this is a global, add the global to this fn or merge if already exists
Chris Lattner7b1ceaa2003-06-30 05:18:26 +0000823 if (isa<GlobalValue>(I->first))
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000824 ScalarMap[I->first].mergeWith(H);
Chris Lattnercf15db32002-10-17 20:09:52 +0000825 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000826
Chris Lattner679e8e12002-11-08 21:27:12 +0000827 if (!(CloneFlags & DontCloneCallNodes)) {
828 // Copy the function calls list...
829 unsigned FC = FunctionCalls.size(); // FirstCall
830 FunctionCalls.reserve(FC+G.FunctionCalls.size());
831 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
832 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000833 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000834
Chris Lattneracf491f2002-11-08 22:27:09 +0000835 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000836 // Copy the auxillary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000837 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000838 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
839 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
840 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
841 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000842
Chris Lattner5a540632003-06-30 03:15:25 +0000843 // Map the return node pointers over...
844 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
845 E = G.getReturnNodes().end(); I != E; ++I) {
846 const DSNodeHandle &Ret = I->second;
847 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
848 OldReturnNodes.insert(std::make_pair(I->first,
849 DSNodeHandle(MappedRet.getNode(),
850 MappedRet.getOffset()+Ret.getOffset())));
851 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000852}
853
Chris Lattner076c1f92002-11-07 06:31:54 +0000854/// mergeInGraph - The method is used for merging graphs together. If the
855/// argument graph is not *this, it makes a clone of the specified graph, then
856/// merges the nodes specified in the call site with the formal arguments in the
857/// graph.
858///
Chris Lattner9f930552003-06-30 05:27:18 +0000859void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
860 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000861 ScalarMapTy OldValMap, *ScalarMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000862 DSNodeHandle RetVal;
Chris Lattner076c1f92002-11-07 06:31:54 +0000863
864 // If this is not a recursive call, clone the graph into this graph...
865 if (&Graph != this) {
866 // Clone the callee's graph into the current graph, keeping
867 // track of where scalars in the old graph _used_ to point,
868 // and of the new nodes matching nodes of the old graph.
Chris Lattner5a540632003-06-30 03:15:25 +0000869 NodeMapTy OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000870
871 // The clone call may invalidate any of the vectors in the data
872 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner5a540632003-06-30 03:15:25 +0000873 ReturnNodesTy OldRetNodes;
874 cloneInto(Graph, OldValMap, OldRetNodes, OldNodeMap, CloneFlags);
Chris Lattner58f98d02003-07-02 04:38:49 +0000875
876 // We need to map the arguments for the function to the cloned nodes old
877 // argument values. Do this now.
Chris Lattner5a540632003-06-30 03:15:25 +0000878 RetVal = OldRetNodes[&F];
Chris Lattner076c1f92002-11-07 06:31:54 +0000879 ScalarMap = &OldValMap;
880 } else {
Chris Lattner5a540632003-06-30 03:15:25 +0000881 RetVal = getReturnNodeFor(F);
Chris Lattner076c1f92002-11-07 06:31:54 +0000882 ScalarMap = &getScalarMap();
883 }
884
885 // Merge the return value with the return value of the context...
886 RetVal.mergeWith(CS.getRetVal());
887
888 // Resolve all of the function arguments...
Chris Lattner076c1f92002-11-07 06:31:54 +0000889 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000890
Chris Lattner076c1f92002-11-07 06:31:54 +0000891 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
892 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +0000893 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +0000894 ++AI;
895#ifndef NDEBUG
896 if (AI == F.aend())
897 std::cerr << "Bad call to Function: " << F.getName() << "\n";
898#endif
Chris Lattner076c1f92002-11-07 06:31:54 +0000899 }
Chris Lattner5d274582003-02-06 00:15:08 +0000900 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +0000901
902 // Add the link from the argument scalar to the provided value
Chris Lattner72d29a42003-02-11 23:11:51 +0000903 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
Chris Lattner076c1f92002-11-07 06:31:54 +0000904 DSNodeHandle &NH = (*ScalarMap)[AI];
905 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
906 NH.mergeWith(CS.getPtrArg(i));
907 }
908}
909
Chris Lattner58f98d02003-07-02 04:38:49 +0000910/// getCallSiteForArguments - Get the arguments and return value bindings for
911/// the specified function in the current graph.
912///
913DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
914 std::vector<DSNodeHandle> Args;
915
916 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
917 if (isPointerType(I->getType()))
918 Args.push_back(getScalarMap().find(I)->second);
919
920 return DSCallSite(*(CallInst*)0, getReturnNodeFor(F), &F, Args);
921}
922
923
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000924
Chris Lattner0d9bab82002-07-18 00:12:30 +0000925// markIncompleteNodes - Mark the specified node as having contents that are not
926// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +0000927// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +0000928// must recursively traverse the data structure graph, marking all reachable
929// nodes as incomplete.
930//
931static void markIncompleteNode(DSNode *N) {
932 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +0000933 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000934
935 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000936 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +0000937
938 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000939 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
940 if (DSNode *DSN = N->getLink(i).getNode())
941 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000942}
943
Chris Lattnere71ffc22002-11-11 03:36:55 +0000944static void markIncomplete(DSCallSite &Call) {
945 // Then the return value is certainly incomplete!
946 markIncompleteNode(Call.getRetVal().getNode());
947
948 // All objects pointed to by function arguments are incomplete!
949 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
950 markIncompleteNode(Call.getPtrArg(i).getNode());
951}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000952
953// markIncompleteNodes - Traverse the graph, identifying nodes that may be
954// modified by other functions that have not been resolved yet. This marks
955// nodes that are reachable through three sources of "unknownness":
956//
957// Global Variables, Function Calls, and Incoming Arguments
958//
959// For any node that may have unknown components (because something outside the
960// scope of current analysis may have modified it), the 'Incomplete' flag is
961// added to the NodeType.
962//
Chris Lattner394471f2003-01-23 22:05:33 +0000963void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000964 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +0000965 if (Flags & DSGraph::MarkFormalArgs)
966 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
967 FI != E; ++FI) {
968 Function &F = *FI->first;
969 if (F.getName() != "main")
970 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
971 if (isPointerType(I->getType()) &&
972 ScalarMap.find(I) != ScalarMap.end())
973 markIncompleteNode(ScalarMap[I].getNode());
974 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000975
976 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +0000977 if (!shouldPrintAuxCalls())
978 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
979 markIncomplete(FunctionCalls[i]);
980 else
981 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
982 markIncomplete(AuxFunctionCalls[i]);
983
Chris Lattner0d9bab82002-07-18 00:12:30 +0000984
Chris Lattner93d7a212003-02-09 18:41:49 +0000985 // Mark all global nodes as incomplete...
986 if ((Flags & DSGraph::IgnoreGlobals) == 0)
987 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +0000988 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +0000989 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000990}
991
Chris Lattneraa8146f2002-11-10 06:59:55 +0000992static inline void killIfUselessEdge(DSNodeHandle &Edge) {
993 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +0000994 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +0000995 // No interesting info?
996 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +0000997 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +0000998 Edge.setNode(0); // Kill the edge!
999}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001000
Chris Lattneraa8146f2002-11-10 06:59:55 +00001001static inline bool nodeContainsExternalFunction(const DSNode *N) {
1002 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1003 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1004 if (Globals[i]->isExternal())
1005 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001006 return false;
1007}
1008
Chris Lattner5a540632003-06-30 03:15:25 +00001009static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Chris Lattner18f07a12003-07-01 16:28:11 +00001010
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001011 // Remove trivially identical function calls
1012 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001013 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1014
1015 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001016 DSNode *LastCalleeNode = 0;
1017 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001018 unsigned NumDuplicateCalls = 0;
1019 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001020 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001021 DSCallSite &CS = Calls[i];
1022
Chris Lattnere4258442002-11-11 21:35:38 +00001023 // If the Callee is a useless edge, this must be an unreachable call site,
1024 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001025 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001026 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +00001027 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +00001028 CS.swap(Calls.back());
1029 Calls.pop_back();
1030 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001031 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001032 // If the return value or any arguments point to a void node with no
1033 // information at all in it, and the call node is the only node to point
1034 // to it, remove the edge to the node (killing the node).
1035 //
1036 killIfUselessEdge(CS.getRetVal());
1037 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1038 killIfUselessEdge(CS.getPtrArg(a));
1039
1040 // If this call site calls the same function as the last call site, and if
1041 // the function pointer contains an external function, this node will
1042 // never be resolved. Merge the arguments of the call node because no
1043 // information will be lost.
1044 //
Chris Lattner923fc052003-02-05 21:59:58 +00001045 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1046 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001047 ++NumDuplicateCalls;
1048 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001049 if (LastCalleeNode)
1050 LastCalleeContainsExternalFunction =
1051 nodeContainsExternalFunction(LastCalleeNode);
1052 else
1053 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001054 }
1055
Chris Lattner58f98d02003-07-02 04:38:49 +00001056#if 1
Chris Lattnere4258442002-11-11 21:35:38 +00001057 if (LastCalleeContainsExternalFunction ||
1058 // This should be more than enough context sensitivity!
1059 // FIXME: Evaluate how many times this is tripped!
1060 NumDuplicateCalls > 20) {
1061 DSCallSite &OCS = Calls[i-1];
1062 OCS.mergeWith(CS);
1063
1064 // The node will now be eliminated as a duplicate!
1065 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1066 CS = OCS;
1067 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1068 OCS = CS;
1069 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001070#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001071 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001072 if (CS.isDirectCall()) {
1073 LastCalleeFunc = CS.getCalleeFunc();
1074 LastCalleeNode = 0;
1075 } else {
1076 LastCalleeNode = CS.getCalleeNode();
1077 LastCalleeFunc = 0;
1078 }
Chris Lattnere4258442002-11-11 21:35:38 +00001079 NumDuplicateCalls = 0;
1080 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001081 }
1082 }
1083
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001084 Calls.erase(std::unique(Calls.begin(), Calls.end()),
1085 Calls.end());
1086
Chris Lattner33312f72002-11-08 01:21:07 +00001087 // Track the number of call nodes merged away...
1088 NumCallNodesMerged += NumFns-Calls.size();
1089
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001090 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001091 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001092}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001093
Chris Lattneraa8146f2002-11-10 06:59:55 +00001094
Chris Lattnere2219762002-07-18 18:22:40 +00001095// removeTriviallyDeadNodes - After the graph has been constructed, this method
1096// removes all unreachable nodes that are created because they got merged with
1097// other nodes in the graph. These nodes will all be trivially unreachable, so
1098// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001099//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001100void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner5a540632003-06-30 03:15:25 +00001101 removeIdenticalCalls(FunctionCalls);
1102 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001103
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001104 for (unsigned i = 0; i != Nodes.size(); ++i) {
1105 DSNode *Node = Nodes[i];
Chris Lattner72d50a02003-06-28 21:58:28 +00001106 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001107 // This is a useless node if it has no mod/ref info (checked above),
1108 // outgoing edges (which it cannot, as it is not modified in this
1109 // context), and it has no incoming edges. If it is a global node it may
1110 // have all of these properties and still have incoming edges, due to the
1111 // scalar map, so we check those now.
1112 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001113 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001114 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001115
1116 // Loop through and make sure all of the globals are referring directly
1117 // to the node...
1118 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1119 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1120 assert(N == Node && "ScalarMap doesn't match globals list!");
1121 }
1122
Chris Lattnerbd92b732003-06-19 21:15:11 +00001123 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001124 if (Node->getNumReferrers() == Globals.size()) {
1125 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1126 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001127 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001128 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001129 }
1130 }
1131
Chris Lattnerbd92b732003-06-19 21:15:11 +00001132 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001133 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001134 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001135 Nodes[i--] = Nodes.back();
1136 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001137 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001138 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001139}
1140
1141
Chris Lattner5c7380e2003-01-29 21:10:20 +00001142/// markReachableNodes - This method recursively traverses the specified
1143/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1144/// to the set, which allows it to only traverse visited nodes once.
1145///
Chris Lattner41c04f72003-02-01 04:52:08 +00001146void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001147 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001148 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner41c04f72003-02-01 04:52:08 +00001149 if (ReachableNodes.count(this)) return; // Already marked reachable
1150 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +00001151
Chris Lattner5c7380e2003-01-29 21:10:20 +00001152 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1153 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1154}
1155
Chris Lattner41c04f72003-02-01 04:52:08 +00001156void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001157 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001158 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001159
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001160 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1161 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001162}
1163
Chris Lattnera1220af2003-02-01 06:17:02 +00001164// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1165// looking for a node that is marked alive. If an alive node is found, return
1166// true, otherwise return false. If an alive node is reachable, this node is
1167// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001168//
Chris Lattnera1220af2003-02-01 06:17:02 +00001169static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001170 hash_set<DSNode*> &Visited,
1171 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001172 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001173 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001174
Chris Lattner85cfe012003-07-03 02:03:53 +00001175 // If this is a global node, it will end up in the globals graph anyway, so we
1176 // don't need to worry about it.
1177 if (IgnoreGlobals && N->isGlobalNode()) return false;
1178
Chris Lattneraa8146f2002-11-10 06:59:55 +00001179 // If we know that this node is alive, return so!
1180 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001181
Chris Lattneraa8146f2002-11-10 06:59:55 +00001182 // Otherwise, we don't think the node is alive yet, check for infinite
1183 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001184 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001185 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001186
Chris Lattner08db7192002-11-06 06:20:27 +00001187 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001188 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1189 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001190 N->markReachableNodes(Alive);
1191 return true;
1192 }
1193 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001194}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001195
Chris Lattnera1220af2003-02-01 06:17:02 +00001196// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1197// alive nodes.
1198//
Chris Lattner41c04f72003-02-01 04:52:08 +00001199static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001200 hash_set<DSNode*> &Visited,
1201 bool IgnoreGlobals) {
1202 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1203 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001204 return true;
1205 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001206 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001207 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001208 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001209 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1210 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001211 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001212 return false;
1213}
1214
Chris Lattnere2219762002-07-18 18:22:40 +00001215// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1216// subgraphs that are unreachable. This often occurs because the data
1217// structure doesn't "escape" into it's caller, and thus should be eliminated
1218// from the caller's graph entirely. This is only appropriate to use when
1219// inlining graphs.
1220//
Chris Lattner394471f2003-01-23 22:05:33 +00001221void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner85cfe012003-07-03 02:03:53 +00001222 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1223
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001224 // Reduce the amount of work we have to do... remove dummy nodes left over by
1225 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001226 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001227
Chris Lattnere2219762002-07-18 18:22:40 +00001228 // FIXME: Merge nontrivially identical call nodes...
1229
1230 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001231 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001232 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001233
Chris Lattneraa8146f2002-11-10 06:59:55 +00001234 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner8d327672003-06-30 03:36:09 +00001235 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001236 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001237 assert(I->second.getNode() && "Null global node?");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001238 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1239 ++I;
1240 } else {
1241 // Check to see if this is a worthless node generated for non-pointer
1242 // values, such as integers. Consider an addition of long types: A+B.
1243 // Assuming we can track all uses of the value in this context, and it is
1244 // NOT used as a pointer, we can delete the node. We will be able to
1245 // detect this situation if the node pointed to ONLY has Unknown bit set
1246 // in the node. In this case, the node is not incomplete, does not point
1247 // to any other nodes (no mod/ref bits set), and is therefore
1248 // uninteresting for data structure analysis. If we run across one of
1249 // these, prune the scalar pointing to it.
1250 //
1251 DSNode *N = I->second.getNode();
Chris Lattner85cfe012003-07-03 02:03:53 +00001252 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first)){
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001253 ScalarMap.erase(I++);
1254 } else {
1255 I->second.getNode()->markReachableNodes(Alive);
1256 ++I;
1257 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001258 }
Chris Lattnere2219762002-07-18 18:22:40 +00001259
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001260 // The return value is alive as well...
Chris Lattner5a540632003-06-30 03:15:25 +00001261 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1262 I != E; ++I)
1263 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001264
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001265 // Mark any nodes reachable by primary calls as alive...
1266 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1267 FunctionCalls[i].markReachableNodes(Alive);
1268
1269 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001270 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001271 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1272 do {
1273 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001274 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001275 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001276 // unreachable globals in the list.
1277 //
1278 Iterate = false;
1279 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001280 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1281 Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001282 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1283 GlobalNodes.pop_back(); // Erase efficiently
1284 Iterate = true;
1285 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001286
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001287 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1288 if (!AuxFCallsAlive[i] &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001289 CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1290 Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001291 AuxFunctionCalls[i].markReachableNodes(Alive);
1292 AuxFCallsAlive[i] = true;
1293 Iterate = true;
1294 }
1295 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001296
1297 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001298 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001299 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1300 if (AuxFCallsAlive[i])
1301 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001302 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001303 assert(GlobalsGraph && "No globals graph available??");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001304 // Move the unreachable call nodes to the globals graph...
1305 GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1306 AuxFunctionCalls.begin()+CurIdx,
1307 AuxFunctionCalls.end());
1308 }
1309 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001310 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1311 AuxFunctionCalls.end());
1312
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001313 // At this point, any nodes which are visited, but not alive, are nodes which
1314 // should be moved to the globals graph. Loop over all nodes, eliminating
1315 // completely unreachable nodes, and moving visited nodes to the globals graph
1316 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001317 std::vector<DSNode*> DeadNodes;
1318 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001319 for (unsigned i = 0; i != Nodes.size(); ++i)
1320 if (!Alive.count(Nodes[i])) {
1321 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001322 Nodes[i--] = Nodes.back(); // move node to end of vector
1323 Nodes.pop_back(); // Erase node from alive list.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001324 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && // Not in TD pass
1325 Visited.count(N)) { // Visited but not alive?
1326 GlobalsGraph->Nodes.push_back(N); // Move node to globals graph
Chris Lattner72d29a42003-02-11 23:11:51 +00001327 N->setParentGraph(GlobalsGraph);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001328 } else { // Otherwise, delete the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001329 assert((!N->isGlobalNode() ||
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001330 (Flags & DSGraph::RemoveUnreachableGlobals))
1331 && "Killing a global?");
Chris Lattner72d29a42003-02-11 23:11:51 +00001332 //std::cerr << "[" << i+1 << "/" << DeadNodes.size()
1333 // << "] Node is dead: "; N->dump();
1334 DeadNodes.push_back(N);
1335 N->dropAllReferences();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001336 }
Chris Lattner72d29a42003-02-11 23:11:51 +00001337 } else {
1338 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001339 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001340
1341 // Now that the nodes have either been deleted or moved to the globals graph,
1342 // loop over the scalarmap, updating the entries for globals...
1343 //
1344 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) { // Not in the TD pass?
1345 // In this array we start the remapping, which can cause merging. Because
1346 // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1347 // must always go through the ScalarMap (which contains DSNodeHandles [which
1348 // cannot be invalidated by merging]).
1349 //
1350 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1351 Value *G = GlobalNodes[i].first;
Chris Lattner8d327672003-06-30 03:36:09 +00001352 ScalarMapTy::iterator I = ScalarMap.find(G);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001353 assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1354 assert(I->second.getNode() && "Global not pointing to anything?");
1355 assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1356 GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1357 assert(GlobalsGraph->ScalarMap[G].getNode() &&
1358 "Global not pointing to anything?");
1359 ScalarMap.erase(I);
1360 }
1361
1362 // Merging leaves behind silly nodes, we remove them to avoid polluting the
1363 // globals graph.
Chris Lattner72d29a42003-02-11 23:11:51 +00001364 if (!GlobalNodes.empty())
1365 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001366 } else {
1367 // If we are in the top-down pass, remove all unreachable globals from the
1368 // ScalarMap...
1369 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001370 if (!Alive.count(GlobalNodes[i].second))
1371 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001372 }
1373
Chris Lattner72d29a42003-02-11 23:11:51 +00001374 // Loop over all of the dead nodes now, deleting them since their referrer
1375 // count is zero.
1376 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1377 delete DeadNodes[i];
1378
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001379 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001380}
1381
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001382void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001383 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1384 Nodes[i]->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001385
Chris Lattner8d327672003-06-30 03:36:09 +00001386 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001387 E = ScalarMap.end(); I != E; ++I) {
1388 assert(I->second.getNode() && "Null node in scalarmap!");
1389 AssertNodeInGraph(I->second.getNode());
1390 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001391 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001392 "Global points to node, but node isn't global?");
1393 AssertNodeContainsGlobal(I->second.getNode(), GV);
1394 }
1395 }
1396 AssertCallNodesInGraph();
1397 AssertAuxCallNodesInGraph();
1398}