blob: 179f286378f497457d991c77d17ea558bbd47d0a [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 Lattner4dabb2c2004-07-07 06:32:21 +000014#include "llvm/Analysis/DataStructure/DSGraphTraits.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000015#include "llvm/Function.h"
Chris Lattnercf14e712004-02-25 23:36:08 +000016#include "llvm/GlobalVariable.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000017#include "llvm/Instructions.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000018#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000019#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000020#include "llvm/Assembly/Writer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000021#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/Debug.h"
23#include "llvm/ADT/DepthFirstIterator.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000027#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000028using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000029
Chris Lattner08db7192002-11-06 06:20:27 +000030namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000031 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
32 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
33 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
34 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000035 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
36 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Chris Lattner08db7192002-11-06 06:20:27 +000037};
38
Chris Lattnera88a55c2004-01-28 02:41:32 +000039#if 1
Chris Lattner93ddd7e2004-01-22 16:36:28 +000040#define TIME_REGION(VARNAME, DESC) \
41 NamedRegionTimer VARNAME(DESC)
42#else
43#define TIME_REGION(VARNAME, DESC)
44#endif
45
Chris Lattnerb1060432002-11-07 05:20:53 +000046using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000047
Chris Lattner6f967742004-10-30 04:05:01 +000048/// isForwarding - Return true if this NodeHandle is forwarding to another
49/// one.
50bool DSNodeHandle::isForwarding() const {
51 return N && N->isForwarding();
52}
53
Chris Lattner731b2d72003-02-13 19:09:00 +000054DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000055 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000056
57 // Handle node forwarding here!
58 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
59 Offset += N->ForwardNH.getOffset();
60
61 if (--N->NumReferrers == 0) {
62 // Removing the last referrer to the node, sever the forwarding link
63 N->stopForwarding();
64 }
65
66 N = Next;
67 N->NumReferrers++;
68 if (N->Size <= Offset) {
69 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
70 Offset = 0;
71 }
72 return N;
73}
74
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000075//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000076// DSNode Implementation
77//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000078
Chris Lattnerbd92b732003-06-19 21:15:11 +000079DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000080 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000081 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000082 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +000083 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000084 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000085}
86
Chris Lattner0d9bab82002-07-18 00:12:30 +000087// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +000088DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +000089 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattnerf590ced2004-03-04 17:06:53 +000090 Ty(N.Ty), NodeType(N.NodeType) {
91 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +000092 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +000093 Globals = N.Globals;
94 } else
Chris Lattner0b144872004-01-27 22:03:40 +000095 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +000096 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000097 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +000098}
99
Chris Lattner15869aa2003-11-02 22:27:28 +0000100/// getTargetData - Get the target data object used to construct this node.
101///
102const TargetData &DSNode::getTargetData() const {
103 return ParentGraph->getTargetData();
104}
105
Chris Lattner72d29a42003-02-11 23:11:51 +0000106void DSNode::assertOK() const {
107 assert((Ty != Type::VoidTy ||
108 Ty == Type::VoidTy && (Size == 0 ||
109 (NodeType & DSNode::Array))) &&
110 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000111
112 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000113 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000114 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnera88a55c2004-01-28 02:41:32 +0000115 assert(SM.count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000116 assert(SM.find(Globals[i])->second.getNode() == this);
117 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000118}
119
120/// forwardNode - Mark this node as being obsolete, and all references to it
121/// should be forwarded to the specified node and offset.
122///
123void DSNode::forwardNode(DSNode *To, unsigned Offset) {
124 assert(this != To && "Cannot forward a node to itself!");
125 assert(ForwardNH.isNull() && "Already forwarding from this node!");
126 if (To->Size <= 1) Offset = 0;
127 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
128 "Forwarded offset is wrong!");
Chris Lattnerefffdc92004-07-07 06:12:52 +0000129 ForwardNH.setTo(To, Offset);
Chris Lattner72d29a42003-02-11 23:11:51 +0000130 NodeType = DEAD;
131 Size = 0;
132 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000133
134 // Remove this node from the parent graph's Nodes list.
135 ParentGraph->unlinkNode(this);
136 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000137}
138
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000139// addGlobal - Add an entry for a global value to the Globals list. This also
140// marks the node with the 'G' flag if it does not already have it.
141//
142void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000143 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000144 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000145 std::lower_bound(Globals.begin(), Globals.end(), GV);
146
147 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000148 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000149 Globals.insert(I, GV);
150 NodeType |= GlobalNode;
151 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000152}
153
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000154/// foldNodeCompletely - If we determine that this node has some funny
155/// behavior happening to it that we cannot represent, we fold it down to a
156/// single, completely pessimistic, node. This node is represented as a
157/// single byte with a single TypeEntry of "void".
158///
159void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000160 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000161
Chris Lattner08db7192002-11-06 06:20:27 +0000162 ++NumFolds;
163
Chris Lattner0b144872004-01-27 22:03:40 +0000164 // If this node has a size that is <= 1, we don't need to create a forwarding
165 // node.
166 if (getSize() <= 1) {
167 NodeType |= DSNode::Array;
168 Ty = Type::VoidTy;
169 Size = 1;
170 assert(Links.size() <= 1 && "Size is 1, but has more links?");
171 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000172 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000173 // Create the node we are going to forward to. This is required because
174 // some referrers may have an offset that is > 0. By forcing them to
175 // forward, the forwarder has the opportunity to correct the offset.
176 DSNode *DestNode = new DSNode(0, ParentGraph);
177 DestNode->NodeType = NodeType|DSNode::Array;
178 DestNode->Ty = Type::VoidTy;
179 DestNode->Size = 1;
180 DestNode->Globals.swap(Globals);
181
182 // Start forwarding to the destination node...
183 forwardNode(DestNode, 0);
184
185 if (!Links.empty()) {
186 DestNode->Links.reserve(1);
187
188 DSNodeHandle NH(DestNode);
189 DestNode->Links.push_back(Links[0]);
190
191 // If we have links, merge all of our outgoing links together...
192 for (unsigned i = Links.size()-1; i != 0; --i)
193 NH.getNode()->Links[0].mergeWith(Links[i]);
194 Links.clear();
195 } else {
196 DestNode->Links.resize(1);
197 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000198 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000199}
Chris Lattner076c1f92002-11-07 06:31:54 +0000200
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000201/// isNodeCompletelyFolded - Return true if this node has been completely
202/// folded down to something that can never be expanded, effectively losing
203/// all of the field sensitivity that may be present in the node.
204///
205bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000206 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000207}
208
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000209namespace {
210 /// TypeElementWalker Class - Used for implementation of physical subtyping...
211 ///
212 class TypeElementWalker {
213 struct StackState {
214 const Type *Ty;
215 unsigned Offset;
216 unsigned Idx;
217 StackState(const Type *T, unsigned Off = 0)
218 : Ty(T), Offset(Off), Idx(0) {}
219 };
220
221 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000222 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000223 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000224 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000225 Stack.push_back(T);
226 StepToLeaf();
227 }
228
229 bool isDone() const { return Stack.empty(); }
230 const Type *getCurrentType() const { return Stack.back().Ty; }
231 unsigned getCurrentOffset() const { return Stack.back().Offset; }
232
233 void StepToNextType() {
234 PopStackAndAdvance();
235 StepToLeaf();
236 }
237
238 private:
239 /// PopStackAndAdvance - Pop the current element off of the stack and
240 /// advance the underlying element to the next contained member.
241 void PopStackAndAdvance() {
242 assert(!Stack.empty() && "Cannot pop an empty stack!");
243 Stack.pop_back();
244 while (!Stack.empty()) {
245 StackState &SS = Stack.back();
246 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
247 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000248 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000249 const StructLayout *SL = TD.getStructLayout(ST);
250 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
251 return;
252 }
253 Stack.pop_back(); // At the end of the structure
254 } else {
255 const ArrayType *AT = cast<ArrayType>(SS.Ty);
256 ++SS.Idx;
257 if (SS.Idx != AT->getNumElements()) {
258 SS.Offset += TD.getTypeSize(AT->getElementType());
259 return;
260 }
261 Stack.pop_back(); // At the end of the array
262 }
263 }
264 }
265
266 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
267 /// on the type stack.
268 void StepToLeaf() {
269 if (Stack.empty()) return;
270 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
271 StackState &SS = Stack.back();
272 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000273 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000274 assert(SS.Idx == 0);
275 PopStackAndAdvance();
276 } else {
277 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000278 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000279 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000280 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000281 SS.Offset+SL->MemberOffsets[SS.Idx]));
282 }
283 } else {
284 const ArrayType *AT = cast<ArrayType>(SS.Ty);
285 if (AT->getNumElements() == 0) {
286 assert(SS.Idx == 0);
287 PopStackAndAdvance();
288 } else {
289 // Step into the array...
290 assert(SS.Idx < AT->getNumElements());
291 Stack.push_back(StackState(AT->getElementType(),
292 SS.Offset+SS.Idx*
293 TD.getTypeSize(AT->getElementType())));
294 }
295 }
296 }
297 }
298 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000299} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000300
301/// ElementTypesAreCompatible - Check to see if the specified types are
302/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000303/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
304/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000305///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000306static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000307 bool AllowLargerT1, const TargetData &TD){
308 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000309
310 while (!T1W.isDone() && !T2W.isDone()) {
311 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
312 return false;
313
314 const Type *T1 = T1W.getCurrentType();
315 const Type *T2 = T2W.getCurrentType();
316 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
317 return false;
318
319 T1W.StepToNextType();
320 T2W.StepToNextType();
321 }
322
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000323 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000324}
325
326
Chris Lattner08db7192002-11-06 06:20:27 +0000327/// mergeTypeInfo - This method merges the specified type into the current node
328/// at the specified offset. This may update the current node's type record if
329/// this gives more information to the node, it may do nothing to the node if
330/// this information is already known, or it may merge the node completely (and
331/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000332///
Chris Lattner08db7192002-11-06 06:20:27 +0000333/// This method returns true if the node is completely folded, otherwise false.
334///
Chris Lattner088b6392003-03-03 17:13:31 +0000335bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
336 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000337 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000338 // Check to make sure the Size member is up-to-date. Size can be one of the
339 // following:
340 // Size = 0, Ty = Void: Nothing is known about this node.
341 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
342 // Size = 1, Ty = Void, Array = 1: The node is collapsed
343 // Otherwise, sizeof(Ty) = Size
344 //
Chris Lattner18552922002-11-18 21:44:46 +0000345 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
346 (Size == 0 && !Ty->isSized() && !isArray()) ||
347 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
348 (Size == 0 && !Ty->isSized() && !isArray()) ||
349 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000350 "Size member of DSNode doesn't match the type structure!");
351 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000352
Chris Lattner18552922002-11-18 21:44:46 +0000353 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000354 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000355
Chris Lattner08db7192002-11-06 06:20:27 +0000356 // Return true immediately if the node is completely folded.
357 if (isNodeCompletelyFolded()) return true;
358
Chris Lattner23f83dc2002-11-08 22:49:57 +0000359 // If this is an array type, eliminate the outside arrays because they won't
360 // be used anyway. This greatly reduces the size of large static arrays used
361 // as global variables, for example.
362 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000363 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000364 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
365 // FIXME: we might want to keep small arrays, but must be careful about
366 // things like: [2 x [10000 x int*]]
367 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000368 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000369 }
370
Chris Lattner08db7192002-11-06 06:20:27 +0000371 // Figure out how big the new type we're merging in is...
372 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
373
374 // Otherwise check to see if we can fold this type into the current node. If
375 // we can't, we fold the node completely, if we can, we potentially update our
376 // internal state.
377 //
Chris Lattner18552922002-11-18 21:44:46 +0000378 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000379 // If this is the first type that this node has seen, just accept it without
380 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000381 assert(Offset == 0 && !isArray() &&
382 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000383 Ty = NewTy;
384 NodeType &= ~Array;
385 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000386 Size = NewTySize;
387
388 // Calculate the number of outgoing links from this node.
389 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
390 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000391 }
Chris Lattner08db7192002-11-06 06:20:27 +0000392
393 // Handle node expansion case here...
394 if (Offset+NewTySize > Size) {
395 // It is illegal to grow this node if we have treated it as an array of
396 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000397 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000398 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000399 return true;
400 }
401
402 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000403 std::cerr << "UNIMP: Trying to merge a growth type into "
404 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000405 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000406 return true;
407 }
408
409 // Okay, the situation is nice and simple, we are trying to merge a type in
410 // at offset 0 that is bigger than our current type. Implement this by
411 // switching to the new type and then merge in the smaller one, which should
412 // hit the other code path here. If the other code path decides it's not
413 // ok, it will collapse the node as appropriate.
414 //
Chris Lattner18552922002-11-18 21:44:46 +0000415 const Type *OldTy = Ty;
416 Ty = NewTy;
417 NodeType &= ~Array;
418 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000419 Size = NewTySize;
420
421 // Must grow links to be the appropriate size...
422 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
423
424 // Merge in the old type now... which is guaranteed to be smaller than the
425 // "current" type.
426 return mergeTypeInfo(OldTy, 0);
427 }
428
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000429 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000430 "Cannot merge something into a part of our type that doesn't exist!");
431
Chris Lattner18552922002-11-18 21:44:46 +0000432 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000433 // type that starts at offset Offset.
434 //
435 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000436 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000437 while (O < Offset) {
438 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
439
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000440 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000441 case Type::StructTyID: {
442 const StructType *STy = cast<StructType>(SubType);
443 const StructLayout &SL = *TD.getStructLayout(STy);
444
445 unsigned i = 0, e = SL.MemberOffsets.size();
446 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
447 /* empty */;
448
449 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000450 SubType = STy->getElementType(i);
Chris Lattner08db7192002-11-06 06:20:27 +0000451 O += SL.MemberOffsets[i];
452 break;
453 }
454 case Type::ArrayTyID: {
455 SubType = cast<ArrayType>(SubType)->getElementType();
456 unsigned ElSize = TD.getTypeSize(SubType);
457 unsigned Remainder = (Offset-O) % ElSize;
458 O = Offset-Remainder;
459 break;
460 }
461 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000462 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000463 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000464 }
465 }
466
467 assert(O == Offset && "Could not achieve the correct offset!");
468
469 // If we found our type exactly, early exit
470 if (SubType == NewTy) return false;
471
Misha Brukman96a8bd72004-04-29 04:05:30 +0000472 // Differing function types don't require us to merge. They are not values
473 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000474 if (isa<FunctionType>(SubType) &&
475 isa<FunctionType>(NewTy)) return false;
476
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000477 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
478
479 // Ok, we are getting desperate now. Check for physical subtyping, where we
480 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000481 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000482 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000483 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000484 return false;
485
Chris Lattner08db7192002-11-06 06:20:27 +0000486 // Okay, so we found the leader type at the offset requested. Search the list
487 // of types that starts at this offset. If SubType is currently an array or
488 // structure, the type desired may actually be the first element of the
489 // composite type...
490 //
Chris Lattner18552922002-11-18 21:44:46 +0000491 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000492 while (SubType != NewTy) {
493 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000494 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000495 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000496 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000497 case Type::StructTyID: {
498 const StructType *STy = cast<StructType>(SubType);
499 const StructLayout &SL = *TD.getStructLayout(STy);
500 if (SL.MemberOffsets.size() > 1)
501 NextPadSize = SL.MemberOffsets[1];
502 else
503 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000504 NextSubType = STy->getElementType(0);
Chris Lattner18552922002-11-18 21:44:46 +0000505 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000506 break;
Chris Lattner18552922002-11-18 21:44:46 +0000507 }
Chris Lattner08db7192002-11-06 06:20:27 +0000508 case Type::ArrayTyID:
509 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000510 NextSubTypeSize = TD.getTypeSize(NextSubType);
511 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000512 break;
513 default: ;
514 // fall out
515 }
516
517 if (NextSubType == 0)
518 break; // In the default case, break out of the loop
519
Chris Lattner18552922002-11-18 21:44:46 +0000520 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000521 break; // Don't allow shrinking to a smaller type than NewTySize
522 SubType = NextSubType;
523 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000524 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000525 }
526
527 // If we found the type exactly, return it...
528 if (SubType == NewTy)
529 return false;
530
531 // Check to see if we have a compatible, but different type...
532 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000533 // Check to see if this type is obviously convertible... int -> uint f.e.
534 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000535 return false;
536
537 // Check to see if we have a pointer & integer mismatch going on here,
538 // loading a pointer as a long, for example.
539 //
540 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
541 NewTy->isInteger() && isa<PointerType>(SubType))
542 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000543 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
544 // We are accessing the field, plus some structure padding. Ignore the
545 // structure padding.
546 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000547 }
548
Chris Lattner58f98d02003-07-02 04:38:49 +0000549 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000550 if (getParentGraph()->getReturnNodes().size())
551 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000552 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
553 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
554 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
555 << "SubType: ";
556 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000557
Chris Lattner088b6392003-03-03 17:13:31 +0000558 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000559 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000560}
561
Chris Lattner08db7192002-11-06 06:20:27 +0000562
563
Misha Brukman96a8bd72004-04-29 04:05:30 +0000564/// addEdgeTo - Add an edge from the current node to the specified node. This
565/// can cause merging of nodes in the graph.
566///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000567void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000568 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000569
Chris Lattner08db7192002-11-06 06:20:27 +0000570 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000571 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000572 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000573 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000574 } else { // No merging to perform...
575 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000576 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000577}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000578
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000579
Misha Brukman96a8bd72004-04-29 04:05:30 +0000580/// MergeSortedVectors - Efficiently merge a vector into another vector where
581/// duplicates are not allowed and both are sorted. This assumes that 'T's are
582/// efficiently copyable and have sane comparison semantics.
583///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000584static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
585 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000586 // By far, the most common cases will be the simple ones. In these cases,
587 // avoid having to allocate a temporary vector...
588 //
589 if (Src.empty()) { // Nothing to merge in...
590 return;
591 } else if (Dest.empty()) { // Just copy the result in...
592 Dest = Src;
593 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000594 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000595 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000596 std::lower_bound(Dest.begin(), Dest.end(), V);
597 if (I == Dest.end() || *I != Src[0]) // If not already contained...
598 Dest.insert(I, Src[0]);
599 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000600 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000601 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000602 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000603 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
604 if (I == Dest.end() || *I != Tmp) // If not already contained...
605 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000606
607 } else {
608 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000609 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000610
611 // Make space for all of the type entries now...
612 Dest.resize(Dest.size()+Src.size());
613
614 // Merge the two sorted ranges together... into Dest.
615 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
616
617 // Now erase any duplicate entries that may have accumulated into the
618 // vectors (because they were in both of the input sets)
619 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
620 }
621}
622
Chris Lattner0b144872004-01-27 22:03:40 +0000623void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
624 MergeSortedVectors(Globals, RHS);
625}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000626
Chris Lattner0b144872004-01-27 22:03:40 +0000627// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000628// This function does the hard work of merging two nodes, CurNodeH
629// and NH after filtering out trivial cases and making sure that
630// CurNodeH.offset >= NH.offset.
631//
632// ***WARNING***
633// Since merging may cause either node to go away, we must always
634// use the node-handles to refer to the nodes. These node handles are
635// automatically updated during merging, so will always provide access
636// to the correct node after a merge.
637//
638void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
639 assert(CurNodeH.getOffset() >= NH.getOffset() &&
640 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000641 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
642 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000643
644 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
645 // respect to NH.Offset) is now zero. NOffset is the distance from the base
646 // of our object that N starts from.
647 //
648 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
649 unsigned NSize = NH.getNode()->getSize();
650
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000651 // If the two nodes are of different size, and the smaller node has the array
652 // bit set, collapse!
653 if (NSize != CurNodeH.getNode()->getSize()) {
654 if (NSize < CurNodeH.getNode()->getSize()) {
655 if (NH.getNode()->isArray())
656 NH.getNode()->foldNodeCompletely();
657 } else if (CurNodeH.getNode()->isArray()) {
658 NH.getNode()->foldNodeCompletely();
659 }
660 }
661
662 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000663 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000664 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000665 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000666
667 // If we are merging a node with a completely folded node, then both nodes are
668 // now completely folded.
669 //
670 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
671 if (!NH.getNode()->isNodeCompletelyFolded()) {
672 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000673 assert(NH.getNode() && NH.getOffset() == 0 &&
674 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000675 NOffset = NH.getOffset();
676 NSize = NH.getNode()->getSize();
677 assert(NOffset == 0 && NSize == 1);
678 }
679 } else if (NH.getNode()->isNodeCompletelyFolded()) {
680 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000681 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
682 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000683 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000684 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000685 assert(NOffset == 0 && NSize == 1);
686 }
687
Chris Lattner72d29a42003-02-11 23:11:51 +0000688 DSNode *N = NH.getNode();
689 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000690 assert(!CurNodeH.getNode()->isDeadNode());
691
Chris Lattner0b144872004-01-27 22:03:40 +0000692 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000693 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000694
Chris Lattner72d29a42003-02-11 23:11:51 +0000695 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000696 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000697 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000698
Chris Lattner72d29a42003-02-11 23:11:51 +0000699 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
700 //
701 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
702 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000703 if (Link.getNode()) {
704 // Compute the offset into the current node at which to
705 // merge this link. In the common case, this is a linear
706 // relation to the offset in the original node (with
707 // wrapping), but if the current node gets collapsed due to
708 // recursive merging, we must make sure to merge in all remaining
709 // links at offset zero.
710 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000711 DSNode *CN = CurNodeH.getNode();
712 if (CN->Size != 1)
713 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
714 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000715 }
716 }
717
718 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000719 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000720
721 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000722 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000723 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000724
725 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000726 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000727 }
728}
729
730
Misha Brukman96a8bd72004-04-29 04:05:30 +0000731/// mergeWith - Merge this node and the specified node, moving all links to and
732/// from the argument node into the current node, deleting the node argument.
733/// Offset indicates what offset the specified node is to be merged into the
734/// current node.
735///
736/// The specified node may be a null pointer (in which case, we update it to
737/// point to this node).
738///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000739void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
740 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000741 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000742 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000743
Chris Lattner5254a8d2004-01-22 16:31:08 +0000744 // If the RHS is a null node, make it point to this node!
745 if (N == 0) {
746 NH.mergeWith(DSNodeHandle(this, Offset));
747 return;
748 }
749
Chris Lattnerbd92b732003-06-19 21:15:11 +0000750 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000751 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
752
Chris Lattner02606632002-11-04 06:48:26 +0000753 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000754 // We cannot merge two pieces of the same node together, collapse the node
755 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000756 DEBUG(std::cerr << "Attempting to merge two chunks of"
757 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000758 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000759 return;
760 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000761
Chris Lattner5190ce82002-11-12 07:20:45 +0000762 // If both nodes are not at offset 0, make sure that we are merging the node
763 // at an later offset into the node with the zero offset.
764 //
765 if (Offset < NH.getOffset()) {
766 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
767 return;
768 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
769 // If the offsets are the same, merge the smaller node into the bigger node
770 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
771 return;
772 }
773
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000774 // Ok, now we can merge the two nodes. Use a static helper that works with
775 // two node handles, since "this" may get merged away at intermediate steps.
776 DSNodeHandle CurNodeH(this, Offset);
777 DSNodeHandle NHCopy(NH);
778 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000779}
780
Chris Lattner0b144872004-01-27 22:03:40 +0000781
782//===----------------------------------------------------------------------===//
783// ReachabilityCloner Implementation
784//===----------------------------------------------------------------------===//
785
786DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
787 if (SrcNH.isNull()) return DSNodeHandle();
788 const DSNode *SN = SrcNH.getNode();
789
790 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000791 if (!NH.isNull()) { // Node already mapped?
792 DSNode *NHN = NH.getNode();
793 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
794 }
Chris Lattner0b144872004-01-27 22:03:40 +0000795
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000796 // If SrcNH has globals and the destination graph has one of the same globals,
797 // merge this node with the destination node, which is much more efficient.
798 if (SN->global_begin() != SN->global_end()) {
799 DSScalarMap &DestSM = Dest.getScalarMap();
800 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
801 I != E; ++I) {
802 GlobalValue *GV = *I;
803 DSScalarMap::iterator GI = DestSM.find(GV);
804 if (GI != DestSM.end() && !GI->second.isNull()) {
805 // We found one, use merge instead!
806 merge(GI->second, Src.getNodeForValue(GV));
807 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000808 DSNode *NHN = NH.getNode();
809 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000810 }
811 }
812 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000813
Chris Lattner0b144872004-01-27 22:03:40 +0000814 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
815 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000816 NH = DN;
Chris Lattner0b144872004-01-27 22:03:40 +0000817
818 // Next, recursively clone all outgoing links as necessary. Note that
819 // adding these links can cause the node to collapse itself at any time, and
820 // the current node may be merged with arbitrary other nodes. For this
821 // reason, we must always go through NH.
822 DN = 0;
823 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
824 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
825 if (!SrcEdge.isNull()) {
826 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
827 // Compute the offset into the current node at which to
828 // merge this link. In the common case, this is a linear
829 // relation to the offset in the original node (with
830 // wrapping), but if the current node gets collapsed due to
831 // recursive merging, we must make sure to merge in all remaining
832 // links at offset zero.
833 unsigned MergeOffset = 0;
834 DSNode *CN = NH.getNode();
835 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +0000836 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +0000837 CN->addEdgeTo(MergeOffset, DestEdge);
838 }
839 }
840
841 // If this node contains any globals, make sure they end up in the scalar
842 // map with the correct offset.
843 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
844 I != E; ++I) {
845 GlobalValue *GV = *I;
846 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
847 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
848 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
849 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000850 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000851
852 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
853 Dest.getInlinedGlobals().insert(GV);
854 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000855 NH.getNode()->mergeGlobals(SN->getGlobals());
Chris Lattner0b144872004-01-27 22:03:40 +0000856
857 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
858}
859
860void ReachabilityCloner::merge(const DSNodeHandle &NH,
861 const DSNodeHandle &SrcNH) {
862 if (SrcNH.isNull()) return; // Noop
863 if (NH.isNull()) {
864 // If there is no destination node, just clone the source and assign the
865 // destination node to be it.
866 NH.mergeWith(getClonedNH(SrcNH));
867 return;
868 }
869
870 // Okay, at this point, we know that we have both a destination and a source
871 // node that need to be merged. Check to see if the source node has already
872 // been cloned.
873 const DSNode *SN = SrcNH.getNode();
874 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +0000875 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +0000876 DSNode *SCNHN = SCNH.getNode();
877 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +0000878 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000879 return; // Nothing to do!
880 }
Chris Lattner6f967742004-10-30 04:05:01 +0000881
Chris Lattner0b144872004-01-27 22:03:40 +0000882 // Okay, so the source node has not already been cloned. Instead of creating
883 // a new DSNode, only to merge it into the one we already have, try to perform
884 // the merge in-place. The only case we cannot handle here is when the offset
885 // into the existing node is less than the offset into the virtual node we are
886 // merging in. In this case, we have to extend the existing node, which
887 // requires an allocation anyway.
888 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
889 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000890 if (!DN->isNodeCompletelyFolded()) {
891 // Make sure the destination node is folded if the source node is folded.
892 if (SN->isNodeCompletelyFolded()) {
893 DN->foldNodeCompletely();
894 DN = NH.getNode();
895 } else if (SN->getSize() != DN->getSize()) {
896 // If the two nodes are of different size, and the smaller node has the
897 // array bit set, collapse!
898 if (SN->getSize() < DN->getSize()) {
899 if (SN->isArray()) {
900 DN->foldNodeCompletely();
901 DN = NH.getNode();
902 }
903 } else if (DN->isArray()) {
904 DN->foldNodeCompletely();
905 DN = NH.getNode();
906 }
907 }
908
909 // Merge the type entries of the two nodes together...
910 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
911 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
912 DN = NH.getNode();
913 }
914 }
915
916 assert(!DN->isDeadNode());
917
918 // Merge the NodeType information.
919 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
920
921 // Before we start merging outgoing links and updating the scalar map, make
922 // sure it is known that this is the representative node for the src node.
923 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
924
925 // If the source node contains any globals, make sure they end up in the
926 // scalar map with the correct offset.
927 if (SN->global_begin() != SN->global_end()) {
928 // Update the globals in the destination node itself.
929 DN->mergeGlobals(SN->getGlobals());
930
931 // Update the scalar map for the graph we are merging the source node
932 // into.
933 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
934 I != E; ++I) {
935 GlobalValue *GV = *I;
936 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
937 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
938 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
939 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +0000940 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000941
942 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
943 Dest.getInlinedGlobals().insert(GV);
944 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000945 NH.getNode()->mergeGlobals(SN->getGlobals());
Chris Lattner0b144872004-01-27 22:03:40 +0000946 }
947 } else {
948 // We cannot handle this case without allocating a temporary node. Fall
949 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +0000950 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
951 NewDN->maskNodeTypes(BitsToKeep);
952
953 unsigned NHOffset = NH.getOffset();
954 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +0000955
Chris Lattner0b144872004-01-27 22:03:40 +0000956 assert(NH.getNode() &&
957 (NH.getOffset() > NHOffset ||
958 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
959 "Merging did not adjust the offset!");
960
961 // Before we start merging outgoing links and updating the scalar map, make
962 // sure it is known that this is the representative node for the src node.
963 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +0000964
965 // If the source node contained any globals, make sure to create entries
966 // in the scalar map for them!
967 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
968 I != E; ++I) {
969 GlobalValue *GV = *I;
970 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
971 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
972 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
973 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
974 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
975 DestGNH.getOffset()+SrcGNH.getOffset()));
976
977 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
978 Dest.getInlinedGlobals().insert(GV);
979 }
Chris Lattner0b144872004-01-27 22:03:40 +0000980 }
981
982
983 // Next, recursively merge all outgoing links as necessary. Note that
984 // adding these links can cause the destination node to collapse itself at
985 // any time, and the current node may be merged with arbitrary other nodes.
986 // For this reason, we must always go through NH.
987 DN = 0;
988 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
989 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
990 if (!SrcEdge.isNull()) {
991 // Compute the offset into the current node at which to
992 // merge this link. In the common case, this is a linear
993 // relation to the offset in the original node (with
994 // wrapping), but if the current node gets collapsed due to
995 // recursive merging, we must make sure to merge in all remaining
996 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +0000997 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +0000998 unsigned MergeOffset =
999 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +00001000
Chris Lattnerf590ced2004-03-04 17:06:53 +00001001 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1002 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001003 // Perform the recursive merging. Make sure to create a temporary NH,
1004 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001005 merge(Tmp, SrcEdge);
1006 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001007 Tmp.mergeWith(getClonedNH(SrcEdge));
1008 // Merging this could cause all kinds of recursive things to happen,
1009 // culminating in the current node being eliminated. Since this is
1010 // possible, make sure to reaquire the link from 'CN'.
1011
1012 unsigned MergeOffset = 0;
1013 CN = SCNH.getNode();
1014 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1015 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001016 }
Chris Lattner0b144872004-01-27 22:03:40 +00001017 }
1018 }
1019}
1020
1021/// mergeCallSite - Merge the nodes reachable from the specified src call
1022/// site into the nodes reachable from DestCS.
1023void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
1024 const DSCallSite &SrcCS) {
1025 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1026 unsigned MinArgs = DestCS.getNumPtrArgs();
1027 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1028
1029 for (unsigned a = 0; a != MinArgs; ++a)
1030 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1031}
1032
1033
Chris Lattner9de906c2002-10-20 22:11:44 +00001034//===----------------------------------------------------------------------===//
1035// DSCallSite Implementation
1036//===----------------------------------------------------------------------===//
1037
Vikram S. Adve26b98262002-10-20 21:41:02 +00001038// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001039Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001040 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001041}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001042
Chris Lattner0b144872004-01-27 22:03:40 +00001043void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1044 ReachabilityCloner &RC) {
1045 NH = RC.getClonedNH(Src);
1046}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001047
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001048//===----------------------------------------------------------------------===//
1049// DSGraph Implementation
1050//===----------------------------------------------------------------------===//
1051
Chris Lattnera9d65662003-06-30 05:57:30 +00001052/// getFunctionNames - Return a space separated list of the name of the
1053/// functions in this graph (if any)
1054std::string DSGraph::getFunctionNames() const {
1055 switch (getReturnNodes().size()) {
1056 case 0: return "Globals graph";
1057 case 1: return getReturnNodes().begin()->first->getName();
1058 default:
1059 std::string Return;
1060 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1061 I != getReturnNodes().end(); ++I)
1062 Return += I->first->getName() + " ";
1063 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1064 return Return;
1065 }
1066}
1067
1068
Chris Lattner15869aa2003-11-02 22:27:28 +00001069DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001070 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001071 NodeMapTy NodeMap;
1072 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001073}
1074
Chris Lattner5a540632003-06-30 03:15:25 +00001075DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001076 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001077 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001078 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001079}
1080
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001081DSGraph::~DSGraph() {
1082 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001083 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001084 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001085 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001086 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001087
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001088 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001089 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1090 (*NI)->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001091
Chris Lattner28897e12004-02-08 00:53:26 +00001092 // Free all of the nodes.
1093 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001094}
1095
Chris Lattner0d9bab82002-07-18 00:12:30 +00001096// dump - Allow inspection of graph in a debugger.
1097void DSGraph::dump() const { print(std::cerr); }
1098
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001099
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001100/// remapLinks - Change all of the Links in the current node according to the
1101/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001102///
Chris Lattner8d327672003-06-30 03:36:09 +00001103void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001104 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1105 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001106 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001107 if (ONMI != OldNodeMap.end()) {
1108 DSNode *ONMIN = ONMI->second.getNode();
1109 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1110 }
Chris Lattner2f561382004-01-22 16:56:13 +00001111 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001112}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001113
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001114/// updateFromGlobalGraph - This function rematerializes global nodes and
1115/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001116/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1117/// are already up-to-date in the current graph. In practice, in the TD pass,
1118/// this is likely to be a large fraction of the live global nodes in each
1119/// function (since most live nodes are likely to have been brought up-to-date
1120/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001121///
1122void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001123 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001124 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1125
1126 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001127 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1128 E = getScalarMap().global_end(); I != E; ++I)
1129 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001130 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001131 if (It != GlobalsGraph->ScalarMap.end())
1132 RC.merge(getNodeForValue(*I), It->second);
1133 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001134}
1135
Chris Lattner5a540632003-06-30 03:15:25 +00001136/// cloneInto - Clone the specified DSGraph into the current graph. The
1137/// translated ScalarMap for the old function is filled into the OldValMap
1138/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1139///
1140/// The CloneFlags member controls various aspects of the cloning process.
1141///
Chris Lattner62482e52004-01-28 09:15:42 +00001142void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001143 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1144 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001145 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001146 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001147 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001148
Chris Lattner1e883692003-02-03 20:08:51 +00001149 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001150 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1151 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1152 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001153 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001154
Chris Lattnerd85645f2004-02-21 22:28:26 +00001155 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1156 assert(!(*I)->isForwarding() &&
1157 "Forward nodes shouldn't be in node list!");
1158 DSNode *New = new DSNode(**I, this);
1159 New->maskNodeTypes(~BitsToClear);
1160 OldNodeMap[*I] = New;
1161 }
1162
Chris Lattner18552922002-11-18 21:44:46 +00001163#ifndef NDEBUG
1164 Timer::addPeakMemoryMeasurement();
1165#endif
Chris Lattnerd85645f2004-02-21 22:28:26 +00001166
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001167 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001168 // Note that we don't loop over the node's list to do this. The problem is
1169 // that remaping links can cause recursive merging to happen, which means
1170 // that node_iterator's can get easily invalidated! Because of this, we
1171 // loop over the OldNodeMap, which contains all of the new nodes as the
1172 // .second element of the map elements. Also note that if we remap a node
1173 // more than once, we won't break anything.
1174 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1175 I != E; ++I)
1176 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001177
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001178 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001179 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001180 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001181 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001182 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner6f967742004-10-30 04:05:01 +00001183 DSNode *MappedNodeN = MappedNode.getNode();
1184 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001185 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001186
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001187 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001188 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1189 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001190 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1191 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001192 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001193 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001194
Chris Lattner679e8e12002-11-08 21:27:12 +00001195 if (!(CloneFlags & DontCloneCallNodes)) {
1196 // Copy the function calls list...
1197 unsigned FC = FunctionCalls.size(); // FirstCall
1198 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1199 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1200 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001201 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001202
Chris Lattneracf491f2002-11-08 22:27:09 +00001203 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +00001204 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +00001205 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +00001206 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1207 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1208 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1209 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001210
Chris Lattner5a540632003-06-30 03:15:25 +00001211 // Map the return node pointers over...
1212 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1213 E = G.getReturnNodes().end(); I != E; ++I) {
1214 const DSNodeHandle &Ret = I->second;
1215 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001216 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattner5a540632003-06-30 03:15:25 +00001217 OldReturnNodes.insert(std::make_pair(I->first,
Chris Lattner6f967742004-10-30 04:05:01 +00001218 DSNodeHandle(MappedRetN,
Chris Lattner5a540632003-06-30 03:15:25 +00001219 MappedRet.getOffset()+Ret.getOffset())));
1220 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001221}
1222
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001223static bool PathExistsToClonedNode(const DSNode *N, ReachabilityCloner &RC) {
Chris Lattner2f346902004-03-04 03:57:53 +00001224 if (N)
1225 for (df_iterator<const DSNode*> I = df_begin(N), E = df_end(N); I != E; ++I)
1226 if (RC.hasClonedNode(*I))
1227 return true;
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001228 return false;
1229}
1230
Chris Lattner2f346902004-03-04 03:57:53 +00001231static bool PathExistsToClonedNode(const DSCallSite &CS,
1232 ReachabilityCloner &RC) {
1233 if (PathExistsToClonedNode(CS.getRetVal().getNode(), RC))
1234 return true;
1235 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1236 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode(), RC))
1237 return true;
1238 return false;
1239}
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001240
Chris Lattner076c1f92002-11-07 06:31:54 +00001241/// mergeInGraph - The method is used for merging graphs together. If the
1242/// argument graph is not *this, it makes a clone of the specified graph, then
1243/// merges the nodes specified in the call site with the formal arguments in the
1244/// graph.
1245///
Chris Lattner9f930552003-06-30 05:27:18 +00001246void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1247 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001248 TIME_REGION(X, "mergeInGraph");
1249
Chris Lattner2c7725a2004-03-03 20:55:27 +00001250 // Fastpath for a noop inline.
1251 if (CS.getNumPtrArgs() == 0 && CS.getRetVal().isNull())
1252 return;
1253
Chris Lattner076c1f92002-11-07 06:31:54 +00001254 // If this is not a recursive call, clone the graph into this graph...
1255 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001256 // Clone the callee's graph into the current graph, keeping track of where
1257 // scalars in the old graph _used_ to point, and of the new nodes matching
1258 // nodes of the old graph.
1259 ReachabilityCloner RC(*this, Graph, CloneFlags);
1260
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001261 // Set up argument bindings
1262 Function::aiterator AI = F.abegin();
1263 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1264 // Advance the argument iterator to the first pointer argument...
1265 while (AI != F.aend() && !isPointerType(AI->getType())) {
1266 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001267#ifndef NDEBUG // FIXME: We should merge vararg arguments!
1268 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001269 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001270#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001271 }
1272 if (AI == F.aend()) break;
1273
1274 // Add the link from the argument scalar to the provided value.
Chris Lattner0b144872004-01-27 22:03:40 +00001275 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
Chris Lattner076c1f92002-11-07 06:31:54 +00001276 }
1277
Chris Lattner0b144872004-01-27 22:03:40 +00001278 // Map the return node pointer over.
Chris Lattner0ad91702004-02-22 00:53:54 +00001279 if (!CS.getRetVal().isNull())
Chris Lattner0b144872004-01-27 22:03:40 +00001280 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
Chris Lattnerf590ced2004-03-04 17:06:53 +00001281
Chris Lattner2f346902004-03-04 03:57:53 +00001282 // If requested, copy all of the calls.
Chris Lattner0b144872004-01-27 22:03:40 +00001283 if (!(CloneFlags & DontCloneCallNodes)) {
1284 // Copy the function calls list...
1285 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1286 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1287 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1288 }
Chris Lattner2f346902004-03-04 03:57:53 +00001289
1290 // If the user has us copying aux calls (the normal case), set up a data
1291 // structure to keep track of which ones we've copied over.
1292 std::vector<bool> CopiedAuxCall;
Chris Lattner0b144872004-01-27 22:03:40 +00001293 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001294 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1295 Graph.AuxFunctionCalls.size());
Chris Lattner2f346902004-03-04 03:57:53 +00001296 CopiedAuxCall.resize(Graph.AuxFunctionCalls.size());
Chris Lattner0b144872004-01-27 22:03:40 +00001297 }
1298
Chris Lattner0321b682004-02-27 20:05:15 +00001299 // Clone over all globals that appear in the caller and callee graphs.
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001300 hash_set<GlobalVariable*> NonCopiedGlobals;
Chris Lattner0321b682004-02-27 20:05:15 +00001301 for (DSScalarMap::global_iterator GI = Graph.getScalarMap().global_begin(),
1302 E = Graph.getScalarMap().global_end(); GI != E; ++GI)
1303 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*GI))
1304 if (ScalarMap.count(GV))
1305 RC.merge(ScalarMap[GV], Graph.getNodeForValue(GV));
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001306 else
1307 NonCopiedGlobals.insert(GV);
1308
1309 // If the global does not appear in the callers graph we generally don't
1310 // want to copy the node. However, if there is a path from the node global
1311 // node to a node that we did copy in the graph, we *must* copy it to
1312 // maintain the connection information. Every time we decide to include a
1313 // new global, this might make other globals live, so we must iterate
1314 // unfortunately.
Chris Lattner2f346902004-03-04 03:57:53 +00001315 bool MadeChange = true;
1316 while (MadeChange) {
1317 MadeChange = false;
1318 for (hash_set<GlobalVariable*>::iterator I = NonCopiedGlobals.begin();
1319 I != NonCopiedGlobals.end();) {
1320 DSNode *GlobalNode = Graph.getNodeForValue(*I).getNode();
1321 if (RC.hasClonedNode(GlobalNode)) {
1322 // Already cloned it, remove from set.
1323 NonCopiedGlobals.erase(I++);
1324 MadeChange = true;
1325 } else if (PathExistsToClonedNode(GlobalNode, RC)) {
1326 RC.getClonedNH(Graph.getNodeForValue(*I));
1327 NonCopiedGlobals.erase(I++);
1328 MadeChange = true;
1329 } else {
1330 ++I;
1331 }
1332 }
1333
1334 // If requested, copy any aux calls that can reach copied nodes.
1335 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1336 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1337 if (!CopiedAuxCall[i] &&
1338 PathExistsToClonedNode(Graph.AuxFunctionCalls[i], RC)) {
1339 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i],
1340 RC));
1341 CopiedAuxCall[i] = true;
1342 MadeChange = true;
1343 }
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001344 }
1345 }
1346
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001347 } else {
1348 DSNodeHandle RetVal = getReturnNodeFor(F);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001349
1350 // Merge the return value with the return value of the context...
1351 RetVal.mergeWith(CS.getRetVal());
1352
1353 // Resolve all of the function arguments...
1354 Function::aiterator AI = F.abegin();
1355
1356 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1357 // Advance the argument iterator to the first pointer argument...
1358 while (AI != F.aend() && !isPointerType(AI->getType())) {
1359 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001360#ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1361 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001362 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1363#endif
1364 }
1365 if (AI == F.aend()) break;
1366
1367 // Add the link from the argument scalar to the provided value
Chris Lattner0b144872004-01-27 22:03:40 +00001368 DSNodeHandle &NH = getNodeForValue(AI);
Chris Lattner6f967742004-10-30 04:05:01 +00001369 assert(!NH.isNull() && "Pointer argument without scalarmap entry?");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001370 NH.mergeWith(CS.getPtrArg(i));
1371 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001372 }
1373}
1374
Chris Lattner58f98d02003-07-02 04:38:49 +00001375/// getCallSiteForArguments - Get the arguments and return value bindings for
1376/// the specified function in the current graph.
1377///
1378DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1379 std::vector<DSNodeHandle> Args;
1380
1381 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1382 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001383 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001384
Chris Lattner808a7ae2003-09-20 16:34:13 +00001385 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001386}
1387
Chris Lattner85fb1be2004-03-09 19:37:06 +00001388/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1389/// the context of this graph, return the DSCallSite for it.
1390DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1391 DSNodeHandle RetVal;
1392 Instruction *I = CS.getInstruction();
1393 if (isPointerType(I->getType()))
1394 RetVal = getNodeForValue(I);
1395
1396 std::vector<DSNodeHandle> Args;
1397 Args.reserve(CS.arg_end()-CS.arg_begin());
1398
1399 // Calculate the arguments vector...
1400 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1401 if (isPointerType((*I)->getType()))
1402 Args.push_back(getNodeForValue(*I));
1403
1404 // Add a new function call entry...
1405 if (Function *F = CS.getCalledFunction())
1406 return DSCallSite(CS, RetVal, F, Args);
1407 else
1408 return DSCallSite(CS, RetVal,
1409 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1410}
1411
Chris Lattner58f98d02003-07-02 04:38:49 +00001412
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001413
Chris Lattner0d9bab82002-07-18 00:12:30 +00001414// markIncompleteNodes - Mark the specified node as having contents that are not
1415// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001416// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001417// must recursively traverse the data structure graph, marking all reachable
1418// nodes as incomplete.
1419//
1420static void markIncompleteNode(DSNode *N) {
1421 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001422 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001423
1424 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001425 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001426
Misha Brukman2f2d0652003-09-11 18:14:24 +00001427 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001428 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1429 if (DSNode *DSN = N->getLink(i).getNode())
1430 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001431}
1432
Chris Lattnere71ffc22002-11-11 03:36:55 +00001433static void markIncomplete(DSCallSite &Call) {
1434 // Then the return value is certainly incomplete!
1435 markIncompleteNode(Call.getRetVal().getNode());
1436
1437 // All objects pointed to by function arguments are incomplete!
1438 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1439 markIncompleteNode(Call.getPtrArg(i).getNode());
1440}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001441
1442// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1443// modified by other functions that have not been resolved yet. This marks
1444// nodes that are reachable through three sources of "unknownness":
1445//
1446// Global Variables, Function Calls, and Incoming Arguments
1447//
1448// For any node that may have unknown components (because something outside the
1449// scope of current analysis may have modified it), the 'Incomplete' flag is
1450// added to the NodeType.
1451//
Chris Lattner394471f2003-01-23 22:05:33 +00001452void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001453 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001454 if (Flags & DSGraph::MarkFormalArgs)
1455 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1456 FI != E; ++FI) {
1457 Function &F = *FI->first;
1458 if (F.getName() != "main")
1459 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001460 if (isPointerType(I->getType()))
1461 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001462 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001463
1464 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001465 if (!shouldPrintAuxCalls())
1466 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1467 markIncomplete(FunctionCalls[i]);
1468 else
1469 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1470 markIncomplete(AuxFunctionCalls[i]);
1471
Chris Lattner0d9bab82002-07-18 00:12:30 +00001472
Chris Lattner93d7a212003-02-09 18:41:49 +00001473 // Mark all global nodes as incomplete...
1474 if ((Flags & DSGraph::IgnoreGlobals) == 0)
Chris Lattner51c06ab2004-02-25 23:08:00 +00001475 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1476 E = ScalarMap.global_end(); I != E; ++I)
Chris Lattnercf14e712004-02-25 23:36:08 +00001477 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
Chris Lattnerd84d3502004-03-08 03:52:24 +00001478 if (!GV->isConstant() || !GV->hasInitializer())
Chris Lattnercf14e712004-02-25 23:36:08 +00001479 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001480}
1481
Chris Lattneraa8146f2002-11-10 06:59:55 +00001482static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1483 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001484 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001485 // No interesting info?
1486 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001487 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001488 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001489}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001490
Chris Lattneraa8146f2002-11-10 06:59:55 +00001491static inline bool nodeContainsExternalFunction(const DSNode *N) {
1492 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1493 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
Chris Lattner857eb062004-10-30 05:41:23 +00001494 if (Globals[i]->isExternal() && isa<Function>(Globals[i]))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001495 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001496 return false;
1497}
1498
Chris Lattner5a540632003-06-30 03:15:25 +00001499static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001500 // Remove trivially identical function calls
1501 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001502 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1503
Chris Lattner0b144872004-01-27 22:03:40 +00001504#if 1
Chris Lattneraa8146f2002-11-10 06:59:55 +00001505 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001506 DSNode *LastCalleeNode = 0;
1507 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001508 unsigned NumDuplicateCalls = 0;
1509 bool LastCalleeContainsExternalFunction = false;
Chris Lattner857eb062004-10-30 05:41:23 +00001510
1511 std::vector<unsigned> CallsToDelete;
1512
Chris Lattnere4258442002-11-11 21:35:38 +00001513 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001514 DSCallSite &CS = Calls[i];
1515
Chris Lattnere4258442002-11-11 21:35:38 +00001516 // If the Callee is a useless edge, this must be an unreachable call site,
1517 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001518 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerabcdf802004-02-26 03:43:43 +00001519 CS.getCalleeNode()->isComplete() &&
Chris Lattneraf6926a2004-02-26 03:45:03 +00001520 CS.getCalleeNode()->getGlobals().empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001521#ifndef NDEBUG
Chris Lattnerabcdf802004-02-26 03:43:43 +00001522 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001523#endif
Chris Lattner857eb062004-10-30 05:41:23 +00001524 CallsToDelete.push_back(i);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001525 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001526 // If the return value or any arguments point to a void node with no
1527 // information at all in it, and the call node is the only node to point
1528 // to it, remove the edge to the node (killing the node).
1529 //
1530 killIfUselessEdge(CS.getRetVal());
1531 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1532 killIfUselessEdge(CS.getPtrArg(a));
1533
1534 // If this call site calls the same function as the last call site, and if
1535 // the function pointer contains an external function, this node will
1536 // never be resolved. Merge the arguments of the call node because no
1537 // information will be lost.
1538 //
Chris Lattner923fc052003-02-05 21:59:58 +00001539 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1540 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001541 ++NumDuplicateCalls;
1542 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001543 if (LastCalleeNode)
1544 LastCalleeContainsExternalFunction =
1545 nodeContainsExternalFunction(LastCalleeNode);
1546 else
1547 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001548 }
Chris Lattner0b144872004-01-27 22:03:40 +00001549
1550 // It is not clear why, but enabling this code makes DSA really
1551 // sensitive to node forwarding. Basically, with this enabled, DSA
1552 // performs different number of inlinings based on which nodes are
1553 // forwarding or not. This is clearly a problem, so this code is
1554 // disabled until this can be resolved.
Chris Lattner58f98d02003-07-02 04:38:49 +00001555#if 1
Chris Lattner0b144872004-01-27 22:03:40 +00001556 if (LastCalleeContainsExternalFunction
1557#if 0
1558 ||
Chris Lattnere4258442002-11-11 21:35:38 +00001559 // This should be more than enough context sensitivity!
1560 // FIXME: Evaluate how many times this is tripped!
Chris Lattner0b144872004-01-27 22:03:40 +00001561 NumDuplicateCalls > 20
1562#endif
1563 ) {
Chris Lattnere4258442002-11-11 21:35:38 +00001564 DSCallSite &OCS = Calls[i-1];
1565 OCS.mergeWith(CS);
1566
Chris Lattner857eb062004-10-30 05:41:23 +00001567 // No need to keep this call anymore.
1568 CallsToDelete.push_back(i);
Chris Lattnere4258442002-11-11 21:35:38 +00001569 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001570#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001571 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001572 if (CS.isDirectCall()) {
1573 LastCalleeFunc = CS.getCalleeFunc();
1574 LastCalleeNode = 0;
1575 } else {
1576 LastCalleeNode = CS.getCalleeNode();
1577 LastCalleeFunc = 0;
1578 }
Chris Lattnere4258442002-11-11 21:35:38 +00001579 NumDuplicateCalls = 0;
1580 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001581 }
1582 }
Chris Lattner0b144872004-01-27 22:03:40 +00001583#endif
Chris Lattner857eb062004-10-30 05:41:23 +00001584
1585 unsigned NumDeleted = 0;
1586 for (unsigned i = 0, e = CallsToDelete.size(); i != e; ++i)
1587 Calls.erase(Calls.begin()+CallsToDelete[i]-NumDeleted++);
1588
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001589 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001590
Chris Lattner33312f72002-11-08 01:21:07 +00001591 // Track the number of call nodes merged away...
1592 NumCallNodesMerged += NumFns-Calls.size();
1593
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001594 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001595 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001596}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001597
Chris Lattneraa8146f2002-11-10 06:59:55 +00001598
Chris Lattnere2219762002-07-18 18:22:40 +00001599// removeTriviallyDeadNodes - After the graph has been constructed, this method
1600// removes all unreachable nodes that are created because they got merged with
1601// other nodes in the graph. These nodes will all be trivially unreachable, so
1602// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001603//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001604void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001605 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001606
Chris Lattner5ace1e42004-07-08 07:25:51 +00001607#if 0
1608 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1609 /// substantially!
1610
Chris Lattnerbab8c282003-09-20 21:34:07 +00001611 // Loop over all of the nodes in the graph, calling getNode on each field.
1612 // This will cause all nodes to update their forwarding edges, causing
1613 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001614 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001615 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1616 DSNode *N = *NI;
Chris Lattnerbab8c282003-09-20 21:34:07 +00001617 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1618 N->getLink(l*N->getPointerSize()).getNode();
1619 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001620 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001621
Chris Lattner0b144872004-01-27 22:03:40 +00001622 // NOTE: This code is disabled. Though it should, in theory, allow us to
1623 // remove more nodes down below, the scan of the scalar map is incredibly
1624 // expensive for certain programs (with large SCCs). In the future, if we can
1625 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001626 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1627
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001628 // Likewise, forward any edges from the scalar nodes. While we are at it,
1629 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001630 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001631 I->second.getNode();
1632 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001633 }
Chris Lattner0b144872004-01-27 22:03:40 +00001634 }
1635#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001636 bool isGlobalsGraph = !GlobalsGraph;
1637
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001638 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001639 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001640
1641 // Do not remove *any* global nodes in the globals graph.
1642 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001643 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001644 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001645 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001646 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001647
Chris Lattner28897e12004-02-08 00:53:26 +00001648 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001649 // This is a useless node if it has no mod/ref info (checked above),
1650 // outgoing edges (which it cannot, as it is not modified in this
1651 // context), and it has no incoming edges. If it is a global node it may
1652 // have all of these properties and still have incoming edges, due to the
1653 // scalar map, so we check those now.
1654 //
Chris Lattner28897e12004-02-08 00:53:26 +00001655 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1656 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001657
Chris Lattner17a93e22004-01-29 03:32:15 +00001658 // Loop through and make sure all of the globals are referring directly
1659 // to the node...
1660 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1661 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001662 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001663 }
1664
Chris Lattnerbd92b732003-06-19 21:15:11 +00001665 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001666 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001667 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1668 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001669 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001670 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001671 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001672 }
1673 }
1674
Chris Lattner28897e12004-02-08 00:53:26 +00001675 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001676 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001677 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001678 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001679 } else {
1680 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001681 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001682 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001683
1684 removeIdenticalCalls(FunctionCalls);
1685 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001686}
1687
1688
Chris Lattner5c7380e2003-01-29 21:10:20 +00001689/// markReachableNodes - This method recursively traverses the specified
1690/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1691/// to the set, which allows it to only traverse visited nodes once.
1692///
Chris Lattner41c04f72003-02-01 04:52:08 +00001693void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001694 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001695 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001696 if (ReachableNodes.insert(this).second) // Is newly reachable?
1697 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1698 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001699}
1700
Chris Lattner41c04f72003-02-01 04:52:08 +00001701void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001702 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001703 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001704
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001705 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1706 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001707}
1708
Chris Lattnera1220af2003-02-01 06:17:02 +00001709// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1710// looking for a node that is marked alive. If an alive node is found, return
1711// true, otherwise return false. If an alive node is reachable, this node is
1712// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001713//
Chris Lattnera1220af2003-02-01 06:17:02 +00001714static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001715 hash_set<DSNode*> &Visited,
1716 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001717 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001718 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001719
Chris Lattner85cfe012003-07-03 02:03:53 +00001720 // If this is a global node, it will end up in the globals graph anyway, so we
1721 // don't need to worry about it.
1722 if (IgnoreGlobals && N->isGlobalNode()) return false;
1723
Chris Lattneraa8146f2002-11-10 06:59:55 +00001724 // If we know that this node is alive, return so!
1725 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001726
Chris Lattneraa8146f2002-11-10 06:59:55 +00001727 // Otherwise, we don't think the node is alive yet, check for infinite
1728 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001729 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001730 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001731
Chris Lattner08db7192002-11-06 06:20:27 +00001732 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001733 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1734 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001735 N->markReachableNodes(Alive);
1736 return true;
1737 }
1738 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001739}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001740
Chris Lattnera1220af2003-02-01 06:17:02 +00001741// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1742// alive nodes.
1743//
Chris Lattner41c04f72003-02-01 04:52:08 +00001744static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001745 hash_set<DSNode*> &Visited,
1746 bool IgnoreGlobals) {
1747 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1748 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001749 return true;
1750 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001751 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001752 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001753 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001754 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1755 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001756 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001757 return false;
1758}
1759
Chris Lattnere2219762002-07-18 18:22:40 +00001760// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1761// subgraphs that are unreachable. This often occurs because the data
1762// structure doesn't "escape" into it's caller, and thus should be eliminated
1763// from the caller's graph entirely. This is only appropriate to use when
1764// inlining graphs.
1765//
Chris Lattner394471f2003-01-23 22:05:33 +00001766void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001767 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001768
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001769 // Reduce the amount of work we have to do... remove dummy nodes left over by
1770 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001771 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001772
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001773 TIME_REGION(X, "removeDeadNodes");
1774
Misha Brukman2f2d0652003-09-11 18:14:24 +00001775 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001776
1777 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001778 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001779 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001780
Chris Lattner0b144872004-01-27 22:03:40 +00001781 // Copy and merge all information about globals to the GlobalsGraph if this is
1782 // not a final pass (where unreachable globals are removed).
1783 //
1784 // Strip all alloca bits since the current function is only for the BU pass.
1785 // Strip all incomplete bits since they are short-lived properties and they
1786 // will be correctly computed when rematerializing nodes into the functions.
1787 //
1788 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1789 DSGraph::StripIncompleteBit);
1790
Chris Lattneraa8146f2002-11-10 06:59:55 +00001791 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner00948c02004-01-28 02:05:05 +00001792 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
Chris Lattner62482e52004-01-28 09:15:42 +00001793 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001794 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00001795 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001796 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001797 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001798
1799 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001800 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1801 DSGraph::ScalarMapTy::iterator SMI =
1802 GlobalsGraph->getScalarMap().find(I->first);
1803 if (SMI != GlobalsGraph->getScalarMap().end())
1804 GGCloner.merge(SMI->second, I->second);
1805 else
1806 GGCloner.getClonedNH(I->second);
1807 }
Chris Lattner0b144872004-01-27 22:03:40 +00001808 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001809 } else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001810 DSNode *N = I->second.getNode();
1811#if 0
Chris Lattner0b144872004-01-27 22:03:40 +00001812 // Check to see if this is a worthless node generated for non-pointer
1813 // values, such as integers. Consider an addition of long types: A+B.
1814 // Assuming we can track all uses of the value in this context, and it is
1815 // NOT used as a pointer, we can delete the node. We will be able to
1816 // detect this situation if the node pointed to ONLY has Unknown bit set
1817 // in the node. In this case, the node is not incomplete, does not point
1818 // to any other nodes (no mod/ref bits set), and is therefore
1819 // uninteresting for data structure analysis. If we run across one of
1820 // these, prune the scalar pointing to it.
1821 //
Chris Lattner0b144872004-01-27 22:03:40 +00001822 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1823 ScalarMap.erase(I++);
1824 else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001825#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001826 N->markReachableNodes(Alive);
1827 ++I;
Chris Lattnera88a55c2004-01-28 02:41:32 +00001828 //}
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001829 }
Chris Lattner00948c02004-01-28 02:05:05 +00001830 }
Chris Lattnere2219762002-07-18 18:22:40 +00001831
Chris Lattner0b144872004-01-27 22:03:40 +00001832 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001833 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1834 I != E; ++I)
1835 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001836
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001837 // Mark any nodes reachable by primary calls as alive...
1838 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1839 FunctionCalls[i].markReachableNodes(Alive);
1840
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001841
1842 // Now find globals and aux call nodes that are already live or reach a live
1843 // value (which makes them live in turn), and continue till no more are found.
1844 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001845 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001846 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001847 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1848 do {
1849 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001850 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001851 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001852 // unreachable globals in the list.
1853 //
1854 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001855 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001856 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1857 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1858 Flags & DSGraph::RemoveUnreachableGlobals)) {
1859 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1860 GlobalNodes.pop_back(); // erase efficiently
1861 Iterate = true;
1862 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001863
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001864 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1865 // call nodes that get resolved will be difficult to remove from that graph.
1866 // The final unresolved call nodes must be handled specially at the end of
1867 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001868 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1869 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001870 (AuxFunctionCalls[i].isIndirectCall()
1871 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1872 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001873 AuxFunctionCalls[i].markReachableNodes(Alive);
1874 AuxFCallsAlive[i] = true;
1875 Iterate = true;
1876 }
1877 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001878
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001879 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001880 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001881 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1882 if (AuxFCallsAlive[i])
1883 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001884
1885 // Copy and merge all global nodes and dead aux call nodes into the
1886 // GlobalsGraph, and all nodes reachable from those nodes
1887 //
1888 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001889 // Copy the unreachable call nodes to the globals graph, updating their
1890 // target pointers using the GGCloner
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001891 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1892 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
Chris Lattner0b144872004-01-27 22:03:40 +00001893 GGCloner));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001894 }
1895 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001896 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1897 AuxFunctionCalls.end());
1898
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001899 // We are finally done with the GGCloner so we can destroy it.
1900 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001901
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001902 // At this point, any nodes which are visited, but not alive, are nodes
1903 // which can be removed. Loop over all nodes, eliminating completely
1904 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001905 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001906 std::vector<DSNode*> DeadNodes;
1907 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00001908 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
1909 DSNode *N = NI++;
1910 assert(!N->isForwarding() && "Forwarded node in nodes list?");
1911
1912 if (!Alive.count(N)) {
1913 Nodes.remove(N);
1914 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001915 DeadNodes.push_back(N);
1916 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00001917 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00001918 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00001919 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001920
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001921 // Remove all unreachable globals from the ScalarMap.
1922 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1923 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001924 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001925 if (!Alive.count(GlobalNodes[i].second))
1926 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00001927 else
1928 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001929
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001930 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001931 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1932 delete DeadNodes[i];
1933
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001934 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001935}
1936
Chris Lattner2c7725a2004-03-03 20:55:27 +00001937void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
1938 if (CS.isIndirectCall()) {
1939 AssertNodeInGraph(CS.getCalleeNode());
1940#if 0
1941 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
1942 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
1943 std::cerr << "WARNING: WIERD CALL SITE FOUND!\n";
1944#endif
1945 }
1946 AssertNodeInGraph(CS.getRetVal().getNode());
1947 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
1948 AssertNodeInGraph(CS.getPtrArg(j).getNode());
1949}
1950
1951void DSGraph::AssertCallNodesInGraph() const {
1952 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1953 AssertCallSiteInGraph(FunctionCalls[i]);
1954}
1955void DSGraph::AssertAuxCallNodesInGraph() const {
1956 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1957 AssertCallSiteInGraph(AuxFunctionCalls[i]);
1958}
1959
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001960void DSGraph::AssertGraphOK() const {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001961 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1962 (*NI)->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001963
Chris Lattner8d327672003-06-30 03:36:09 +00001964 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001965 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00001966 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001967 AssertNodeInGraph(I->second.getNode());
1968 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001969 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001970 "Global points to node, but node isn't global?");
1971 AssertNodeContainsGlobal(I->second.getNode(), GV);
1972 }
1973 }
1974 AssertCallNodesInGraph();
1975 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00001976
1977 // Check that all pointer arguments to any functions in this graph have
1978 // destinations.
1979 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
1980 E = ReturnNodes.end();
1981 RI != E; ++RI) {
1982 Function &F = *RI->first;
1983 for (Function::aiterator AI = F.abegin(); AI != F.aend(); ++AI)
1984 if (isPointerType(AI->getType()))
1985 assert(!getNodeForValue(AI).isNull() &&
1986 "Pointer argument must be in the scalar map!");
1987 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001988}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001989
Chris Lattner400433d2003-11-11 05:08:59 +00001990/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00001991/// nodes reachable from the two graphs, computing the mapping of nodes from the
1992/// first to the second graph. This mapping may be many-to-one (i.e. the first
1993/// graph may have multiple nodes representing one node in the second graph),
1994/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00001995///
1996void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001997 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1998 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001999 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2000 if (N1 == 0 || N2 == 0) return;
2001
2002 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002003 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002004 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002005 if (StrictChecking) {
2006 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2007 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2008 Entry.getNode()->isNodeCompletelyFolded()) &&
2009 "Inconsistent mapping detected!");
2010 }
Chris Lattner400433d2003-11-11 05:08:59 +00002011 return;
2012 }
2013
Chris Lattnerefffdc92004-07-07 06:12:52 +00002014 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002015
2016 // Loop over all of the fields that N1 and N2 have in common, recursively
2017 // mapping the edges together now.
2018 int N2Idx = NH2.getOffset()-NH1.getOffset();
2019 unsigned N2Size = N2->getSize();
2020 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
2021 if (unsigned(N2Idx)+i < N2Size)
2022 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
Chris Lattnerb1aaeee2004-03-03 05:34:31 +00002023 else
2024 computeNodeMapping(N1->getLink(i),
2025 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
Chris Lattner400433d2003-11-11 05:08:59 +00002026}