blob: 68530f043ed467d5481a339a39059f9a9c163130 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00009//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerfccd06f2002-10-01 22:33:50 +000014#include "llvm/Analysis/DSGraph.h"
15#include "llvm/Function.h"
Vikram S. Adve26b98262002-10-20 21:41:02 +000016#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000017#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000018#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000019#include "llvm/Assembly/Writer.h"
Chris Lattner0b144872004-01-27 22:03:40 +000020#include "Support/CommandLine.h"
Chris Lattner6806f562003-08-01 22:15:03 +000021#include "Support/Debug.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000022#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000023#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000024#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000025#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000026using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000027
Chris Lattner08db7192002-11-06 06:20:27 +000028namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000029 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
30 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
31 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
32 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattner0b144872004-01-27 22:03:40 +000033
34 cl::opt<bool>
35 EnableDSNodeGlobalRootsHack("enable-dsa-globalrootshack", cl::Hidden,
36 cl::desc("Make DSA less aggressive when cloning graphs"));
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;
242 if (SS.Idx != ST->getElementTypes().size()) {
243 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)) {
267 if (ST->getElementTypes().empty()) {
268 assert(SS.Idx == 0);
269 PopStackAndAdvance();
270 } else {
271 // Step into the structure...
272 assert(SS.Idx < ST->getElementTypes().size());
273 const StructLayout *SL = TD.getStructLayout(ST);
274 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
275 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...
444 SubType = STy->getElementTypes()[i];
445 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;
497 NextSubType = STy->getElementTypes()[0];
498 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
846 if (SCNH.getNode()) { // Node already cloned?
847 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
972 // Perform the recursive merging. Make sure to create a temporary NH,
973 // because the Link can disappear in the process of recursive merging.
974 DSNodeHandle Tmp = CN->getLink(MergeOffset);
975 merge(Tmp, SrcEdge);
976 }
977 }
978}
979
980/// mergeCallSite - Merge the nodes reachable from the specified src call
981/// site into the nodes reachable from DestCS.
982void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
983 const DSCallSite &SrcCS) {
984 merge(DestCS.getRetVal(), SrcCS.getRetVal());
985 unsigned MinArgs = DestCS.getNumPtrArgs();
986 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
987
988 for (unsigned a = 0; a != MinArgs; ++a)
989 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
990}
991
992
Chris Lattner9de906c2002-10-20 22:11:44 +0000993//===----------------------------------------------------------------------===//
994// DSCallSite Implementation
995//===----------------------------------------------------------------------===//
996
Vikram S. Adve26b98262002-10-20 21:41:02 +0000997// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000998Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000999 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001000}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001001
Chris Lattner0b144872004-01-27 22:03:40 +00001002void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1003 ReachabilityCloner &RC) {
1004 NH = RC.getClonedNH(Src);
1005}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001006
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001007//===----------------------------------------------------------------------===//
1008// DSGraph Implementation
1009//===----------------------------------------------------------------------===//
1010
Chris Lattnera9d65662003-06-30 05:57:30 +00001011/// getFunctionNames - Return a space separated list of the name of the
1012/// functions in this graph (if any)
1013std::string DSGraph::getFunctionNames() const {
1014 switch (getReturnNodes().size()) {
1015 case 0: return "Globals graph";
1016 case 1: return getReturnNodes().begin()->first->getName();
1017 default:
1018 std::string Return;
1019 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1020 I != getReturnNodes().end(); ++I)
1021 Return += I->first->getName() + " ";
1022 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1023 return Return;
1024 }
1025}
1026
1027
Chris Lattner15869aa2003-11-02 22:27:28 +00001028DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001029 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001030 NodeMapTy NodeMap;
1031 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001032}
1033
Chris Lattner5a540632003-06-30 03:15:25 +00001034DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001035 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001036 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001037 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001038}
1039
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001040DSGraph::~DSGraph() {
1041 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001042 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001043 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001044 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001045 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001046
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001047 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001048 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1049 (*NI)->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001050
Chris Lattner28897e12004-02-08 00:53:26 +00001051 // Free all of the nodes.
1052 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001053}
1054
Chris Lattner0d9bab82002-07-18 00:12:30 +00001055// dump - Allow inspection of graph in a debugger.
1056void DSGraph::dump() const { print(std::cerr); }
1057
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001058
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001059/// remapLinks - Change all of the Links in the current node according to the
1060/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001061///
Chris Lattner8d327672003-06-30 03:36:09 +00001062void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001063 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1064 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001065 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1066 if (ONMI != OldNodeMap.end()) {
1067 Links[i].setNode(ONMI->second.getNode());
1068 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1069 }
Chris Lattner2f561382004-01-22 16:56:13 +00001070 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001071}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001072
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001073/// updateFromGlobalGraph - This function rematerializes global nodes and
1074/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001075/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1076/// are already up-to-date in the current graph. In practice, in the TD pass,
1077/// this is likely to be a large fraction of the live global nodes in each
1078/// function (since most live nodes are likely to have been brought up-to-date
1079/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001080///
1081void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001082 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001083 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1084
1085 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001086 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1087 E = getScalarMap().global_end(); I != E; ++I)
1088 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001089 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001090 if (It != GlobalsGraph->ScalarMap.end())
1091 RC.merge(getNodeForValue(*I), It->second);
1092 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001093}
1094
Chris Lattner5a540632003-06-30 03:15:25 +00001095/// cloneInto - Clone the specified DSGraph into the current graph. The
1096/// translated ScalarMap for the old function is filled into the OldValMap
1097/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1098///
1099/// The CloneFlags member controls various aspects of the cloning process.
1100///
Chris Lattner62482e52004-01-28 09:15:42 +00001101void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001102 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1103 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001104 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001105 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001106 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001107
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001108 // Remember the last node that existed before, or node_end() if there are no
1109 // nodes.
1110 node_iterator FN = node_end();
1111 if (FN != node_begin()) --FN;
Chris Lattner1e883692003-02-03 20:08:51 +00001112
1113 // 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 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I)
1119 if (!(*I)->isForwarding()) {
1120 DSNode *New = new DSNode(**I, this);
Chris Lattnera5ca28c2004-02-07 22:00:03 +00001121 New->maskNodeTypes(~BitsToClear);
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001122 OldNodeMap[*I] = New;
Chris Lattnera5ca28c2004-02-07 22:00:03 +00001123 }
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001124
Chris Lattner18552922002-11-18 21:44:46 +00001125#ifndef NDEBUG
1126 Timer::addPeakMemoryMeasurement();
1127#endif
1128
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001129 // Move FN to the first newly added node.
1130 if (FN != node_end())
1131 ++FN;
1132 else
1133 FN = node_begin();
1134
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001135 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001136 for (; FN != node_end(); ++FN)
1137 (*FN)->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001138
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001139 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001140 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001141 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001142 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001143 DSNodeHandle &H = OldValMap[I->first];
1144 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1145 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001146
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001147 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001148 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1149 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001150 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1151 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001152 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001153 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001154
Chris Lattner679e8e12002-11-08 21:27:12 +00001155 if (!(CloneFlags & DontCloneCallNodes)) {
1156 // Copy the function calls list...
1157 unsigned FC = FunctionCalls.size(); // FirstCall
1158 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1159 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1160 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001161 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001162
Chris Lattneracf491f2002-11-08 22:27:09 +00001163 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +00001164 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +00001165 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +00001166 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1167 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1168 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1169 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001170
Chris Lattner5a540632003-06-30 03:15:25 +00001171 // Map the return node pointers over...
1172 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1173 E = G.getReturnNodes().end(); I != E; ++I) {
1174 const DSNodeHandle &Ret = I->second;
1175 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1176 OldReturnNodes.insert(std::make_pair(I->first,
1177 DSNodeHandle(MappedRet.getNode(),
1178 MappedRet.getOffset()+Ret.getOffset())));
1179 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001180}
1181
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001182
Chris Lattner076c1f92002-11-07 06:31:54 +00001183/// mergeInGraph - The method is used for merging graphs together. If the
1184/// argument graph is not *this, it makes a clone of the specified graph, then
1185/// merges the nodes specified in the call site with the formal arguments in the
1186/// graph.
1187///
Chris Lattner9f930552003-06-30 05:27:18 +00001188void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1189 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001190 TIME_REGION(X, "mergeInGraph");
1191
Chris Lattner076c1f92002-11-07 06:31:54 +00001192 // If this is not a recursive call, clone the graph into this graph...
1193 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001194 // Clone the callee's graph into the current graph, keeping track of where
1195 // scalars in the old graph _used_ to point, and of the new nodes matching
1196 // nodes of the old graph.
1197 ReachabilityCloner RC(*this, Graph, CloneFlags);
1198
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001199 // Set up argument bindings
1200 Function::aiterator AI = F.abegin();
1201 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1202 // Advance the argument iterator to the first pointer argument...
1203 while (AI != F.aend() && !isPointerType(AI->getType())) {
1204 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001205#ifndef NDEBUG // FIXME: We should merge vararg arguments!
1206 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001207 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001208#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001209 }
1210 if (AI == F.aend()) break;
1211
1212 // Add the link from the argument scalar to the provided value.
Chris Lattner0b144872004-01-27 22:03:40 +00001213 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
Chris Lattner076c1f92002-11-07 06:31:54 +00001214 }
1215
Chris Lattner0b144872004-01-27 22:03:40 +00001216 // Map the return node pointer over.
1217 if (CS.getRetVal().getNode())
1218 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
1219
1220 // If requested, copy the calls or aux-calls lists.
1221 if (!(CloneFlags & DontCloneCallNodes)) {
1222 // Copy the function calls list...
1223 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1224 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1225 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1226 }
1227
1228 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1229 // Copy the auxiliary function calls list...
1230 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1231 Graph.AuxFunctionCalls.size());
1232 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1233 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i], RC));
1234 }
1235
1236 // If the user requested it, add the nodes that we need to clone to the
1237 // RootNodes set.
1238 if (!EnableDSNodeGlobalRootsHack)
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001239 for (node_iterator NI = Graph.node_begin(), E = Graph.node_end();
1240 NI != E; ++NI)
1241 if (!(*NI)->getGlobals().empty())
1242 RC.getClonedNH(*NI);
Chris Lattner0b144872004-01-27 22:03:40 +00001243
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001244 } else {
1245 DSNodeHandle RetVal = getReturnNodeFor(F);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001246
1247 // Merge the return value with the return value of the context...
1248 RetVal.mergeWith(CS.getRetVal());
1249
1250 // Resolve all of the function arguments...
1251 Function::aiterator AI = F.abegin();
1252
1253 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1254 // Advance the argument iterator to the first pointer argument...
1255 while (AI != F.aend() && !isPointerType(AI->getType())) {
1256 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001257#ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1258 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001259 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1260#endif
1261 }
1262 if (AI == F.aend()) break;
1263
1264 // Add the link from the argument scalar to the provided value
Chris Lattner0b144872004-01-27 22:03:40 +00001265 DSNodeHandle &NH = getNodeForValue(AI);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001266 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1267 NH.mergeWith(CS.getPtrArg(i));
1268 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001269 }
1270}
1271
Chris Lattner58f98d02003-07-02 04:38:49 +00001272/// getCallSiteForArguments - Get the arguments and return value bindings for
1273/// the specified function in the current graph.
1274///
1275DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1276 std::vector<DSNodeHandle> Args;
1277
1278 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1279 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001280 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001281
Chris Lattner808a7ae2003-09-20 16:34:13 +00001282 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001283}
1284
1285
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001286
Chris Lattner0d9bab82002-07-18 00:12:30 +00001287// markIncompleteNodes - Mark the specified node as having contents that are not
1288// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001289// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001290// must recursively traverse the data structure graph, marking all reachable
1291// nodes as incomplete.
1292//
1293static void markIncompleteNode(DSNode *N) {
1294 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001295 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001296
1297 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001298 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001299
Misha Brukman2f2d0652003-09-11 18:14:24 +00001300 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001301 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1302 if (DSNode *DSN = N->getLink(i).getNode())
1303 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001304}
1305
Chris Lattnere71ffc22002-11-11 03:36:55 +00001306static void markIncomplete(DSCallSite &Call) {
1307 // Then the return value is certainly incomplete!
1308 markIncompleteNode(Call.getRetVal().getNode());
1309
1310 // All objects pointed to by function arguments are incomplete!
1311 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1312 markIncompleteNode(Call.getPtrArg(i).getNode());
1313}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001314
1315// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1316// modified by other functions that have not been resolved yet. This marks
1317// nodes that are reachable through three sources of "unknownness":
1318//
1319// Global Variables, Function Calls, and Incoming Arguments
1320//
1321// For any node that may have unknown components (because something outside the
1322// scope of current analysis may have modified it), the 'Incomplete' flag is
1323// added to the NodeType.
1324//
Chris Lattner394471f2003-01-23 22:05:33 +00001325void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001326 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001327 if (Flags & DSGraph::MarkFormalArgs)
1328 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1329 FI != E; ++FI) {
1330 Function &F = *FI->first;
1331 if (F.getName() != "main")
1332 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001333 if (isPointerType(I->getType()))
1334 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001335 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001336
1337 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001338 if (!shouldPrintAuxCalls())
1339 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1340 markIncomplete(FunctionCalls[i]);
1341 else
1342 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1343 markIncomplete(AuxFunctionCalls[i]);
1344
Chris Lattner0d9bab82002-07-18 00:12:30 +00001345
Chris Lattner93d7a212003-02-09 18:41:49 +00001346 // Mark all global nodes as incomplete...
1347 if ((Flags & DSGraph::IgnoreGlobals) == 0)
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001348 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1349 if ((*NI)->isGlobalNode() && (*NI)->getNumLinks())
1350 markIncompleteNode(*NI);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001351}
1352
Chris Lattneraa8146f2002-11-10 06:59:55 +00001353static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1354 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001355 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001356 // No interesting info?
1357 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001358 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001359 Edge.setNode(0); // Kill the edge!
1360}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001361
Chris Lattneraa8146f2002-11-10 06:59:55 +00001362static inline bool nodeContainsExternalFunction(const DSNode *N) {
1363 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1364 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1365 if (Globals[i]->isExternal())
1366 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001367 return false;
1368}
1369
Chris Lattner5a540632003-06-30 03:15:25 +00001370static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001371 // Remove trivially identical function calls
1372 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001373 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1374
Chris Lattner0b144872004-01-27 22:03:40 +00001375#if 1
Chris Lattneraa8146f2002-11-10 06:59:55 +00001376 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001377 DSNode *LastCalleeNode = 0;
1378 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001379 unsigned NumDuplicateCalls = 0;
1380 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001381 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001382 DSCallSite &CS = Calls[i];
1383
Chris Lattnere4258442002-11-11 21:35:38 +00001384 // If the Callee is a useless edge, this must be an unreachable call site,
1385 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001386 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001387 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001388#ifndef NDEBUG
Chris Lattner923fc052003-02-05 21:59:58 +00001389 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001390#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001391 CS.swap(Calls.back());
1392 Calls.pop_back();
1393 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001394 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001395 // If the return value or any arguments point to a void node with no
1396 // information at all in it, and the call node is the only node to point
1397 // to it, remove the edge to the node (killing the node).
1398 //
1399 killIfUselessEdge(CS.getRetVal());
1400 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1401 killIfUselessEdge(CS.getPtrArg(a));
1402
1403 // If this call site calls the same function as the last call site, and if
1404 // the function pointer contains an external function, this node will
1405 // never be resolved. Merge the arguments of the call node because no
1406 // information will be lost.
1407 //
Chris Lattner923fc052003-02-05 21:59:58 +00001408 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1409 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001410 ++NumDuplicateCalls;
1411 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001412 if (LastCalleeNode)
1413 LastCalleeContainsExternalFunction =
1414 nodeContainsExternalFunction(LastCalleeNode);
1415 else
1416 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001417 }
Chris Lattner0b144872004-01-27 22:03:40 +00001418
1419 // It is not clear why, but enabling this code makes DSA really
1420 // sensitive to node forwarding. Basically, with this enabled, DSA
1421 // performs different number of inlinings based on which nodes are
1422 // forwarding or not. This is clearly a problem, so this code is
1423 // disabled until this can be resolved.
Chris Lattner58f98d02003-07-02 04:38:49 +00001424#if 1
Chris Lattner0b144872004-01-27 22:03:40 +00001425 if (LastCalleeContainsExternalFunction
1426#if 0
1427 ||
Chris Lattnere4258442002-11-11 21:35:38 +00001428 // This should be more than enough context sensitivity!
1429 // FIXME: Evaluate how many times this is tripped!
Chris Lattner0b144872004-01-27 22:03:40 +00001430 NumDuplicateCalls > 20
1431#endif
1432 ) {
Chris Lattnere4258442002-11-11 21:35:38 +00001433 DSCallSite &OCS = Calls[i-1];
1434 OCS.mergeWith(CS);
1435
1436 // The node will now be eliminated as a duplicate!
1437 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1438 CS = OCS;
1439 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1440 OCS = CS;
1441 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001442#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001443 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001444 if (CS.isDirectCall()) {
1445 LastCalleeFunc = CS.getCalleeFunc();
1446 LastCalleeNode = 0;
1447 } else {
1448 LastCalleeNode = CS.getCalleeNode();
1449 LastCalleeFunc = 0;
1450 }
Chris Lattnere4258442002-11-11 21:35:38 +00001451 NumDuplicateCalls = 0;
1452 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001453 }
1454 }
Chris Lattner0b144872004-01-27 22:03:40 +00001455#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001456 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001457
Chris Lattner33312f72002-11-08 01:21:07 +00001458 // Track the number of call nodes merged away...
1459 NumCallNodesMerged += NumFns-Calls.size();
1460
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001461 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001462 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001463}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001464
Chris Lattneraa8146f2002-11-10 06:59:55 +00001465
Chris Lattnere2219762002-07-18 18:22:40 +00001466// removeTriviallyDeadNodes - After the graph has been constructed, this method
1467// removes all unreachable nodes that are created because they got merged with
1468// other nodes in the graph. These nodes will all be trivially unreachable, so
1469// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001470//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001471void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001472 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattner5a540632003-06-30 03:15:25 +00001473 removeIdenticalCalls(FunctionCalls);
1474 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001475
Chris Lattnerbab8c282003-09-20 21:34:07 +00001476 // Loop over all of the nodes in the graph, calling getNode on each field.
1477 // This will cause all nodes to update their forwarding edges, causing
1478 // forwarded nodes to be delete-able.
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001479 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1480 DSNode *N = *NI;
Chris Lattnerbab8c282003-09-20 21:34:07 +00001481 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1482 N->getLink(l*N->getPointerSize()).getNode();
1483 }
1484
Chris Lattner0b144872004-01-27 22:03:40 +00001485 // NOTE: This code is disabled. Though it should, in theory, allow us to
1486 // remove more nodes down below, the scan of the scalar map is incredibly
1487 // expensive for certain programs (with large SCCs). In the future, if we can
1488 // make the scalar map scan more efficient, then we can reenable this.
1489#if 0
1490 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1491
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001492 // Likewise, forward any edges from the scalar nodes. While we are at it,
1493 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001494 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001495 I->second.getNode();
1496 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001497 }
Chris Lattner0b144872004-01-27 22:03:40 +00001498 }
1499#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001500 bool isGlobalsGraph = !GlobalsGraph;
1501
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001502 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001503 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001504
1505 // Do not remove *any* global nodes in the globals graph.
1506 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001507 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001508 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001509 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001510 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001511
Chris Lattner28897e12004-02-08 00:53:26 +00001512 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001513 // This is a useless node if it has no mod/ref info (checked above),
1514 // outgoing edges (which it cannot, as it is not modified in this
1515 // context), and it has no incoming edges. If it is a global node it may
1516 // have all of these properties and still have incoming edges, due to the
1517 // scalar map, so we check those now.
1518 //
Chris Lattner28897e12004-02-08 00:53:26 +00001519 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1520 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001521
Chris Lattner17a93e22004-01-29 03:32:15 +00001522 // Loop through and make sure all of the globals are referring directly
1523 // to the node...
1524 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1525 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001526 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001527 }
1528
Chris Lattnerbd92b732003-06-19 21:15:11 +00001529 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001530 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001531 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1532 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001533 Node.makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001534 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001535 }
1536 }
1537
Chris Lattner28897e12004-02-08 00:53:26 +00001538 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001539 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001540 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001541 } else {
1542 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001543 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001544 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001545}
1546
1547
Chris Lattner5c7380e2003-01-29 21:10:20 +00001548/// markReachableNodes - This method recursively traverses the specified
1549/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1550/// to the set, which allows it to only traverse visited nodes once.
1551///
Chris Lattner41c04f72003-02-01 04:52:08 +00001552void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001553 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001554 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001555 if (ReachableNodes.insert(this).second) // Is newly reachable?
1556 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1557 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001558}
1559
Chris Lattner41c04f72003-02-01 04:52:08 +00001560void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001561 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001562 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001563
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001564 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1565 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001566}
1567
Chris Lattnera1220af2003-02-01 06:17:02 +00001568// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1569// looking for a node that is marked alive. If an alive node is found, return
1570// true, otherwise return false. If an alive node is reachable, this node is
1571// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001572//
Chris Lattnera1220af2003-02-01 06:17:02 +00001573static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001574 hash_set<DSNode*> &Visited,
1575 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001576 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001577 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001578
Chris Lattner85cfe012003-07-03 02:03:53 +00001579 // If this is a global node, it will end up in the globals graph anyway, so we
1580 // don't need to worry about it.
1581 if (IgnoreGlobals && N->isGlobalNode()) return false;
1582
Chris Lattneraa8146f2002-11-10 06:59:55 +00001583 // If we know that this node is alive, return so!
1584 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001585
Chris Lattneraa8146f2002-11-10 06:59:55 +00001586 // Otherwise, we don't think the node is alive yet, check for infinite
1587 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001588 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001589 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001590
Chris Lattner08db7192002-11-06 06:20:27 +00001591 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001592 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1593 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001594 N->markReachableNodes(Alive);
1595 return true;
1596 }
1597 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001598}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001599
Chris Lattnera1220af2003-02-01 06:17:02 +00001600// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1601// alive nodes.
1602//
Chris Lattner41c04f72003-02-01 04:52:08 +00001603static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001604 hash_set<DSNode*> &Visited,
1605 bool IgnoreGlobals) {
1606 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1607 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001608 return true;
1609 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001610 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001611 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001612 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001613 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1614 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001615 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001616 return false;
1617}
1618
Chris Lattnere2219762002-07-18 18:22:40 +00001619// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1620// subgraphs that are unreachable. This often occurs because the data
1621// structure doesn't "escape" into it's caller, and thus should be eliminated
1622// from the caller's graph entirely. This is only appropriate to use when
1623// inlining graphs.
1624//
Chris Lattner394471f2003-01-23 22:05:33 +00001625void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001626 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001627
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001628 // Reduce the amount of work we have to do... remove dummy nodes left over by
1629 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001630 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001631
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001632 TIME_REGION(X, "removeDeadNodes");
1633
Misha Brukman2f2d0652003-09-11 18:14:24 +00001634 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001635
1636 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001637 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001638 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001639
Chris Lattner0b144872004-01-27 22:03:40 +00001640 // Copy and merge all information about globals to the GlobalsGraph if this is
1641 // not a final pass (where unreachable globals are removed).
1642 //
1643 // Strip all alloca bits since the current function is only for the BU pass.
1644 // Strip all incomplete bits since they are short-lived properties and they
1645 // will be correctly computed when rematerializing nodes into the functions.
1646 //
1647 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1648 DSGraph::StripIncompleteBit);
1649
Chris Lattneraa8146f2002-11-10 06:59:55 +00001650 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner00948c02004-01-28 02:05:05 +00001651 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
Chris Lattner62482e52004-01-28 09:15:42 +00001652 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001653 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001654 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001655 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001656 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001657
1658 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001659 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1660 DSGraph::ScalarMapTy::iterator SMI =
1661 GlobalsGraph->getScalarMap().find(I->first);
1662 if (SMI != GlobalsGraph->getScalarMap().end())
1663 GGCloner.merge(SMI->second, I->second);
1664 else
1665 GGCloner.getClonedNH(I->second);
1666 }
Chris Lattner0b144872004-01-27 22:03:40 +00001667 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001668 } else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001669 DSNode *N = I->second.getNode();
1670#if 0
Chris Lattner0b144872004-01-27 22:03:40 +00001671 // Check to see if this is a worthless node generated for non-pointer
1672 // values, such as integers. Consider an addition of long types: A+B.
1673 // Assuming we can track all uses of the value in this context, and it is
1674 // NOT used as a pointer, we can delete the node. We will be able to
1675 // detect this situation if the node pointed to ONLY has Unknown bit set
1676 // in the node. In this case, the node is not incomplete, does not point
1677 // to any other nodes (no mod/ref bits set), and is therefore
1678 // uninteresting for data structure analysis. If we run across one of
1679 // these, prune the scalar pointing to it.
1680 //
Chris Lattner0b144872004-01-27 22:03:40 +00001681 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1682 ScalarMap.erase(I++);
1683 else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001684#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001685 N->markReachableNodes(Alive);
1686 ++I;
Chris Lattnera88a55c2004-01-28 02:41:32 +00001687 //}
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001688 }
Chris Lattner00948c02004-01-28 02:05:05 +00001689 }
Chris Lattnere2219762002-07-18 18:22:40 +00001690
Chris Lattner0b144872004-01-27 22:03:40 +00001691 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001692 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1693 I != E; ++I)
1694 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001695
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001696 // Mark any nodes reachable by primary calls as alive...
1697 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1698 FunctionCalls[i].markReachableNodes(Alive);
1699
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001700
1701 // Now find globals and aux call nodes that are already live or reach a live
1702 // value (which makes them live in turn), and continue till no more are found.
1703 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001704 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001705 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001706 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1707 do {
1708 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001709 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001710 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001711 // unreachable globals in the list.
1712 //
1713 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001714 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001715 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1716 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1717 Flags & DSGraph::RemoveUnreachableGlobals)) {
1718 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1719 GlobalNodes.pop_back(); // erase efficiently
1720 Iterate = true;
1721 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001722
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001723 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1724 // call nodes that get resolved will be difficult to remove from that graph.
1725 // The final unresolved call nodes must be handled specially at the end of
1726 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001727 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1728 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001729 (AuxFunctionCalls[i].isIndirectCall()
1730 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1731 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001732 AuxFunctionCalls[i].markReachableNodes(Alive);
1733 AuxFCallsAlive[i] = true;
1734 Iterate = true;
1735 }
1736 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001737
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001738 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001739 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001740 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1741 if (AuxFCallsAlive[i])
1742 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001743
1744 // Copy and merge all global nodes and dead aux call nodes into the
1745 // GlobalsGraph, and all nodes reachable from those nodes
1746 //
1747 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001748 // Copy the unreachable call nodes to the globals graph, updating their
1749 // target pointers using the GGCloner
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001750 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1751 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
Chris Lattner0b144872004-01-27 22:03:40 +00001752 GGCloner));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001753 }
1754 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001755 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1756 AuxFunctionCalls.end());
1757
Chris Lattner0b144872004-01-27 22:03:40 +00001758 // We are finally done with the GGCloner so we can clear it and then get rid
1759 // of unused nodes in the GlobalsGraph produced by merging.
1760 if (GGCloner.clonedNode()) {
1761 GGCloner.destroy();
1762 GlobalsGraph->removeTriviallyDeadNodes();
1763 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001764
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001765 // At this point, any nodes which are visited, but not alive, are nodes
1766 // which can be removed. Loop over all nodes, eliminating completely
1767 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001768 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001769 std::vector<DSNode*> DeadNodes;
1770 DeadNodes.reserve(Nodes.size());
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001771 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;)
Chris Lattner28897e12004-02-08 00:53:26 +00001772 if (!Alive.count(NI)) {
Chris Lattnere92e7642004-02-07 23:58:05 +00001773 ++NumDNE;
Chris Lattner28897e12004-02-08 00:53:26 +00001774 DSNode *N = Nodes.remove(NI++);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001775 DeadNodes.push_back(N);
1776 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001777 } else {
Chris Lattner28897e12004-02-08 00:53:26 +00001778 assert(NI->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001779 ++NI;
Chris Lattnere2219762002-07-18 18:22:40 +00001780 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001781
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001782 // Remove all unreachable globals from the ScalarMap.
1783 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1784 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001785 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001786 if (!Alive.count(GlobalNodes[i].second))
1787 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00001788 else
1789 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001790
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001791 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001792 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1793 delete DeadNodes[i];
1794
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001795 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001796}
1797
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001798void DSGraph::AssertGraphOK() const {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001799 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1800 (*NI)->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001801
Chris Lattner8d327672003-06-30 03:36:09 +00001802 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001803 E = ScalarMap.end(); I != E; ++I) {
1804 assert(I->second.getNode() && "Null node in scalarmap!");
1805 AssertNodeInGraph(I->second.getNode());
1806 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001807 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001808 "Global points to node, but node isn't global?");
1809 AssertNodeContainsGlobal(I->second.getNode(), GV);
1810 }
1811 }
1812 AssertCallNodesInGraph();
1813 AssertAuxCallNodesInGraph();
1814}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001815
Chris Lattner400433d2003-11-11 05:08:59 +00001816/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1817/// nodes reachable from the two graphs, computing the mapping of nodes from
1818/// the first to the second graph.
1819///
1820void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001821 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1822 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001823 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1824 if (N1 == 0 || N2 == 0) return;
1825
1826 DSNodeHandle &Entry = NodeMap[N1];
1827 if (Entry.getNode()) {
1828 // Termination of recursion!
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001829 assert(!StrictChecking ||
1830 (Entry.getNode() == N2 &&
1831 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
Chris Lattner400433d2003-11-11 05:08:59 +00001832 "Inconsistent mapping detected!");
1833 return;
1834 }
1835
1836 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001837 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001838
1839 // Loop over all of the fields that N1 and N2 have in common, recursively
1840 // mapping the edges together now.
1841 int N2Idx = NH2.getOffset()-NH1.getOffset();
1842 unsigned N2Size = N2->getSize();
1843 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1844 if (unsigned(N2Idx)+i < N2Size)
1845 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1846}