blob: 3339d6152f007d472ca6a5a7553a5db0ff80ede1 [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 Lattner0b144872004-01-27 22:03:40 +000020#include "Support/CommandLine.h"
Chris Lattner6806f562003-08-01 22:15:03 +000021#include "Support/Debug.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000022#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000023#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000024#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000025#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000026using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000027
Chris Lattner08db7192002-11-06 06:20:27 +000028namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000029 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
30 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
31 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
32 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000033 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
34 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Chris Lattner0b144872004-01-27 22:03:40 +000035
36 cl::opt<bool>
37 EnableDSNodeGlobalRootsHack("enable-dsa-globalrootshack", cl::Hidden,
38 cl::desc("Make DSA less aggressive when cloning graphs"));
Chris Lattner08db7192002-11-06 06:20:27 +000039};
40
Chris Lattnera88a55c2004-01-28 02:41:32 +000041#if 1
Chris Lattner93ddd7e2004-01-22 16:36:28 +000042#define TIME_REGION(VARNAME, DESC) \
43 NamedRegionTimer VARNAME(DESC)
44#else
45#define TIME_REGION(VARNAME, DESC)
46#endif
47
Chris Lattnerb1060432002-11-07 05:20:53 +000048using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000049
Chris Lattner731b2d72003-02-13 19:09:00 +000050DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000051 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000052
53 // Handle node forwarding here!
54 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
55 Offset += N->ForwardNH.getOffset();
56
57 if (--N->NumReferrers == 0) {
58 // Removing the last referrer to the node, sever the forwarding link
59 N->stopForwarding();
60 }
61
62 N = Next;
63 N->NumReferrers++;
64 if (N->Size <= Offset) {
65 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
66 Offset = 0;
67 }
68 return N;
69}
70
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000071//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000072// DSNode Implementation
73//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000074
Chris Lattnerbd92b732003-06-19 21:15:11 +000075DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000076 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000077 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000078 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +000079 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000080 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000081}
82
Chris Lattner0d9bab82002-07-18 00:12:30 +000083// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +000084DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +000085 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner0b144872004-01-27 22:03:40 +000086 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
87 if (!NullLinks)
88 Links = N.Links;
89 else
90 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +000091 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000092 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +000093}
94
Chris Lattner15869aa2003-11-02 22:27:28 +000095/// getTargetData - Get the target data object used to construct this node.
96///
97const TargetData &DSNode::getTargetData() const {
98 return ParentGraph->getTargetData();
99}
100
Chris Lattner72d29a42003-02-11 23:11:51 +0000101void DSNode::assertOK() const {
102 assert((Ty != Type::VoidTy ||
103 Ty == Type::VoidTy && (Size == 0 ||
104 (NodeType & DSNode::Array))) &&
105 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000106
107 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000108 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000109 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnera88a55c2004-01-28 02:41:32 +0000110 assert(SM.count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000111 assert(SM.find(Globals[i])->second.getNode() == this);
112 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000113}
114
115/// forwardNode - Mark this node as being obsolete, and all references to it
116/// should be forwarded to the specified node and offset.
117///
118void DSNode::forwardNode(DSNode *To, unsigned Offset) {
119 assert(this != To && "Cannot forward a node to itself!");
120 assert(ForwardNH.isNull() && "Already forwarding from this node!");
121 if (To->Size <= 1) Offset = 0;
122 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
123 "Forwarded offset is wrong!");
124 ForwardNH.setNode(To);
125 ForwardNH.setOffset(Offset);
126 NodeType = DEAD;
127 Size = 0;
128 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000129
130 // Remove this node from the parent graph's Nodes list.
131 ParentGraph->unlinkNode(this);
132 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000133}
134
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000135// addGlobal - Add an entry for a global value to the Globals list. This also
136// marks the node with the 'G' flag if it does not already have it.
137//
138void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000139 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000140 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000141 std::lower_bound(Globals.begin(), Globals.end(), GV);
142
143 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000144 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000145 Globals.insert(I, GV);
146 NodeType |= GlobalNode;
147 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000148}
149
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000150/// foldNodeCompletely - If we determine that this node has some funny
151/// behavior happening to it that we cannot represent, we fold it down to a
152/// single, completely pessimistic, node. This node is represented as a
153/// single byte with a single TypeEntry of "void".
154///
155void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000156 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000157
Chris Lattner08db7192002-11-06 06:20:27 +0000158 ++NumFolds;
159
Chris Lattner0b144872004-01-27 22:03:40 +0000160 // If this node has a size that is <= 1, we don't need to create a forwarding
161 // node.
162 if (getSize() <= 1) {
163 NodeType |= DSNode::Array;
164 Ty = Type::VoidTy;
165 Size = 1;
166 assert(Links.size() <= 1 && "Size is 1, but has more links?");
167 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000168 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000169 // Create the node we are going to forward to. This is required because
170 // some referrers may have an offset that is > 0. By forcing them to
171 // forward, the forwarder has the opportunity to correct the offset.
172 DSNode *DestNode = new DSNode(0, ParentGraph);
173 DestNode->NodeType = NodeType|DSNode::Array;
174 DestNode->Ty = Type::VoidTy;
175 DestNode->Size = 1;
176 DestNode->Globals.swap(Globals);
177
178 // Start forwarding to the destination node...
179 forwardNode(DestNode, 0);
180
181 if (!Links.empty()) {
182 DestNode->Links.reserve(1);
183
184 DSNodeHandle NH(DestNode);
185 DestNode->Links.push_back(Links[0]);
186
187 // If we have links, merge all of our outgoing links together...
188 for (unsigned i = Links.size()-1; i != 0; --i)
189 NH.getNode()->Links[0].mergeWith(Links[i]);
190 Links.clear();
191 } else {
192 DestNode->Links.resize(1);
193 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000194 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000195}
Chris Lattner076c1f92002-11-07 06:31:54 +0000196
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000197/// isNodeCompletelyFolded - Return true if this node has been completely
198/// folded down to something that can never be expanded, effectively losing
199/// all of the field sensitivity that may be present in the node.
200///
201bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000202 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000203}
204
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000205namespace {
206 /// TypeElementWalker Class - Used for implementation of physical subtyping...
207 ///
208 class TypeElementWalker {
209 struct StackState {
210 const Type *Ty;
211 unsigned Offset;
212 unsigned Idx;
213 StackState(const Type *T, unsigned Off = 0)
214 : Ty(T), Offset(Off), Idx(0) {}
215 };
216
217 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000218 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000219 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000220 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000221 Stack.push_back(T);
222 StepToLeaf();
223 }
224
225 bool isDone() const { return Stack.empty(); }
226 const Type *getCurrentType() const { return Stack.back().Ty; }
227 unsigned getCurrentOffset() const { return Stack.back().Offset; }
228
229 void StepToNextType() {
230 PopStackAndAdvance();
231 StepToLeaf();
232 }
233
234 private:
235 /// PopStackAndAdvance - Pop the current element off of the stack and
236 /// advance the underlying element to the next contained member.
237 void PopStackAndAdvance() {
238 assert(!Stack.empty() && "Cannot pop an empty stack!");
239 Stack.pop_back();
240 while (!Stack.empty()) {
241 StackState &SS = Stack.back();
242 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
243 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000244 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000245 const StructLayout *SL = TD.getStructLayout(ST);
246 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
247 return;
248 }
249 Stack.pop_back(); // At the end of the structure
250 } else {
251 const ArrayType *AT = cast<ArrayType>(SS.Ty);
252 ++SS.Idx;
253 if (SS.Idx != AT->getNumElements()) {
254 SS.Offset += TD.getTypeSize(AT->getElementType());
255 return;
256 }
257 Stack.pop_back(); // At the end of the array
258 }
259 }
260 }
261
262 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
263 /// on the type stack.
264 void StepToLeaf() {
265 if (Stack.empty()) return;
266 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
267 StackState &SS = Stack.back();
268 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000269 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000270 assert(SS.Idx == 0);
271 PopStackAndAdvance();
272 } else {
273 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000274 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000275 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000276 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000277 SS.Offset+SL->MemberOffsets[SS.Idx]));
278 }
279 } else {
280 const ArrayType *AT = cast<ArrayType>(SS.Ty);
281 if (AT->getNumElements() == 0) {
282 assert(SS.Idx == 0);
283 PopStackAndAdvance();
284 } else {
285 // Step into the array...
286 assert(SS.Idx < AT->getNumElements());
287 Stack.push_back(StackState(AT->getElementType(),
288 SS.Offset+SS.Idx*
289 TD.getTypeSize(AT->getElementType())));
290 }
291 }
292 }
293 }
294 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000295} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000296
297/// ElementTypesAreCompatible - Check to see if the specified types are
298/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000299/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
300/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000301///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000302static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000303 bool AllowLargerT1, const TargetData &TD){
304 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000305
306 while (!T1W.isDone() && !T2W.isDone()) {
307 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
308 return false;
309
310 const Type *T1 = T1W.getCurrentType();
311 const Type *T2 = T2W.getCurrentType();
312 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
313 return false;
314
315 T1W.StepToNextType();
316 T2W.StepToNextType();
317 }
318
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000319 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000320}
321
322
Chris Lattner08db7192002-11-06 06:20:27 +0000323/// mergeTypeInfo - This method merges the specified type into the current node
324/// at the specified offset. This may update the current node's type record if
325/// this gives more information to the node, it may do nothing to the node if
326/// this information is already known, or it may merge the node completely (and
327/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000328///
Chris Lattner08db7192002-11-06 06:20:27 +0000329/// This method returns true if the node is completely folded, otherwise false.
330///
Chris Lattner088b6392003-03-03 17:13:31 +0000331bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
332 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000333 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000334 // Check to make sure the Size member is up-to-date. Size can be one of the
335 // following:
336 // Size = 0, Ty = Void: Nothing is known about this node.
337 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
338 // Size = 1, Ty = Void, Array = 1: The node is collapsed
339 // Otherwise, sizeof(Ty) = Size
340 //
Chris Lattner18552922002-11-18 21:44:46 +0000341 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
342 (Size == 0 && !Ty->isSized() && !isArray()) ||
343 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
344 (Size == 0 && !Ty->isSized() && !isArray()) ||
345 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000346 "Size member of DSNode doesn't match the type structure!");
347 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000348
Chris Lattner18552922002-11-18 21:44:46 +0000349 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000350 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000351
Chris Lattner08db7192002-11-06 06:20:27 +0000352 // Return true immediately if the node is completely folded.
353 if (isNodeCompletelyFolded()) return true;
354
Chris Lattner23f83dc2002-11-08 22:49:57 +0000355 // If this is an array type, eliminate the outside arrays because they won't
356 // be used anyway. This greatly reduces the size of large static arrays used
357 // as global variables, for example.
358 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000359 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000360 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
361 // FIXME: we might want to keep small arrays, but must be careful about
362 // things like: [2 x [10000 x int*]]
363 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000364 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000365 }
366
Chris Lattner08db7192002-11-06 06:20:27 +0000367 // Figure out how big the new type we're merging in is...
368 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
369
370 // Otherwise check to see if we can fold this type into the current node. If
371 // we can't, we fold the node completely, if we can, we potentially update our
372 // internal state.
373 //
Chris Lattner18552922002-11-18 21:44:46 +0000374 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000375 // If this is the first type that this node has seen, just accept it without
376 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000377 assert(Offset == 0 && !isArray() &&
378 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000379 Ty = NewTy;
380 NodeType &= ~Array;
381 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000382 Size = NewTySize;
383
384 // Calculate the number of outgoing links from this node.
385 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
386 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000387 }
Chris Lattner08db7192002-11-06 06:20:27 +0000388
389 // Handle node expansion case here...
390 if (Offset+NewTySize > Size) {
391 // It is illegal to grow this node if we have treated it as an array of
392 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000393 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000394 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000395 return true;
396 }
397
398 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000399 std::cerr << "UNIMP: Trying to merge a growth type into "
400 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000401 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000402 return true;
403 }
404
405 // Okay, the situation is nice and simple, we are trying to merge a type in
406 // at offset 0 that is bigger than our current type. Implement this by
407 // switching to the new type and then merge in the smaller one, which should
408 // hit the other code path here. If the other code path decides it's not
409 // ok, it will collapse the node as appropriate.
410 //
Chris Lattner18552922002-11-18 21:44:46 +0000411 const Type *OldTy = Ty;
412 Ty = NewTy;
413 NodeType &= ~Array;
414 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000415 Size = NewTySize;
416
417 // Must grow links to be the appropriate size...
418 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
419
420 // Merge in the old type now... which is guaranteed to be smaller than the
421 // "current" type.
422 return mergeTypeInfo(OldTy, 0);
423 }
424
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000425 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000426 "Cannot merge something into a part of our type that doesn't exist!");
427
Chris Lattner18552922002-11-18 21:44:46 +0000428 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000429 // type that starts at offset Offset.
430 //
431 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000432 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000433 while (O < Offset) {
434 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
435
436 switch (SubType->getPrimitiveID()) {
437 case Type::StructTyID: {
438 const StructType *STy = cast<StructType>(SubType);
439 const StructLayout &SL = *TD.getStructLayout(STy);
440
441 unsigned i = 0, e = SL.MemberOffsets.size();
442 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
443 /* empty */;
444
445 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000446 SubType = STy->getElementType(i);
Chris Lattner08db7192002-11-06 06:20:27 +0000447 O += SL.MemberOffsets[i];
448 break;
449 }
450 case Type::ArrayTyID: {
451 SubType = cast<ArrayType>(SubType)->getElementType();
452 unsigned ElSize = TD.getTypeSize(SubType);
453 unsigned Remainder = (Offset-O) % ElSize;
454 O = Offset-Remainder;
455 break;
456 }
457 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000458 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000459 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000460 }
461 }
462
463 assert(O == Offset && "Could not achieve the correct offset!");
464
465 // If we found our type exactly, early exit
466 if (SubType == NewTy) return false;
467
Chris Lattner0b144872004-01-27 22:03:40 +0000468 // Differing function types don't require us to merge. They are not values anyway.
469 if (isa<FunctionType>(SubType) &&
470 isa<FunctionType>(NewTy)) return false;
471
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000472 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
473
474 // Ok, we are getting desperate now. Check for physical subtyping, where we
475 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000476 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000477 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000478 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000479 return false;
480
Chris Lattner08db7192002-11-06 06:20:27 +0000481 // Okay, so we found the leader type at the offset requested. Search the list
482 // of types that starts at this offset. If SubType is currently an array or
483 // structure, the type desired may actually be the first element of the
484 // composite type...
485 //
Chris Lattner18552922002-11-18 21:44:46 +0000486 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000487 while (SubType != NewTy) {
488 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000489 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000490 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000491 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000492 case Type::StructTyID: {
493 const StructType *STy = cast<StructType>(SubType);
494 const StructLayout &SL = *TD.getStructLayout(STy);
495 if (SL.MemberOffsets.size() > 1)
496 NextPadSize = SL.MemberOffsets[1];
497 else
498 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000499 NextSubType = STy->getElementType(0);
Chris Lattner18552922002-11-18 21:44:46 +0000500 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000501 break;
Chris Lattner18552922002-11-18 21:44:46 +0000502 }
Chris Lattner08db7192002-11-06 06:20:27 +0000503 case Type::ArrayTyID:
504 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000505 NextSubTypeSize = TD.getTypeSize(NextSubType);
506 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000507 break;
508 default: ;
509 // fall out
510 }
511
512 if (NextSubType == 0)
513 break; // In the default case, break out of the loop
514
Chris Lattner18552922002-11-18 21:44:46 +0000515 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000516 break; // Don't allow shrinking to a smaller type than NewTySize
517 SubType = NextSubType;
518 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000519 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000520 }
521
522 // If we found the type exactly, return it...
523 if (SubType == NewTy)
524 return false;
525
526 // Check to see if we have a compatible, but different type...
527 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000528 // Check to see if this type is obviously convertible... int -> uint f.e.
529 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000530 return false;
531
532 // Check to see if we have a pointer & integer mismatch going on here,
533 // loading a pointer as a long, for example.
534 //
535 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
536 NewTy->isInteger() && isa<PointerType>(SubType))
537 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000538 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
539 // We are accessing the field, plus some structure padding. Ignore the
540 // structure padding.
541 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000542 }
543
Chris Lattner58f98d02003-07-02 04:38:49 +0000544 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000545 if (getParentGraph()->getReturnNodes().size())
546 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000547 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
548 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
549 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
550 << "SubType: ";
551 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000552
Chris Lattner088b6392003-03-03 17:13:31 +0000553 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000554 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000555}
556
Chris Lattner08db7192002-11-06 06:20:27 +0000557
558
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000559// addEdgeTo - Add an edge from the current node to the specified node. This
560// can cause merging of nodes in the graph.
561//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000562void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000563 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000564
Chris Lattner08db7192002-11-06 06:20:27 +0000565 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000566 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000567 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000568 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000569 } else { // No merging to perform...
570 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000571 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000572}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000573
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000574
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000575// MergeSortedVectors - Efficiently merge a vector into another vector where
576// duplicates are not allowed and both are sorted. This assumes that 'T's are
577// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000578//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000579static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
580 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000581 // By far, the most common cases will be the simple ones. In these cases,
582 // avoid having to allocate a temporary vector...
583 //
584 if (Src.empty()) { // Nothing to merge in...
585 return;
586 } else if (Dest.empty()) { // Just copy the result in...
587 Dest = Src;
588 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000589 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000590 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000591 std::lower_bound(Dest.begin(), Dest.end(), V);
592 if (I == Dest.end() || *I != Src[0]) // If not already contained...
593 Dest.insert(I, Src[0]);
594 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000595 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000596 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000597 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000598 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
599 if (I == Dest.end() || *I != Tmp) // If not already contained...
600 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000601
602 } else {
603 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000604 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000605
606 // Make space for all of the type entries now...
607 Dest.resize(Dest.size()+Src.size());
608
609 // Merge the two sorted ranges together... into Dest.
610 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
611
612 // Now erase any duplicate entries that may have accumulated into the
613 // vectors (because they were in both of the input sets)
614 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
615 }
616}
617
Chris Lattner0b144872004-01-27 22:03:40 +0000618void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
619 MergeSortedVectors(Globals, RHS);
620}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000621
Chris Lattner0b144872004-01-27 22:03:40 +0000622// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000623// This function does the hard work of merging two nodes, CurNodeH
624// and NH after filtering out trivial cases and making sure that
625// CurNodeH.offset >= NH.offset.
626//
627// ***WARNING***
628// Since merging may cause either node to go away, we must always
629// use the node-handles to refer to the nodes. These node handles are
630// automatically updated during merging, so will always provide access
631// to the correct node after a merge.
632//
633void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
634 assert(CurNodeH.getOffset() >= NH.getOffset() &&
635 "This should have been enforced in the caller.");
636
637 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
638 // respect to NH.Offset) is now zero. NOffset is the distance from the base
639 // of our object that N starts from.
640 //
641 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
642 unsigned NSize = NH.getNode()->getSize();
643
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000644 // If the two nodes are of different size, and the smaller node has the array
645 // bit set, collapse!
646 if (NSize != CurNodeH.getNode()->getSize()) {
647 if (NSize < CurNodeH.getNode()->getSize()) {
648 if (NH.getNode()->isArray())
649 NH.getNode()->foldNodeCompletely();
650 } else if (CurNodeH.getNode()->isArray()) {
651 NH.getNode()->foldNodeCompletely();
652 }
653 }
654
655 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000656 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000657 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000658 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000659
660 // If we are merging a node with a completely folded node, then both nodes are
661 // now completely folded.
662 //
663 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
664 if (!NH.getNode()->isNodeCompletelyFolded()) {
665 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000666 assert(NH.getNode() && NH.getOffset() == 0 &&
667 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000668 NOffset = NH.getOffset();
669 NSize = NH.getNode()->getSize();
670 assert(NOffset == 0 && NSize == 1);
671 }
672 } else if (NH.getNode()->isNodeCompletelyFolded()) {
673 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000674 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
675 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000676 NOffset = NH.getOffset();
677 NSize = NH.getNode()->getSize();
678 assert(NOffset == 0 && NSize == 1);
679 }
680
Chris Lattner72d29a42003-02-11 23:11:51 +0000681 DSNode *N = NH.getNode();
682 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000683 assert(!CurNodeH.getNode()->isDeadNode());
684
Chris Lattner0b144872004-01-27 22:03:40 +0000685 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000686 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000687
Chris Lattner72d29a42003-02-11 23:11:51 +0000688 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000689 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000690 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000691
Chris Lattner72d29a42003-02-11 23:11:51 +0000692 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
693 //
694 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
695 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000696 if (Link.getNode()) {
697 // Compute the offset into the current node at which to
698 // merge this link. In the common case, this is a linear
699 // relation to the offset in the original node (with
700 // wrapping), but if the current node gets collapsed due to
701 // recursive merging, we must make sure to merge in all remaining
702 // links at offset zero.
703 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000704 DSNode *CN = CurNodeH.getNode();
705 if (CN->Size != 1)
706 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
707 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000708 }
709 }
710
711 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000712 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000713
714 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000715 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000716 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000717
718 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000719 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000720 }
721}
722
723
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000724// mergeWith - Merge this node and the specified node, moving all links to and
725// from the argument node into the current node, deleting the node argument.
726// Offset indicates what offset the specified node is to be merged into the
727// current node.
728//
Chris Lattner5254a8d2004-01-22 16:31:08 +0000729// The specified node may be a null pointer (in which case, we update it to
730// point to this node).
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000731//
732void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
733 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000734 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000735 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000736
Chris Lattner5254a8d2004-01-22 16:31:08 +0000737 // If the RHS is a null node, make it point to this node!
738 if (N == 0) {
739 NH.mergeWith(DSNodeHandle(this, Offset));
740 return;
741 }
742
Chris Lattnerbd92b732003-06-19 21:15:11 +0000743 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000744 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
745
Chris Lattner02606632002-11-04 06:48:26 +0000746 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000747 // We cannot merge two pieces of the same node together, collapse the node
748 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000749 DEBUG(std::cerr << "Attempting to merge two chunks of"
750 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000751 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000752 return;
753 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000754
Chris Lattner5190ce82002-11-12 07:20:45 +0000755 // If both nodes are not at offset 0, make sure that we are merging the node
756 // at an later offset into the node with the zero offset.
757 //
758 if (Offset < NH.getOffset()) {
759 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
760 return;
761 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
762 // If the offsets are the same, merge the smaller node into the bigger node
763 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
764 return;
765 }
766
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000767 // Ok, now we can merge the two nodes. Use a static helper that works with
768 // two node handles, since "this" may get merged away at intermediate steps.
769 DSNodeHandle CurNodeH(this, Offset);
770 DSNodeHandle NHCopy(NH);
771 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000772}
773
Chris Lattner0b144872004-01-27 22:03:40 +0000774
775//===----------------------------------------------------------------------===//
776// ReachabilityCloner Implementation
777//===----------------------------------------------------------------------===//
778
779DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
780 if (SrcNH.isNull()) return DSNodeHandle();
781 const DSNode *SN = SrcNH.getNode();
782
783 DSNodeHandle &NH = NodeMap[SN];
784 if (!NH.isNull()) // Node already mapped?
785 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
786
787 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
788 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000789 NH = DN;
Chris Lattner0b144872004-01-27 22:03:40 +0000790
791 // Next, recursively clone all outgoing links as necessary. Note that
792 // adding these links can cause the node to collapse itself at any time, and
793 // the current node may be merged with arbitrary other nodes. For this
794 // reason, we must always go through NH.
795 DN = 0;
796 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
797 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
798 if (!SrcEdge.isNull()) {
799 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
800 // Compute the offset into the current node at which to
801 // merge this link. In the common case, this is a linear
802 // relation to the offset in the original node (with
803 // wrapping), but if the current node gets collapsed due to
804 // recursive merging, we must make sure to merge in all remaining
805 // links at offset zero.
806 unsigned MergeOffset = 0;
807 DSNode *CN = NH.getNode();
808 if (CN->getSize() != 1)
809 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()
810 - SrcNH.getOffset()) %CN->getSize();
811 CN->addEdgeTo(MergeOffset, DestEdge);
812 }
813 }
814
815 // If this node contains any globals, make sure they end up in the scalar
816 // map with the correct offset.
817 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
818 I != E; ++I) {
819 GlobalValue *GV = *I;
820 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
821 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
822 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
823 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000824 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000825
826 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
827 Dest.getInlinedGlobals().insert(GV);
828 }
829
830 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
831}
832
833void ReachabilityCloner::merge(const DSNodeHandle &NH,
834 const DSNodeHandle &SrcNH) {
835 if (SrcNH.isNull()) return; // Noop
836 if (NH.isNull()) {
837 // If there is no destination node, just clone the source and assign the
838 // destination node to be it.
839 NH.mergeWith(getClonedNH(SrcNH));
840 return;
841 }
842
843 // Okay, at this point, we know that we have both a destination and a source
844 // node that need to be merged. Check to see if the source node has already
845 // been cloned.
846 const DSNode *SN = SrcNH.getNode();
847 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +0000848 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner0b144872004-01-27 22:03:40 +0000849 NH.mergeWith(DSNodeHandle(SCNH.getNode(),
850 SCNH.getOffset()+SrcNH.getOffset()));
851
852 return; // Nothing to do!
853 }
854
855 // Okay, so the source node has not already been cloned. Instead of creating
856 // a new DSNode, only to merge it into the one we already have, try to perform
857 // the merge in-place. The only case we cannot handle here is when the offset
858 // into the existing node is less than the offset into the virtual node we are
859 // merging in. In this case, we have to extend the existing node, which
860 // requires an allocation anyway.
861 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
862 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000863 if (!DN->isNodeCompletelyFolded()) {
864 // Make sure the destination node is folded if the source node is folded.
865 if (SN->isNodeCompletelyFolded()) {
866 DN->foldNodeCompletely();
867 DN = NH.getNode();
868 } else if (SN->getSize() != DN->getSize()) {
869 // If the two nodes are of different size, and the smaller node has the
870 // array bit set, collapse!
871 if (SN->getSize() < DN->getSize()) {
872 if (SN->isArray()) {
873 DN->foldNodeCompletely();
874 DN = NH.getNode();
875 }
876 } else if (DN->isArray()) {
877 DN->foldNodeCompletely();
878 DN = NH.getNode();
879 }
880 }
881
882 // Merge the type entries of the two nodes together...
883 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
884 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
885 DN = NH.getNode();
886 }
887 }
888
889 assert(!DN->isDeadNode());
890
891 // Merge the NodeType information.
892 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
893
894 // Before we start merging outgoing links and updating the scalar map, make
895 // sure it is known that this is the representative node for the src node.
896 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
897
898 // If the source node contains any globals, make sure they end up in the
899 // scalar map with the correct offset.
900 if (SN->global_begin() != SN->global_end()) {
901 // Update the globals in the destination node itself.
902 DN->mergeGlobals(SN->getGlobals());
903
904 // Update the scalar map for the graph we are merging the source node
905 // into.
906 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
907 I != E; ++I) {
908 GlobalValue *GV = *I;
909 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
910 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
911 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
912 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +0000913 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000914
915 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
916 Dest.getInlinedGlobals().insert(GV);
917 }
918 }
919 } else {
920 // We cannot handle this case without allocating a temporary node. Fall
921 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +0000922 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
923 NewDN->maskNodeTypes(BitsToKeep);
924
925 unsigned NHOffset = NH.getOffset();
926 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +0000927
Chris Lattner0b144872004-01-27 22:03:40 +0000928 assert(NH.getNode() &&
929 (NH.getOffset() > NHOffset ||
930 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
931 "Merging did not adjust the offset!");
932
933 // Before we start merging outgoing links and updating the scalar map, make
934 // sure it is known that this is the representative node for the src node.
935 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +0000936
937 // If the source node contained any globals, make sure to create entries
938 // in the scalar map for them!
939 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
940 I != E; ++I) {
941 GlobalValue *GV = *I;
942 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
943 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
944 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
945 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
946 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
947 DestGNH.getOffset()+SrcGNH.getOffset()));
948
949 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
950 Dest.getInlinedGlobals().insert(GV);
951 }
Chris Lattner0b144872004-01-27 22:03:40 +0000952 }
953
954
955 // Next, recursively merge all outgoing links as necessary. Note that
956 // adding these links can cause the destination node to collapse itself at
957 // any time, and the current node may be merged with arbitrary other nodes.
958 // For this reason, we must always go through NH.
959 DN = 0;
960 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
961 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
962 if (!SrcEdge.isNull()) {
963 // Compute the offset into the current node at which to
964 // merge this link. In the common case, this is a linear
965 // relation to the offset in the original node (with
966 // wrapping), but if the current node gets collapsed due to
967 // recursive merging, we must make sure to merge in all remaining
968 // links at offset zero.
969 unsigned MergeOffset = 0;
970 DSNode *CN = SCNH.getNode();
971 if (CN->getSize() != 1)
972 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
973
Chris Lattner0ad91702004-02-22 00:53:54 +0000974 DSNodeHandle &Link = CN->getLink(MergeOffset);
975 if (!Link.isNull()) {
976 // Perform the recursive merging. Make sure to create a temporary NH,
977 // because the Link can disappear in the process of recursive merging.
978 DSNodeHandle Tmp = Link;
979 merge(Tmp, SrcEdge);
980 } else {
981 merge(Link, SrcEdge);
982 }
Chris Lattner0b144872004-01-27 22:03:40 +0000983 }
984 }
985}
986
987/// mergeCallSite - Merge the nodes reachable from the specified src call
988/// site into the nodes reachable from DestCS.
989void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
990 const DSCallSite &SrcCS) {
991 merge(DestCS.getRetVal(), SrcCS.getRetVal());
992 unsigned MinArgs = DestCS.getNumPtrArgs();
993 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
994
995 for (unsigned a = 0; a != MinArgs; ++a)
996 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
997}
998
999
Chris Lattner9de906c2002-10-20 22:11:44 +00001000//===----------------------------------------------------------------------===//
1001// DSCallSite Implementation
1002//===----------------------------------------------------------------------===//
1003
Vikram S. Adve26b98262002-10-20 21:41:02 +00001004// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001005Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001006 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001007}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001008
Chris Lattner0b144872004-01-27 22:03:40 +00001009void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1010 ReachabilityCloner &RC) {
1011 NH = RC.getClonedNH(Src);
1012}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001013
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001014//===----------------------------------------------------------------------===//
1015// DSGraph Implementation
1016//===----------------------------------------------------------------------===//
1017
Chris Lattnera9d65662003-06-30 05:57:30 +00001018/// getFunctionNames - Return a space separated list of the name of the
1019/// functions in this graph (if any)
1020std::string DSGraph::getFunctionNames() const {
1021 switch (getReturnNodes().size()) {
1022 case 0: return "Globals graph";
1023 case 1: return getReturnNodes().begin()->first->getName();
1024 default:
1025 std::string Return;
1026 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1027 I != getReturnNodes().end(); ++I)
1028 Return += I->first->getName() + " ";
1029 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1030 return Return;
1031 }
1032}
1033
1034
Chris Lattner15869aa2003-11-02 22:27:28 +00001035DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001036 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001037 NodeMapTy NodeMap;
1038 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001039}
1040
Chris Lattner5a540632003-06-30 03:15:25 +00001041DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001042 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001043 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001044 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001045}
1046
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001047DSGraph::~DSGraph() {
1048 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001049 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001050 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001051 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001052 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001053
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001054 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001055 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1056 (*NI)->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001057
Chris Lattner28897e12004-02-08 00:53:26 +00001058 // Free all of the nodes.
1059 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001060}
1061
Chris Lattner0d9bab82002-07-18 00:12:30 +00001062// dump - Allow inspection of graph in a debugger.
1063void DSGraph::dump() const { print(std::cerr); }
1064
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001065
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001066/// remapLinks - Change all of the Links in the current node according to the
1067/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001068///
Chris Lattner8d327672003-06-30 03:36:09 +00001069void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001070 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1071 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001072 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1073 if (ONMI != OldNodeMap.end()) {
1074 Links[i].setNode(ONMI->second.getNode());
1075 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1076 }
Chris Lattner2f561382004-01-22 16:56:13 +00001077 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001078}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001079
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001080/// updateFromGlobalGraph - This function rematerializes global nodes and
1081/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001082/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1083/// are already up-to-date in the current graph. In practice, in the TD pass,
1084/// this is likely to be a large fraction of the live global nodes in each
1085/// function (since most live nodes are likely to have been brought up-to-date
1086/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001087///
1088void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001089 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001090 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1091
1092 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001093 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1094 E = getScalarMap().global_end(); I != E; ++I)
1095 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001096 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001097 if (It != GlobalsGraph->ScalarMap.end())
1098 RC.merge(getNodeForValue(*I), It->second);
1099 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001100}
1101
Chris Lattner5a540632003-06-30 03:15:25 +00001102/// cloneInto - Clone the specified DSGraph into the current graph. The
1103/// translated ScalarMap for the old function is filled into the OldValMap
1104/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1105///
1106/// The CloneFlags member controls various aspects of the cloning process.
1107///
Chris Lattner62482e52004-01-28 09:15:42 +00001108void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001109 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1110 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001111 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001112 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001113 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001114
Chris Lattner1e883692003-02-03 20:08:51 +00001115 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001116 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1117 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1118 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001119 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001120
Chris Lattnerd85645f2004-02-21 22:28:26 +00001121 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1122 assert(!(*I)->isForwarding() &&
1123 "Forward nodes shouldn't be in node list!");
1124 DSNode *New = new DSNode(**I, this);
1125 New->maskNodeTypes(~BitsToClear);
1126 OldNodeMap[*I] = New;
1127 }
1128
Chris Lattner18552922002-11-18 21:44:46 +00001129#ifndef NDEBUG
1130 Timer::addPeakMemoryMeasurement();
1131#endif
Chris Lattnerd85645f2004-02-21 22:28:26 +00001132
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001133 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001134 // Note that we don't loop over the node's list to do this. The problem is
1135 // that remaping links can cause recursive merging to happen, which means
1136 // that node_iterator's can get easily invalidated! Because of this, we
1137 // loop over the OldNodeMap, which contains all of the new nodes as the
1138 // .second element of the map elements. Also note that if we remap a node
1139 // more than once, we won't break anything.
1140 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1141 I != E; ++I)
1142 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001143
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001144 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001145 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001146 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001147 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001148 DSNodeHandle &H = OldValMap[I->first];
1149 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1150 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001151
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001152 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001153 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1154 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001155 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1156 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001157 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001158 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001159
Chris Lattner679e8e12002-11-08 21:27:12 +00001160 if (!(CloneFlags & DontCloneCallNodes)) {
1161 // Copy the function calls list...
1162 unsigned FC = FunctionCalls.size(); // FirstCall
1163 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1164 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1165 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001166 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001167
Chris Lattneracf491f2002-11-08 22:27:09 +00001168 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +00001169 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +00001170 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +00001171 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1172 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1173 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1174 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001175
Chris Lattner5a540632003-06-30 03:15:25 +00001176 // Map the return node pointers over...
1177 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1178 E = G.getReturnNodes().end(); I != E; ++I) {
1179 const DSNodeHandle &Ret = I->second;
1180 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1181 OldReturnNodes.insert(std::make_pair(I->first,
1182 DSNodeHandle(MappedRet.getNode(),
1183 MappedRet.getOffset()+Ret.getOffset())));
1184 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001185}
1186
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001187
Chris Lattner076c1f92002-11-07 06:31:54 +00001188/// mergeInGraph - The method is used for merging graphs together. If the
1189/// argument graph is not *this, it makes a clone of the specified graph, then
1190/// merges the nodes specified in the call site with the formal arguments in the
1191/// graph.
1192///
Chris Lattner9f930552003-06-30 05:27:18 +00001193void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1194 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001195 TIME_REGION(X, "mergeInGraph");
1196
Chris Lattner076c1f92002-11-07 06:31:54 +00001197 // If this is not a recursive call, clone the graph into this graph...
1198 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001199 // Clone the callee's graph into the current graph, keeping track of where
1200 // scalars in the old graph _used_ to point, and of the new nodes matching
1201 // nodes of the old graph.
1202 ReachabilityCloner RC(*this, Graph, CloneFlags);
1203
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001204 // Set up argument bindings
1205 Function::aiterator AI = F.abegin();
1206 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1207 // Advance the argument iterator to the first pointer argument...
1208 while (AI != F.aend() && !isPointerType(AI->getType())) {
1209 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001210#ifndef NDEBUG // FIXME: We should merge vararg arguments!
1211 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001212 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001213#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001214 }
1215 if (AI == F.aend()) break;
1216
1217 // Add the link from the argument scalar to the provided value.
Chris Lattner0b144872004-01-27 22:03:40 +00001218 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
Chris Lattner076c1f92002-11-07 06:31:54 +00001219 }
1220
Chris Lattner0b144872004-01-27 22:03:40 +00001221 // Map the return node pointer over.
Chris Lattner0ad91702004-02-22 00:53:54 +00001222 if (!CS.getRetVal().isNull())
Chris Lattner0b144872004-01-27 22:03:40 +00001223 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
1224
1225 // If requested, copy the calls or aux-calls lists.
1226 if (!(CloneFlags & DontCloneCallNodes)) {
1227 // Copy the function calls list...
1228 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1229 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1230 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1231 }
1232
1233 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1234 // Copy the auxiliary function calls list...
1235 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1236 Graph.AuxFunctionCalls.size());
1237 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1238 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i], RC));
1239 }
1240
1241 // If the user requested it, add the nodes that we need to clone to the
1242 // RootNodes set.
1243 if (!EnableDSNodeGlobalRootsHack)
Chris Lattnerd85645f2004-02-21 22:28:26 +00001244 // FIXME: Why is this not iterating over the globals in the graph??
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001245 for (node_iterator NI = Graph.node_begin(), E = Graph.node_end();
1246 NI != E; ++NI)
1247 if (!(*NI)->getGlobals().empty())
1248 RC.getClonedNH(*NI);
Chris Lattner0b144872004-01-27 22:03:40 +00001249
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001250 } else {
1251 DSNodeHandle RetVal = getReturnNodeFor(F);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001252
1253 // Merge the return value with the return value of the context...
1254 RetVal.mergeWith(CS.getRetVal());
1255
1256 // Resolve all of the function arguments...
1257 Function::aiterator AI = F.abegin();
1258
1259 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1260 // Advance the argument iterator to the first pointer argument...
1261 while (AI != F.aend() && !isPointerType(AI->getType())) {
1262 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001263#ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1264 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001265 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1266#endif
1267 }
1268 if (AI == F.aend()) break;
1269
1270 // Add the link from the argument scalar to the provided value
Chris Lattner0b144872004-01-27 22:03:40 +00001271 DSNodeHandle &NH = getNodeForValue(AI);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001272 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1273 NH.mergeWith(CS.getPtrArg(i));
1274 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001275 }
1276}
1277
Chris Lattner58f98d02003-07-02 04:38:49 +00001278/// getCallSiteForArguments - Get the arguments and return value bindings for
1279/// the specified function in the current graph.
1280///
1281DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1282 std::vector<DSNodeHandle> Args;
1283
1284 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1285 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001286 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001287
Chris Lattner808a7ae2003-09-20 16:34:13 +00001288 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001289}
1290
1291
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001292
Chris Lattner0d9bab82002-07-18 00:12:30 +00001293// markIncompleteNodes - Mark the specified node as having contents that are not
1294// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001295// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001296// must recursively traverse the data structure graph, marking all reachable
1297// nodes as incomplete.
1298//
1299static void markIncompleteNode(DSNode *N) {
1300 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001301 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001302
1303 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001304 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001305
Misha Brukman2f2d0652003-09-11 18:14:24 +00001306 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001307 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1308 if (DSNode *DSN = N->getLink(i).getNode())
1309 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001310}
1311
Chris Lattnere71ffc22002-11-11 03:36:55 +00001312static void markIncomplete(DSCallSite &Call) {
1313 // Then the return value is certainly incomplete!
1314 markIncompleteNode(Call.getRetVal().getNode());
1315
1316 // All objects pointed to by function arguments are incomplete!
1317 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1318 markIncompleteNode(Call.getPtrArg(i).getNode());
1319}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001320
1321// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1322// modified by other functions that have not been resolved yet. This marks
1323// nodes that are reachable through three sources of "unknownness":
1324//
1325// Global Variables, Function Calls, and Incoming Arguments
1326//
1327// For any node that may have unknown components (because something outside the
1328// scope of current analysis may have modified it), the 'Incomplete' flag is
1329// added to the NodeType.
1330//
Chris Lattner394471f2003-01-23 22:05:33 +00001331void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001332 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001333 if (Flags & DSGraph::MarkFormalArgs)
1334 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1335 FI != E; ++FI) {
1336 Function &F = *FI->first;
1337 if (F.getName() != "main")
1338 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001339 if (isPointerType(I->getType()))
1340 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001341 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001342
1343 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001344 if (!shouldPrintAuxCalls())
1345 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1346 markIncomplete(FunctionCalls[i]);
1347 else
1348 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1349 markIncomplete(AuxFunctionCalls[i]);
1350
Chris Lattner0d9bab82002-07-18 00:12:30 +00001351
Chris Lattner93d7a212003-02-09 18:41:49 +00001352 // Mark all global nodes as incomplete...
1353 if ((Flags & DSGraph::IgnoreGlobals) == 0)
Chris Lattner51c06ab2004-02-25 23:08:00 +00001354 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1355 E = ScalarMap.global_end(); I != E; ++I)
1356 markIncompleteNode(ScalarMap[*I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001357}
1358
Chris Lattneraa8146f2002-11-10 06:59:55 +00001359static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1360 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001361 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001362 // No interesting info?
1363 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001364 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001365 Edge.setNode(0); // Kill the edge!
1366}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001367
Chris Lattneraa8146f2002-11-10 06:59:55 +00001368static inline bool nodeContainsExternalFunction(const DSNode *N) {
1369 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1370 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1371 if (Globals[i]->isExternal())
1372 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001373 return false;
1374}
1375
Chris Lattner5a540632003-06-30 03:15:25 +00001376static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001377 // Remove trivially identical function calls
1378 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001379 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1380
Chris Lattner0b144872004-01-27 22:03:40 +00001381#if 1
Chris Lattneraa8146f2002-11-10 06:59:55 +00001382 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001383 DSNode *LastCalleeNode = 0;
1384 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001385 unsigned NumDuplicateCalls = 0;
1386 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001387 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001388 DSCallSite &CS = Calls[i];
1389
Chris Lattnere4258442002-11-11 21:35:38 +00001390 // If the Callee is a useless edge, this must be an unreachable call site,
1391 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001392 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001393 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001394#ifndef NDEBUG
Chris Lattner923fc052003-02-05 21:59:58 +00001395 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001396#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001397 CS.swap(Calls.back());
1398 Calls.pop_back();
1399 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001400 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001401 // If the return value or any arguments point to a void node with no
1402 // information at all in it, and the call node is the only node to point
1403 // to it, remove the edge to the node (killing the node).
1404 //
1405 killIfUselessEdge(CS.getRetVal());
1406 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1407 killIfUselessEdge(CS.getPtrArg(a));
1408
1409 // If this call site calls the same function as the last call site, and if
1410 // the function pointer contains an external function, this node will
1411 // never be resolved. Merge the arguments of the call node because no
1412 // information will be lost.
1413 //
Chris Lattner923fc052003-02-05 21:59:58 +00001414 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1415 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001416 ++NumDuplicateCalls;
1417 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001418 if (LastCalleeNode)
1419 LastCalleeContainsExternalFunction =
1420 nodeContainsExternalFunction(LastCalleeNode);
1421 else
1422 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001423 }
Chris Lattner0b144872004-01-27 22:03:40 +00001424
1425 // It is not clear why, but enabling this code makes DSA really
1426 // sensitive to node forwarding. Basically, with this enabled, DSA
1427 // performs different number of inlinings based on which nodes are
1428 // forwarding or not. This is clearly a problem, so this code is
1429 // disabled until this can be resolved.
Chris Lattner58f98d02003-07-02 04:38:49 +00001430#if 1
Chris Lattner0b144872004-01-27 22:03:40 +00001431 if (LastCalleeContainsExternalFunction
1432#if 0
1433 ||
Chris Lattnere4258442002-11-11 21:35:38 +00001434 // This should be more than enough context sensitivity!
1435 // FIXME: Evaluate how many times this is tripped!
Chris Lattner0b144872004-01-27 22:03:40 +00001436 NumDuplicateCalls > 20
1437#endif
1438 ) {
Chris Lattnere4258442002-11-11 21:35:38 +00001439 DSCallSite &OCS = Calls[i-1];
1440 OCS.mergeWith(CS);
1441
1442 // The node will now be eliminated as a duplicate!
1443 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1444 CS = OCS;
1445 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1446 OCS = CS;
1447 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001448#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001449 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001450 if (CS.isDirectCall()) {
1451 LastCalleeFunc = CS.getCalleeFunc();
1452 LastCalleeNode = 0;
1453 } else {
1454 LastCalleeNode = CS.getCalleeNode();
1455 LastCalleeFunc = 0;
1456 }
Chris Lattnere4258442002-11-11 21:35:38 +00001457 NumDuplicateCalls = 0;
1458 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001459 }
1460 }
Chris Lattner0b144872004-01-27 22:03:40 +00001461#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001462 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001463
Chris Lattner33312f72002-11-08 01:21:07 +00001464 // Track the number of call nodes merged away...
1465 NumCallNodesMerged += NumFns-Calls.size();
1466
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001467 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001468 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001469}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001470
Chris Lattneraa8146f2002-11-10 06:59:55 +00001471
Chris Lattnere2219762002-07-18 18:22:40 +00001472// removeTriviallyDeadNodes - After the graph has been constructed, this method
1473// removes all unreachable nodes that are created because they got merged with
1474// other nodes in the graph. These nodes will all be trivially unreachable, so
1475// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001476//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001477void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001478 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001479
Chris Lattnerbab8c282003-09-20 21:34:07 +00001480 // Loop over all of the nodes in the graph, calling getNode on each field.
1481 // This will cause all nodes to update their forwarding edges, causing
1482 // forwarded nodes to be delete-able.
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001483 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1484 DSNode *N = *NI;
Chris Lattnerbab8c282003-09-20 21:34:07 +00001485 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1486 N->getLink(l*N->getPointerSize()).getNode();
1487 }
1488
Chris Lattner0b144872004-01-27 22:03:40 +00001489 // NOTE: This code is disabled. Though it should, in theory, allow us to
1490 // remove more nodes down below, the scan of the scalar map is incredibly
1491 // expensive for certain programs (with large SCCs). In the future, if we can
1492 // make the scalar map scan more efficient, then we can reenable this.
1493#if 0
1494 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1495
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001496 // Likewise, forward any edges from the scalar nodes. While we are at it,
1497 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001498 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001499 I->second.getNode();
1500 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001501 }
Chris Lattner0b144872004-01-27 22:03:40 +00001502 }
1503#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001504 bool isGlobalsGraph = !GlobalsGraph;
1505
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001506 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001507 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001508
1509 // Do not remove *any* global nodes in the globals graph.
1510 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001511 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001512 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001513 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001514 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001515
Chris Lattner28897e12004-02-08 00:53:26 +00001516 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001517 // This is a useless node if it has no mod/ref info (checked above),
1518 // outgoing edges (which it cannot, as it is not modified in this
1519 // context), and it has no incoming edges. If it is a global node it may
1520 // have all of these properties and still have incoming edges, due to the
1521 // scalar map, so we check those now.
1522 //
Chris Lattner28897e12004-02-08 00:53:26 +00001523 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1524 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001525
Chris Lattner17a93e22004-01-29 03:32:15 +00001526 // Loop through and make sure all of the globals are referring directly
1527 // to the node...
1528 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1529 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001530 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001531 }
1532
Chris Lattnerbd92b732003-06-19 21:15:11 +00001533 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001534 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001535 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1536 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001537 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001538 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001539 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001540 }
1541 }
1542
Chris Lattner28897e12004-02-08 00:53:26 +00001543 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001544 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001545 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001546 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001547 } else {
1548 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001549 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001550 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001551
1552 removeIdenticalCalls(FunctionCalls);
1553 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001554}
1555
1556
Chris Lattner5c7380e2003-01-29 21:10:20 +00001557/// markReachableNodes - This method recursively traverses the specified
1558/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1559/// to the set, which allows it to only traverse visited nodes once.
1560///
Chris Lattner41c04f72003-02-01 04:52:08 +00001561void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001562 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001563 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001564 if (ReachableNodes.insert(this).second) // Is newly reachable?
1565 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1566 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001567}
1568
Chris Lattner41c04f72003-02-01 04:52:08 +00001569void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001570 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001571 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001572
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001573 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1574 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001575}
1576
Chris Lattnera1220af2003-02-01 06:17:02 +00001577// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1578// looking for a node that is marked alive. If an alive node is found, return
1579// true, otherwise return false. If an alive node is reachable, this node is
1580// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001581//
Chris Lattnera1220af2003-02-01 06:17:02 +00001582static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001583 hash_set<DSNode*> &Visited,
1584 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001585 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001586 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001587
Chris Lattner85cfe012003-07-03 02:03:53 +00001588 // If this is a global node, it will end up in the globals graph anyway, so we
1589 // don't need to worry about it.
1590 if (IgnoreGlobals && N->isGlobalNode()) return false;
1591
Chris Lattneraa8146f2002-11-10 06:59:55 +00001592 // If we know that this node is alive, return so!
1593 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001594
Chris Lattneraa8146f2002-11-10 06:59:55 +00001595 // Otherwise, we don't think the node is alive yet, check for infinite
1596 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001597 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001598 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001599
Chris Lattner08db7192002-11-06 06:20:27 +00001600 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001601 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1602 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001603 N->markReachableNodes(Alive);
1604 return true;
1605 }
1606 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001607}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001608
Chris Lattnera1220af2003-02-01 06:17:02 +00001609// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1610// alive nodes.
1611//
Chris Lattner41c04f72003-02-01 04:52:08 +00001612static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001613 hash_set<DSNode*> &Visited,
1614 bool IgnoreGlobals) {
1615 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1616 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001617 return true;
1618 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001619 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001620 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001621 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001622 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1623 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001624 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001625 return false;
1626}
1627
Chris Lattnere2219762002-07-18 18:22:40 +00001628// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1629// subgraphs that are unreachable. This often occurs because the data
1630// structure doesn't "escape" into it's caller, and thus should be eliminated
1631// from the caller's graph entirely. This is only appropriate to use when
1632// inlining graphs.
1633//
Chris Lattner394471f2003-01-23 22:05:33 +00001634void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001635 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001636
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001637 // Reduce the amount of work we have to do... remove dummy nodes left over by
1638 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001639 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001640
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001641 TIME_REGION(X, "removeDeadNodes");
1642
Misha Brukman2f2d0652003-09-11 18:14:24 +00001643 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001644
1645 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001646 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001647 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001648
Chris Lattner0b144872004-01-27 22:03:40 +00001649 // Copy and merge all information about globals to the GlobalsGraph if this is
1650 // not a final pass (where unreachable globals are removed).
1651 //
1652 // Strip all alloca bits since the current function is only for the BU pass.
1653 // Strip all incomplete bits since they are short-lived properties and they
1654 // will be correctly computed when rematerializing nodes into the functions.
1655 //
1656 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1657 DSGraph::StripIncompleteBit);
1658
Chris Lattneraa8146f2002-11-10 06:59:55 +00001659 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner00948c02004-01-28 02:05:05 +00001660 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
Chris Lattner62482e52004-01-28 09:15:42 +00001661 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001662 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001663 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001664 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001665 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001666
1667 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001668 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1669 DSGraph::ScalarMapTy::iterator SMI =
1670 GlobalsGraph->getScalarMap().find(I->first);
1671 if (SMI != GlobalsGraph->getScalarMap().end())
1672 GGCloner.merge(SMI->second, I->second);
1673 else
1674 GGCloner.getClonedNH(I->second);
1675 }
Chris Lattner0b144872004-01-27 22:03:40 +00001676 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001677 } else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001678 DSNode *N = I->second.getNode();
1679#if 0
Chris Lattner0b144872004-01-27 22:03:40 +00001680 // Check to see if this is a worthless node generated for non-pointer
1681 // values, such as integers. Consider an addition of long types: A+B.
1682 // Assuming we can track all uses of the value in this context, and it is
1683 // NOT used as a pointer, we can delete the node. We will be able to
1684 // detect this situation if the node pointed to ONLY has Unknown bit set
1685 // in the node. In this case, the node is not incomplete, does not point
1686 // to any other nodes (no mod/ref bits set), and is therefore
1687 // uninteresting for data structure analysis. If we run across one of
1688 // these, prune the scalar pointing to it.
1689 //
Chris Lattner0b144872004-01-27 22:03:40 +00001690 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1691 ScalarMap.erase(I++);
1692 else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001693#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001694 N->markReachableNodes(Alive);
1695 ++I;
Chris Lattnera88a55c2004-01-28 02:41:32 +00001696 //}
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001697 }
Chris Lattner00948c02004-01-28 02:05:05 +00001698 }
Chris Lattnere2219762002-07-18 18:22:40 +00001699
Chris Lattner0b144872004-01-27 22:03:40 +00001700 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001701 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1702 I != E; ++I)
1703 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001704
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001705 // Mark any nodes reachable by primary calls as alive...
1706 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1707 FunctionCalls[i].markReachableNodes(Alive);
1708
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001709
1710 // Now find globals and aux call nodes that are already live or reach a live
1711 // value (which makes them live in turn), and continue till no more are found.
1712 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001713 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001714 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001715 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1716 do {
1717 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001718 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001719 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001720 // unreachable globals in the list.
1721 //
1722 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001723 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001724 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1725 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1726 Flags & DSGraph::RemoveUnreachableGlobals)) {
1727 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1728 GlobalNodes.pop_back(); // erase efficiently
1729 Iterate = true;
1730 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001731
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001732 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1733 // call nodes that get resolved will be difficult to remove from that graph.
1734 // The final unresolved call nodes must be handled specially at the end of
1735 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001736 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1737 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001738 (AuxFunctionCalls[i].isIndirectCall()
1739 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1740 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001741 AuxFunctionCalls[i].markReachableNodes(Alive);
1742 AuxFCallsAlive[i] = true;
1743 Iterate = true;
1744 }
1745 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001746
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001747 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001748 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001749 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1750 if (AuxFCallsAlive[i])
1751 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001752
1753 // Copy and merge all global nodes and dead aux call nodes into the
1754 // GlobalsGraph, and all nodes reachable from those nodes
1755 //
1756 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001757 // Copy the unreachable call nodes to the globals graph, updating their
1758 // target pointers using the GGCloner
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001759 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1760 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
Chris Lattner0b144872004-01-27 22:03:40 +00001761 GGCloner));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001762 }
1763 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001764 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1765 AuxFunctionCalls.end());
1766
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001767 // We are finally done with the GGCloner so we can destroy it.
1768 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001769
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001770 // At this point, any nodes which are visited, but not alive, are nodes
1771 // which can be removed. Loop over all nodes, eliminating completely
1772 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001773 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001774 std::vector<DSNode*> DeadNodes;
1775 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00001776 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
1777 DSNode *N = NI++;
1778 assert(!N->isForwarding() && "Forwarded node in nodes list?");
1779
1780 if (!Alive.count(N)) {
1781 Nodes.remove(N);
1782 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001783 DeadNodes.push_back(N);
1784 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00001785 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00001786 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00001787 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001788
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001789 // Remove all unreachable globals from the ScalarMap.
1790 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1791 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001792 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001793 if (!Alive.count(GlobalNodes[i].second))
1794 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00001795 else
1796 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001797
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001798 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001799 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1800 delete DeadNodes[i];
1801
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001802 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001803}
1804
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001805void DSGraph::AssertGraphOK() const {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001806 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1807 (*NI)->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001808
Chris Lattner8d327672003-06-30 03:36:09 +00001809 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001810 E = ScalarMap.end(); I != E; ++I) {
1811 assert(I->second.getNode() && "Null node in scalarmap!");
1812 AssertNodeInGraph(I->second.getNode());
1813 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001814 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001815 "Global points to node, but node isn't global?");
1816 AssertNodeContainsGlobal(I->second.getNode(), GV);
1817 }
1818 }
1819 AssertCallNodesInGraph();
1820 AssertAuxCallNodesInGraph();
1821}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001822
Chris Lattner400433d2003-11-11 05:08:59 +00001823/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1824/// nodes reachable from the two graphs, computing the mapping of nodes from
1825/// the first to the second graph.
1826///
1827void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001828 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1829 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001830 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1831 if (N1 == 0 || N2 == 0) return;
1832
1833 DSNodeHandle &Entry = NodeMap[N1];
1834 if (Entry.getNode()) {
1835 // Termination of recursion!
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001836 assert(!StrictChecking ||
1837 (Entry.getNode() == N2 &&
1838 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
Chris Lattner400433d2003-11-11 05:08:59 +00001839 "Inconsistent mapping detected!");
1840 return;
1841 }
1842
1843 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001844 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001845
1846 // Loop over all of the fields that N1 and N2 have in common, recursively
1847 // mapping the edges together now.
1848 int N2Idx = NH2.getOffset()-NH1.getOffset();
1849 unsigned N2Size = N2->getSize();
1850 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1851 if (unsigned(N2Idx)+i < N2Size)
1852 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1853}