blob: 96284957334e3cf5cda40c9646afaff2dd25f591 [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 Lattnerc4ebdce2004-03-03 22:01:09 +000014#include "llvm/Analysis/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"
Vikram S. Adve26b98262002-10-20 21:41:02 +000017#include "llvm/iOther.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"
Chris Lattner0b144872004-01-27 22:03:40 +000021#include "Support/CommandLine.h"
Chris Lattner6806f562003-08-01 22:15:03 +000022#include "Support/Debug.h"
Chris Lattnerc4ebdce2004-03-03 22:01:09 +000023#include "Support/DepthFirstIterator.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000024#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000025#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000026#include "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 Lattner731b2d72003-02-13 19:09:00 +000048DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000049 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000050
51 // Handle node forwarding here!
52 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
53 Offset += N->ForwardNH.getOffset();
54
55 if (--N->NumReferrers == 0) {
56 // Removing the last referrer to the node, sever the forwarding link
57 N->stopForwarding();
58 }
59
60 N = Next;
61 N->NumReferrers++;
62 if (N->Size <= Offset) {
63 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
64 Offset = 0;
65 }
66 return N;
67}
68
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000069//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000070// DSNode Implementation
71//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000072
Chris Lattnerbd92b732003-06-19 21:15:11 +000073DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000074 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000075 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000076 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +000077 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000078 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000079}
80
Chris Lattner0d9bab82002-07-18 00:12:30 +000081// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +000082DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +000083 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner0b144872004-01-27 22:03:40 +000084 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
85 if (!NullLinks)
86 Links = N.Links;
87 else
88 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +000089 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000090 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +000091}
92
Chris Lattner15869aa2003-11-02 22:27:28 +000093/// getTargetData - Get the target data object used to construct this node.
94///
95const TargetData &DSNode::getTargetData() const {
96 return ParentGraph->getTargetData();
97}
98
Chris Lattner72d29a42003-02-11 23:11:51 +000099void DSNode::assertOK() const {
100 assert((Ty != Type::VoidTy ||
101 Ty == Type::VoidTy && (Size == 0 ||
102 (NodeType & DSNode::Array))) &&
103 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000104
105 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000106 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000107 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnera88a55c2004-01-28 02:41:32 +0000108 assert(SM.count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000109 assert(SM.find(Globals[i])->second.getNode() == this);
110 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000111}
112
113/// forwardNode - Mark this node as being obsolete, and all references to it
114/// should be forwarded to the specified node and offset.
115///
116void DSNode::forwardNode(DSNode *To, unsigned Offset) {
117 assert(this != To && "Cannot forward a node to itself!");
118 assert(ForwardNH.isNull() && "Already forwarding from this node!");
119 if (To->Size <= 1) Offset = 0;
120 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
121 "Forwarded offset is wrong!");
122 ForwardNH.setNode(To);
123 ForwardNH.setOffset(Offset);
124 NodeType = DEAD;
125 Size = 0;
126 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000127
128 // Remove this node from the parent graph's Nodes list.
129 ParentGraph->unlinkNode(this);
130 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000131}
132
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000133// addGlobal - Add an entry for a global value to the Globals list. This also
134// marks the node with the 'G' flag if it does not already have it.
135//
136void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000137 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000138 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000139 std::lower_bound(Globals.begin(), Globals.end(), GV);
140
141 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000142 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000143 Globals.insert(I, GV);
144 NodeType |= GlobalNode;
145 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000146}
147
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000148/// foldNodeCompletely - If we determine that this node has some funny
149/// behavior happening to it that we cannot represent, we fold it down to a
150/// single, completely pessimistic, node. This node is represented as a
151/// single byte with a single TypeEntry of "void".
152///
153void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000154 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000155
Chris Lattner08db7192002-11-06 06:20:27 +0000156 ++NumFolds;
157
Chris Lattner0b144872004-01-27 22:03:40 +0000158 // If this node has a size that is <= 1, we don't need to create a forwarding
159 // node.
160 if (getSize() <= 1) {
161 NodeType |= DSNode::Array;
162 Ty = Type::VoidTy;
163 Size = 1;
164 assert(Links.size() <= 1 && "Size is 1, but has more links?");
165 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000166 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000167 // Create the node we are going to forward to. This is required because
168 // some referrers may have an offset that is > 0. By forcing them to
169 // forward, the forwarder has the opportunity to correct the offset.
170 DSNode *DestNode = new DSNode(0, ParentGraph);
171 DestNode->NodeType = NodeType|DSNode::Array;
172 DestNode->Ty = Type::VoidTy;
173 DestNode->Size = 1;
174 DestNode->Globals.swap(Globals);
175
176 // Start forwarding to the destination node...
177 forwardNode(DestNode, 0);
178
179 if (!Links.empty()) {
180 DestNode->Links.reserve(1);
181
182 DSNodeHandle NH(DestNode);
183 DestNode->Links.push_back(Links[0]);
184
185 // If we have links, merge all of our outgoing links together...
186 for (unsigned i = Links.size()-1; i != 0; --i)
187 NH.getNode()->Links[0].mergeWith(Links[i]);
188 Links.clear();
189 } else {
190 DestNode->Links.resize(1);
191 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000192 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000193}
Chris Lattner076c1f92002-11-07 06:31:54 +0000194
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000195/// isNodeCompletelyFolded - Return true if this node has been completely
196/// folded down to something that can never be expanded, effectively losing
197/// all of the field sensitivity that may be present in the node.
198///
199bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000200 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000201}
202
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000203namespace {
204 /// TypeElementWalker Class - Used for implementation of physical subtyping...
205 ///
206 class TypeElementWalker {
207 struct StackState {
208 const Type *Ty;
209 unsigned Offset;
210 unsigned Idx;
211 StackState(const Type *T, unsigned Off = 0)
212 : Ty(T), Offset(Off), Idx(0) {}
213 };
214
215 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000216 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000217 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000218 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000219 Stack.push_back(T);
220 StepToLeaf();
221 }
222
223 bool isDone() const { return Stack.empty(); }
224 const Type *getCurrentType() const { return Stack.back().Ty; }
225 unsigned getCurrentOffset() const { return Stack.back().Offset; }
226
227 void StepToNextType() {
228 PopStackAndAdvance();
229 StepToLeaf();
230 }
231
232 private:
233 /// PopStackAndAdvance - Pop the current element off of the stack and
234 /// advance the underlying element to the next contained member.
235 void PopStackAndAdvance() {
236 assert(!Stack.empty() && "Cannot pop an empty stack!");
237 Stack.pop_back();
238 while (!Stack.empty()) {
239 StackState &SS = Stack.back();
240 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
241 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000242 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000243 const StructLayout *SL = TD.getStructLayout(ST);
244 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
245 return;
246 }
247 Stack.pop_back(); // At the end of the structure
248 } else {
249 const ArrayType *AT = cast<ArrayType>(SS.Ty);
250 ++SS.Idx;
251 if (SS.Idx != AT->getNumElements()) {
252 SS.Offset += TD.getTypeSize(AT->getElementType());
253 return;
254 }
255 Stack.pop_back(); // At the end of the array
256 }
257 }
258 }
259
260 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
261 /// on the type stack.
262 void StepToLeaf() {
263 if (Stack.empty()) return;
264 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
265 StackState &SS = Stack.back();
266 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000267 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000268 assert(SS.Idx == 0);
269 PopStackAndAdvance();
270 } else {
271 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000272 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000273 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000274 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000275 SS.Offset+SL->MemberOffsets[SS.Idx]));
276 }
277 } else {
278 const ArrayType *AT = cast<ArrayType>(SS.Ty);
279 if (AT->getNumElements() == 0) {
280 assert(SS.Idx == 0);
281 PopStackAndAdvance();
282 } else {
283 // Step into the array...
284 assert(SS.Idx < AT->getNumElements());
285 Stack.push_back(StackState(AT->getElementType(),
286 SS.Offset+SS.Idx*
287 TD.getTypeSize(AT->getElementType())));
288 }
289 }
290 }
291 }
292 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000293} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000294
295/// ElementTypesAreCompatible - Check to see if the specified types are
296/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000297/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
298/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000299///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000300static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000301 bool AllowLargerT1, const TargetData &TD){
302 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000303
304 while (!T1W.isDone() && !T2W.isDone()) {
305 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
306 return false;
307
308 const Type *T1 = T1W.getCurrentType();
309 const Type *T2 = T2W.getCurrentType();
310 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
311 return false;
312
313 T1W.StepToNextType();
314 T2W.StepToNextType();
315 }
316
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000317 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000318}
319
320
Chris Lattner08db7192002-11-06 06:20:27 +0000321/// mergeTypeInfo - This method merges the specified type into the current node
322/// at the specified offset. This may update the current node's type record if
323/// this gives more information to the node, it may do nothing to the node if
324/// this information is already known, or it may merge the node completely (and
325/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000326///
Chris Lattner08db7192002-11-06 06:20:27 +0000327/// This method returns true if the node is completely folded, otherwise false.
328///
Chris Lattner088b6392003-03-03 17:13:31 +0000329bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
330 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000331 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000332 // Check to make sure the Size member is up-to-date. Size can be one of the
333 // following:
334 // Size = 0, Ty = Void: Nothing is known about this node.
335 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
336 // Size = 1, Ty = Void, Array = 1: The node is collapsed
337 // Otherwise, sizeof(Ty) = Size
338 //
Chris Lattner18552922002-11-18 21:44:46 +0000339 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
340 (Size == 0 && !Ty->isSized() && !isArray()) ||
341 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
342 (Size == 0 && !Ty->isSized() && !isArray()) ||
343 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000344 "Size member of DSNode doesn't match the type structure!");
345 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000346
Chris Lattner18552922002-11-18 21:44:46 +0000347 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000348 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000349
Chris Lattner08db7192002-11-06 06:20:27 +0000350 // Return true immediately if the node is completely folded.
351 if (isNodeCompletelyFolded()) return true;
352
Chris Lattner23f83dc2002-11-08 22:49:57 +0000353 // If this is an array type, eliminate the outside arrays because they won't
354 // be used anyway. This greatly reduces the size of large static arrays used
355 // as global variables, for example.
356 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000357 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000358 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
359 // FIXME: we might want to keep small arrays, but must be careful about
360 // things like: [2 x [10000 x int*]]
361 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000362 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000363 }
364
Chris Lattner08db7192002-11-06 06:20:27 +0000365 // Figure out how big the new type we're merging in is...
366 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
367
368 // Otherwise check to see if we can fold this type into the current node. If
369 // we can't, we fold the node completely, if we can, we potentially update our
370 // internal state.
371 //
Chris Lattner18552922002-11-18 21:44:46 +0000372 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000373 // If this is the first type that this node has seen, just accept it without
374 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000375 assert(Offset == 0 && !isArray() &&
376 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000377 Ty = NewTy;
378 NodeType &= ~Array;
379 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000380 Size = NewTySize;
381
382 // Calculate the number of outgoing links from this node.
383 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
384 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000385 }
Chris Lattner08db7192002-11-06 06:20:27 +0000386
387 // Handle node expansion case here...
388 if (Offset+NewTySize > Size) {
389 // It is illegal to grow this node if we have treated it as an array of
390 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000391 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000392 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000393 return true;
394 }
395
396 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000397 std::cerr << "UNIMP: Trying to merge a growth type into "
398 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000399 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000400 return true;
401 }
402
403 // Okay, the situation is nice and simple, we are trying to merge a type in
404 // at offset 0 that is bigger than our current type. Implement this by
405 // switching to the new type and then merge in the smaller one, which should
406 // hit the other code path here. If the other code path decides it's not
407 // ok, it will collapse the node as appropriate.
408 //
Chris Lattner18552922002-11-18 21:44:46 +0000409 const Type *OldTy = Ty;
410 Ty = NewTy;
411 NodeType &= ~Array;
412 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000413 Size = NewTySize;
414
415 // Must grow links to be the appropriate size...
416 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
417
418 // Merge in the old type now... which is guaranteed to be smaller than the
419 // "current" type.
420 return mergeTypeInfo(OldTy, 0);
421 }
422
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000423 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000424 "Cannot merge something into a part of our type that doesn't exist!");
425
Chris Lattner18552922002-11-18 21:44:46 +0000426 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000427 // type that starts at offset Offset.
428 //
429 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000430 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000431 while (O < Offset) {
432 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
433
434 switch (SubType->getPrimitiveID()) {
435 case Type::StructTyID: {
436 const StructType *STy = cast<StructType>(SubType);
437 const StructLayout &SL = *TD.getStructLayout(STy);
438
439 unsigned i = 0, e = SL.MemberOffsets.size();
440 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
441 /* empty */;
442
443 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000444 SubType = STy->getElementType(i);
Chris Lattner08db7192002-11-06 06:20:27 +0000445 O += SL.MemberOffsets[i];
446 break;
447 }
448 case Type::ArrayTyID: {
449 SubType = cast<ArrayType>(SubType)->getElementType();
450 unsigned ElSize = TD.getTypeSize(SubType);
451 unsigned Remainder = (Offset-O) % ElSize;
452 O = Offset-Remainder;
453 break;
454 }
455 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000456 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000457 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000458 }
459 }
460
461 assert(O == Offset && "Could not achieve the correct offset!");
462
463 // If we found our type exactly, early exit
464 if (SubType == NewTy) return false;
465
Chris Lattner0b144872004-01-27 22:03:40 +0000466 // Differing function types don't require us to merge. They are not values anyway.
467 if (isa<FunctionType>(SubType) &&
468 isa<FunctionType>(NewTy)) return false;
469
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000470 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
471
472 // Ok, we are getting desperate now. Check for physical subtyping, where we
473 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000474 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000475 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000476 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000477 return false;
478
Chris Lattner08db7192002-11-06 06:20:27 +0000479 // Okay, so we found the leader type at the offset requested. Search the list
480 // of types that starts at this offset. If SubType is currently an array or
481 // structure, the type desired may actually be the first element of the
482 // composite type...
483 //
Chris Lattner18552922002-11-18 21:44:46 +0000484 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000485 while (SubType != NewTy) {
486 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000487 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000488 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000489 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000490 case Type::StructTyID: {
491 const StructType *STy = cast<StructType>(SubType);
492 const StructLayout &SL = *TD.getStructLayout(STy);
493 if (SL.MemberOffsets.size() > 1)
494 NextPadSize = SL.MemberOffsets[1];
495 else
496 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000497 NextSubType = STy->getElementType(0);
Chris Lattner18552922002-11-18 21:44:46 +0000498 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000499 break;
Chris Lattner18552922002-11-18 21:44:46 +0000500 }
Chris Lattner08db7192002-11-06 06:20:27 +0000501 case Type::ArrayTyID:
502 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000503 NextSubTypeSize = TD.getTypeSize(NextSubType);
504 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000505 break;
506 default: ;
507 // fall out
508 }
509
510 if (NextSubType == 0)
511 break; // In the default case, break out of the loop
512
Chris Lattner18552922002-11-18 21:44:46 +0000513 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000514 break; // Don't allow shrinking to a smaller type than NewTySize
515 SubType = NextSubType;
516 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000517 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000518 }
519
520 // If we found the type exactly, return it...
521 if (SubType == NewTy)
522 return false;
523
524 // Check to see if we have a compatible, but different type...
525 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000526 // Check to see if this type is obviously convertible... int -> uint f.e.
527 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000528 return false;
529
530 // Check to see if we have a pointer & integer mismatch going on here,
531 // loading a pointer as a long, for example.
532 //
533 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
534 NewTy->isInteger() && isa<PointerType>(SubType))
535 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000536 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
537 // We are accessing the field, plus some structure padding. Ignore the
538 // structure padding.
539 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000540 }
541
Chris Lattner58f98d02003-07-02 04:38:49 +0000542 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000543 if (getParentGraph()->getReturnNodes().size())
544 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000545 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
546 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
547 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
548 << "SubType: ";
549 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000550
Chris Lattner088b6392003-03-03 17:13:31 +0000551 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000552 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000553}
554
Chris Lattner08db7192002-11-06 06:20:27 +0000555
556
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000557// addEdgeTo - Add an edge from the current node to the specified node. This
558// can cause merging of nodes in the graph.
559//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000560void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000561 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000562
Chris Lattner08db7192002-11-06 06:20:27 +0000563 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000564 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000565 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000566 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000567 } else { // No merging to perform...
568 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000569 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000570}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000571
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000572
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000573// MergeSortedVectors - Efficiently merge a vector into another vector where
574// duplicates are not allowed and both are sorted. This assumes that 'T's are
575// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000576//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000577static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
578 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000579 // By far, the most common cases will be the simple ones. In these cases,
580 // avoid having to allocate a temporary vector...
581 //
582 if (Src.empty()) { // Nothing to merge in...
583 return;
584 } else if (Dest.empty()) { // Just copy the result in...
585 Dest = Src;
586 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000587 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000588 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000589 std::lower_bound(Dest.begin(), Dest.end(), V);
590 if (I == Dest.end() || *I != Src[0]) // If not already contained...
591 Dest.insert(I, Src[0]);
592 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000593 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000594 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000595 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000596 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
597 if (I == Dest.end() || *I != Tmp) // If not already contained...
598 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000599
600 } else {
601 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000602 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000603
604 // Make space for all of the type entries now...
605 Dest.resize(Dest.size()+Src.size());
606
607 // Merge the two sorted ranges together... into Dest.
608 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
609
610 // Now erase any duplicate entries that may have accumulated into the
611 // vectors (because they were in both of the input sets)
612 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
613 }
614}
615
Chris Lattner0b144872004-01-27 22:03:40 +0000616void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
617 MergeSortedVectors(Globals, RHS);
618}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000619
Chris Lattner0b144872004-01-27 22:03:40 +0000620// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000621// This function does the hard work of merging two nodes, CurNodeH
622// and NH after filtering out trivial cases and making sure that
623// CurNodeH.offset >= NH.offset.
624//
625// ***WARNING***
626// Since merging may cause either node to go away, we must always
627// use the node-handles to refer to the nodes. These node handles are
628// automatically updated during merging, so will always provide access
629// to the correct node after a merge.
630//
631void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
632 assert(CurNodeH.getOffset() >= NH.getOffset() &&
633 "This should have been enforced in the caller.");
634
635 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
636 // respect to NH.Offset) is now zero. NOffset is the distance from the base
637 // of our object that N starts from.
638 //
639 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
640 unsigned NSize = NH.getNode()->getSize();
641
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000642 // If the two nodes are of different size, and the smaller node has the array
643 // bit set, collapse!
644 if (NSize != CurNodeH.getNode()->getSize()) {
645 if (NSize < CurNodeH.getNode()->getSize()) {
646 if (NH.getNode()->isArray())
647 NH.getNode()->foldNodeCompletely();
648 } else if (CurNodeH.getNode()->isArray()) {
649 NH.getNode()->foldNodeCompletely();
650 }
651 }
652
653 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000654 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000655 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000656 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000657
658 // If we are merging a node with a completely folded node, then both nodes are
659 // now completely folded.
660 //
661 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
662 if (!NH.getNode()->isNodeCompletelyFolded()) {
663 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000664 assert(NH.getNode() && NH.getOffset() == 0 &&
665 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000666 NOffset = NH.getOffset();
667 NSize = NH.getNode()->getSize();
668 assert(NOffset == 0 && NSize == 1);
669 }
670 } else if (NH.getNode()->isNodeCompletelyFolded()) {
671 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000672 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
673 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000674 NOffset = NH.getOffset();
675 NSize = NH.getNode()->getSize();
676 assert(NOffset == 0 && NSize == 1);
677 }
678
Chris Lattner72d29a42003-02-11 23:11:51 +0000679 DSNode *N = NH.getNode();
680 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000681 assert(!CurNodeH.getNode()->isDeadNode());
682
Chris Lattner0b144872004-01-27 22:03:40 +0000683 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000684 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000685
Chris Lattner72d29a42003-02-11 23:11:51 +0000686 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000687 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000688 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000689
Chris Lattner72d29a42003-02-11 23:11:51 +0000690 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
691 //
692 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
693 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000694 if (Link.getNode()) {
695 // Compute the offset into the current node at which to
696 // merge this link. In the common case, this is a linear
697 // relation to the offset in the original node (with
698 // wrapping), but if the current node gets collapsed due to
699 // recursive merging, we must make sure to merge in all remaining
700 // links at offset zero.
701 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000702 DSNode *CN = CurNodeH.getNode();
703 if (CN->Size != 1)
704 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
705 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000706 }
707 }
708
709 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000710 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000711
712 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000713 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000714 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000715
716 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000717 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000718 }
719}
720
721
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000722// mergeWith - Merge this node and the specified node, moving all links to and
723// from the argument node into the current node, deleting the node argument.
724// Offset indicates what offset the specified node is to be merged into the
725// current node.
726//
Chris Lattner5254a8d2004-01-22 16:31:08 +0000727// The specified node may be a null pointer (in which case, we update it to
728// point to this node).
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000729//
730void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
731 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000732 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000733 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000734
Chris Lattner5254a8d2004-01-22 16:31:08 +0000735 // If the RHS is a null node, make it point to this node!
736 if (N == 0) {
737 NH.mergeWith(DSNodeHandle(this, Offset));
738 return;
739 }
740
Chris Lattnerbd92b732003-06-19 21:15:11 +0000741 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000742 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
743
Chris Lattner02606632002-11-04 06:48:26 +0000744 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000745 // We cannot merge two pieces of the same node together, collapse the node
746 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000747 DEBUG(std::cerr << "Attempting to merge two chunks of"
748 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000749 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000750 return;
751 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000752
Chris Lattner5190ce82002-11-12 07:20:45 +0000753 // If both nodes are not at offset 0, make sure that we are merging the node
754 // at an later offset into the node with the zero offset.
755 //
756 if (Offset < NH.getOffset()) {
757 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
758 return;
759 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
760 // If the offsets are the same, merge the smaller node into the bigger node
761 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
762 return;
763 }
764
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000765 // Ok, now we can merge the two nodes. Use a static helper that works with
766 // two node handles, since "this" may get merged away at intermediate steps.
767 DSNodeHandle CurNodeH(this, Offset);
768 DSNodeHandle NHCopy(NH);
769 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000770}
771
Chris Lattner0b144872004-01-27 22:03:40 +0000772
773//===----------------------------------------------------------------------===//
774// ReachabilityCloner Implementation
775//===----------------------------------------------------------------------===//
776
777DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
778 if (SrcNH.isNull()) return DSNodeHandle();
779 const DSNode *SN = SrcNH.getNode();
780
781 DSNodeHandle &NH = NodeMap[SN];
782 if (!NH.isNull()) // Node already mapped?
783 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
784
785 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
786 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000787 NH = DN;
Chris Lattner0b144872004-01-27 22:03:40 +0000788
789 // Next, recursively clone all outgoing links as necessary. Note that
790 // adding these links can cause the node to collapse itself at any time, and
791 // the current node may be merged with arbitrary other nodes. For this
792 // reason, we must always go through NH.
793 DN = 0;
794 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
795 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
796 if (!SrcEdge.isNull()) {
797 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
798 // Compute the offset into the current node at which to
799 // merge this link. In the common case, this is a linear
800 // relation to the offset in the original node (with
801 // wrapping), but if the current node gets collapsed due to
802 // recursive merging, we must make sure to merge in all remaining
803 // links at offset zero.
804 unsigned MergeOffset = 0;
805 DSNode *CN = NH.getNode();
806 if (CN->getSize() != 1)
807 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()
808 - SrcNH.getOffset()) %CN->getSize();
809 CN->addEdgeTo(MergeOffset, DestEdge);
810 }
811 }
812
813 // If this node contains any globals, make sure they end up in the scalar
814 // map with the correct offset.
815 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
816 I != E; ++I) {
817 GlobalValue *GV = *I;
818 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
819 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
820 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
821 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000822 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000823
824 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
825 Dest.getInlinedGlobals().insert(GV);
826 }
827
828 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
829}
830
831void ReachabilityCloner::merge(const DSNodeHandle &NH,
832 const DSNodeHandle &SrcNH) {
833 if (SrcNH.isNull()) return; // Noop
834 if (NH.isNull()) {
835 // If there is no destination node, just clone the source and assign the
836 // destination node to be it.
837 NH.mergeWith(getClonedNH(SrcNH));
838 return;
839 }
840
841 // Okay, at this point, we know that we have both a destination and a source
842 // node that need to be merged. Check to see if the source node has already
843 // been cloned.
844 const DSNode *SN = SrcNH.getNode();
845 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +0000846 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner0b144872004-01-27 22:03:40 +0000847 NH.mergeWith(DSNodeHandle(SCNH.getNode(),
848 SCNH.getOffset()+SrcNH.getOffset()));
849
850 return; // Nothing to do!
851 }
852
853 // Okay, so the source node has not already been cloned. Instead of creating
854 // a new DSNode, only to merge it into the one we already have, try to perform
855 // the merge in-place. The only case we cannot handle here is when the offset
856 // into the existing node is less than the offset into the virtual node we are
857 // merging in. In this case, we have to extend the existing node, which
858 // requires an allocation anyway.
859 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
860 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000861 if (!DN->isNodeCompletelyFolded()) {
862 // Make sure the destination node is folded if the source node is folded.
863 if (SN->isNodeCompletelyFolded()) {
864 DN->foldNodeCompletely();
865 DN = NH.getNode();
866 } else if (SN->getSize() != DN->getSize()) {
867 // If the two nodes are of different size, and the smaller node has the
868 // array bit set, collapse!
869 if (SN->getSize() < DN->getSize()) {
870 if (SN->isArray()) {
871 DN->foldNodeCompletely();
872 DN = NH.getNode();
873 }
874 } else if (DN->isArray()) {
875 DN->foldNodeCompletely();
876 DN = NH.getNode();
877 }
878 }
879
880 // Merge the type entries of the two nodes together...
881 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
882 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
883 DN = NH.getNode();
884 }
885 }
886
887 assert(!DN->isDeadNode());
888
889 // Merge the NodeType information.
890 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
891
892 // Before we start merging outgoing links and updating the scalar map, make
893 // sure it is known that this is the representative node for the src node.
894 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
895
896 // If the source node contains any globals, make sure they end up in the
897 // scalar map with the correct offset.
898 if (SN->global_begin() != SN->global_end()) {
899 // Update the globals in the destination node itself.
900 DN->mergeGlobals(SN->getGlobals());
901
902 // Update the scalar map for the graph we are merging the source node
903 // into.
904 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
905 I != E; ++I) {
906 GlobalValue *GV = *I;
907 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
908 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
909 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
910 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +0000911 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000912
913 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
914 Dest.getInlinedGlobals().insert(GV);
915 }
916 }
917 } else {
918 // We cannot handle this case without allocating a temporary node. Fall
919 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +0000920 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
921 NewDN->maskNodeTypes(BitsToKeep);
922
923 unsigned NHOffset = NH.getOffset();
924 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +0000925
Chris Lattner0b144872004-01-27 22:03:40 +0000926 assert(NH.getNode() &&
927 (NH.getOffset() > NHOffset ||
928 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
929 "Merging did not adjust the offset!");
930
931 // Before we start merging outgoing links and updating the scalar map, make
932 // sure it is known that this is the representative node for the src node.
933 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +0000934
935 // If the source node contained any globals, make sure to create entries
936 // in the scalar map for them!
937 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
938 I != E; ++I) {
939 GlobalValue *GV = *I;
940 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
941 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
942 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
943 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
944 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
945 DestGNH.getOffset()+SrcGNH.getOffset()));
946
947 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
948 Dest.getInlinedGlobals().insert(GV);
949 }
Chris Lattner0b144872004-01-27 22:03:40 +0000950 }
951
952
953 // Next, recursively merge all outgoing links as necessary. Note that
954 // adding these links can cause the destination node to collapse itself at
955 // any time, and the current node may be merged with arbitrary other nodes.
956 // For this reason, we must always go through NH.
957 DN = 0;
958 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
959 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
960 if (!SrcEdge.isNull()) {
961 // Compute the offset into the current node at which to
962 // merge this link. In the common case, this is a linear
963 // relation to the offset in the original node (with
964 // wrapping), but if the current node gets collapsed due to
965 // recursive merging, we must make sure to merge in all remaining
966 // links at offset zero.
967 unsigned MergeOffset = 0;
968 DSNode *CN = SCNH.getNode();
969 if (CN->getSize() != 1)
970 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
971
Chris Lattner0ad91702004-02-22 00:53:54 +0000972 DSNodeHandle &Link = CN->getLink(MergeOffset);
973 if (!Link.isNull()) {
974 // Perform the recursive merging. Make sure to create a temporary NH,
975 // because the Link can disappear in the process of recursive merging.
976 DSNodeHandle Tmp = Link;
977 merge(Tmp, SrcEdge);
978 } else {
979 merge(Link, SrcEdge);
980 }
Chris Lattner0b144872004-01-27 22:03:40 +0000981 }
982 }
983}
984
985/// mergeCallSite - Merge the nodes reachable from the specified src call
986/// site into the nodes reachable from DestCS.
987void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
988 const DSCallSite &SrcCS) {
989 merge(DestCS.getRetVal(), SrcCS.getRetVal());
990 unsigned MinArgs = DestCS.getNumPtrArgs();
991 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
992
993 for (unsigned a = 0; a != MinArgs; ++a)
994 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
995}
996
997
Chris Lattner9de906c2002-10-20 22:11:44 +0000998//===----------------------------------------------------------------------===//
999// DSCallSite Implementation
1000//===----------------------------------------------------------------------===//
1001
Vikram S. Adve26b98262002-10-20 21:41:02 +00001002// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001003Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001004 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001005}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001006
Chris Lattner0b144872004-01-27 22:03:40 +00001007void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1008 ReachabilityCloner &RC) {
1009 NH = RC.getClonedNH(Src);
1010}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001011
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001012//===----------------------------------------------------------------------===//
1013// DSGraph Implementation
1014//===----------------------------------------------------------------------===//
1015
Chris Lattnera9d65662003-06-30 05:57:30 +00001016/// getFunctionNames - Return a space separated list of the name of the
1017/// functions in this graph (if any)
1018std::string DSGraph::getFunctionNames() const {
1019 switch (getReturnNodes().size()) {
1020 case 0: return "Globals graph";
1021 case 1: return getReturnNodes().begin()->first->getName();
1022 default:
1023 std::string Return;
1024 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1025 I != getReturnNodes().end(); ++I)
1026 Return += I->first->getName() + " ";
1027 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1028 return Return;
1029 }
1030}
1031
1032
Chris Lattner15869aa2003-11-02 22:27:28 +00001033DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001034 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001035 NodeMapTy NodeMap;
1036 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001037}
1038
Chris Lattner5a540632003-06-30 03:15:25 +00001039DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001040 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001041 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001042 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001043}
1044
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001045DSGraph::~DSGraph() {
1046 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001047 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001048 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001049 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001050 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001051
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001052 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001053 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1054 (*NI)->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001055
Chris Lattner28897e12004-02-08 00:53:26 +00001056 // Free all of the nodes.
1057 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001058}
1059
Chris Lattner0d9bab82002-07-18 00:12:30 +00001060// dump - Allow inspection of graph in a debugger.
1061void DSGraph::dump() const { print(std::cerr); }
1062
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001063
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001064/// remapLinks - Change all of the Links in the current node according to the
1065/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001066///
Chris Lattner8d327672003-06-30 03:36:09 +00001067void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001068 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1069 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001070 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1071 if (ONMI != OldNodeMap.end()) {
1072 Links[i].setNode(ONMI->second.getNode());
1073 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1074 }
Chris Lattner2f561382004-01-22 16:56:13 +00001075 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001076}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001077
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001078/// updateFromGlobalGraph - This function rematerializes global nodes and
1079/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001080/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1081/// are already up-to-date in the current graph. In practice, in the TD pass,
1082/// this is likely to be a large fraction of the live global nodes in each
1083/// function (since most live nodes are likely to have been brought up-to-date
1084/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001085///
1086void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001087 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001088 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1089
1090 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001091 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1092 E = getScalarMap().global_end(); I != E; ++I)
1093 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001094 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001095 if (It != GlobalsGraph->ScalarMap.end())
1096 RC.merge(getNodeForValue(*I), It->second);
1097 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001098}
1099
Chris Lattner5a540632003-06-30 03:15:25 +00001100/// cloneInto - Clone the specified DSGraph into the current graph. The
1101/// translated ScalarMap for the old function is filled into the OldValMap
1102/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1103///
1104/// The CloneFlags member controls various aspects of the cloning process.
1105///
Chris Lattner62482e52004-01-28 09:15:42 +00001106void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001107 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1108 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001109 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001110 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001111 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001112
Chris Lattner1e883692003-02-03 20:08:51 +00001113 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001114 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1115 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1116 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001117 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001118
Chris Lattnerd85645f2004-02-21 22:28:26 +00001119 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1120 assert(!(*I)->isForwarding() &&
1121 "Forward nodes shouldn't be in node list!");
1122 DSNode *New = new DSNode(**I, this);
1123 New->maskNodeTypes(~BitsToClear);
1124 OldNodeMap[*I] = New;
1125 }
1126
Chris Lattner18552922002-11-18 21:44:46 +00001127#ifndef NDEBUG
1128 Timer::addPeakMemoryMeasurement();
1129#endif
Chris Lattnerd85645f2004-02-21 22:28:26 +00001130
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001131 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001132 // Note that we don't loop over the node's list to do this. The problem is
1133 // that remaping links can cause recursive merging to happen, which means
1134 // that node_iterator's can get easily invalidated! Because of this, we
1135 // loop over the OldNodeMap, which contains all of the new nodes as the
1136 // .second element of the map elements. Also note that if we remap a node
1137 // more than once, we won't break anything.
1138 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1139 I != E; ++I)
1140 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001141
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001142 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001143 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001144 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001145 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001146 DSNodeHandle &H = OldValMap[I->first];
1147 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1148 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001149
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001150 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001151 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1152 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001153 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1154 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001155 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001156 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001157
Chris Lattner679e8e12002-11-08 21:27:12 +00001158 if (!(CloneFlags & DontCloneCallNodes)) {
1159 // Copy the function calls list...
1160 unsigned FC = FunctionCalls.size(); // FirstCall
1161 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1162 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1163 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001164 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001165
Chris Lattneracf491f2002-11-08 22:27:09 +00001166 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +00001167 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +00001168 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +00001169 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1170 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1171 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1172 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001173
Chris Lattner5a540632003-06-30 03:15:25 +00001174 // Map the return node pointers over...
1175 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1176 E = G.getReturnNodes().end(); I != E; ++I) {
1177 const DSNodeHandle &Ret = I->second;
1178 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1179 OldReturnNodes.insert(std::make_pair(I->first,
1180 DSNodeHandle(MappedRet.getNode(),
1181 MappedRet.getOffset()+Ret.getOffset())));
1182 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001183}
1184
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001185static bool PathExistsToClonedNode(const DSNode *N, ReachabilityCloner &RC) {
1186 for (df_iterator<const DSNode*> I = df_begin(N), E = df_end(N); I != E; ++I)
1187 if (RC.hasClonedNode(*I))
1188 return true;
1189 return false;
1190}
1191
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001192
Chris Lattner076c1f92002-11-07 06:31:54 +00001193/// mergeInGraph - The method is used for merging graphs together. If the
1194/// argument graph is not *this, it makes a clone of the specified graph, then
1195/// merges the nodes specified in the call site with the formal arguments in the
1196/// graph.
1197///
Chris Lattner9f930552003-06-30 05:27:18 +00001198void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1199 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001200 TIME_REGION(X, "mergeInGraph");
1201
Chris Lattner2c7725a2004-03-03 20:55:27 +00001202 // Fastpath for a noop inline.
1203 if (CS.getNumPtrArgs() == 0 && CS.getRetVal().isNull())
1204 return;
1205
Chris Lattner076c1f92002-11-07 06:31:54 +00001206 // If this is not a recursive call, clone the graph into this graph...
1207 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001208 // Clone the callee's graph into the current graph, keeping track of where
1209 // scalars in the old graph _used_ to point, and of the new nodes matching
1210 // nodes of the old graph.
1211 ReachabilityCloner RC(*this, Graph, CloneFlags);
1212
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001213 // Set up argument bindings
1214 Function::aiterator AI = F.abegin();
1215 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1216 // Advance the argument iterator to the first pointer argument...
1217 while (AI != F.aend() && !isPointerType(AI->getType())) {
1218 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001219#ifndef NDEBUG // FIXME: We should merge vararg arguments!
1220 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001221 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001222#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001223 }
1224 if (AI == F.aend()) break;
1225
1226 // Add the link from the argument scalar to the provided value.
Chris Lattner0b144872004-01-27 22:03:40 +00001227 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
Chris Lattner076c1f92002-11-07 06:31:54 +00001228 }
1229
Chris Lattner0b144872004-01-27 22:03:40 +00001230 // Map the return node pointer over.
Chris Lattner0ad91702004-02-22 00:53:54 +00001231 if (!CS.getRetVal().isNull())
Chris Lattner0b144872004-01-27 22:03:40 +00001232 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
1233
1234 // If requested, copy the calls or aux-calls lists.
1235 if (!(CloneFlags & DontCloneCallNodes)) {
1236 // Copy the function calls list...
1237 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1238 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1239 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1240 }
1241
1242 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1243 // Copy the auxiliary function calls list...
1244 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1245 Graph.AuxFunctionCalls.size());
1246 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1247 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i], RC));
1248 }
1249
Chris Lattner0321b682004-02-27 20:05:15 +00001250 // Clone over all globals that appear in the caller and callee graphs.
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001251 hash_set<GlobalVariable*> NonCopiedGlobals;
Chris Lattner0321b682004-02-27 20:05:15 +00001252 for (DSScalarMap::global_iterator GI = Graph.getScalarMap().global_begin(),
1253 E = Graph.getScalarMap().global_end(); GI != E; ++GI)
1254 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*GI))
1255 if (ScalarMap.count(GV))
1256 RC.merge(ScalarMap[GV], Graph.getNodeForValue(GV));
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001257 else
1258 NonCopiedGlobals.insert(GV);
1259
1260 // If the global does not appear in the callers graph we generally don't
1261 // want to copy the node. However, if there is a path from the node global
1262 // node to a node that we did copy in the graph, we *must* copy it to
1263 // maintain the connection information. Every time we decide to include a
1264 // new global, this might make other globals live, so we must iterate
1265 // unfortunately.
1266 bool MadeChange = false;
1267 for (hash_set<GlobalVariable*>::iterator I = NonCopiedGlobals.begin();
1268 I != NonCopiedGlobals.end();) {
1269 DSNode *GlobalNode = Graph.getNodeForValue(*I).getNode();
1270 if (RC.hasClonedNode(GlobalNode)) {
1271 // Already cloned it, remove from set.
1272 NonCopiedGlobals.erase(I++);
1273 } else if (PathExistsToClonedNode(GlobalNode, RC)) {
1274 RC.getClonedNH(Graph.getNodeForValue(*I));
1275 NonCopiedGlobals.erase(I++);
1276 } else {
1277 ++I;
1278 }
1279 }
1280
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001281 } else {
1282 DSNodeHandle RetVal = getReturnNodeFor(F);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001283
1284 // Merge the return value with the return value of the context...
1285 RetVal.mergeWith(CS.getRetVal());
1286
1287 // Resolve all of the function arguments...
1288 Function::aiterator AI = F.abegin();
1289
1290 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1291 // Advance the argument iterator to the first pointer argument...
1292 while (AI != F.aend() && !isPointerType(AI->getType())) {
1293 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001294#ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1295 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001296 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1297#endif
1298 }
1299 if (AI == F.aend()) break;
1300
1301 // Add the link from the argument scalar to the provided value
Chris Lattner0b144872004-01-27 22:03:40 +00001302 DSNodeHandle &NH = getNodeForValue(AI);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001303 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1304 NH.mergeWith(CS.getPtrArg(i));
1305 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001306 }
1307}
1308
Chris Lattner58f98d02003-07-02 04:38:49 +00001309/// getCallSiteForArguments - Get the arguments and return value bindings for
1310/// the specified function in the current graph.
1311///
1312DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1313 std::vector<DSNodeHandle> Args;
1314
1315 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1316 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001317 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001318
Chris Lattner808a7ae2003-09-20 16:34:13 +00001319 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001320}
1321
1322
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001323
Chris Lattner0d9bab82002-07-18 00:12:30 +00001324// markIncompleteNodes - Mark the specified node as having contents that are not
1325// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001326// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001327// must recursively traverse the data structure graph, marking all reachable
1328// nodes as incomplete.
1329//
1330static void markIncompleteNode(DSNode *N) {
1331 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001332 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001333
1334 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001335 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001336
Misha Brukman2f2d0652003-09-11 18:14:24 +00001337 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001338 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1339 if (DSNode *DSN = N->getLink(i).getNode())
1340 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001341}
1342
Chris Lattnere71ffc22002-11-11 03:36:55 +00001343static void markIncomplete(DSCallSite &Call) {
1344 // Then the return value is certainly incomplete!
1345 markIncompleteNode(Call.getRetVal().getNode());
1346
1347 // All objects pointed to by function arguments are incomplete!
1348 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1349 markIncompleteNode(Call.getPtrArg(i).getNode());
1350}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001351
1352// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1353// modified by other functions that have not been resolved yet. This marks
1354// nodes that are reachable through three sources of "unknownness":
1355//
1356// Global Variables, Function Calls, and Incoming Arguments
1357//
1358// For any node that may have unknown components (because something outside the
1359// scope of current analysis may have modified it), the 'Incomplete' flag is
1360// added to the NodeType.
1361//
Chris Lattner394471f2003-01-23 22:05:33 +00001362void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001363 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001364 if (Flags & DSGraph::MarkFormalArgs)
1365 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1366 FI != E; ++FI) {
1367 Function &F = *FI->first;
1368 if (F.getName() != "main")
1369 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001370 if (isPointerType(I->getType()))
1371 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001372 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001373
1374 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001375 if (!shouldPrintAuxCalls())
1376 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1377 markIncomplete(FunctionCalls[i]);
1378 else
1379 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1380 markIncomplete(AuxFunctionCalls[i]);
1381
Chris Lattner0d9bab82002-07-18 00:12:30 +00001382
Chris Lattner93d7a212003-02-09 18:41:49 +00001383 // Mark all global nodes as incomplete...
1384 if ((Flags & DSGraph::IgnoreGlobals) == 0)
Chris Lattner51c06ab2004-02-25 23:08:00 +00001385 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1386 E = ScalarMap.global_end(); I != E; ++I)
Chris Lattnercf14e712004-02-25 23:36:08 +00001387 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1388 if (!GV->isConstant())
1389 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001390}
1391
Chris Lattneraa8146f2002-11-10 06:59:55 +00001392static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1393 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001394 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001395 // No interesting info?
1396 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001397 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001398 Edge.setNode(0); // Kill the edge!
1399}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001400
Chris Lattneraa8146f2002-11-10 06:59:55 +00001401static inline bool nodeContainsExternalFunction(const DSNode *N) {
1402 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1403 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1404 if (Globals[i]->isExternal())
1405 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001406 return false;
1407}
1408
Chris Lattner5a540632003-06-30 03:15:25 +00001409static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001410 // Remove trivially identical function calls
1411 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001412 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1413
Chris Lattner0b144872004-01-27 22:03:40 +00001414#if 1
Chris Lattneraa8146f2002-11-10 06:59:55 +00001415 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001416 DSNode *LastCalleeNode = 0;
1417 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001418 unsigned NumDuplicateCalls = 0;
1419 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001420 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001421 DSCallSite &CS = Calls[i];
1422
Chris Lattnere4258442002-11-11 21:35:38 +00001423 // If the Callee is a useless edge, this must be an unreachable call site,
1424 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001425 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerabcdf802004-02-26 03:43:43 +00001426 CS.getCalleeNode()->isComplete() &&
Chris Lattneraf6926a2004-02-26 03:45:03 +00001427 CS.getCalleeNode()->getGlobals().empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001428#ifndef NDEBUG
Chris Lattnerabcdf802004-02-26 03:43:43 +00001429 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001430#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001431 CS.swap(Calls.back());
1432 Calls.pop_back();
1433 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001434 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001435 // If the return value or any arguments point to a void node with no
1436 // information at all in it, and the call node is the only node to point
1437 // to it, remove the edge to the node (killing the node).
1438 //
1439 killIfUselessEdge(CS.getRetVal());
1440 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1441 killIfUselessEdge(CS.getPtrArg(a));
1442
1443 // If this call site calls the same function as the last call site, and if
1444 // the function pointer contains an external function, this node will
1445 // never be resolved. Merge the arguments of the call node because no
1446 // information will be lost.
1447 //
Chris Lattner923fc052003-02-05 21:59:58 +00001448 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1449 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001450 ++NumDuplicateCalls;
1451 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001452 if (LastCalleeNode)
1453 LastCalleeContainsExternalFunction =
1454 nodeContainsExternalFunction(LastCalleeNode);
1455 else
1456 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001457 }
Chris Lattner0b144872004-01-27 22:03:40 +00001458
1459 // It is not clear why, but enabling this code makes DSA really
1460 // sensitive to node forwarding. Basically, with this enabled, DSA
1461 // performs different number of inlinings based on which nodes are
1462 // forwarding or not. This is clearly a problem, so this code is
1463 // disabled until this can be resolved.
Chris Lattner58f98d02003-07-02 04:38:49 +00001464#if 1
Chris Lattner0b144872004-01-27 22:03:40 +00001465 if (LastCalleeContainsExternalFunction
1466#if 0
1467 ||
Chris Lattnere4258442002-11-11 21:35:38 +00001468 // This should be more than enough context sensitivity!
1469 // FIXME: Evaluate how many times this is tripped!
Chris Lattner0b144872004-01-27 22:03:40 +00001470 NumDuplicateCalls > 20
1471#endif
1472 ) {
Chris Lattnere4258442002-11-11 21:35:38 +00001473 DSCallSite &OCS = Calls[i-1];
1474 OCS.mergeWith(CS);
1475
1476 // The node will now be eliminated as a duplicate!
1477 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1478 CS = OCS;
1479 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1480 OCS = CS;
1481 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001482#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001483 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001484 if (CS.isDirectCall()) {
1485 LastCalleeFunc = CS.getCalleeFunc();
1486 LastCalleeNode = 0;
1487 } else {
1488 LastCalleeNode = CS.getCalleeNode();
1489 LastCalleeFunc = 0;
1490 }
Chris Lattnere4258442002-11-11 21:35:38 +00001491 NumDuplicateCalls = 0;
1492 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001493 }
1494 }
Chris Lattner0b144872004-01-27 22:03:40 +00001495#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001496 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001497
Chris Lattner33312f72002-11-08 01:21:07 +00001498 // Track the number of call nodes merged away...
1499 NumCallNodesMerged += NumFns-Calls.size();
1500
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001501 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001502 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001503}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001504
Chris Lattneraa8146f2002-11-10 06:59:55 +00001505
Chris Lattnere2219762002-07-18 18:22:40 +00001506// removeTriviallyDeadNodes - After the graph has been constructed, this method
1507// removes all unreachable nodes that are created because they got merged with
1508// other nodes in the graph. These nodes will all be trivially unreachable, so
1509// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001510//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001511void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001512 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001513
Chris Lattnerbab8c282003-09-20 21:34:07 +00001514 // Loop over all of the nodes in the graph, calling getNode on each field.
1515 // This will cause all nodes to update their forwarding edges, causing
1516 // forwarded nodes to be delete-able.
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001517 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1518 DSNode *N = *NI;
Chris Lattnerbab8c282003-09-20 21:34:07 +00001519 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1520 N->getLink(l*N->getPointerSize()).getNode();
1521 }
1522
Chris Lattner0b144872004-01-27 22:03:40 +00001523 // NOTE: This code is disabled. Though it should, in theory, allow us to
1524 // remove more nodes down below, the scan of the scalar map is incredibly
1525 // expensive for certain programs (with large SCCs). In the future, if we can
1526 // make the scalar map scan more efficient, then we can reenable this.
1527#if 0
1528 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1529
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001530 // Likewise, forward any edges from the scalar nodes. While we are at it,
1531 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001532 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001533 I->second.getNode();
1534 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001535 }
Chris Lattner0b144872004-01-27 22:03:40 +00001536 }
1537#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001538 bool isGlobalsGraph = !GlobalsGraph;
1539
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001540 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001541 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001542
1543 // Do not remove *any* global nodes in the globals graph.
1544 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001545 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001546 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001547 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001548 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001549
Chris Lattner28897e12004-02-08 00:53:26 +00001550 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001551 // This is a useless node if it has no mod/ref info (checked above),
1552 // outgoing edges (which it cannot, as it is not modified in this
1553 // context), and it has no incoming edges. If it is a global node it may
1554 // have all of these properties and still have incoming edges, due to the
1555 // scalar map, so we check those now.
1556 //
Chris Lattner28897e12004-02-08 00:53:26 +00001557 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1558 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001559
Chris Lattner17a93e22004-01-29 03:32:15 +00001560 // Loop through and make sure all of the globals are referring directly
1561 // to the node...
1562 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1563 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001564 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001565 }
1566
Chris Lattnerbd92b732003-06-19 21:15:11 +00001567 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001568 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001569 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1570 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001571 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001572 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001573 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001574 }
1575 }
1576
Chris Lattner28897e12004-02-08 00:53:26 +00001577 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001578 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001579 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001580 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001581 } else {
1582 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001583 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001584 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001585
1586 removeIdenticalCalls(FunctionCalls);
1587 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001588}
1589
1590
Chris Lattner5c7380e2003-01-29 21:10:20 +00001591/// markReachableNodes - This method recursively traverses the specified
1592/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1593/// to the set, which allows it to only traverse visited nodes once.
1594///
Chris Lattner41c04f72003-02-01 04:52:08 +00001595void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001596 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001597 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001598 if (ReachableNodes.insert(this).second) // Is newly reachable?
1599 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1600 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001601}
1602
Chris Lattner41c04f72003-02-01 04:52:08 +00001603void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001604 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001605 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001606
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001607 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1608 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001609}
1610
Chris Lattnera1220af2003-02-01 06:17:02 +00001611// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1612// looking for a node that is marked alive. If an alive node is found, return
1613// true, otherwise return false. If an alive node is reachable, this node is
1614// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001615//
Chris Lattnera1220af2003-02-01 06:17:02 +00001616static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001617 hash_set<DSNode*> &Visited,
1618 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001619 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001620 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001621
Chris Lattner85cfe012003-07-03 02:03:53 +00001622 // If this is a global node, it will end up in the globals graph anyway, so we
1623 // don't need to worry about it.
1624 if (IgnoreGlobals && N->isGlobalNode()) return false;
1625
Chris Lattneraa8146f2002-11-10 06:59:55 +00001626 // If we know that this node is alive, return so!
1627 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001628
Chris Lattneraa8146f2002-11-10 06:59:55 +00001629 // Otherwise, we don't think the node is alive yet, check for infinite
1630 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001631 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001632 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001633
Chris Lattner08db7192002-11-06 06:20:27 +00001634 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001635 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1636 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001637 N->markReachableNodes(Alive);
1638 return true;
1639 }
1640 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001641}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001642
Chris Lattnera1220af2003-02-01 06:17:02 +00001643// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1644// alive nodes.
1645//
Chris Lattner41c04f72003-02-01 04:52:08 +00001646static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001647 hash_set<DSNode*> &Visited,
1648 bool IgnoreGlobals) {
1649 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1650 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001651 return true;
1652 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001653 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001654 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001655 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001656 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1657 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001658 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001659 return false;
1660}
1661
Chris Lattnere2219762002-07-18 18:22:40 +00001662// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1663// subgraphs that are unreachable. This often occurs because the data
1664// structure doesn't "escape" into it's caller, and thus should be eliminated
1665// from the caller's graph entirely. This is only appropriate to use when
1666// inlining graphs.
1667//
Chris Lattner394471f2003-01-23 22:05:33 +00001668void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001669 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001670
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001671 // Reduce the amount of work we have to do... remove dummy nodes left over by
1672 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001673 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001674
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001675 TIME_REGION(X, "removeDeadNodes");
1676
Misha Brukman2f2d0652003-09-11 18:14:24 +00001677 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001678
1679 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001680 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001681 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001682
Chris Lattner0b144872004-01-27 22:03:40 +00001683 // Copy and merge all information about globals to the GlobalsGraph if this is
1684 // not a final pass (where unreachable globals are removed).
1685 //
1686 // Strip all alloca bits since the current function is only for the BU pass.
1687 // Strip all incomplete bits since they are short-lived properties and they
1688 // will be correctly computed when rematerializing nodes into the functions.
1689 //
1690 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1691 DSGraph::StripIncompleteBit);
1692
Chris Lattneraa8146f2002-11-10 06:59:55 +00001693 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner00948c02004-01-28 02:05:05 +00001694 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
Chris Lattner62482e52004-01-28 09:15:42 +00001695 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001696 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001697 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001698 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001699 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001700
1701 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001702 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1703 DSGraph::ScalarMapTy::iterator SMI =
1704 GlobalsGraph->getScalarMap().find(I->first);
1705 if (SMI != GlobalsGraph->getScalarMap().end())
1706 GGCloner.merge(SMI->second, I->second);
1707 else
1708 GGCloner.getClonedNH(I->second);
1709 }
Chris Lattner0b144872004-01-27 22:03:40 +00001710 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001711 } else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001712 DSNode *N = I->second.getNode();
1713#if 0
Chris Lattner0b144872004-01-27 22:03:40 +00001714 // Check to see if this is a worthless node generated for non-pointer
1715 // values, such as integers. Consider an addition of long types: A+B.
1716 // Assuming we can track all uses of the value in this context, and it is
1717 // NOT used as a pointer, we can delete the node. We will be able to
1718 // detect this situation if the node pointed to ONLY has Unknown bit set
1719 // in the node. In this case, the node is not incomplete, does not point
1720 // to any other nodes (no mod/ref bits set), and is therefore
1721 // uninteresting for data structure analysis. If we run across one of
1722 // these, prune the scalar pointing to it.
1723 //
Chris Lattner0b144872004-01-27 22:03:40 +00001724 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1725 ScalarMap.erase(I++);
1726 else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001727#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001728 N->markReachableNodes(Alive);
1729 ++I;
Chris Lattnera88a55c2004-01-28 02:41:32 +00001730 //}
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001731 }
Chris Lattner00948c02004-01-28 02:05:05 +00001732 }
Chris Lattnere2219762002-07-18 18:22:40 +00001733
Chris Lattner0b144872004-01-27 22:03:40 +00001734 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001735 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1736 I != E; ++I)
1737 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001738
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001739 // Mark any nodes reachable by primary calls as alive...
1740 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1741 FunctionCalls[i].markReachableNodes(Alive);
1742
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001743
1744 // Now find globals and aux call nodes that are already live or reach a live
1745 // value (which makes them live in turn), and continue till no more are found.
1746 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001747 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001748 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001749 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1750 do {
1751 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001752 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001753 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001754 // unreachable globals in the list.
1755 //
1756 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001757 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001758 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1759 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1760 Flags & DSGraph::RemoveUnreachableGlobals)) {
1761 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1762 GlobalNodes.pop_back(); // erase efficiently
1763 Iterate = true;
1764 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001765
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001766 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1767 // call nodes that get resolved will be difficult to remove from that graph.
1768 // The final unresolved call nodes must be handled specially at the end of
1769 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001770 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1771 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001772 (AuxFunctionCalls[i].isIndirectCall()
1773 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1774 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001775 AuxFunctionCalls[i].markReachableNodes(Alive);
1776 AuxFCallsAlive[i] = true;
1777 Iterate = true;
1778 }
1779 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001780
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001781 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001782 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001783 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1784 if (AuxFCallsAlive[i])
1785 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001786
1787 // Copy and merge all global nodes and dead aux call nodes into the
1788 // GlobalsGraph, and all nodes reachable from those nodes
1789 //
1790 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001791 // Copy the unreachable call nodes to the globals graph, updating their
1792 // target pointers using the GGCloner
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001793 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1794 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
Chris Lattner0b144872004-01-27 22:03:40 +00001795 GGCloner));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001796 }
1797 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001798 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1799 AuxFunctionCalls.end());
1800
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001801 // We are finally done with the GGCloner so we can destroy it.
1802 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001803
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001804 // At this point, any nodes which are visited, but not alive, are nodes
1805 // which can be removed. Loop over all nodes, eliminating completely
1806 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001807 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001808 std::vector<DSNode*> DeadNodes;
1809 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00001810 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
1811 DSNode *N = NI++;
1812 assert(!N->isForwarding() && "Forwarded node in nodes list?");
1813
1814 if (!Alive.count(N)) {
1815 Nodes.remove(N);
1816 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001817 DeadNodes.push_back(N);
1818 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00001819 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00001820 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00001821 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001822
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001823 // Remove all unreachable globals from the ScalarMap.
1824 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1825 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001826 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001827 if (!Alive.count(GlobalNodes[i].second))
1828 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00001829 else
1830 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001831
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001832 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001833 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1834 delete DeadNodes[i];
1835
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001836 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001837}
1838
Chris Lattner2c7725a2004-03-03 20:55:27 +00001839void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
1840 if (CS.isIndirectCall()) {
1841 AssertNodeInGraph(CS.getCalleeNode());
1842#if 0
1843 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
1844 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
1845 std::cerr << "WARNING: WIERD CALL SITE FOUND!\n";
1846#endif
1847 }
1848 AssertNodeInGraph(CS.getRetVal().getNode());
1849 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
1850 AssertNodeInGraph(CS.getPtrArg(j).getNode());
1851}
1852
1853void DSGraph::AssertCallNodesInGraph() const {
1854 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1855 AssertCallSiteInGraph(FunctionCalls[i]);
1856}
1857void DSGraph::AssertAuxCallNodesInGraph() const {
1858 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1859 AssertCallSiteInGraph(AuxFunctionCalls[i]);
1860}
1861
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001862void DSGraph::AssertGraphOK() const {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001863 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1864 (*NI)->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001865
Chris Lattner8d327672003-06-30 03:36:09 +00001866 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001867 E = ScalarMap.end(); I != E; ++I) {
1868 assert(I->second.getNode() && "Null node in scalarmap!");
1869 AssertNodeInGraph(I->second.getNode());
1870 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001871 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001872 "Global points to node, but node isn't global?");
1873 AssertNodeContainsGlobal(I->second.getNode(), GV);
1874 }
1875 }
1876 AssertCallNodesInGraph();
1877 AssertAuxCallNodesInGraph();
1878}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001879
Chris Lattner400433d2003-11-11 05:08:59 +00001880/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1881/// nodes reachable from the two graphs, computing the mapping of nodes from
1882/// the first to the second graph.
1883///
1884void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001885 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1886 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001887 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1888 if (N1 == 0 || N2 == 0) return;
1889
1890 DSNodeHandle &Entry = NodeMap[N1];
1891 if (Entry.getNode()) {
1892 // Termination of recursion!
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001893 assert(!StrictChecking ||
1894 (Entry.getNode() == N2 &&
1895 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
Chris Lattner400433d2003-11-11 05:08:59 +00001896 "Inconsistent mapping detected!");
1897 return;
1898 }
1899
1900 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001901 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001902
1903 // Loop over all of the fields that N1 and N2 have in common, recursively
1904 // mapping the edges together now.
1905 int N2Idx = NH2.getOffset()-NH1.getOffset();
1906 unsigned N2Size = N2->getSize();
1907 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1908 if (unsigned(N2Idx)+i < N2Size)
1909 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
Chris Lattnerb1aaeee2004-03-03 05:34:31 +00001910 else
1911 computeNodeMapping(N1->getLink(i),
1912 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
Chris Lattner400433d2003-11-11 05:08:59 +00001913}