blob: 528a62235ff50de69a64e1a05e0a8b81cde1cd47 [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
848 if (SCNH.getNode()) { // Node already cloned?
849 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
974 // Perform the recursive merging. Make sure to create a temporary NH,
975 // because the Link can disappear in the process of recursive merging.
976 DSNodeHandle Tmp = CN->getLink(MergeOffset);
977 merge(Tmp, SrcEdge);
978 }
979 }
980}
981
982/// mergeCallSite - Merge the nodes reachable from the specified src call
983/// site into the nodes reachable from DestCS.
984void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
985 const DSCallSite &SrcCS) {
986 merge(DestCS.getRetVal(), SrcCS.getRetVal());
987 unsigned MinArgs = DestCS.getNumPtrArgs();
988 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
989
990 for (unsigned a = 0; a != MinArgs; ++a)
991 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
992}
993
994
Chris Lattner9de906c2002-10-20 22:11:44 +0000995//===----------------------------------------------------------------------===//
996// DSCallSite Implementation
997//===----------------------------------------------------------------------===//
998
Vikram S. Adve26b98262002-10-20 21:41:02 +0000999// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001000Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001001 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001002}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001003
Chris Lattner0b144872004-01-27 22:03:40 +00001004void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1005 ReachabilityCloner &RC) {
1006 NH = RC.getClonedNH(Src);
1007}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001008
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001009//===----------------------------------------------------------------------===//
1010// DSGraph Implementation
1011//===----------------------------------------------------------------------===//
1012
Chris Lattnera9d65662003-06-30 05:57:30 +00001013/// getFunctionNames - Return a space separated list of the name of the
1014/// functions in this graph (if any)
1015std::string DSGraph::getFunctionNames() const {
1016 switch (getReturnNodes().size()) {
1017 case 0: return "Globals graph";
1018 case 1: return getReturnNodes().begin()->first->getName();
1019 default:
1020 std::string Return;
1021 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1022 I != getReturnNodes().end(); ++I)
1023 Return += I->first->getName() + " ";
1024 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1025 return Return;
1026 }
1027}
1028
1029
Chris Lattner15869aa2003-11-02 22:27:28 +00001030DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001031 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001032 NodeMapTy NodeMap;
1033 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001034}
1035
Chris Lattner5a540632003-06-30 03:15:25 +00001036DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001037 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001038 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001039 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001040}
1041
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001042DSGraph::~DSGraph() {
1043 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001044 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001045 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001046 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001047 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001048
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001049 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001050 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1051 (*NI)->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001052
Chris Lattner28897e12004-02-08 00:53:26 +00001053 // Free all of the nodes.
1054 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001055}
1056
Chris Lattner0d9bab82002-07-18 00:12:30 +00001057// dump - Allow inspection of graph in a debugger.
1058void DSGraph::dump() const { print(std::cerr); }
1059
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001060
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001061/// remapLinks - Change all of the Links in the current node according to the
1062/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001063///
Chris Lattner8d327672003-06-30 03:36:09 +00001064void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001065 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1066 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001067 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1068 if (ONMI != OldNodeMap.end()) {
1069 Links[i].setNode(ONMI->second.getNode());
1070 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1071 }
Chris Lattner2f561382004-01-22 16:56:13 +00001072 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001073}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001074
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001075/// updateFromGlobalGraph - This function rematerializes global nodes and
1076/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001077/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1078/// are already up-to-date in the current graph. In practice, in the TD pass,
1079/// this is likely to be a large fraction of the live global nodes in each
1080/// function (since most live nodes are likely to have been brought up-to-date
1081/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001082///
1083void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001084 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001085 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1086
1087 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001088 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1089 E = getScalarMap().global_end(); I != E; ++I)
1090 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001091 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001092 if (It != GlobalsGraph->ScalarMap.end())
1093 RC.merge(getNodeForValue(*I), It->second);
1094 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001095}
1096
Chris Lattner5a540632003-06-30 03:15:25 +00001097/// cloneInto - Clone the specified DSGraph into the current graph. The
1098/// translated ScalarMap for the old function is filled into the OldValMap
1099/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1100///
1101/// The CloneFlags member controls various aspects of the cloning process.
1102///
Chris Lattner62482e52004-01-28 09:15:42 +00001103void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001104 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1105 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001106 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001107 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001108 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001109
Chris Lattner1e883692003-02-03 20:08:51 +00001110 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001111 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1112 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1113 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001114 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001115
Chris Lattnerd85645f2004-02-21 22:28:26 +00001116 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1117 assert(!(*I)->isForwarding() &&
1118 "Forward nodes shouldn't be in node list!");
1119 DSNode *New = new DSNode(**I, this);
1120 New->maskNodeTypes(~BitsToClear);
1121 OldNodeMap[*I] = New;
1122 }
1123
Chris Lattner18552922002-11-18 21:44:46 +00001124#ifndef NDEBUG
1125 Timer::addPeakMemoryMeasurement();
1126#endif
Chris Lattnerd85645f2004-02-21 22:28:26 +00001127
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001128 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001129 // Note that we don't loop over the node's list to do this. The problem is
1130 // that remaping links can cause recursive merging to happen, which means
1131 // that node_iterator's can get easily invalidated! Because of this, we
1132 // loop over the OldNodeMap, which contains all of the new nodes as the
1133 // .second element of the map elements. Also note that if we remap a node
1134 // more than once, we won't break anything.
1135 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1136 I != E; ++I)
1137 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001138
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001139 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001140 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001141 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001142 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001143 DSNodeHandle &H = OldValMap[I->first];
1144 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1145 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001146
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001147 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001148 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1149 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001150 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1151 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001152 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001153 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001154
Chris Lattner679e8e12002-11-08 21:27:12 +00001155 if (!(CloneFlags & DontCloneCallNodes)) {
1156 // Copy the function calls list...
1157 unsigned FC = FunctionCalls.size(); // FirstCall
1158 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1159 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1160 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001161 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001162
Chris Lattneracf491f2002-11-08 22:27:09 +00001163 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +00001164 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +00001165 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +00001166 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1167 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1168 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1169 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001170
Chris Lattner5a540632003-06-30 03:15:25 +00001171 // Map the return node pointers over...
1172 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1173 E = G.getReturnNodes().end(); I != E; ++I) {
1174 const DSNodeHandle &Ret = I->second;
1175 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1176 OldReturnNodes.insert(std::make_pair(I->first,
1177 DSNodeHandle(MappedRet.getNode(),
1178 MappedRet.getOffset()+Ret.getOffset())));
1179 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001180}
1181
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001182
Chris Lattner076c1f92002-11-07 06:31:54 +00001183/// mergeInGraph - The method is used for merging graphs together. If the
1184/// argument graph is not *this, it makes a clone of the specified graph, then
1185/// merges the nodes specified in the call site with the formal arguments in the
1186/// graph.
1187///
Chris Lattner9f930552003-06-30 05:27:18 +00001188void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1189 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001190 TIME_REGION(X, "mergeInGraph");
1191
Chris Lattner076c1f92002-11-07 06:31:54 +00001192 // If this is not a recursive call, clone the graph into this graph...
1193 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001194 // Clone the callee's graph into the current graph, keeping track of where
1195 // scalars in the old graph _used_ to point, and of the new nodes matching
1196 // nodes of the old graph.
1197 ReachabilityCloner RC(*this, Graph, CloneFlags);
1198
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001199 // Set up argument bindings
1200 Function::aiterator AI = F.abegin();
1201 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1202 // Advance the argument iterator to the first pointer argument...
1203 while (AI != F.aend() && !isPointerType(AI->getType())) {
1204 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001205#ifndef NDEBUG // FIXME: We should merge vararg arguments!
1206 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001207 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001208#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001209 }
1210 if (AI == F.aend()) break;
1211
1212 // Add the link from the argument scalar to the provided value.
Chris Lattner0b144872004-01-27 22:03:40 +00001213 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
Chris Lattner076c1f92002-11-07 06:31:54 +00001214 }
1215
Chris Lattner0b144872004-01-27 22:03:40 +00001216 // Map the return node pointer over.
1217 if (CS.getRetVal().getNode())
1218 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
1219
1220 // If requested, copy the calls or aux-calls lists.
1221 if (!(CloneFlags & DontCloneCallNodes)) {
1222 // Copy the function calls list...
1223 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1224 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1225 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1226 }
1227
1228 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1229 // Copy the auxiliary function calls list...
1230 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1231 Graph.AuxFunctionCalls.size());
1232 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1233 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i], RC));
1234 }
1235
1236 // If the user requested it, add the nodes that we need to clone to the
1237 // RootNodes set.
1238 if (!EnableDSNodeGlobalRootsHack)
Chris Lattnerd85645f2004-02-21 22:28:26 +00001239 // FIXME: Why is this not iterating over the globals in the graph??
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001240 for (node_iterator NI = Graph.node_begin(), E = Graph.node_end();
1241 NI != E; ++NI)
1242 if (!(*NI)->getGlobals().empty())
1243 RC.getClonedNH(*NI);
Chris Lattner0b144872004-01-27 22:03:40 +00001244
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001245 } else {
1246 DSNodeHandle RetVal = getReturnNodeFor(F);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001247
1248 // Merge the return value with the return value of the context...
1249 RetVal.mergeWith(CS.getRetVal());
1250
1251 // Resolve all of the function arguments...
1252 Function::aiterator AI = F.abegin();
1253
1254 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1255 // Advance the argument iterator to the first pointer argument...
1256 while (AI != F.aend() && !isPointerType(AI->getType())) {
1257 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001258#ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1259 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001260 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1261#endif
1262 }
1263 if (AI == F.aend()) break;
1264
1265 // Add the link from the argument scalar to the provided value
Chris Lattner0b144872004-01-27 22:03:40 +00001266 DSNodeHandle &NH = getNodeForValue(AI);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001267 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1268 NH.mergeWith(CS.getPtrArg(i));
1269 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001270 }
1271}
1272
Chris Lattner58f98d02003-07-02 04:38:49 +00001273/// getCallSiteForArguments - Get the arguments and return value bindings for
1274/// the specified function in the current graph.
1275///
1276DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1277 std::vector<DSNodeHandle> Args;
1278
1279 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1280 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001281 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001282
Chris Lattner808a7ae2003-09-20 16:34:13 +00001283 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001284}
1285
1286
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001287
Chris Lattner0d9bab82002-07-18 00:12:30 +00001288// markIncompleteNodes - Mark the specified node as having contents that are not
1289// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001290// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001291// must recursively traverse the data structure graph, marking all reachable
1292// nodes as incomplete.
1293//
1294static void markIncompleteNode(DSNode *N) {
1295 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001296 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001297
1298 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001299 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001300
Misha Brukman2f2d0652003-09-11 18:14:24 +00001301 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001302 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1303 if (DSNode *DSN = N->getLink(i).getNode())
1304 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001305}
1306
Chris Lattnere71ffc22002-11-11 03:36:55 +00001307static void markIncomplete(DSCallSite &Call) {
1308 // Then the return value is certainly incomplete!
1309 markIncompleteNode(Call.getRetVal().getNode());
1310
1311 // All objects pointed to by function arguments are incomplete!
1312 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1313 markIncompleteNode(Call.getPtrArg(i).getNode());
1314}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001315
1316// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1317// modified by other functions that have not been resolved yet. This marks
1318// nodes that are reachable through three sources of "unknownness":
1319//
1320// Global Variables, Function Calls, and Incoming Arguments
1321//
1322// For any node that may have unknown components (because something outside the
1323// scope of current analysis may have modified it), the 'Incomplete' flag is
1324// added to the NodeType.
1325//
Chris Lattner394471f2003-01-23 22:05:33 +00001326void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001327 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001328 if (Flags & DSGraph::MarkFormalArgs)
1329 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1330 FI != E; ++FI) {
1331 Function &F = *FI->first;
1332 if (F.getName() != "main")
1333 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001334 if (isPointerType(I->getType()))
1335 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001336 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001337
1338 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001339 if (!shouldPrintAuxCalls())
1340 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1341 markIncomplete(FunctionCalls[i]);
1342 else
1343 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1344 markIncomplete(AuxFunctionCalls[i]);
1345
Chris Lattner0d9bab82002-07-18 00:12:30 +00001346
Chris Lattner93d7a212003-02-09 18:41:49 +00001347 // Mark all global nodes as incomplete...
1348 if ((Flags & DSGraph::IgnoreGlobals) == 0)
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001349 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1350 if ((*NI)->isGlobalNode() && (*NI)->getNumLinks())
1351 markIncompleteNode(*NI);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001352}
1353
Chris Lattneraa8146f2002-11-10 06:59:55 +00001354static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1355 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001356 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001357 // No interesting info?
1358 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001359 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001360 Edge.setNode(0); // Kill the edge!
1361}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001362
Chris Lattneraa8146f2002-11-10 06:59:55 +00001363static inline bool nodeContainsExternalFunction(const DSNode *N) {
1364 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1365 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1366 if (Globals[i]->isExternal())
1367 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001368 return false;
1369}
1370
Chris Lattner5a540632003-06-30 03:15:25 +00001371static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001372 // Remove trivially identical function calls
1373 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001374 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1375
Chris Lattner0b144872004-01-27 22:03:40 +00001376#if 1
Chris Lattneraa8146f2002-11-10 06:59:55 +00001377 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001378 DSNode *LastCalleeNode = 0;
1379 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001380 unsigned NumDuplicateCalls = 0;
1381 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001382 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001383 DSCallSite &CS = Calls[i];
1384
Chris Lattnere4258442002-11-11 21:35:38 +00001385 // If the Callee is a useless edge, this must be an unreachable call site,
1386 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001387 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001388 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001389#ifndef NDEBUG
Chris Lattner923fc052003-02-05 21:59:58 +00001390 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001391#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001392 CS.swap(Calls.back());
1393 Calls.pop_back();
1394 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001395 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001396 // If the return value or any arguments point to a void node with no
1397 // information at all in it, and the call node is the only node to point
1398 // to it, remove the edge to the node (killing the node).
1399 //
1400 killIfUselessEdge(CS.getRetVal());
1401 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1402 killIfUselessEdge(CS.getPtrArg(a));
1403
1404 // If this call site calls the same function as the last call site, and if
1405 // the function pointer contains an external function, this node will
1406 // never be resolved. Merge the arguments of the call node because no
1407 // information will be lost.
1408 //
Chris Lattner923fc052003-02-05 21:59:58 +00001409 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1410 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001411 ++NumDuplicateCalls;
1412 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001413 if (LastCalleeNode)
1414 LastCalleeContainsExternalFunction =
1415 nodeContainsExternalFunction(LastCalleeNode);
1416 else
1417 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001418 }
Chris Lattner0b144872004-01-27 22:03:40 +00001419
1420 // It is not clear why, but enabling this code makes DSA really
1421 // sensitive to node forwarding. Basically, with this enabled, DSA
1422 // performs different number of inlinings based on which nodes are
1423 // forwarding or not. This is clearly a problem, so this code is
1424 // disabled until this can be resolved.
Chris Lattner58f98d02003-07-02 04:38:49 +00001425#if 1
Chris Lattner0b144872004-01-27 22:03:40 +00001426 if (LastCalleeContainsExternalFunction
1427#if 0
1428 ||
Chris Lattnere4258442002-11-11 21:35:38 +00001429 // This should be more than enough context sensitivity!
1430 // FIXME: Evaluate how many times this is tripped!
Chris Lattner0b144872004-01-27 22:03:40 +00001431 NumDuplicateCalls > 20
1432#endif
1433 ) {
Chris Lattnere4258442002-11-11 21:35:38 +00001434 DSCallSite &OCS = Calls[i-1];
1435 OCS.mergeWith(CS);
1436
1437 // The node will now be eliminated as a duplicate!
1438 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1439 CS = OCS;
1440 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1441 OCS = CS;
1442 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001443#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001444 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001445 if (CS.isDirectCall()) {
1446 LastCalleeFunc = CS.getCalleeFunc();
1447 LastCalleeNode = 0;
1448 } else {
1449 LastCalleeNode = CS.getCalleeNode();
1450 LastCalleeFunc = 0;
1451 }
Chris Lattnere4258442002-11-11 21:35:38 +00001452 NumDuplicateCalls = 0;
1453 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001454 }
1455 }
Chris Lattner0b144872004-01-27 22:03:40 +00001456#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001457 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001458
Chris Lattner33312f72002-11-08 01:21:07 +00001459 // Track the number of call nodes merged away...
1460 NumCallNodesMerged += NumFns-Calls.size();
1461
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001462 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001463 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001464}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001465
Chris Lattneraa8146f2002-11-10 06:59:55 +00001466
Chris Lattnere2219762002-07-18 18:22:40 +00001467// removeTriviallyDeadNodes - After the graph has been constructed, this method
1468// removes all unreachable nodes that are created because they got merged with
1469// other nodes in the graph. These nodes will all be trivially unreachable, so
1470// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001471//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001472void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001473 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001474
Chris Lattnerbab8c282003-09-20 21:34:07 +00001475 // Loop over all of the nodes in the graph, calling getNode on each field.
1476 // This will cause all nodes to update their forwarding edges, causing
1477 // forwarded nodes to be delete-able.
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001478 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1479 DSNode *N = *NI;
Chris Lattnerbab8c282003-09-20 21:34:07 +00001480 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1481 N->getLink(l*N->getPointerSize()).getNode();
1482 }
1483
Chris Lattner0b144872004-01-27 22:03:40 +00001484 // NOTE: This code is disabled. Though it should, in theory, allow us to
1485 // remove more nodes down below, the scan of the scalar map is incredibly
1486 // expensive for certain programs (with large SCCs). In the future, if we can
1487 // make the scalar map scan more efficient, then we can reenable this.
1488#if 0
1489 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1490
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001491 // Likewise, forward any edges from the scalar nodes. While we are at it,
1492 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001493 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001494 I->second.getNode();
1495 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001496 }
Chris Lattner0b144872004-01-27 22:03:40 +00001497 }
1498#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001499 bool isGlobalsGraph = !GlobalsGraph;
1500
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001501 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001502 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001503
1504 // Do not remove *any* global nodes in the globals graph.
1505 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001506 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001507 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001508 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001509 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001510
Chris Lattner28897e12004-02-08 00:53:26 +00001511 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001512 // This is a useless node if it has no mod/ref info (checked above),
1513 // outgoing edges (which it cannot, as it is not modified in this
1514 // context), and it has no incoming edges. If it is a global node it may
1515 // have all of these properties and still have incoming edges, due to the
1516 // scalar map, so we check those now.
1517 //
Chris Lattner28897e12004-02-08 00:53:26 +00001518 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1519 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001520
Chris Lattner17a93e22004-01-29 03:32:15 +00001521 // Loop through and make sure all of the globals are referring directly
1522 // to the node...
1523 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1524 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001525 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001526 }
1527
Chris Lattnerbd92b732003-06-19 21:15:11 +00001528 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001529 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001530 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1531 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001532 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001533 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001534 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001535 }
1536 }
1537
Chris Lattner28897e12004-02-08 00:53:26 +00001538 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001539 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001540 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001541 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001542 } else {
1543 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001544 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001545 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001546
1547 removeIdenticalCalls(FunctionCalls);
1548 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001549}
1550
1551
Chris Lattner5c7380e2003-01-29 21:10:20 +00001552/// markReachableNodes - This method recursively traverses the specified
1553/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1554/// to the set, which allows it to only traverse visited nodes once.
1555///
Chris Lattner41c04f72003-02-01 04:52:08 +00001556void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001557 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001558 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001559 if (ReachableNodes.insert(this).second) // Is newly reachable?
1560 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1561 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001562}
1563
Chris Lattner41c04f72003-02-01 04:52:08 +00001564void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001565 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001566 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001567
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001568 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1569 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001570}
1571
Chris Lattnera1220af2003-02-01 06:17:02 +00001572// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1573// looking for a node that is marked alive. If an alive node is found, return
1574// true, otherwise return false. If an alive node is reachable, this node is
1575// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001576//
Chris Lattnera1220af2003-02-01 06:17:02 +00001577static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001578 hash_set<DSNode*> &Visited,
1579 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001580 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001581 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001582
Chris Lattner85cfe012003-07-03 02:03:53 +00001583 // If this is a global node, it will end up in the globals graph anyway, so we
1584 // don't need to worry about it.
1585 if (IgnoreGlobals && N->isGlobalNode()) return false;
1586
Chris Lattneraa8146f2002-11-10 06:59:55 +00001587 // If we know that this node is alive, return so!
1588 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001589
Chris Lattneraa8146f2002-11-10 06:59:55 +00001590 // Otherwise, we don't think the node is alive yet, check for infinite
1591 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001592 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001593 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001594
Chris Lattner08db7192002-11-06 06:20:27 +00001595 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001596 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1597 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001598 N->markReachableNodes(Alive);
1599 return true;
1600 }
1601 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001602}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001603
Chris Lattnera1220af2003-02-01 06:17:02 +00001604// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1605// alive nodes.
1606//
Chris Lattner41c04f72003-02-01 04:52:08 +00001607static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001608 hash_set<DSNode*> &Visited,
1609 bool IgnoreGlobals) {
1610 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1611 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001612 return true;
1613 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001614 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001615 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001616 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001617 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1618 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001619 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001620 return false;
1621}
1622
Chris Lattnere2219762002-07-18 18:22:40 +00001623// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1624// subgraphs that are unreachable. This often occurs because the data
1625// structure doesn't "escape" into it's caller, and thus should be eliminated
1626// from the caller's graph entirely. This is only appropriate to use when
1627// inlining graphs.
1628//
Chris Lattner394471f2003-01-23 22:05:33 +00001629void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001630 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001631
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001632 // Reduce the amount of work we have to do... remove dummy nodes left over by
1633 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001634 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001635
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001636 TIME_REGION(X, "removeDeadNodes");
1637
Misha Brukman2f2d0652003-09-11 18:14:24 +00001638 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001639
1640 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001641 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001642 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001643
Chris Lattner0b144872004-01-27 22:03:40 +00001644 // Copy and merge all information about globals to the GlobalsGraph if this is
1645 // not a final pass (where unreachable globals are removed).
1646 //
1647 // Strip all alloca bits since the current function is only for the BU pass.
1648 // Strip all incomplete bits since they are short-lived properties and they
1649 // will be correctly computed when rematerializing nodes into the functions.
1650 //
1651 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1652 DSGraph::StripIncompleteBit);
1653
Chris Lattneraa8146f2002-11-10 06:59:55 +00001654 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner00948c02004-01-28 02:05:05 +00001655 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
Chris Lattner62482e52004-01-28 09:15:42 +00001656 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001657 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001658 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001659 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001660 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001661
1662 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001663 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1664 DSGraph::ScalarMapTy::iterator SMI =
1665 GlobalsGraph->getScalarMap().find(I->first);
1666 if (SMI != GlobalsGraph->getScalarMap().end())
1667 GGCloner.merge(SMI->second, I->second);
1668 else
1669 GGCloner.getClonedNH(I->second);
1670 }
Chris Lattner0b144872004-01-27 22:03:40 +00001671 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001672 } else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001673 DSNode *N = I->second.getNode();
1674#if 0
Chris Lattner0b144872004-01-27 22:03:40 +00001675 // Check to see if this is a worthless node generated for non-pointer
1676 // values, such as integers. Consider an addition of long types: A+B.
1677 // Assuming we can track all uses of the value in this context, and it is
1678 // NOT used as a pointer, we can delete the node. We will be able to
1679 // detect this situation if the node pointed to ONLY has Unknown bit set
1680 // in the node. In this case, the node is not incomplete, does not point
1681 // to any other nodes (no mod/ref bits set), and is therefore
1682 // uninteresting for data structure analysis. If we run across one of
1683 // these, prune the scalar pointing to it.
1684 //
Chris Lattner0b144872004-01-27 22:03:40 +00001685 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1686 ScalarMap.erase(I++);
1687 else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001688#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001689 N->markReachableNodes(Alive);
1690 ++I;
Chris Lattnera88a55c2004-01-28 02:41:32 +00001691 //}
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001692 }
Chris Lattner00948c02004-01-28 02:05:05 +00001693 }
Chris Lattnere2219762002-07-18 18:22:40 +00001694
Chris Lattner0b144872004-01-27 22:03:40 +00001695 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001696 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1697 I != E; ++I)
1698 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001699
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001700 // Mark any nodes reachable by primary calls as alive...
1701 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1702 FunctionCalls[i].markReachableNodes(Alive);
1703
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001704
1705 // Now find globals and aux call nodes that are already live or reach a live
1706 // value (which makes them live in turn), and continue till no more are found.
1707 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001708 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001709 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001710 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1711 do {
1712 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001713 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001714 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001715 // unreachable globals in the list.
1716 //
1717 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001718 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001719 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1720 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1721 Flags & DSGraph::RemoveUnreachableGlobals)) {
1722 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1723 GlobalNodes.pop_back(); // erase efficiently
1724 Iterate = true;
1725 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001726
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001727 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1728 // call nodes that get resolved will be difficult to remove from that graph.
1729 // The final unresolved call nodes must be handled specially at the end of
1730 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001731 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1732 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001733 (AuxFunctionCalls[i].isIndirectCall()
1734 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1735 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001736 AuxFunctionCalls[i].markReachableNodes(Alive);
1737 AuxFCallsAlive[i] = true;
1738 Iterate = true;
1739 }
1740 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001741
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001742 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001743 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001744 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1745 if (AuxFCallsAlive[i])
1746 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001747
1748 // Copy and merge all global nodes and dead aux call nodes into the
1749 // GlobalsGraph, and all nodes reachable from those nodes
1750 //
1751 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001752 // Copy the unreachable call nodes to the globals graph, updating their
1753 // target pointers using the GGCloner
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001754 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1755 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
Chris Lattner0b144872004-01-27 22:03:40 +00001756 GGCloner));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001757 }
1758 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001759 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1760 AuxFunctionCalls.end());
1761
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001762 // We are finally done with the GGCloner so we can destroy it.
1763 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001764
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001765 // At this point, any nodes which are visited, but not alive, are nodes
1766 // which can be removed. Loop over all nodes, eliminating completely
1767 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001768 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001769 std::vector<DSNode*> DeadNodes;
1770 DeadNodes.reserve(Nodes.size());
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001771 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;)
Chris Lattner28897e12004-02-08 00:53:26 +00001772 if (!Alive.count(NI)) {
Chris Lattnere92e7642004-02-07 23:58:05 +00001773 ++NumDNE;
Chris Lattner28897e12004-02-08 00:53:26 +00001774 DSNode *N = Nodes.remove(NI++);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001775 DeadNodes.push_back(N);
1776 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001777 } else {
Chris Lattner28897e12004-02-08 00:53:26 +00001778 assert(NI->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001779 ++NI;
Chris Lattnere2219762002-07-18 18:22:40 +00001780 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001781
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001782 // Remove all unreachable globals from the ScalarMap.
1783 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1784 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001785 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001786 if (!Alive.count(GlobalNodes[i].second))
1787 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00001788 else
1789 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001790
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001791 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001792 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1793 delete DeadNodes[i];
1794
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001795 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001796}
1797
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001798void DSGraph::AssertGraphOK() const {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001799 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1800 (*NI)->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001801
Chris Lattner8d327672003-06-30 03:36:09 +00001802 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001803 E = ScalarMap.end(); I != E; ++I) {
1804 assert(I->second.getNode() && "Null node in scalarmap!");
1805 AssertNodeInGraph(I->second.getNode());
1806 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001807 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001808 "Global points to node, but node isn't global?");
1809 AssertNodeContainsGlobal(I->second.getNode(), GV);
1810 }
1811 }
1812 AssertCallNodesInGraph();
1813 AssertAuxCallNodesInGraph();
1814}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001815
Chris Lattner400433d2003-11-11 05:08:59 +00001816/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1817/// nodes reachable from the two graphs, computing the mapping of nodes from
1818/// the first to the second graph.
1819///
1820void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001821 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1822 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001823 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1824 if (N1 == 0 || N2 == 0) return;
1825
1826 DSNodeHandle &Entry = NodeMap[N1];
1827 if (Entry.getNode()) {
1828 // Termination of recursion!
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001829 assert(!StrictChecking ||
1830 (Entry.getNode() == N2 &&
1831 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
Chris Lattner400433d2003-11-11 05:08:59 +00001832 "Inconsistent mapping detected!");
1833 return;
1834 }
1835
1836 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001837 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001838
1839 // Loop over all of the fields that N1 and N2 have in common, recursively
1840 // mapping the edges together now.
1841 int N2Idx = NH2.getOffset()-NH1.getOffset();
1842 unsigned N2Size = N2->getSize();
1843 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1844 if (unsigned(N2Idx)+i < N2Size)
1845 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1846}