blob: efcae9826ef72efbc27a92889f1e30e577994d66 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00009//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerfccd06f2002-10-01 22:33:50 +000014#include "llvm/Analysis/DSGraph.h"
15#include "llvm/Function.h"
Vikram S. Adve26b98262002-10-20 21:41:02 +000016#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000017#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000018#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000019#include "llvm/Assembly/Writer.h"
Chris Lattner6806f562003-08-01 22:15:03 +000020#include "Support/Debug.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000021#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000022#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000023#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000024#include <algorithm>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000025
Chris Lattner08db7192002-11-06 06:20:27 +000026namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000027 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
28 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000029};
30
Chris Lattnerb1060432002-11-07 05:20:53 +000031namespace DS { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000032 extern TargetData TD;
33}
Chris Lattnerb1060432002-11-07 05:20:53 +000034using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000035
Chris Lattner731b2d72003-02-13 19:09:00 +000036DSNode *DSNodeHandle::HandleForwarding() const {
37 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
38
39 // Handle node forwarding here!
40 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
41 Offset += N->ForwardNH.getOffset();
42
43 if (--N->NumReferrers == 0) {
44 // Removing the last referrer to the node, sever the forwarding link
45 N->stopForwarding();
46 }
47
48 N = Next;
49 N->NumReferrers++;
50 if (N->Size <= Offset) {
51 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
52 Offset = 0;
53 }
54 return N;
55}
56
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000057//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000058// DSNode Implementation
59//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000060
Chris Lattnerbd92b732003-06-19 21:15:11 +000061DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000062 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000063 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000064 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000065 G->getNodes().push_back(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000066}
67
Chris Lattner0d9bab82002-07-18 00:12:30 +000068// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner72d29a42003-02-11 23:11:51 +000069DSNode::DSNode(const DSNode &N, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000070 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner58f98d02003-07-02 04:38:49 +000071 Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner72d29a42003-02-11 23:11:51 +000072 G->getNodes().push_back(this);
Chris Lattner0d9bab82002-07-18 00:12:30 +000073}
74
Chris Lattner72d29a42003-02-11 23:11:51 +000075void DSNode::assertOK() const {
76 assert((Ty != Type::VoidTy ||
77 Ty == Type::VoidTy && (Size == 0 ||
78 (NodeType & DSNode::Array))) &&
79 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +000080
81 assert(ParentGraph && "Node has no parent?");
82 const DSGraph::ScalarMapTy &SM = ParentGraph->getScalarMap();
83 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
84 assert(SM.find(Globals[i]) != SM.end());
85 assert(SM.find(Globals[i])->second.getNode() == this);
86 }
Chris Lattner72d29a42003-02-11 23:11:51 +000087}
88
89/// forwardNode - Mark this node as being obsolete, and all references to it
90/// should be forwarded to the specified node and offset.
91///
92void DSNode::forwardNode(DSNode *To, unsigned Offset) {
93 assert(this != To && "Cannot forward a node to itself!");
94 assert(ForwardNH.isNull() && "Already forwarding from this node!");
95 if (To->Size <= 1) Offset = 0;
96 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
97 "Forwarded offset is wrong!");
98 ForwardNH.setNode(To);
99 ForwardNH.setOffset(Offset);
100 NodeType = DEAD;
101 Size = 0;
102 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000103}
104
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000105// addGlobal - Add an entry for a global value to the Globals list. This also
106// marks the node with the 'G' flag if it does not already have it.
107//
108void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000109 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000110 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000111 std::lower_bound(Globals.begin(), Globals.end(), GV);
112
113 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000114 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000115 Globals.insert(I, GV);
116 NodeType |= GlobalNode;
117 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000118}
119
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000120/// foldNodeCompletely - If we determine that this node has some funny
121/// behavior happening to it that we cannot represent, we fold it down to a
122/// single, completely pessimistic, node. This node is represented as a
123/// single byte with a single TypeEntry of "void".
124///
125void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000126 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000127
Chris Lattner08db7192002-11-06 06:20:27 +0000128 ++NumFolds;
129
Chris Lattner72d29a42003-02-11 23:11:51 +0000130 // Create the node we are going to forward to...
Chris Lattner70793862003-07-02 23:57:05 +0000131 DSNode *DestNode = new DSNode(0, ParentGraph);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000132 DestNode->NodeType = NodeType|DSNode::Array;
Chris Lattner72d29a42003-02-11 23:11:51 +0000133 DestNode->Ty = Type::VoidTy;
134 DestNode->Size = 1;
135 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000136
Chris Lattner72d29a42003-02-11 23:11:51 +0000137 // Start forwarding to the destination node...
138 forwardNode(DestNode, 0);
139
140 if (Links.size()) {
141 DestNode->Links.push_back(Links[0]);
142 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000143
Chris Lattner72d29a42003-02-11 23:11:51 +0000144 // If we have links, merge all of our outgoing links together...
145 for (unsigned i = Links.size()-1; i != 0; --i)
146 NH.getNode()->Links[0].mergeWith(Links[i]);
147 Links.clear();
148 } else {
149 DestNode->Links.resize(1);
150 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000151}
Chris Lattner076c1f92002-11-07 06:31:54 +0000152
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000153/// isNodeCompletelyFolded - Return true if this node has been completely
154/// folded down to something that can never be expanded, effectively losing
155/// all of the field sensitivity that may be present in the node.
156///
157bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000158 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000159}
160
161
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000162namespace {
163 /// TypeElementWalker Class - Used for implementation of physical subtyping...
164 ///
165 class TypeElementWalker {
166 struct StackState {
167 const Type *Ty;
168 unsigned Offset;
169 unsigned Idx;
170 StackState(const Type *T, unsigned Off = 0)
171 : Ty(T), Offset(Off), Idx(0) {}
172 };
173
174 std::vector<StackState> Stack;
175 public:
176 TypeElementWalker(const Type *T) {
177 Stack.push_back(T);
178 StepToLeaf();
179 }
180
181 bool isDone() const { return Stack.empty(); }
182 const Type *getCurrentType() const { return Stack.back().Ty; }
183 unsigned getCurrentOffset() const { return Stack.back().Offset; }
184
185 void StepToNextType() {
186 PopStackAndAdvance();
187 StepToLeaf();
188 }
189
190 private:
191 /// PopStackAndAdvance - Pop the current element off of the stack and
192 /// advance the underlying element to the next contained member.
193 void PopStackAndAdvance() {
194 assert(!Stack.empty() && "Cannot pop an empty stack!");
195 Stack.pop_back();
196 while (!Stack.empty()) {
197 StackState &SS = Stack.back();
198 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
199 ++SS.Idx;
200 if (SS.Idx != ST->getElementTypes().size()) {
201 const StructLayout *SL = TD.getStructLayout(ST);
202 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
203 return;
204 }
205 Stack.pop_back(); // At the end of the structure
206 } else {
207 const ArrayType *AT = cast<ArrayType>(SS.Ty);
208 ++SS.Idx;
209 if (SS.Idx != AT->getNumElements()) {
210 SS.Offset += TD.getTypeSize(AT->getElementType());
211 return;
212 }
213 Stack.pop_back(); // At the end of the array
214 }
215 }
216 }
217
218 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
219 /// on the type stack.
220 void StepToLeaf() {
221 if (Stack.empty()) return;
222 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
223 StackState &SS = Stack.back();
224 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
225 if (ST->getElementTypes().empty()) {
226 assert(SS.Idx == 0);
227 PopStackAndAdvance();
228 } else {
229 // Step into the structure...
230 assert(SS.Idx < ST->getElementTypes().size());
231 const StructLayout *SL = TD.getStructLayout(ST);
232 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
233 SS.Offset+SL->MemberOffsets[SS.Idx]));
234 }
235 } else {
236 const ArrayType *AT = cast<ArrayType>(SS.Ty);
237 if (AT->getNumElements() == 0) {
238 assert(SS.Idx == 0);
239 PopStackAndAdvance();
240 } else {
241 // Step into the array...
242 assert(SS.Idx < AT->getNumElements());
243 Stack.push_back(StackState(AT->getElementType(),
244 SS.Offset+SS.Idx*
245 TD.getTypeSize(AT->getElementType())));
246 }
247 }
248 }
249 }
250 };
251}
252
253/// ElementTypesAreCompatible - Check to see if the specified types are
254/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000255/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
256/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000257///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000258static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
259 bool AllowLargerT1) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000260 TypeElementWalker T1W(T1), T2W(T2);
261
262 while (!T1W.isDone() && !T2W.isDone()) {
263 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
264 return false;
265
266 const Type *T1 = T1W.getCurrentType();
267 const Type *T2 = T2W.getCurrentType();
268 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
269 return false;
270
271 T1W.StepToNextType();
272 T2W.StepToNextType();
273 }
274
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000275 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000276}
277
278
Chris Lattner08db7192002-11-06 06:20:27 +0000279/// mergeTypeInfo - This method merges the specified type into the current node
280/// at the specified offset. This may update the current node's type record if
281/// this gives more information to the node, it may do nothing to the node if
282/// this information is already known, or it may merge the node completely (and
283/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000284///
Chris Lattner08db7192002-11-06 06:20:27 +0000285/// This method returns true if the node is completely folded, otherwise false.
286///
Chris Lattner088b6392003-03-03 17:13:31 +0000287bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
288 bool FoldIfIncompatible) {
Chris Lattner08db7192002-11-06 06:20:27 +0000289 // Check to make sure the Size member is up-to-date. Size can be one of the
290 // following:
291 // Size = 0, Ty = Void: Nothing is known about this node.
292 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
293 // Size = 1, Ty = Void, Array = 1: The node is collapsed
294 // Otherwise, sizeof(Ty) = Size
295 //
Chris Lattner18552922002-11-18 21:44:46 +0000296 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
297 (Size == 0 && !Ty->isSized() && !isArray()) ||
298 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
299 (Size == 0 && !Ty->isSized() && !isArray()) ||
300 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000301 "Size member of DSNode doesn't match the type structure!");
302 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000303
Chris Lattner18552922002-11-18 21:44:46 +0000304 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000305 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000306
Chris Lattner08db7192002-11-06 06:20:27 +0000307 // Return true immediately if the node is completely folded.
308 if (isNodeCompletelyFolded()) return true;
309
Chris Lattner23f83dc2002-11-08 22:49:57 +0000310 // If this is an array type, eliminate the outside arrays because they won't
311 // be used anyway. This greatly reduces the size of large static arrays used
312 // as global variables, for example.
313 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000314 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000315 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
316 // FIXME: we might want to keep small arrays, but must be careful about
317 // things like: [2 x [10000 x int*]]
318 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000319 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000320 }
321
Chris Lattner08db7192002-11-06 06:20:27 +0000322 // Figure out how big the new type we're merging in is...
323 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
324
325 // Otherwise check to see if we can fold this type into the current node. If
326 // we can't, we fold the node completely, if we can, we potentially update our
327 // internal state.
328 //
Chris Lattner18552922002-11-18 21:44:46 +0000329 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000330 // If this is the first type that this node has seen, just accept it without
331 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000332 assert(Offset == 0 && !isArray() &&
333 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000334 Ty = NewTy;
335 NodeType &= ~Array;
336 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000337 Size = NewTySize;
338
339 // Calculate the number of outgoing links from this node.
340 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
341 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000342 }
Chris Lattner08db7192002-11-06 06:20:27 +0000343
344 // Handle node expansion case here...
345 if (Offset+NewTySize > Size) {
346 // It is illegal to grow this node if we have treated it as an array of
347 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000348 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000349 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000350 return true;
351 }
352
353 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000354 std::cerr << "UNIMP: Trying to merge a growth type into "
355 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000356 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000357 return true;
358 }
359
360 // Okay, the situation is nice and simple, we are trying to merge a type in
361 // at offset 0 that is bigger than our current type. Implement this by
362 // switching to the new type and then merge in the smaller one, which should
363 // hit the other code path here. If the other code path decides it's not
364 // ok, it will collapse the node as appropriate.
365 //
Chris Lattner18552922002-11-18 21:44:46 +0000366 const Type *OldTy = Ty;
367 Ty = NewTy;
368 NodeType &= ~Array;
369 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000370 Size = NewTySize;
371
372 // Must grow links to be the appropriate size...
373 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
374
375 // Merge in the old type now... which is guaranteed to be smaller than the
376 // "current" type.
377 return mergeTypeInfo(OldTy, 0);
378 }
379
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000380 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000381 "Cannot merge something into a part of our type that doesn't exist!");
382
Chris Lattner18552922002-11-18 21:44:46 +0000383 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000384 // type that starts at offset Offset.
385 //
386 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000387 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000388 while (O < Offset) {
389 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
390
391 switch (SubType->getPrimitiveID()) {
392 case Type::StructTyID: {
393 const StructType *STy = cast<StructType>(SubType);
394 const StructLayout &SL = *TD.getStructLayout(STy);
395
396 unsigned i = 0, e = SL.MemberOffsets.size();
397 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
398 /* empty */;
399
400 // The offset we are looking for must be in the i'th element...
401 SubType = STy->getElementTypes()[i];
402 O += SL.MemberOffsets[i];
403 break;
404 }
405 case Type::ArrayTyID: {
406 SubType = cast<ArrayType>(SubType)->getElementType();
407 unsigned ElSize = TD.getTypeSize(SubType);
408 unsigned Remainder = (Offset-O) % ElSize;
409 O = Offset-Remainder;
410 break;
411 }
412 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000413 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000414 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000415 }
416 }
417
418 assert(O == Offset && "Could not achieve the correct offset!");
419
420 // If we found our type exactly, early exit
421 if (SubType == NewTy) return false;
422
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000423 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
424
425 // Ok, we are getting desperate now. Check for physical subtyping, where we
426 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000427 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000428 SubTypeSize && SubTypeSize < 256 &&
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000429 ElementTypesAreCompatible(NewTy, SubType, !isArray()))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000430 return false;
431
Chris Lattner08db7192002-11-06 06:20:27 +0000432 // Okay, so we found the leader type at the offset requested. Search the list
433 // of types that starts at this offset. If SubType is currently an array or
434 // structure, the type desired may actually be the first element of the
435 // composite type...
436 //
Chris Lattner18552922002-11-18 21:44:46 +0000437 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000438 while (SubType != NewTy) {
439 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000440 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000441 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000442 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000443 case Type::StructTyID: {
444 const StructType *STy = cast<StructType>(SubType);
445 const StructLayout &SL = *TD.getStructLayout(STy);
446 if (SL.MemberOffsets.size() > 1)
447 NextPadSize = SL.MemberOffsets[1];
448 else
449 NextPadSize = SubTypeSize;
450 NextSubType = STy->getElementTypes()[0];
451 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000452 break;
Chris Lattner18552922002-11-18 21:44:46 +0000453 }
Chris Lattner08db7192002-11-06 06:20:27 +0000454 case Type::ArrayTyID:
455 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000456 NextSubTypeSize = TD.getTypeSize(NextSubType);
457 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000458 break;
459 default: ;
460 // fall out
461 }
462
463 if (NextSubType == 0)
464 break; // In the default case, break out of the loop
465
Chris Lattner18552922002-11-18 21:44:46 +0000466 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000467 break; // Don't allow shrinking to a smaller type than NewTySize
468 SubType = NextSubType;
469 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000470 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000471 }
472
473 // If we found the type exactly, return it...
474 if (SubType == NewTy)
475 return false;
476
477 // Check to see if we have a compatible, but different type...
478 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000479 // Check to see if this type is obviously convertible... int -> uint f.e.
480 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000481 return false;
482
483 // Check to see if we have a pointer & integer mismatch going on here,
484 // loading a pointer as a long, for example.
485 //
486 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
487 NewTy->isInteger() && isa<PointerType>(SubType))
488 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000489 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
490 // We are accessing the field, plus some structure padding. Ignore the
491 // structure padding.
492 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000493 }
494
Chris Lattner58f98d02003-07-02 04:38:49 +0000495 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000496 if (getParentGraph()->getReturnNodes().size())
497 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000498 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
499 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
500 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
501 << "SubType: ";
502 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000503
Chris Lattner088b6392003-03-03 17:13:31 +0000504 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000505 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000506}
507
Chris Lattner08db7192002-11-06 06:20:27 +0000508
509
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000510// addEdgeTo - Add an edge from the current node to the specified node. This
511// can cause merging of nodes in the graph.
512//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000513void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000514 if (NH.getNode() == 0) return; // Nothing to do
515
Chris Lattner08db7192002-11-06 06:20:27 +0000516 DSNodeHandle &ExistingEdge = getLink(Offset);
517 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000518 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000519 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000520 } else { // No merging to perform...
521 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000522 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000523}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000524
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000525
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000526// MergeSortedVectors - Efficiently merge a vector into another vector where
527// duplicates are not allowed and both are sorted. This assumes that 'T's are
528// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000529//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000530static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
531 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000532 // By far, the most common cases will be the simple ones. In these cases,
533 // avoid having to allocate a temporary vector...
534 //
535 if (Src.empty()) { // Nothing to merge in...
536 return;
537 } else if (Dest.empty()) { // Just copy the result in...
538 Dest = Src;
539 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000540 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000541 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000542 std::lower_bound(Dest.begin(), Dest.end(), V);
543 if (I == Dest.end() || *I != Src[0]) // If not already contained...
544 Dest.insert(I, Src[0]);
545 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000546 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000547 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000548 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000549 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
550 if (I == Dest.end() || *I != Tmp) // If not already contained...
551 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000552
553 } else {
554 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000555 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000556
557 // Make space for all of the type entries now...
558 Dest.resize(Dest.size()+Src.size());
559
560 // Merge the two sorted ranges together... into Dest.
561 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
562
563 // Now erase any duplicate entries that may have accumulated into the
564 // vectors (because they were in both of the input sets)
565 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
566 }
567}
568
569
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000570// MergeNodes() - Helper function for DSNode::mergeWith().
571// This function does the hard work of merging two nodes, CurNodeH
572// and NH after filtering out trivial cases and making sure that
573// CurNodeH.offset >= NH.offset.
574//
575// ***WARNING***
576// Since merging may cause either node to go away, we must always
577// use the node-handles to refer to the nodes. These node handles are
578// automatically updated during merging, so will always provide access
579// to the correct node after a merge.
580//
581void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
582 assert(CurNodeH.getOffset() >= NH.getOffset() &&
583 "This should have been enforced in the caller.");
584
585 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
586 // respect to NH.Offset) is now zero. NOffset is the distance from the base
587 // of our object that N starts from.
588 //
589 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
590 unsigned NSize = NH.getNode()->getSize();
591
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000592 // If the two nodes are of different size, and the smaller node has the array
593 // bit set, collapse!
594 if (NSize != CurNodeH.getNode()->getSize()) {
595 if (NSize < CurNodeH.getNode()->getSize()) {
596 if (NH.getNode()->isArray())
597 NH.getNode()->foldNodeCompletely();
598 } else if (CurNodeH.getNode()->isArray()) {
599 NH.getNode()->foldNodeCompletely();
600 }
601 }
602
603 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000604 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000605 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000606 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000607
608 // If we are merging a node with a completely folded node, then both nodes are
609 // now completely folded.
610 //
611 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
612 if (!NH.getNode()->isNodeCompletelyFolded()) {
613 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000614 assert(NH.getNode() && NH.getOffset() == 0 &&
615 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000616 NOffset = NH.getOffset();
617 NSize = NH.getNode()->getSize();
618 assert(NOffset == 0 && NSize == 1);
619 }
620 } else if (NH.getNode()->isNodeCompletelyFolded()) {
621 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000622 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
623 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000624 NOffset = NH.getOffset();
625 NSize = NH.getNode()->getSize();
626 assert(NOffset == 0 && NSize == 1);
627 }
628
Chris Lattner72d29a42003-02-11 23:11:51 +0000629 DSNode *N = NH.getNode();
630 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000631 assert(!CurNodeH.getNode()->isDeadNode());
632
633 // Merge the NodeType information...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000634 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000635
Chris Lattner72d29a42003-02-11 23:11:51 +0000636 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000637 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000638 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000639
Chris Lattner72d29a42003-02-11 23:11:51 +0000640 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
641 //
642 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
643 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000644 if (Link.getNode()) {
645 // Compute the offset into the current node at which to
646 // merge this link. In the common case, this is a linear
647 // relation to the offset in the original node (with
648 // wrapping), but if the current node gets collapsed due to
649 // recursive merging, we must make sure to merge in all remaining
650 // links at offset zero.
651 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000652 DSNode *CN = CurNodeH.getNode();
653 if (CN->Size != 1)
654 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
655 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000656 }
657 }
658
659 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000660 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000661
662 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000663 if (!N->Globals.empty()) {
664 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000665
666 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000667 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000668 }
669}
670
671
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000672// mergeWith - Merge this node and the specified node, moving all links to and
673// from the argument node into the current node, deleting the node argument.
674// Offset indicates what offset the specified node is to be merged into the
675// current node.
676//
677// The specified node may be a null pointer (in which case, nothing happens).
678//
679void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
680 DSNode *N = NH.getNode();
681 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000682 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000683
Chris Lattnerbd92b732003-06-19 21:15:11 +0000684 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000685 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
686
Chris Lattner02606632002-11-04 06:48:26 +0000687 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000688 // We cannot merge two pieces of the same node together, collapse the node
689 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000690 DEBUG(std::cerr << "Attempting to merge two chunks of"
691 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000692 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000693 return;
694 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000695
Chris Lattner5190ce82002-11-12 07:20:45 +0000696 // If both nodes are not at offset 0, make sure that we are merging the node
697 // at an later offset into the node with the zero offset.
698 //
699 if (Offset < NH.getOffset()) {
700 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
701 return;
702 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
703 // If the offsets are the same, merge the smaller node into the bigger node
704 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
705 return;
706 }
707
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000708 // Ok, now we can merge the two nodes. Use a static helper that works with
709 // two node handles, since "this" may get merged away at intermediate steps.
710 DSNodeHandle CurNodeH(this, Offset);
711 DSNodeHandle NHCopy(NH);
712 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000713}
714
Chris Lattner9de906c2002-10-20 22:11:44 +0000715//===----------------------------------------------------------------------===//
716// DSCallSite Implementation
717//===----------------------------------------------------------------------===//
718
Vikram S. Adve26b98262002-10-20 21:41:02 +0000719// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000720Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000721 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000722}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000723
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000724
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000725//===----------------------------------------------------------------------===//
726// DSGraph Implementation
727//===----------------------------------------------------------------------===//
728
Chris Lattnera9d65662003-06-30 05:57:30 +0000729/// getFunctionNames - Return a space separated list of the name of the
730/// functions in this graph (if any)
731std::string DSGraph::getFunctionNames() const {
732 switch (getReturnNodes().size()) {
733 case 0: return "Globals graph";
734 case 1: return getReturnNodes().begin()->first->getName();
735 default:
736 std::string Return;
737 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
738 I != getReturnNodes().end(); ++I)
739 Return += I->first->getName() + " ";
740 Return.erase(Return.end()-1, Return.end()); // Remove last space character
741 return Return;
742 }
743}
744
745
Chris Lattner5a540632003-06-30 03:15:25 +0000746DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000747 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000748 NodeMapTy NodeMap;
749 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000750 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattner0d9bab82002-07-18 00:12:30 +0000751}
752
Chris Lattner5a540632003-06-30 03:15:25 +0000753DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
754 : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000755 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000756 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000757 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattnereff0da92002-10-21 15:32:34 +0000758}
759
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000760DSGraph::~DSGraph() {
761 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000762 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000763 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000764 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +0000765 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000766
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000767 // Drop all intra-node references, so that assertions don't fail...
768 std::for_each(Nodes.begin(), Nodes.end(),
769 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000770
771 // Delete all of the nodes themselves...
772 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
773}
774
Chris Lattner0d9bab82002-07-18 00:12:30 +0000775// dump - Allow inspection of graph in a debugger.
776void DSGraph::dump() const { print(std::cerr); }
777
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000778
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000779/// remapLinks - Change all of the Links in the current node according to the
780/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000781///
Chris Lattner8d327672003-06-30 03:36:09 +0000782void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000783 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
784 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
785 Links[i].setNode(H.getNode());
786 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
787 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000788}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000789
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000790
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000791/// cloneReachableNodes - Clone all reachable nodes from *Node into the
792/// current graph. This is a recursive function. The map OldNodeMap is a
793/// map from the original nodes to their clones.
794///
795void DSGraph::cloneReachableNodes(const DSNode* Node,
796 unsigned BitsToClear,
797 NodeMapTy& OldNodeMap,
798 NodeMapTy& CompletedNodeMap) {
799 if (CompletedNodeMap.find(Node) != CompletedNodeMap.end())
800 return;
801
802 DSNodeHandle& NH = OldNodeMap[Node];
803 if (NH.getNode() != NULL)
804 return;
805
806 // else Node has not yet been cloned: clone it and clear the specified bits
807 NH = new DSNode(*Node, this); // enters in OldNodeMap
808 NH.getNode()->maskNodeTypes(~BitsToClear);
809
810 // now recursively clone nodes pointed to by this node
811 for (unsigned i = 0, e = Node->getNumLinks(); i != e; ++i) {
812 const DSNodeHandle &Link = Node->getLink(i << DS::PointerShift);
813 if (const DSNode* nextNode = Link.getNode())
814 cloneReachableNodes(nextNode, BitsToClear, OldNodeMap, CompletedNodeMap);
815 }
816}
817
818void DSGraph::cloneReachableSubgraph(const DSGraph& G,
819 const hash_set<const DSNode*>& RootNodes,
820 NodeMapTy& OldNodeMap,
821 NodeMapTy& CompletedNodeMap,
822 unsigned CloneFlags) {
823 if (RootNodes.empty())
824 return;
825
826 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
827 assert(&G != this && "Cannot clone graph into itself!");
828 assert((*RootNodes.begin())->getParentGraph() == &G &&
829 "Root nodes do not belong to this graph!");
830
831 // Remove alloca or mod/ref bits as specified...
832 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
833 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
834 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
835 BitsToClear |= DSNode::DEAD; // Clear dead flag...
836
837 // Clone all nodes reachable from each root node, using a recursive helper
838 for (hash_set<const DSNode*>::const_iterator I = RootNodes.begin(),
839 E = RootNodes.end(); I != E; ++I)
840 cloneReachableNodes(*I, BitsToClear, OldNodeMap, CompletedNodeMap);
841
842 // Merge the map entries in OldNodeMap and CompletedNodeMap to remap links
843 NodeMapTy MergedMap(OldNodeMap);
844 MergedMap.insert(CompletedNodeMap.begin(), CompletedNodeMap.end());
845
846 // Rewrite the links in the newly created nodes (the nodes in OldNodeMap)
847 // to point into the current graph. MergedMap gives the full mapping.
848 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
849 I->second.getNode()->remapLinks(MergedMap);
850
851 // Now merge cloned global nodes with their copies in the current graph
852 // Just look through OldNodeMap to find such nodes!
853 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
854 if (I->first->isGlobalNode()) {
855 DSNodeHandle &GClone = I->second;
856 assert(GClone.getNode() != NULL && "NULL node in OldNodeMap?");
857 const std::vector<GlobalValue*> &Globals = I->first->getGlobals();
858 for (unsigned gi = 0, ge = Globals.size(); gi != ge; ++gi) {
859 DSNodeHandle &GH = ScalarMap[Globals[gi]];
860 GH.mergeWith(GClone);
861 }
862 }
863}
864
865
866/// updateFromGlobalGraph - This function rematerializes global nodes and
867/// nodes reachable from them from the globals graph into the current graph.
868/// It invokes cloneReachableSubgraph, using the globals in the current graph
869/// as the roots. It also uses the vector InlinedGlobals to avoid cloning and
870/// merging globals that are already up-to-date in the current graph. In
871/// practice, in the TD pass, this is likely to be a large fraction of the
872/// live global nodes in each function (since most live nodes are likely to
873/// have been brought up-to-date in at _some_ caller or callee).
874///
875void DSGraph::updateFromGlobalGraph() {
876
877 // Use a map to keep track of the mapping between nodes in the globals graph
878 // and this graph for up-to-date global nodes, which do not need to be cloned.
879 NodeMapTy CompletedMap;
880
881 // Put the live, non-up-to-date global nodes into a set and the up-to-date
882 // ones in the map above, mapping node in GlobalsGraph to the up-to-date node.
883 hash_set<const DSNode*> GlobalNodeSet;
884 for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
885 E = getScalarMap().end(); I != E; ++I)
886 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
887 DSNode* GNode = I->second.getNode();
888 assert(GNode && "No node for live global in current Graph?");
889 if (const DSNode* GGNode = GlobalsGraph->ScalarMap[GV].getNode())
890 if (InlinedGlobals.count(GV) == 0) // GNode is not up-to-date
891 GlobalNodeSet.insert(GGNode);
892 else { // GNode is up-to-date
893 CompletedMap[GGNode] = I->second;
894 assert(GGNode->getNumLinks() == GNode->getNumLinks() &&
895 "Links dont match in a node that is supposed to be up-to-date?"
896 "\nremapLinks() will not work if the links don't match!");
897 }
898 }
899
900 // Clone the subgraph reachable from the vector of nodes in GlobalNodes
901 // and merge the cloned global nodes with the corresponding ones, if any.
902 NodeMapTy OldNodeMap;
903 cloneReachableSubgraph(*GlobalsGraph, GlobalNodeSet, OldNodeMap,CompletedMap);
904
905 // Merging global nodes leaves behind unused nodes: get rid of them now.
906 OldNodeMap.clear(); // remove references before dead node cleanup
907 CompletedMap.clear(); // remove references before dead node cleanup
908 removeTriviallyDeadNodes();
909}
910
Chris Lattner5a540632003-06-30 03:15:25 +0000911/// cloneInto - Clone the specified DSGraph into the current graph. The
912/// translated ScalarMap for the old function is filled into the OldValMap
913/// member, and the translated ReturnNodes map is returned into ReturnNodes.
914///
915/// The CloneFlags member controls various aspects of the cloning process.
916///
917void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
918 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
919 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000920 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000921 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000922
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000923 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000924
925 // Duplicate all of the nodes, populating the node map...
926 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000927
928 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000929 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
930 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
931 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000932 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000933 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000934 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000935 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000936 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000937 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000938 }
939
Chris Lattner18552922002-11-18 21:44:46 +0000940#ifndef NDEBUG
941 Timer::addPeakMemoryMeasurement();
942#endif
943
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000944 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000945 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000946 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000947
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000948 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +0000949 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000950 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000951 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000952 DSNodeHandle &H = OldValMap[I->first];
953 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
954 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +0000955
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000956 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000957 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
958 ScalarMap[GV].mergeWith(H);
959 InlinedGlobals.insert(GV);
960 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000961 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000962
Chris Lattner679e8e12002-11-08 21:27:12 +0000963 if (!(CloneFlags & DontCloneCallNodes)) {
964 // Copy the function calls list...
965 unsigned FC = FunctionCalls.size(); // FirstCall
966 FunctionCalls.reserve(FC+G.FunctionCalls.size());
967 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
968 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000969 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000970
Chris Lattneracf491f2002-11-08 22:27:09 +0000971 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +0000972 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000973 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000974 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
975 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
976 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
977 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000978
Chris Lattner5a540632003-06-30 03:15:25 +0000979 // Map the return node pointers over...
980 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
981 E = G.getReturnNodes().end(); I != E; ++I) {
982 const DSNodeHandle &Ret = I->second;
983 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
984 OldReturnNodes.insert(std::make_pair(I->first,
985 DSNodeHandle(MappedRet.getNode(),
986 MappedRet.getOffset()+Ret.getOffset())));
987 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000988}
989
Chris Lattner076c1f92002-11-07 06:31:54 +0000990/// mergeInGraph - The method is used for merging graphs together. If the
991/// argument graph is not *this, it makes a clone of the specified graph, then
992/// merges the nodes specified in the call site with the formal arguments in the
993/// graph.
994///
Chris Lattner9f930552003-06-30 05:27:18 +0000995void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
996 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000997 ScalarMapTy OldValMap, *ScalarMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000998 DSNodeHandle RetVal;
Chris Lattner076c1f92002-11-07 06:31:54 +0000999
1000 // If this is not a recursive call, clone the graph into this graph...
1001 if (&Graph != this) {
1002 // Clone the callee's graph into the current graph, keeping
1003 // track of where scalars in the old graph _used_ to point,
1004 // and of the new nodes matching nodes of the old graph.
Chris Lattner5a540632003-06-30 03:15:25 +00001005 NodeMapTy OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +00001006
1007 // The clone call may invalidate any of the vectors in the data
1008 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner5a540632003-06-30 03:15:25 +00001009 ReturnNodesTy OldRetNodes;
1010 cloneInto(Graph, OldValMap, OldRetNodes, OldNodeMap, CloneFlags);
Chris Lattner58f98d02003-07-02 04:38:49 +00001011
1012 // We need to map the arguments for the function to the cloned nodes old
1013 // argument values. Do this now.
Chris Lattner5a540632003-06-30 03:15:25 +00001014 RetVal = OldRetNodes[&F];
Chris Lattner076c1f92002-11-07 06:31:54 +00001015 ScalarMap = &OldValMap;
1016 } else {
Chris Lattner5a540632003-06-30 03:15:25 +00001017 RetVal = getReturnNodeFor(F);
Chris Lattner076c1f92002-11-07 06:31:54 +00001018 ScalarMap = &getScalarMap();
1019 }
1020
1021 // Merge the return value with the return value of the context...
1022 RetVal.mergeWith(CS.getRetVal());
1023
1024 // Resolve all of the function arguments...
Chris Lattner076c1f92002-11-07 06:31:54 +00001025 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +00001026
Chris Lattner076c1f92002-11-07 06:31:54 +00001027 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1028 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +00001029 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +00001030 ++AI;
1031#ifndef NDEBUG
1032 if (AI == F.aend())
1033 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1034#endif
Chris Lattner076c1f92002-11-07 06:31:54 +00001035 }
Chris Lattner5d274582003-02-06 00:15:08 +00001036 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +00001037
1038 // Add the link from the argument scalar to the provided value
Chris Lattner72d29a42003-02-11 23:11:51 +00001039 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
Chris Lattner076c1f92002-11-07 06:31:54 +00001040 DSNodeHandle &NH = (*ScalarMap)[AI];
1041 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1042 NH.mergeWith(CS.getPtrArg(i));
1043 }
1044}
1045
Chris Lattner58f98d02003-07-02 04:38:49 +00001046/// getCallSiteForArguments - Get the arguments and return value bindings for
1047/// the specified function in the current graph.
1048///
1049DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1050 std::vector<DSNodeHandle> Args;
1051
1052 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1053 if (isPointerType(I->getType()))
1054 Args.push_back(getScalarMap().find(I)->second);
1055
Chris Lattner808a7ae2003-09-20 16:34:13 +00001056 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001057}
1058
1059
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001060
Chris Lattner0d9bab82002-07-18 00:12:30 +00001061// markIncompleteNodes - Mark the specified node as having contents that are not
1062// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001063// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001064// must recursively traverse the data structure graph, marking all reachable
1065// nodes as incomplete.
1066//
1067static void markIncompleteNode(DSNode *N) {
1068 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001069 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001070
1071 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001072 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001073
Misha Brukman2f2d0652003-09-11 18:14:24 +00001074 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001075 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1076 if (DSNode *DSN = N->getLink(i).getNode())
1077 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001078}
1079
Chris Lattnere71ffc22002-11-11 03:36:55 +00001080static void markIncomplete(DSCallSite &Call) {
1081 // Then the return value is certainly incomplete!
1082 markIncompleteNode(Call.getRetVal().getNode());
1083
1084 // All objects pointed to by function arguments are incomplete!
1085 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1086 markIncompleteNode(Call.getPtrArg(i).getNode());
1087}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001088
1089// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1090// modified by other functions that have not been resolved yet. This marks
1091// nodes that are reachable through three sources of "unknownness":
1092//
1093// Global Variables, Function Calls, and Incoming Arguments
1094//
1095// For any node that may have unknown components (because something outside the
1096// scope of current analysis may have modified it), the 'Incomplete' flag is
1097// added to the NodeType.
1098//
Chris Lattner394471f2003-01-23 22:05:33 +00001099void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001100 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001101 if (Flags & DSGraph::MarkFormalArgs)
1102 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1103 FI != E; ++FI) {
1104 Function &F = *FI->first;
1105 if (F.getName() != "main")
1106 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1107 if (isPointerType(I->getType()) &&
1108 ScalarMap.find(I) != ScalarMap.end())
1109 markIncompleteNode(ScalarMap[I].getNode());
1110 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001111
1112 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001113 if (!shouldPrintAuxCalls())
1114 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1115 markIncomplete(FunctionCalls[i]);
1116 else
1117 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1118 markIncomplete(AuxFunctionCalls[i]);
1119
Chris Lattner0d9bab82002-07-18 00:12:30 +00001120
Chris Lattner93d7a212003-02-09 18:41:49 +00001121 // Mark all global nodes as incomplete...
1122 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1123 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +00001124 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +00001125 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001126}
1127
Chris Lattneraa8146f2002-11-10 06:59:55 +00001128static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1129 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001130 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001131 // No interesting info?
1132 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001133 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001134 Edge.setNode(0); // Kill the edge!
1135}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001136
Chris Lattneraa8146f2002-11-10 06:59:55 +00001137static inline bool nodeContainsExternalFunction(const DSNode *N) {
1138 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1139 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1140 if (Globals[i]->isExternal())
1141 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001142 return false;
1143}
1144
Chris Lattner5a540632003-06-30 03:15:25 +00001145static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Chris Lattner18f07a12003-07-01 16:28:11 +00001146
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001147 // Remove trivially identical function calls
1148 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001149 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1150
1151 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001152 DSNode *LastCalleeNode = 0;
1153 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001154 unsigned NumDuplicateCalls = 0;
1155 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001156 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001157 DSCallSite &CS = Calls[i];
1158
Chris Lattnere4258442002-11-11 21:35:38 +00001159 // If the Callee is a useless edge, this must be an unreachable call site,
1160 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001161 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001162 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +00001163 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +00001164 CS.swap(Calls.back());
1165 Calls.pop_back();
1166 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001167 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001168 // If the return value or any arguments point to a void node with no
1169 // information at all in it, and the call node is the only node to point
1170 // to it, remove the edge to the node (killing the node).
1171 //
1172 killIfUselessEdge(CS.getRetVal());
1173 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1174 killIfUselessEdge(CS.getPtrArg(a));
1175
1176 // If this call site calls the same function as the last call site, and if
1177 // the function pointer contains an external function, this node will
1178 // never be resolved. Merge the arguments of the call node because no
1179 // information will be lost.
1180 //
Chris Lattner923fc052003-02-05 21:59:58 +00001181 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1182 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001183 ++NumDuplicateCalls;
1184 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001185 if (LastCalleeNode)
1186 LastCalleeContainsExternalFunction =
1187 nodeContainsExternalFunction(LastCalleeNode);
1188 else
1189 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001190 }
1191
Chris Lattner58f98d02003-07-02 04:38:49 +00001192#if 1
Chris Lattnere4258442002-11-11 21:35:38 +00001193 if (LastCalleeContainsExternalFunction ||
1194 // This should be more than enough context sensitivity!
1195 // FIXME: Evaluate how many times this is tripped!
1196 NumDuplicateCalls > 20) {
1197 DSCallSite &OCS = Calls[i-1];
1198 OCS.mergeWith(CS);
1199
1200 // The node will now be eliminated as a duplicate!
1201 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1202 CS = OCS;
1203 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1204 OCS = CS;
1205 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001206#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001207 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001208 if (CS.isDirectCall()) {
1209 LastCalleeFunc = CS.getCalleeFunc();
1210 LastCalleeNode = 0;
1211 } else {
1212 LastCalleeNode = CS.getCalleeNode();
1213 LastCalleeFunc = 0;
1214 }
Chris Lattnere4258442002-11-11 21:35:38 +00001215 NumDuplicateCalls = 0;
1216 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001217 }
1218 }
1219
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001220 Calls.erase(std::unique(Calls.begin(), Calls.end()),
1221 Calls.end());
1222
Chris Lattner33312f72002-11-08 01:21:07 +00001223 // Track the number of call nodes merged away...
1224 NumCallNodesMerged += NumFns-Calls.size();
1225
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001226 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001227 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001228}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001229
Chris Lattneraa8146f2002-11-10 06:59:55 +00001230
Chris Lattnere2219762002-07-18 18:22:40 +00001231// removeTriviallyDeadNodes - After the graph has been constructed, this method
1232// removes all unreachable nodes that are created because they got merged with
1233// other nodes in the graph. These nodes will all be trivially unreachable, so
1234// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001235//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001236void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner5a540632003-06-30 03:15:25 +00001237 removeIdenticalCalls(FunctionCalls);
1238 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001239
Chris Lattnerbab8c282003-09-20 21:34:07 +00001240 // Loop over all of the nodes in the graph, calling getNode on each field.
1241 // This will cause all nodes to update their forwarding edges, causing
1242 // forwarded nodes to be delete-able.
1243 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1244 DSNode *N = Nodes[i];
1245 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1246 N->getLink(l*N->getPointerSize()).getNode();
1247 }
1248
1249 // Likewise, forward any edges from the scalar nodes...
1250 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1251 I != E; ++I)
1252 I->second.getNode();
1253
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001254 bool isGlobalsGraph = !GlobalsGraph;
1255
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001256 for (unsigned i = 0; i != Nodes.size(); ++i) {
1257 DSNode *Node = Nodes[i];
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001258
1259 // Do not remove *any* global nodes in the globals graph.
1260 // This is a special case because such nodes may not have I, M, R flags set.
1261 if (Node->isGlobalNode() && isGlobalsGraph)
1262 continue;
1263
Chris Lattner72d50a02003-06-28 21:58:28 +00001264 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001265 // This is a useless node if it has no mod/ref info (checked above),
1266 // outgoing edges (which it cannot, as it is not modified in this
1267 // context), and it has no incoming edges. If it is a global node it may
1268 // have all of these properties and still have incoming edges, due to the
1269 // scalar map, so we check those now.
1270 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001271 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001272 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001273
1274 // Loop through and make sure all of the globals are referring directly
1275 // to the node...
1276 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1277 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1278 assert(N == Node && "ScalarMap doesn't match globals list!");
1279 }
1280
Chris Lattnerbd92b732003-06-19 21:15:11 +00001281 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001282 if (Node->getNumReferrers() == Globals.size()) {
1283 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1284 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001285 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001286 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001287 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001288
1289#ifdef SANER_CODE_FOR_CHECKING_IF_ALL_REFERRERS_ARE_FROM_SCALARMAP
1290 //
1291 // *** It seems to me that we should be able to simply check if
1292 // *** there are fewer or equal #referrers as #globals and make
1293 // *** sure that all those referrers are in the scalar map?
1294 //
1295 if (Node->getNumReferrers() <= Node->getGlobals().size()) {
1296 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1297
1298#ifndef NDEBUG
1299 // Loop through and make sure all of the globals are referring directly
1300 // to the node...
1301 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1302 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1303 assert(N == Node && "ScalarMap doesn't match globals list!");
1304 }
1305#endif
1306
1307 // Make sure NumReferrers still agrees. The node is truly dead.
1308 assert(Node->getNumReferrers() == Globals.size());
1309 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1310 ScalarMap.erase(Globals[j]);
1311 Node->makeNodeDead();
1312 }
1313#endif
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001314 }
1315
Chris Lattnerbd92b732003-06-19 21:15:11 +00001316 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001317 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001318 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001319 Nodes[i--] = Nodes.back();
1320 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001321 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001322 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001323}
1324
1325
Chris Lattner5c7380e2003-01-29 21:10:20 +00001326/// markReachableNodes - This method recursively traverses the specified
1327/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1328/// to the set, which allows it to only traverse visited nodes once.
1329///
Chris Lattner41c04f72003-02-01 04:52:08 +00001330void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001331 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001332 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner41c04f72003-02-01 04:52:08 +00001333 if (ReachableNodes.count(this)) return; // Already marked reachable
1334 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +00001335
Chris Lattner5c7380e2003-01-29 21:10:20 +00001336 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1337 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1338}
1339
Chris Lattner41c04f72003-02-01 04:52:08 +00001340void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001341 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001342 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001343
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001344 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1345 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001346}
1347
Chris Lattnera1220af2003-02-01 06:17:02 +00001348// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1349// looking for a node that is marked alive. If an alive node is found, return
1350// true, otherwise return false. If an alive node is reachable, this node is
1351// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001352//
Chris Lattnera1220af2003-02-01 06:17:02 +00001353static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001354 hash_set<DSNode*> &Visited,
1355 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001356 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001357 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001358
Chris Lattner85cfe012003-07-03 02:03:53 +00001359 // If this is a global node, it will end up in the globals graph anyway, so we
1360 // don't need to worry about it.
1361 if (IgnoreGlobals && N->isGlobalNode()) return false;
1362
Chris Lattneraa8146f2002-11-10 06:59:55 +00001363 // If we know that this node is alive, return so!
1364 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001365
Chris Lattneraa8146f2002-11-10 06:59:55 +00001366 // Otherwise, we don't think the node is alive yet, check for infinite
1367 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001368 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001369 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001370
Chris Lattner08db7192002-11-06 06:20:27 +00001371 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001372 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1373 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001374 N->markReachableNodes(Alive);
1375 return true;
1376 }
1377 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001378}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001379
Chris Lattnera1220af2003-02-01 06:17:02 +00001380// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1381// alive nodes.
1382//
Chris Lattner41c04f72003-02-01 04:52:08 +00001383static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001384 hash_set<DSNode*> &Visited,
1385 bool IgnoreGlobals) {
1386 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1387 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001388 return true;
1389 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001390 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001391 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001392 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001393 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1394 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001395 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001396 return false;
1397}
1398
Chris Lattnere2219762002-07-18 18:22:40 +00001399// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1400// subgraphs that are unreachable. This often occurs because the data
1401// structure doesn't "escape" into it's caller, and thus should be eliminated
1402// from the caller's graph entirely. This is only appropriate to use when
1403// inlining graphs.
1404//
Chris Lattner394471f2003-01-23 22:05:33 +00001405void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner85cfe012003-07-03 02:03:53 +00001406 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1407
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001408 // Reduce the amount of work we have to do... remove dummy nodes left over by
1409 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001410 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001411
Misha Brukman2f2d0652003-09-11 18:14:24 +00001412 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001413
1414 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001415 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001416 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001417
Chris Lattneraa8146f2002-11-10 06:59:55 +00001418 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner8d327672003-06-30 03:36:09 +00001419 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001420 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001421 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001422 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001423 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1424 ++I;
1425 } else {
1426 // Check to see if this is a worthless node generated for non-pointer
1427 // values, such as integers. Consider an addition of long types: A+B.
1428 // Assuming we can track all uses of the value in this context, and it is
1429 // NOT used as a pointer, we can delete the node. We will be able to
1430 // detect this situation if the node pointed to ONLY has Unknown bit set
1431 // in the node. In this case, the node is not incomplete, does not point
1432 // to any other nodes (no mod/ref bits set), and is therefore
1433 // uninteresting for data structure analysis. If we run across one of
1434 // these, prune the scalar pointing to it.
1435 //
1436 DSNode *N = I->second.getNode();
Chris Lattner85cfe012003-07-03 02:03:53 +00001437 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first)){
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001438 ScalarMap.erase(I++);
1439 } else {
1440 I->second.getNode()->markReachableNodes(Alive);
1441 ++I;
1442 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001443 }
Chris Lattnere2219762002-07-18 18:22:40 +00001444
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001445 // The return value is alive as well...
Chris Lattner5a540632003-06-30 03:15:25 +00001446 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1447 I != E; ++I)
1448 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001449
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001450 // Mark any nodes reachable by primary calls as alive...
1451 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1452 FunctionCalls[i].markReachableNodes(Alive);
1453
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001454 // Copy and merge all information about globals to the GlobalsGraph
1455 // if this is not a final pass (where unreachable globals are removed)
1456 NodeMapTy GlobalNodeMap;
1457 hash_set<const DSNode*> GlobalNodeSet;
1458
1459 for (std::vector<std::pair<Value*, DSNode*> >::const_iterator
1460 I = GlobalNodes.begin(), E = GlobalNodes.end(); I != E; ++I)
1461 GlobalNodeSet.insert(I->second); // put global nodes into a set
1462
1463 // Now find globals and aux call nodes that are already live or reach a live
1464 // value (which makes them live in turn), and continue till no more are found.
1465 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001466 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001467 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001468 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1469 do {
1470 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001471 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001472 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001473 // unreachable globals in the list.
1474 //
1475 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001476 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1477 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1478 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1479 Flags & DSGraph::RemoveUnreachableGlobals)) {
1480 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1481 GlobalNodes.pop_back(); // erase efficiently
1482 Iterate = true;
1483 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001484
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001485 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1486 // call nodes that get resolved will be difficult to remove from that graph.
1487 // The final unresolved call nodes must be handled specially at the end of
1488 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001489 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1490 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001491 (AuxFunctionCalls[i].isIndirectCall()
1492 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1493 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001494 AuxFunctionCalls[i].markReachableNodes(Alive);
1495 AuxFCallsAlive[i] = true;
1496 Iterate = true;
1497 }
1498 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001499
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001500 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001501 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001502 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1503 if (AuxFCallsAlive[i])
1504 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001505
1506 // Copy and merge all global nodes and dead aux call nodes into the
1507 // GlobalsGraph, and all nodes reachable from those nodes
1508 //
1509 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1510
1511 // First, add the dead aux call nodes to the set of root nodes for cloning
1512 // -- return value at this call site, if any
1513 // -- actual arguments passed at this call site
1514 // -- callee node at this call site, if this is an indirect call
1515 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i) {
1516 if (const DSNode* RetNode = AuxFunctionCalls[i].getRetVal().getNode())
1517 GlobalNodeSet.insert(RetNode);
1518 for (unsigned j=0, N=AuxFunctionCalls[i].getNumPtrArgs(); j < N; ++j)
1519 if (const DSNode* ArgTarget=AuxFunctionCalls[i].getPtrArg(j).getNode())
1520 GlobalNodeSet.insert(ArgTarget);
1521 if (AuxFunctionCalls[i].isIndirectCall())
1522 GlobalNodeSet.insert(AuxFunctionCalls[i].getCalleeNode());
1523 }
1524
1525 // There are no "pre-completed" nodes so use any empty map for those.
1526 // Strip all alloca bits since the current function is only for the BU pass.
1527 // Strip all incomplete bits since they are short-lived properties and they
1528 // will be correctly computed when rematerializing nodes into the functions.
1529 //
1530 NodeMapTy CompletedMap;
1531 GlobalsGraph->cloneReachableSubgraph(*this, GlobalNodeSet,
1532 GlobalNodeMap, CompletedMap,
1533 (DSGraph::StripAllocaBit |
1534 DSGraph::StripIncompleteBit));
1535 }
1536
1537 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001538 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001539 assert(GlobalsGraph && "No globals graph available??");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001540
1541 // Copy the unreachable call nodes to the globals graph, updating
1542 // their target pointers using the GlobalNodeMap
1543 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1544 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1545 GlobalNodeMap));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001546 }
1547 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001548 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1549 AuxFunctionCalls.end());
1550
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001551 // We are finally done with the GlobalNodeMap so we can clear it and
1552 // then get rid of unused nodes in the GlobalsGraph produced by merging.
1553 GlobalNodeMap.clear();
1554 GlobalsGraph->removeTriviallyDeadNodes();
1555
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001556 // At this point, any nodes which are visited, but not alive, are nodes
1557 // which can be removed. Loop over all nodes, eliminating completely
1558 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001559 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001560 std::vector<DSNode*> DeadNodes;
1561 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001562 for (unsigned i = 0; i != Nodes.size(); ++i)
1563 if (!Alive.count(Nodes[i])) {
1564 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001565 Nodes[i--] = Nodes.back(); // move node to end of vector
1566 Nodes.pop_back(); // Erase node from alive list.
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001567 DeadNodes.push_back(N);
1568 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001569 } else {
1570 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001571 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001572
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001573 // Remove all unreachable globals from the ScalarMap.
1574 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1575 // In either case, the dead nodes will not be in the set Alive.
1576 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1577 assert(((Flags & DSGraph::RemoveUnreachableGlobals) ||
1578 !Alive.count(GlobalNodes[i].second)) && "huh? non-dead global");
1579 if (!Alive.count(GlobalNodes[i].second))
1580 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001581 }
1582
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001583 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001584 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1585 delete DeadNodes[i];
1586
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001587 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001588}
1589
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001590void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001591 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1592 Nodes[i]->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001593
Chris Lattner8d327672003-06-30 03:36:09 +00001594 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001595 E = ScalarMap.end(); I != E; ++I) {
1596 assert(I->second.getNode() && "Null node in scalarmap!");
1597 AssertNodeInGraph(I->second.getNode());
1598 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001599 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001600 "Global points to node, but node isn't global?");
1601 AssertNodeContainsGlobal(I->second.getNode(), GV);
1602 }
1603 }
1604 AssertCallNodesInGraph();
1605 AssertAuxCallNodesInGraph();
1606}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001607
Chris Lattner7ddb0132003-08-05 18:38:37 +00001608/// mergeInGlobalsGraph - This method is useful for clients to incorporate the
1609/// globals graph into the DS, BU or TD graph for a function. This code retains
1610/// all globals, i.e., does not delete unreachable globals after they are
1611/// inlined.
1612///
1613void DSGraph::mergeInGlobalsGraph() {
Sumant Kowshik108421a2003-08-05 17:04:41 +00001614 NodeMapTy GlobalNodeMap;
1615 ScalarMapTy OldValMap;
1616 ReturnNodesTy OldRetNodes;
Chris Lattner7ddb0132003-08-05 18:38:37 +00001617 cloneInto(*GlobalsGraph, OldValMap, OldRetNodes, GlobalNodeMap,
1618 DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes |
1619 DSGraph::DontCloneAuxCallNodes);
Sumant Kowshik108421a2003-08-05 17:04:41 +00001620
1621 // Now merge existing global nodes in the GlobalsGraph with their copies
1622 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1623 I != E; ++I)
1624 if (isa<GlobalValue>(I->first)) { // Found a global node
1625 DSNodeHandle &GH = I->second;
1626 DSNodeHandle &GGNodeH = GlobalsGraph->getScalarMap()[I->first];
1627 GH.mergeWith(GlobalNodeMap[GGNodeH.getNode()]);
1628 }
1629
1630 // Merging leaves behind unused nodes: get rid of them now.
1631 GlobalNodeMap.clear();
1632 OldValMap.clear();
1633 OldRetNodes.clear();
1634 removeTriviallyDeadNodes();
1635}