blob: df5530c15df7721c40001d1a245ae7da50d517af [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00009//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner4dabb2c2004-07-07 06:32:21 +000014#include "llvm/Analysis/DataStructure/DSGraphTraits.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000015#include "llvm/Function.h"
Chris Lattnercf14e712004-02-25 23:36:08 +000016#include "llvm/GlobalVariable.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000017#include "llvm/Instructions.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000018#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000019#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000020#include "llvm/Assembly/Writer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000021#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/Debug.h"
23#include "llvm/ADT/DepthFirstIterator.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000027#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000028using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000029
Chris Lattnerb29dd0f2004-12-08 21:03:56 +000030#define COLLAPSE_ARRAYS_AGGRESSIVELY 0
31
Chris Lattner08db7192002-11-06 06:20:27 +000032namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000033 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
34 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
35 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
36 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000037 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
38 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Chris Lattner08db7192002-11-06 06:20:27 +000039};
40
Chris Lattnera88a55c2004-01-28 02:41:32 +000041#if 1
Chris Lattner93ddd7e2004-01-22 16:36:28 +000042#define TIME_REGION(VARNAME, DESC) \
43 NamedRegionTimer VARNAME(DESC)
44#else
45#define TIME_REGION(VARNAME, DESC)
46#endif
47
Chris Lattnerb1060432002-11-07 05:20:53 +000048using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000049
Chris Lattner6f967742004-10-30 04:05:01 +000050/// isForwarding - Return true if this NodeHandle is forwarding to another
51/// one.
52bool DSNodeHandle::isForwarding() const {
53 return N && N->isForwarding();
54}
55
Chris Lattner731b2d72003-02-13 19:09:00 +000056DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000057 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000058
59 // Handle node forwarding here!
60 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
61 Offset += N->ForwardNH.getOffset();
62
63 if (--N->NumReferrers == 0) {
64 // Removing the last referrer to the node, sever the forwarding link
65 N->stopForwarding();
66 }
67
68 N = Next;
69 N->NumReferrers++;
70 if (N->Size <= Offset) {
71 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
72 Offset = 0;
73 }
74 return N;
75}
76
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000077//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000078// DSNode Implementation
79//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000080
Chris Lattnerbd92b732003-06-19 21:15:11 +000081DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000082 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000083 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000084 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +000085 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000086 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000087}
88
Chris Lattner0d9bab82002-07-18 00:12:30 +000089// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +000090DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +000091 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattnerf590ced2004-03-04 17:06:53 +000092 Ty(N.Ty), NodeType(N.NodeType) {
93 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +000094 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +000095 Globals = N.Globals;
96 } else
Chris Lattner0b144872004-01-27 22:03:40 +000097 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +000098 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000099 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000100}
101
Chris Lattner15869aa2003-11-02 22:27:28 +0000102/// getTargetData - Get the target data object used to construct this node.
103///
104const TargetData &DSNode::getTargetData() const {
105 return ParentGraph->getTargetData();
106}
107
Chris Lattner72d29a42003-02-11 23:11:51 +0000108void DSNode::assertOK() const {
109 assert((Ty != Type::VoidTy ||
110 Ty == Type::VoidTy && (Size == 0 ||
111 (NodeType & DSNode::Array))) &&
112 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000113
114 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000115 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000116 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnera88a55c2004-01-28 02:41:32 +0000117 assert(SM.count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000118 assert(SM.find(Globals[i])->second.getNode() == this);
119 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000120}
121
122/// forwardNode - Mark this node as being obsolete, and all references to it
123/// should be forwarded to the specified node and offset.
124///
125void DSNode::forwardNode(DSNode *To, unsigned Offset) {
126 assert(this != To && "Cannot forward a node to itself!");
127 assert(ForwardNH.isNull() && "Already forwarding from this node!");
128 if (To->Size <= 1) Offset = 0;
129 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
130 "Forwarded offset is wrong!");
Chris Lattnerefffdc92004-07-07 06:12:52 +0000131 ForwardNH.setTo(To, Offset);
Chris Lattner72d29a42003-02-11 23:11:51 +0000132 NodeType = DEAD;
133 Size = 0;
134 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000135
136 // Remove this node from the parent graph's Nodes list.
137 ParentGraph->unlinkNode(this);
138 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000139}
140
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000141// addGlobal - Add an entry for a global value to the Globals list. This also
142// marks the node with the 'G' flag if it does not already have it.
143//
144void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000145 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000146 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000147 std::lower_bound(Globals.begin(), Globals.end(), GV);
148
149 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000150 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000151 Globals.insert(I, GV);
152 NodeType |= GlobalNode;
153 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000154}
155
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000156/// foldNodeCompletely - If we determine that this node has some funny
157/// behavior happening to it that we cannot represent, we fold it down to a
158/// single, completely pessimistic, node. This node is represented as a
159/// single byte with a single TypeEntry of "void".
160///
161void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000162 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000163
Chris Lattner08db7192002-11-06 06:20:27 +0000164 ++NumFolds;
165
Chris Lattner0b144872004-01-27 22:03:40 +0000166 // If this node has a size that is <= 1, we don't need to create a forwarding
167 // node.
168 if (getSize() <= 1) {
169 NodeType |= DSNode::Array;
170 Ty = Type::VoidTy;
171 Size = 1;
172 assert(Links.size() <= 1 && "Size is 1, but has more links?");
173 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000174 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000175 // Create the node we are going to forward to. This is required because
176 // some referrers may have an offset that is > 0. By forcing them to
177 // forward, the forwarder has the opportunity to correct the offset.
178 DSNode *DestNode = new DSNode(0, ParentGraph);
179 DestNode->NodeType = NodeType|DSNode::Array;
180 DestNode->Ty = Type::VoidTy;
181 DestNode->Size = 1;
182 DestNode->Globals.swap(Globals);
183
184 // Start forwarding to the destination node...
185 forwardNode(DestNode, 0);
186
187 if (!Links.empty()) {
188 DestNode->Links.reserve(1);
189
190 DSNodeHandle NH(DestNode);
191 DestNode->Links.push_back(Links[0]);
192
193 // If we have links, merge all of our outgoing links together...
194 for (unsigned i = Links.size()-1; i != 0; --i)
195 NH.getNode()->Links[0].mergeWith(Links[i]);
196 Links.clear();
197 } else {
198 DestNode->Links.resize(1);
199 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000200 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000201}
Chris Lattner076c1f92002-11-07 06:31:54 +0000202
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000203/// isNodeCompletelyFolded - Return true if this node has been completely
204/// folded down to something that can never be expanded, effectively losing
205/// all of the field sensitivity that may be present in the node.
206///
207bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000208 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000209}
210
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000211namespace {
212 /// TypeElementWalker Class - Used for implementation of physical subtyping...
213 ///
214 class TypeElementWalker {
215 struct StackState {
216 const Type *Ty;
217 unsigned Offset;
218 unsigned Idx;
219 StackState(const Type *T, unsigned Off = 0)
220 : Ty(T), Offset(Off), Idx(0) {}
221 };
222
223 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000224 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000225 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000226 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000227 Stack.push_back(T);
228 StepToLeaf();
229 }
230
231 bool isDone() const { return Stack.empty(); }
232 const Type *getCurrentType() const { return Stack.back().Ty; }
233 unsigned getCurrentOffset() const { return Stack.back().Offset; }
234
235 void StepToNextType() {
236 PopStackAndAdvance();
237 StepToLeaf();
238 }
239
240 private:
241 /// PopStackAndAdvance - Pop the current element off of the stack and
242 /// advance the underlying element to the next contained member.
243 void PopStackAndAdvance() {
244 assert(!Stack.empty() && "Cannot pop an empty stack!");
245 Stack.pop_back();
246 while (!Stack.empty()) {
247 StackState &SS = Stack.back();
248 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
249 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000250 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000251 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattner507bdf92005-01-12 04:51:37 +0000252 SS.Offset +=
253 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000254 return;
255 }
256 Stack.pop_back(); // At the end of the structure
257 } else {
258 const ArrayType *AT = cast<ArrayType>(SS.Ty);
259 ++SS.Idx;
260 if (SS.Idx != AT->getNumElements()) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000261 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000262 return;
263 }
264 Stack.pop_back(); // At the end of the array
265 }
266 }
267 }
268
269 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
270 /// on the type stack.
271 void StepToLeaf() {
272 if (Stack.empty()) return;
273 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
274 StackState &SS = Stack.back();
275 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000276 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000277 assert(SS.Idx == 0);
278 PopStackAndAdvance();
279 } else {
280 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000281 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000282 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000283 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner507bdf92005-01-12 04:51:37 +0000284 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000285 }
286 } else {
287 const ArrayType *AT = cast<ArrayType>(SS.Ty);
288 if (AT->getNumElements() == 0) {
289 assert(SS.Idx == 0);
290 PopStackAndAdvance();
291 } else {
292 // Step into the array...
293 assert(SS.Idx < AT->getNumElements());
294 Stack.push_back(StackState(AT->getElementType(),
295 SS.Offset+SS.Idx*
Chris Lattner507bdf92005-01-12 04:51:37 +0000296 unsigned(TD.getTypeSize(AT->getElementType()))));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000297 }
298 }
299 }
300 }
301 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000302} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000303
304/// ElementTypesAreCompatible - Check to see if the specified types are
305/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000306/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
307/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000308///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000309static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000310 bool AllowLargerT1, const TargetData &TD){
311 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000312
313 while (!T1W.isDone() && !T2W.isDone()) {
314 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
315 return false;
316
317 const Type *T1 = T1W.getCurrentType();
318 const Type *T2 = T2W.getCurrentType();
319 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
320 return false;
321
322 T1W.StepToNextType();
323 T2W.StepToNextType();
324 }
325
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000326 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000327}
328
329
Chris Lattner08db7192002-11-06 06:20:27 +0000330/// mergeTypeInfo - This method merges the specified type into the current node
331/// at the specified offset. This may update the current node's type record if
332/// this gives more information to the node, it may do nothing to the node if
333/// this information is already known, or it may merge the node completely (and
334/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000335///
Chris Lattner08db7192002-11-06 06:20:27 +0000336/// This method returns true if the node is completely folded, otherwise false.
337///
Chris Lattner088b6392003-03-03 17:13:31 +0000338bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
339 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000340 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000341 // Check to make sure the Size member is up-to-date. Size can be one of the
342 // following:
343 // Size = 0, Ty = Void: Nothing is known about this node.
344 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
345 // Size = 1, Ty = Void, Array = 1: The node is collapsed
346 // Otherwise, sizeof(Ty) = Size
347 //
Chris Lattner18552922002-11-18 21:44:46 +0000348 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
349 (Size == 0 && !Ty->isSized() && !isArray()) ||
350 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
351 (Size == 0 && !Ty->isSized() && !isArray()) ||
352 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000353 "Size member of DSNode doesn't match the type structure!");
354 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000355
Chris Lattner18552922002-11-18 21:44:46 +0000356 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000357 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000358
Chris Lattner08db7192002-11-06 06:20:27 +0000359 // Return true immediately if the node is completely folded.
360 if (isNodeCompletelyFolded()) return true;
361
Chris Lattner23f83dc2002-11-08 22:49:57 +0000362 // If this is an array type, eliminate the outside arrays because they won't
363 // be used anyway. This greatly reduces the size of large static arrays used
364 // as global variables, for example.
365 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000366 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000367 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
368 // FIXME: we might want to keep small arrays, but must be careful about
369 // things like: [2 x [10000 x int*]]
370 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000371 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000372 }
373
Chris Lattner08db7192002-11-06 06:20:27 +0000374 // Figure out how big the new type we're merging in is...
Chris Lattner507bdf92005-01-12 04:51:37 +0000375 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000376
377 // Otherwise check to see if we can fold this type into the current node. If
378 // we can't, we fold the node completely, if we can, we potentially update our
379 // internal state.
380 //
Chris Lattner18552922002-11-18 21:44:46 +0000381 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000382 // If this is the first type that this node has seen, just accept it without
383 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000384 assert(Offset == 0 && !isArray() &&
385 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000386 Ty = NewTy;
387 NodeType &= ~Array;
388 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000389 Size = NewTySize;
390
391 // Calculate the number of outgoing links from this node.
392 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
393 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000394 }
Chris Lattner08db7192002-11-06 06:20:27 +0000395
396 // Handle node expansion case here...
397 if (Offset+NewTySize > Size) {
398 // It is illegal to grow this node if we have treated it as an array of
399 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000400 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000401 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000402 return true;
403 }
404
405 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000406 std::cerr << "UNIMP: Trying to merge a growth type into "
407 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000408 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000409 return true;
410 }
411
412 // Okay, the situation is nice and simple, we are trying to merge a type in
413 // at offset 0 that is bigger than our current type. Implement this by
414 // switching to the new type and then merge in the smaller one, which should
415 // hit the other code path here. If the other code path decides it's not
416 // ok, it will collapse the node as appropriate.
417 //
Chris Lattner18552922002-11-18 21:44:46 +0000418 const Type *OldTy = Ty;
419 Ty = NewTy;
420 NodeType &= ~Array;
421 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000422 Size = NewTySize;
423
424 // Must grow links to be the appropriate size...
425 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
426
427 // Merge in the old type now... which is guaranteed to be smaller than the
428 // "current" type.
429 return mergeTypeInfo(OldTy, 0);
430 }
431
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000432 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000433 "Cannot merge something into a part of our type that doesn't exist!");
434
Chris Lattner18552922002-11-18 21:44:46 +0000435 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000436 // type that starts at offset Offset.
437 //
438 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000439 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000440 while (O < Offset) {
441 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
442
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000443 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000444 case Type::StructTyID: {
445 const StructType *STy = cast<StructType>(SubType);
446 const StructLayout &SL = *TD.getStructLayout(STy);
447
448 unsigned i = 0, e = SL.MemberOffsets.size();
449 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
450 /* empty */;
451
452 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000453 SubType = STy->getElementType(i);
Chris Lattner507bdf92005-01-12 04:51:37 +0000454 O += (unsigned)SL.MemberOffsets[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000455 break;
456 }
457 case Type::ArrayTyID: {
458 SubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000459 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000460 unsigned Remainder = (Offset-O) % ElSize;
461 O = Offset-Remainder;
462 break;
463 }
464 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000465 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000466 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000467 }
468 }
469
470 assert(O == Offset && "Could not achieve the correct offset!");
471
472 // If we found our type exactly, early exit
473 if (SubType == NewTy) return false;
474
Misha Brukman96a8bd72004-04-29 04:05:30 +0000475 // Differing function types don't require us to merge. They are not values
476 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000477 if (isa<FunctionType>(SubType) &&
478 isa<FunctionType>(NewTy)) return false;
479
Chris Lattner507bdf92005-01-12 04:51:37 +0000480 unsigned SubTypeSize = SubType->isSized() ?
481 (unsigned)TD.getTypeSize(SubType) : 0;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000482
483 // Ok, we are getting desperate now. Check for physical subtyping, where we
484 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000485 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000486 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000487 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000488 return false;
489
Chris Lattner08db7192002-11-06 06:20:27 +0000490 // Okay, so we found the leader type at the offset requested. Search the list
491 // of types that starts at this offset. If SubType is currently an array or
492 // structure, the type desired may actually be the first element of the
493 // composite type...
494 //
Chris Lattner18552922002-11-18 21:44:46 +0000495 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000496 while (SubType != NewTy) {
497 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000498 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000499 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000500 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000501 case Type::StructTyID: {
502 const StructType *STy = cast<StructType>(SubType);
503 const StructLayout &SL = *TD.getStructLayout(STy);
504 if (SL.MemberOffsets.size() > 1)
Chris Lattner507bdf92005-01-12 04:51:37 +0000505 NextPadSize = (unsigned)SL.MemberOffsets[1];
Chris Lattner18552922002-11-18 21:44:46 +0000506 else
507 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000508 NextSubType = STy->getElementType(0);
Chris Lattner507bdf92005-01-12 04:51:37 +0000509 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000510 break;
Chris Lattner18552922002-11-18 21:44:46 +0000511 }
Chris Lattner08db7192002-11-06 06:20:27 +0000512 case Type::ArrayTyID:
513 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000514 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner18552922002-11-18 21:44:46 +0000515 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000516 break;
517 default: ;
518 // fall out
519 }
520
521 if (NextSubType == 0)
522 break; // In the default case, break out of the loop
523
Chris Lattner18552922002-11-18 21:44:46 +0000524 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000525 break; // Don't allow shrinking to a smaller type than NewTySize
526 SubType = NextSubType;
527 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000528 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000529 }
530
531 // If we found the type exactly, return it...
532 if (SubType == NewTy)
533 return false;
534
535 // Check to see if we have a compatible, but different type...
536 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000537 // Check to see if this type is obviously convertible... int -> uint f.e.
538 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000539 return false;
540
541 // Check to see if we have a pointer & integer mismatch going on here,
542 // loading a pointer as a long, for example.
543 //
544 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
545 NewTy->isInteger() && isa<PointerType>(SubType))
546 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000547 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
548 // We are accessing the field, plus some structure padding. Ignore the
549 // structure padding.
550 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000551 }
552
Chris Lattner58f98d02003-07-02 04:38:49 +0000553 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000554 if (getParentGraph()->getReturnNodes().size())
555 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000556 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
557 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
558 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
559 << "SubType: ";
560 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000561
Chris Lattner088b6392003-03-03 17:13:31 +0000562 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000563 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000564}
565
Chris Lattner08db7192002-11-06 06:20:27 +0000566
567
Misha Brukman96a8bd72004-04-29 04:05:30 +0000568/// addEdgeTo - Add an edge from the current node to the specified node. This
569/// can cause merging of nodes in the graph.
570///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000571void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000572 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000573
Chris Lattner08db7192002-11-06 06:20:27 +0000574 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000575 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000576 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000577 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000578 } else { // No merging to perform...
579 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000580 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000581}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000582
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000583
Misha Brukman96a8bd72004-04-29 04:05:30 +0000584/// MergeSortedVectors - Efficiently merge a vector into another vector where
585/// duplicates are not allowed and both are sorted. This assumes that 'T's are
586/// efficiently copyable and have sane comparison semantics.
587///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000588static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
589 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000590 // By far, the most common cases will be the simple ones. In these cases,
591 // avoid having to allocate a temporary vector...
592 //
593 if (Src.empty()) { // Nothing to merge in...
594 return;
595 } else if (Dest.empty()) { // Just copy the result in...
596 Dest = Src;
597 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000598 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000599 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000600 std::lower_bound(Dest.begin(), Dest.end(), V);
601 if (I == Dest.end() || *I != Src[0]) // If not already contained...
602 Dest.insert(I, Src[0]);
603 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000604 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000605 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000606 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000607 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
608 if (I == Dest.end() || *I != Tmp) // If not already contained...
609 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000610
611 } else {
612 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000613 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000614
615 // Make space for all of the type entries now...
616 Dest.resize(Dest.size()+Src.size());
617
618 // Merge the two sorted ranges together... into Dest.
619 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
620
621 // Now erase any duplicate entries that may have accumulated into the
622 // vectors (because they were in both of the input sets)
623 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
624 }
625}
626
Chris Lattner0b144872004-01-27 22:03:40 +0000627void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
628 MergeSortedVectors(Globals, RHS);
629}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000630
Chris Lattner0b144872004-01-27 22:03:40 +0000631// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000632// This function does the hard work of merging two nodes, CurNodeH
633// and NH after filtering out trivial cases and making sure that
634// CurNodeH.offset >= NH.offset.
635//
636// ***WARNING***
637// Since merging may cause either node to go away, we must always
638// use the node-handles to refer to the nodes. These node handles are
639// automatically updated during merging, so will always provide access
640// to the correct node after a merge.
641//
642void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
643 assert(CurNodeH.getOffset() >= NH.getOffset() &&
644 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000645 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
646 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000647
648 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
649 // respect to NH.Offset) is now zero. NOffset is the distance from the base
650 // of our object that N starts from.
651 //
652 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
653 unsigned NSize = NH.getNode()->getSize();
654
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000655 // If the two nodes are of different size, and the smaller node has the array
656 // bit set, collapse!
657 if (NSize != CurNodeH.getNode()->getSize()) {
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000658#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000659 if (NSize < CurNodeH.getNode()->getSize()) {
660 if (NH.getNode()->isArray())
661 NH.getNode()->foldNodeCompletely();
662 } else if (CurNodeH.getNode()->isArray()) {
663 NH.getNode()->foldNodeCompletely();
664 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000665#endif
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000666 }
667
668 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000669 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000670 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000671 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000672
673 // If we are merging a node with a completely folded node, then both nodes are
674 // now completely folded.
675 //
676 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
677 if (!NH.getNode()->isNodeCompletelyFolded()) {
678 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000679 assert(NH.getNode() && NH.getOffset() == 0 &&
680 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000681 NOffset = NH.getOffset();
682 NSize = NH.getNode()->getSize();
683 assert(NOffset == 0 && NSize == 1);
684 }
685 } else if (NH.getNode()->isNodeCompletelyFolded()) {
686 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000687 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
688 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000689 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000690 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000691 assert(NOffset == 0 && NSize == 1);
692 }
693
Chris Lattner72d29a42003-02-11 23:11:51 +0000694 DSNode *N = NH.getNode();
695 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000696 assert(!CurNodeH.getNode()->isDeadNode());
697
Chris Lattner0b144872004-01-27 22:03:40 +0000698 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000699 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000700
Chris Lattner72d29a42003-02-11 23:11:51 +0000701 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000702 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000703 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000704
Chris Lattner72d29a42003-02-11 23:11:51 +0000705 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
706 //
707 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
708 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000709 if (Link.getNode()) {
710 // Compute the offset into the current node at which to
711 // merge this link. In the common case, this is a linear
712 // relation to the offset in the original node (with
713 // wrapping), but if the current node gets collapsed due to
714 // recursive merging, we must make sure to merge in all remaining
715 // links at offset zero.
716 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000717 DSNode *CN = CurNodeH.getNode();
718 if (CN->Size != 1)
719 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
720 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000721 }
722 }
723
724 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000725 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000726
727 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000728 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000729 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000730
731 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000732 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000733 }
734}
735
736
Misha Brukman96a8bd72004-04-29 04:05:30 +0000737/// mergeWith - Merge this node and the specified node, moving all links to and
738/// from the argument node into the current node, deleting the node argument.
739/// Offset indicates what offset the specified node is to be merged into the
740/// current node.
741///
742/// The specified node may be a null pointer (in which case, we update it to
743/// point to this node).
744///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000745void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
746 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000747 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000748 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000749
Chris Lattner5254a8d2004-01-22 16:31:08 +0000750 // If the RHS is a null node, make it point to this node!
751 if (N == 0) {
752 NH.mergeWith(DSNodeHandle(this, Offset));
753 return;
754 }
755
Chris Lattnerbd92b732003-06-19 21:15:11 +0000756 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000757 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
758
Chris Lattner02606632002-11-04 06:48:26 +0000759 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000760 // We cannot merge two pieces of the same node together, collapse the node
761 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000762 DEBUG(std::cerr << "Attempting to merge two chunks of"
763 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000764 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000765 return;
766 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000767
Chris Lattner5190ce82002-11-12 07:20:45 +0000768 // If both nodes are not at offset 0, make sure that we are merging the node
769 // at an later offset into the node with the zero offset.
770 //
771 if (Offset < NH.getOffset()) {
772 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
773 return;
774 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
775 // If the offsets are the same, merge the smaller node into the bigger node
776 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
777 return;
778 }
779
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000780 // Ok, now we can merge the two nodes. Use a static helper that works with
781 // two node handles, since "this" may get merged away at intermediate steps.
782 DSNodeHandle CurNodeH(this, Offset);
783 DSNodeHandle NHCopy(NH);
784 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000785}
786
Chris Lattner0b144872004-01-27 22:03:40 +0000787
788//===----------------------------------------------------------------------===//
789// ReachabilityCloner Implementation
790//===----------------------------------------------------------------------===//
791
792DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
793 if (SrcNH.isNull()) return DSNodeHandle();
794 const DSNode *SN = SrcNH.getNode();
795
796 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000797 if (!NH.isNull()) { // Node already mapped?
798 DSNode *NHN = NH.getNode();
799 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
800 }
Chris Lattner0b144872004-01-27 22:03:40 +0000801
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000802 // If SrcNH has globals and the destination graph has one of the same globals,
803 // merge this node with the destination node, which is much more efficient.
804 if (SN->global_begin() != SN->global_end()) {
805 DSScalarMap &DestSM = Dest.getScalarMap();
806 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
807 I != E; ++I) {
808 GlobalValue *GV = *I;
809 DSScalarMap::iterator GI = DestSM.find(GV);
810 if (GI != DestSM.end() && !GI->second.isNull()) {
811 // We found one, use merge instead!
812 merge(GI->second, Src.getNodeForValue(GV));
813 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000814 DSNode *NHN = NH.getNode();
815 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000816 }
817 }
818 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000819
Chris Lattner0b144872004-01-27 22:03:40 +0000820 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
821 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000822 NH = DN;
Chris Lattner0b144872004-01-27 22:03:40 +0000823
824 // Next, recursively clone all outgoing links as necessary. Note that
825 // adding these links can cause the node to collapse itself at any time, and
826 // the current node may be merged with arbitrary other nodes. For this
827 // reason, we must always go through NH.
828 DN = 0;
829 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
830 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
831 if (!SrcEdge.isNull()) {
832 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
833 // Compute the offset into the current node at which to
834 // merge this link. In the common case, this is a linear
835 // relation to the offset in the original node (with
836 // wrapping), but if the current node gets collapsed due to
837 // recursive merging, we must make sure to merge in all remaining
838 // links at offset zero.
839 unsigned MergeOffset = 0;
840 DSNode *CN = NH.getNode();
841 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +0000842 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +0000843 CN->addEdgeTo(MergeOffset, DestEdge);
844 }
845 }
846
847 // If this node contains any globals, make sure they end up in the scalar
848 // map with the correct offset.
849 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
850 I != E; ++I) {
851 GlobalValue *GV = *I;
852 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
853 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
854 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
855 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000856 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000857
858 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
859 Dest.getInlinedGlobals().insert(GV);
860 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000861 NH.getNode()->mergeGlobals(SN->getGlobals());
Chris Lattner0b144872004-01-27 22:03:40 +0000862
863 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
864}
865
866void ReachabilityCloner::merge(const DSNodeHandle &NH,
867 const DSNodeHandle &SrcNH) {
868 if (SrcNH.isNull()) return; // Noop
869 if (NH.isNull()) {
870 // If there is no destination node, just clone the source and assign the
871 // destination node to be it.
872 NH.mergeWith(getClonedNH(SrcNH));
873 return;
874 }
875
876 // Okay, at this point, we know that we have both a destination and a source
877 // node that need to be merged. Check to see if the source node has already
878 // been cloned.
879 const DSNode *SN = SrcNH.getNode();
880 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +0000881 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +0000882 DSNode *SCNHN = SCNH.getNode();
883 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +0000884 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000885 return; // Nothing to do!
886 }
Chris Lattner6f967742004-10-30 04:05:01 +0000887
Chris Lattner0b144872004-01-27 22:03:40 +0000888 // Okay, so the source node has not already been cloned. Instead of creating
889 // a new DSNode, only to merge it into the one we already have, try to perform
890 // the merge in-place. The only case we cannot handle here is when the offset
891 // into the existing node is less than the offset into the virtual node we are
892 // merging in. In this case, we have to extend the existing node, which
893 // requires an allocation anyway.
894 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
895 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000896 if (!DN->isNodeCompletelyFolded()) {
897 // Make sure the destination node is folded if the source node is folded.
898 if (SN->isNodeCompletelyFolded()) {
899 DN->foldNodeCompletely();
900 DN = NH.getNode();
901 } else if (SN->getSize() != DN->getSize()) {
902 // If the two nodes are of different size, and the smaller node has the
903 // array bit set, collapse!
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000904#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner0b144872004-01-27 22:03:40 +0000905 if (SN->getSize() < DN->getSize()) {
906 if (SN->isArray()) {
907 DN->foldNodeCompletely();
908 DN = NH.getNode();
909 }
910 } else if (DN->isArray()) {
911 DN->foldNodeCompletely();
912 DN = NH.getNode();
913 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000914#endif
Chris Lattner0b144872004-01-27 22:03:40 +0000915 }
916
917 // Merge the type entries of the two nodes together...
918 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
919 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
920 DN = NH.getNode();
921 }
922 }
923
924 assert(!DN->isDeadNode());
925
926 // Merge the NodeType information.
927 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
928
929 // Before we start merging outgoing links and updating the scalar map, make
930 // sure it is known that this is the representative node for the src node.
931 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
932
933 // If the source node contains any globals, make sure they end up in the
934 // scalar map with the correct offset.
935 if (SN->global_begin() != SN->global_end()) {
936 // Update the globals in the destination node itself.
937 DN->mergeGlobals(SN->getGlobals());
938
939 // Update the scalar map for the graph we are merging the source node
940 // into.
941 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
942 I != E; ++I) {
943 GlobalValue *GV = *I;
944 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
945 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
946 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
947 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +0000948 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000949
950 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
951 Dest.getInlinedGlobals().insert(GV);
952 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000953 NH.getNode()->mergeGlobals(SN->getGlobals());
Chris Lattner0b144872004-01-27 22:03:40 +0000954 }
955 } else {
956 // We cannot handle this case without allocating a temporary node. Fall
957 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +0000958 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
959 NewDN->maskNodeTypes(BitsToKeep);
960
961 unsigned NHOffset = NH.getOffset();
962 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +0000963
Chris Lattner0b144872004-01-27 22:03:40 +0000964 assert(NH.getNode() &&
965 (NH.getOffset() > NHOffset ||
966 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
967 "Merging did not adjust the offset!");
968
969 // Before we start merging outgoing links and updating the scalar map, make
970 // sure it is known that this is the representative node for the src node.
971 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +0000972
973 // If the source node contained any globals, make sure to create entries
974 // in the scalar map for them!
975 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
976 I != E; ++I) {
977 GlobalValue *GV = *I;
978 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
979 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
980 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
981 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
982 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
983 DestGNH.getOffset()+SrcGNH.getOffset()));
984
985 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
986 Dest.getInlinedGlobals().insert(GV);
987 }
Chris Lattner0b144872004-01-27 22:03:40 +0000988 }
989
990
991 // Next, recursively merge all outgoing links as necessary. Note that
992 // adding these links can cause the destination node to collapse itself at
993 // any time, and the current node may be merged with arbitrary other nodes.
994 // For this reason, we must always go through NH.
995 DN = 0;
996 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
997 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
998 if (!SrcEdge.isNull()) {
999 // Compute the offset into the current node at which to
1000 // merge this link. In the common case, this is a linear
1001 // relation to the offset in the original node (with
1002 // wrapping), but if the current node gets collapsed due to
1003 // recursive merging, we must make sure to merge in all remaining
1004 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +00001005 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +00001006 unsigned MergeOffset =
1007 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +00001008
Chris Lattnerf590ced2004-03-04 17:06:53 +00001009 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1010 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001011 // Perform the recursive merging. Make sure to create a temporary NH,
1012 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001013 merge(Tmp, SrcEdge);
1014 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001015 Tmp.mergeWith(getClonedNH(SrcEdge));
1016 // Merging this could cause all kinds of recursive things to happen,
1017 // culminating in the current node being eliminated. Since this is
1018 // possible, make sure to reaquire the link from 'CN'.
1019
1020 unsigned MergeOffset = 0;
1021 CN = SCNH.getNode();
1022 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1023 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001024 }
Chris Lattner0b144872004-01-27 22:03:40 +00001025 }
1026 }
1027}
1028
1029/// mergeCallSite - Merge the nodes reachable from the specified src call
1030/// site into the nodes reachable from DestCS.
1031void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
1032 const DSCallSite &SrcCS) {
1033 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1034 unsigned MinArgs = DestCS.getNumPtrArgs();
1035 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1036
1037 for (unsigned a = 0; a != MinArgs; ++a)
1038 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1039}
1040
1041
Chris Lattner9de906c2002-10-20 22:11:44 +00001042//===----------------------------------------------------------------------===//
1043// DSCallSite Implementation
1044//===----------------------------------------------------------------------===//
1045
Vikram S. Adve26b98262002-10-20 21:41:02 +00001046// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001047Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001048 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001049}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001050
Chris Lattner0b144872004-01-27 22:03:40 +00001051void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1052 ReachabilityCloner &RC) {
1053 NH = RC.getClonedNH(Src);
1054}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001055
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001056//===----------------------------------------------------------------------===//
1057// DSGraph Implementation
1058//===----------------------------------------------------------------------===//
1059
Chris Lattnera9d65662003-06-30 05:57:30 +00001060/// getFunctionNames - Return a space separated list of the name of the
1061/// functions in this graph (if any)
1062std::string DSGraph::getFunctionNames() const {
1063 switch (getReturnNodes().size()) {
1064 case 0: return "Globals graph";
1065 case 1: return getReturnNodes().begin()->first->getName();
1066 default:
1067 std::string Return;
1068 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1069 I != getReturnNodes().end(); ++I)
1070 Return += I->first->getName() + " ";
1071 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1072 return Return;
1073 }
1074}
1075
1076
Chris Lattner15869aa2003-11-02 22:27:28 +00001077DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001078 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001079 NodeMapTy NodeMap;
1080 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001081}
1082
Chris Lattner5a540632003-06-30 03:15:25 +00001083DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001084 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001085 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001086 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001087}
1088
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001089DSGraph::~DSGraph() {
1090 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001091 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001092 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001093 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001094 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001095
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001096 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001097 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1098 (*NI)->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001099
Chris Lattner28897e12004-02-08 00:53:26 +00001100 // Free all of the nodes.
1101 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001102}
1103
Chris Lattner0d9bab82002-07-18 00:12:30 +00001104// dump - Allow inspection of graph in a debugger.
1105void DSGraph::dump() const { print(std::cerr); }
1106
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001107
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001108/// remapLinks - Change all of the Links in the current node according to the
1109/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001110///
Chris Lattner8d327672003-06-30 03:36:09 +00001111void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001112 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1113 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001114 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001115 if (ONMI != OldNodeMap.end()) {
1116 DSNode *ONMIN = ONMI->second.getNode();
1117 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1118 }
Chris Lattner2f561382004-01-22 16:56:13 +00001119 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001120}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001121
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001122/// updateFromGlobalGraph - This function rematerializes global nodes and
1123/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001124/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1125/// are already up-to-date in the current graph. In practice, in the TD pass,
1126/// this is likely to be a large fraction of the live global nodes in each
1127/// function (since most live nodes are likely to have been brought up-to-date
1128/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001129///
1130void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001131 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001132 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1133
1134 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001135 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1136 E = getScalarMap().global_end(); I != E; ++I)
1137 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001138 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001139 if (It != GlobalsGraph->ScalarMap.end())
1140 RC.merge(getNodeForValue(*I), It->second);
1141 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001142}
1143
Chris Lattner5a540632003-06-30 03:15:25 +00001144/// cloneInto - Clone the specified DSGraph into the current graph. The
1145/// translated ScalarMap for the old function is filled into the OldValMap
1146/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1147///
1148/// The CloneFlags member controls various aspects of the cloning process.
1149///
Chris Lattner62482e52004-01-28 09:15:42 +00001150void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001151 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1152 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001153 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001154 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001155 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001156
Chris Lattner1e883692003-02-03 20:08:51 +00001157 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001158 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1159 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1160 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001161 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001162
Chris Lattnerd85645f2004-02-21 22:28:26 +00001163 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1164 assert(!(*I)->isForwarding() &&
1165 "Forward nodes shouldn't be in node list!");
1166 DSNode *New = new DSNode(**I, this);
1167 New->maskNodeTypes(~BitsToClear);
1168 OldNodeMap[*I] = New;
1169 }
1170
Chris Lattner18552922002-11-18 21:44:46 +00001171#ifndef NDEBUG
1172 Timer::addPeakMemoryMeasurement();
1173#endif
Chris Lattnerd85645f2004-02-21 22:28:26 +00001174
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001175 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001176 // Note that we don't loop over the node's list to do this. The problem is
1177 // that remaping links can cause recursive merging to happen, which means
1178 // that node_iterator's can get easily invalidated! Because of this, we
1179 // loop over the OldNodeMap, which contains all of the new nodes as the
1180 // .second element of the map elements. Also note that if we remap a node
1181 // more than once, we won't break anything.
1182 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1183 I != E; ++I)
1184 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001185
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001186 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001187 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001188 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001189 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001190 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner6f967742004-10-30 04:05:01 +00001191 DSNode *MappedNodeN = MappedNode.getNode();
1192 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001193 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001194
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001195 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001196 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1197 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001198 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1199 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001200 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001201 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001202
Chris Lattner679e8e12002-11-08 21:27:12 +00001203 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001204 // Copy the function calls list.
1205 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1206 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001207 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001208
Chris Lattneracf491f2002-11-08 22:27:09 +00001209 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001210 // Copy the auxiliary function calls list.
1211 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1212 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattner679e8e12002-11-08 21:27:12 +00001213 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001214
Chris Lattner5a540632003-06-30 03:15:25 +00001215 // Map the return node pointers over...
1216 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1217 E = G.getReturnNodes().end(); I != E; ++I) {
1218 const DSNodeHandle &Ret = I->second;
1219 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001220 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattner5a540632003-06-30 03:15:25 +00001221 OldReturnNodes.insert(std::make_pair(I->first,
Chris Lattner6f967742004-10-30 04:05:01 +00001222 DSNodeHandle(MappedRetN,
Chris Lattner5a540632003-06-30 03:15:25 +00001223 MappedRet.getOffset()+Ret.getOffset())));
1224 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001225}
1226
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001227static bool PathExistsToClonedNode(const DSNode *N, ReachabilityCloner &RC) {
Chris Lattner2f346902004-03-04 03:57:53 +00001228 if (N)
1229 for (df_iterator<const DSNode*> I = df_begin(N), E = df_end(N); I != E; ++I)
1230 if (RC.hasClonedNode(*I))
1231 return true;
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001232 return false;
1233}
1234
Chris Lattner2f346902004-03-04 03:57:53 +00001235static bool PathExistsToClonedNode(const DSCallSite &CS,
1236 ReachabilityCloner &RC) {
1237 if (PathExistsToClonedNode(CS.getRetVal().getNode(), RC))
1238 return true;
1239 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1240 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode(), RC))
1241 return true;
1242 return false;
1243}
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001244
Chris Lattnerbb753c42005-02-03 18:40:25 +00001245/// getFunctionArgumentsForCall - Given a function that is currently in this
1246/// graph, return the DSNodeHandles that correspond to the pointer-compatible
1247/// function arguments. The vector is filled in with the return value (or
1248/// null if it is not pointer compatible), followed by all of the
1249/// pointer-compatible arguments.
1250void DSGraph::getFunctionArgumentsForCall(Function *F,
1251 std::vector<DSNodeHandle> &Args) const {
1252 Args.push_back(getReturnNodeFor(*F));
1253 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1254 if (isPointerType(AI->getType())) {
1255 Args.push_back(getNodeForValue(AI));
1256 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1257 }
1258}
1259
Chris Lattnere8594442005-02-04 19:58:28 +00001260/// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1261/// nodes from G2 into 'this' graph, merging the bindings specified by the
1262/// call site (in this graph) with the bindings specified by the vector in G2.
1263/// The two DSGraphs must be different.
Chris Lattner076c1f92002-11-07 06:31:54 +00001264///
Chris Lattnere8594442005-02-04 19:58:28 +00001265void DSGraph::mergeInGraph(const DSCallSite &CS,
1266 std::vector<DSNodeHandle> &Args,
Chris Lattner9f930552003-06-30 05:27:18 +00001267 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001268 TIME_REGION(X, "mergeInGraph");
1269
Chris Lattner076c1f92002-11-07 06:31:54 +00001270 // If this is not a recursive call, clone the graph into this graph...
1271 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001272 // Clone the callee's graph into the current graph, keeping track of where
1273 // scalars in the old graph _used_ to point, and of the new nodes matching
1274 // nodes of the old graph.
1275 ReachabilityCloner RC(*this, Graph, CloneFlags);
1276
Chris Lattner0b144872004-01-27 22:03:40 +00001277 // Map the return node pointer over.
Chris Lattner0ad91702004-02-22 00:53:54 +00001278 if (!CS.getRetVal().isNull())
Chris Lattnerbb753c42005-02-03 18:40:25 +00001279 RC.merge(CS.getRetVal(), Args[0]);
Chris Lattnerf590ced2004-03-04 17:06:53 +00001280
Chris Lattnerbb753c42005-02-03 18:40:25 +00001281 // Map over all of the arguments.
1282 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001283 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001284 break;
Chris Lattnerbb753c42005-02-03 18:40:25 +00001285
1286 // Add the link from the argument scalar to the provided value.
1287 RC.merge(CS.getPtrArg(i), Args[i+1]);
1288 }
1289
Chris Lattner2f346902004-03-04 03:57:53 +00001290 // If requested, copy all of the calls.
Chris Lattner0b144872004-01-27 22:03:40 +00001291 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001292 // Copy the function calls list.
1293 for (fc_iterator I = Graph.fc_begin(), E = Graph.fc_end(); I != E; ++I)
1294 FunctionCalls.push_back(DSCallSite(*I, RC));
Chris Lattner0b144872004-01-27 22:03:40 +00001295 }
Chris Lattner2f346902004-03-04 03:57:53 +00001296
1297 // If the user has us copying aux calls (the normal case), set up a data
1298 // structure to keep track of which ones we've copied over.
Chris Lattnera9548d92005-01-30 23:51:02 +00001299 std::set<const DSCallSite*> CopiedAuxCall;
Chris Lattner0b144872004-01-27 22:03:40 +00001300
Chris Lattner0321b682004-02-27 20:05:15 +00001301 // Clone over all globals that appear in the caller and callee graphs.
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001302 hash_set<GlobalVariable*> NonCopiedGlobals;
Chris Lattner0321b682004-02-27 20:05:15 +00001303 for (DSScalarMap::global_iterator GI = Graph.getScalarMap().global_begin(),
1304 E = Graph.getScalarMap().global_end(); GI != E; ++GI)
1305 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*GI))
1306 if (ScalarMap.count(GV))
1307 RC.merge(ScalarMap[GV], Graph.getNodeForValue(GV));
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001308 else
1309 NonCopiedGlobals.insert(GV);
1310
1311 // If the global does not appear in the callers graph we generally don't
1312 // want to copy the node. However, if there is a path from the node global
1313 // node to a node that we did copy in the graph, we *must* copy it to
1314 // maintain the connection information. Every time we decide to include a
1315 // new global, this might make other globals live, so we must iterate
1316 // unfortunately.
Chris Lattner2f346902004-03-04 03:57:53 +00001317 bool MadeChange = true;
1318 while (MadeChange) {
1319 MadeChange = false;
1320 for (hash_set<GlobalVariable*>::iterator I = NonCopiedGlobals.begin();
1321 I != NonCopiedGlobals.end();) {
1322 DSNode *GlobalNode = Graph.getNodeForValue(*I).getNode();
1323 if (RC.hasClonedNode(GlobalNode)) {
1324 // Already cloned it, remove from set.
1325 NonCopiedGlobals.erase(I++);
1326 MadeChange = true;
1327 } else if (PathExistsToClonedNode(GlobalNode, RC)) {
1328 RC.getClonedNH(Graph.getNodeForValue(*I));
1329 NonCopiedGlobals.erase(I++);
1330 MadeChange = true;
1331 } else {
1332 ++I;
1333 }
1334 }
1335
1336 // If requested, copy any aux calls that can reach copied nodes.
1337 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001338 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
1339 if (CopiedAuxCall.insert(&*I).second &&
1340 PathExistsToClonedNode(*I, RC)) {
1341 AuxFunctionCalls.push_back(DSCallSite(*I, RC));
Chris Lattner2f346902004-03-04 03:57:53 +00001342 MadeChange = true;
1343 }
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001344 }
1345 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001346
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001347 } else {
Chris Lattnerbb753c42005-02-03 18:40:25 +00001348 // Merge the return value with the return value of the context.
1349 Args[0].mergeWith(CS.getRetVal());
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001350
Chris Lattnerbb753c42005-02-03 18:40:25 +00001351 // Resolve all of the function arguments.
1352 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001353 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001354 break;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001355
Chris Lattnerbb753c42005-02-03 18:40:25 +00001356 // Add the link from the argument scalar to the provided value.
1357 Args[i+1].mergeWith(CS.getPtrArg(i));
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001358 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001359 }
1360}
1361
Chris Lattnere8594442005-02-04 19:58:28 +00001362
1363
1364/// mergeInGraph - The method is used for merging graphs together. If the
1365/// argument graph is not *this, it makes a clone of the specified graph, then
1366/// merges the nodes specified in the call site with the formal arguments in the
1367/// graph.
1368///
1369void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1370 const DSGraph &Graph, unsigned CloneFlags) {
1371 // Fastpath for a noop inline.
1372 if (CS.getNumPtrArgs() == 0 && CS.getRetVal().isNull())
1373 return;
1374
1375 // Set up argument bindings.
1376 std::vector<DSNodeHandle> Args;
1377 Graph.getFunctionArgumentsForCall(&F, Args);
1378
1379 mergeInGraph(CS, Args, Graph, CloneFlags);
1380}
1381
Chris Lattner58f98d02003-07-02 04:38:49 +00001382/// getCallSiteForArguments - Get the arguments and return value bindings for
1383/// the specified function in the current graph.
1384///
1385DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1386 std::vector<DSNodeHandle> Args;
1387
1388 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1389 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001390 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001391
Chris Lattner808a7ae2003-09-20 16:34:13 +00001392 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001393}
1394
Chris Lattner85fb1be2004-03-09 19:37:06 +00001395/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1396/// the context of this graph, return the DSCallSite for it.
1397DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1398 DSNodeHandle RetVal;
1399 Instruction *I = CS.getInstruction();
1400 if (isPointerType(I->getType()))
1401 RetVal = getNodeForValue(I);
1402
1403 std::vector<DSNodeHandle> Args;
1404 Args.reserve(CS.arg_end()-CS.arg_begin());
1405
1406 // Calculate the arguments vector...
1407 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1408 if (isPointerType((*I)->getType()))
1409 Args.push_back(getNodeForValue(*I));
1410
1411 // Add a new function call entry...
1412 if (Function *F = CS.getCalledFunction())
1413 return DSCallSite(CS, RetVal, F, Args);
1414 else
1415 return DSCallSite(CS, RetVal,
1416 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1417}
1418
Chris Lattner58f98d02003-07-02 04:38:49 +00001419
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001420
Chris Lattner0d9bab82002-07-18 00:12:30 +00001421// markIncompleteNodes - Mark the specified node as having contents that are not
1422// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001423// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001424// must recursively traverse the data structure graph, marking all reachable
1425// nodes as incomplete.
1426//
1427static void markIncompleteNode(DSNode *N) {
1428 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001429 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001430
1431 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001432 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001433
Misha Brukman2f2d0652003-09-11 18:14:24 +00001434 // Recursively process children...
Chris Lattner6be07942005-02-09 03:20:43 +00001435 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1436 if (DSNode *DSN = I->getNode())
Chris Lattner08db7192002-11-06 06:20:27 +00001437 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001438}
1439
Chris Lattnere71ffc22002-11-11 03:36:55 +00001440static void markIncomplete(DSCallSite &Call) {
1441 // Then the return value is certainly incomplete!
1442 markIncompleteNode(Call.getRetVal().getNode());
1443
1444 // All objects pointed to by function arguments are incomplete!
1445 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1446 markIncompleteNode(Call.getPtrArg(i).getNode());
1447}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001448
1449// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1450// modified by other functions that have not been resolved yet. This marks
1451// nodes that are reachable through three sources of "unknownness":
1452//
1453// Global Variables, Function Calls, and Incoming Arguments
1454//
1455// For any node that may have unknown components (because something outside the
1456// scope of current analysis may have modified it), the 'Incomplete' flag is
1457// added to the NodeType.
1458//
Chris Lattner394471f2003-01-23 22:05:33 +00001459void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001460 // Mark any incoming arguments as incomplete.
Chris Lattner5a540632003-06-30 03:15:25 +00001461 if (Flags & DSGraph::MarkFormalArgs)
1462 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1463 FI != E; ++FI) {
1464 Function &F = *FI->first;
1465 if (F.getName() != "main")
1466 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001467 if (isPointerType(I->getType()))
1468 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001469 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001470
Chris Lattnera9548d92005-01-30 23:51:02 +00001471 // Mark stuff passed into functions calls as being incomplete.
Chris Lattnere71ffc22002-11-11 03:36:55 +00001472 if (!shouldPrintAuxCalls())
Chris Lattnera9548d92005-01-30 23:51:02 +00001473 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1474 E = FunctionCalls.end(); I != E; ++I)
1475 markIncomplete(*I);
Chris Lattnere71ffc22002-11-11 03:36:55 +00001476 else
Chris Lattnera9548d92005-01-30 23:51:02 +00001477 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1478 E = AuxFunctionCalls.end(); I != E; ++I)
1479 markIncomplete(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001480
Chris Lattner93d7a212003-02-09 18:41:49 +00001481 // Mark all global nodes as incomplete...
1482 if ((Flags & DSGraph::IgnoreGlobals) == 0)
Chris Lattner51c06ab2004-02-25 23:08:00 +00001483 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1484 E = ScalarMap.global_end(); I != E; ++I)
Chris Lattnercf14e712004-02-25 23:36:08 +00001485 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
Chris Lattnerd84d3502004-03-08 03:52:24 +00001486 if (!GV->isConstant() || !GV->hasInitializer())
Chris Lattnercf14e712004-02-25 23:36:08 +00001487 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001488}
1489
Chris Lattneraa8146f2002-11-10 06:59:55 +00001490static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1491 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001492 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001493 // No interesting info?
1494 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001495 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001496 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001497}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001498
Chris Lattneraa8146f2002-11-10 06:59:55 +00001499static inline bool nodeContainsExternalFunction(const DSNode *N) {
1500 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1501 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
Chris Lattner857eb062004-10-30 05:41:23 +00001502 if (Globals[i]->isExternal() && isa<Function>(Globals[i]))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001503 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001504 return false;
1505}
1506
Chris Lattnera9548d92005-01-30 23:51:02 +00001507static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001508 // Remove trivially identical function calls
Chris Lattnera9548d92005-01-30 23:51:02 +00001509 Calls.sort(); // Sort by callee as primary key!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001510
1511 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001512 DSNode *LastCalleeNode = 0;
1513 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001514 unsigned NumDuplicateCalls = 0;
1515 bool LastCalleeContainsExternalFunction = false;
Chris Lattner857eb062004-10-30 05:41:23 +00001516
Chris Lattnera9548d92005-01-30 23:51:02 +00001517 unsigned NumDeleted = 0;
1518 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1519 I != E;) {
1520 DSCallSite &CS = *I;
1521 std::list<DSCallSite>::iterator OldIt = I++;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001522
Chris Lattnere4258442002-11-11 21:35:38 +00001523 // If the Callee is a useless edge, this must be an unreachable call site,
1524 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001525 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerabcdf802004-02-26 03:43:43 +00001526 CS.getCalleeNode()->isComplete() &&
Chris Lattneraf6926a2004-02-26 03:45:03 +00001527 CS.getCalleeNode()->getGlobals().empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001528#ifndef NDEBUG
Chris Lattnerabcdf802004-02-26 03:43:43 +00001529 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001530#endif
Chris Lattnera9548d92005-01-30 23:51:02 +00001531 Calls.erase(OldIt);
1532 ++NumDeleted;
1533 continue;
1534 }
1535
1536 // If the return value or any arguments point to a void node with no
1537 // information at all in it, and the call node is the only node to point
1538 // to it, remove the edge to the node (killing the node).
1539 //
1540 killIfUselessEdge(CS.getRetVal());
1541 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1542 killIfUselessEdge(CS.getPtrArg(a));
1543
Chris Lattner0b144872004-01-27 22:03:40 +00001544#if 0
Chris Lattnera9548d92005-01-30 23:51:02 +00001545 // If this call site calls the same function as the last call site, and if
1546 // the function pointer contains an external function, this node will
1547 // never be resolved. Merge the arguments of the call node because no
1548 // information will be lost.
1549 //
1550 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1551 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1552 ++NumDuplicateCalls;
1553 if (NumDuplicateCalls == 1) {
1554 if (LastCalleeNode)
1555 LastCalleeContainsExternalFunction =
1556 nodeContainsExternalFunction(LastCalleeNode);
1557 else
1558 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001559 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001560
1561 // It is not clear why, but enabling this code makes DSA really
1562 // sensitive to node forwarding. Basically, with this enabled, DSA
1563 // performs different number of inlinings based on which nodes are
1564 // forwarding or not. This is clearly a problem, so this code is
1565 // disabled until this can be resolved.
1566#if 1
1567 if (LastCalleeContainsExternalFunction
1568#if 0
1569 ||
1570 // This should be more than enough context sensitivity!
1571 // FIXME: Evaluate how many times this is tripped!
1572 NumDuplicateCalls > 20
1573#endif
1574 ) {
1575
1576 std::list<DSCallSite>::iterator PrevIt = OldIt;
1577 --PrevIt;
1578 PrevIt->mergeWith(CS);
1579
1580 // No need to keep this call anymore.
1581 Calls.erase(OldIt);
1582 ++NumDeleted;
1583 continue;
1584 }
1585#endif
1586 } else {
1587 if (CS.isDirectCall()) {
1588 LastCalleeFunc = CS.getCalleeFunc();
1589 LastCalleeNode = 0;
1590 } else {
1591 LastCalleeNode = CS.getCalleeNode();
1592 LastCalleeFunc = 0;
1593 }
1594 NumDuplicateCalls = 0;
1595 }
1596#endif
1597
1598 if (I != Calls.end() && CS == *I) {
1599 Calls.erase(OldIt);
1600 ++NumDeleted;
1601 continue;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001602 }
1603 }
Chris Lattner857eb062004-10-30 05:41:23 +00001604
Chris Lattnera9548d92005-01-30 23:51:02 +00001605 // Resort now that we simplified things.
1606 Calls.sort();
Chris Lattner857eb062004-10-30 05:41:23 +00001607
Chris Lattnera9548d92005-01-30 23:51:02 +00001608 // Now that we are in sorted order, eliminate duplicates.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001609 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1610 if (CI != CE)
Chris Lattnera9548d92005-01-30 23:51:02 +00001611 while (1) {
Chris Lattnerf9aace22005-01-31 00:10:58 +00001612 std::list<DSCallSite>::iterator OldIt = CI++;
1613 if (CI == CE) break;
Chris Lattnera9548d92005-01-30 23:51:02 +00001614
1615 // If this call site is now the same as the previous one, we can delete it
1616 // as a duplicate.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001617 if (*OldIt == *CI) {
1618 Calls.erase(CI);
1619 CI = OldIt;
Chris Lattnera9548d92005-01-30 23:51:02 +00001620 ++NumDeleted;
1621 }
1622 }
1623
1624 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001625
Chris Lattner33312f72002-11-08 01:21:07 +00001626 // Track the number of call nodes merged away...
Chris Lattnera9548d92005-01-30 23:51:02 +00001627 NumCallNodesMerged += NumDeleted;
Chris Lattner33312f72002-11-08 01:21:07 +00001628
Chris Lattnera9548d92005-01-30 23:51:02 +00001629 DEBUG(if (NumDeleted)
1630 std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001631}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001632
Chris Lattneraa8146f2002-11-10 06:59:55 +00001633
Chris Lattnere2219762002-07-18 18:22:40 +00001634// removeTriviallyDeadNodes - After the graph has been constructed, this method
1635// removes all unreachable nodes that are created because they got merged with
1636// other nodes in the graph. These nodes will all be trivially unreachable, so
1637// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001638//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001639void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001640 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001641
Chris Lattner5ace1e42004-07-08 07:25:51 +00001642#if 0
1643 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1644 /// substantially!
1645
Chris Lattnerbab8c282003-09-20 21:34:07 +00001646 // Loop over all of the nodes in the graph, calling getNode on each field.
1647 // This will cause all nodes to update their forwarding edges, causing
1648 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001649 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001650 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1651 DSNode *N = *NI;
Chris Lattnerbab8c282003-09-20 21:34:07 +00001652 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1653 N->getLink(l*N->getPointerSize()).getNode();
1654 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001655 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001656
Chris Lattner0b144872004-01-27 22:03:40 +00001657 // NOTE: This code is disabled. Though it should, in theory, allow us to
1658 // remove more nodes down below, the scan of the scalar map is incredibly
1659 // expensive for certain programs (with large SCCs). In the future, if we can
1660 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001661 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1662
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001663 // Likewise, forward any edges from the scalar nodes. While we are at it,
1664 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001665 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001666 I->second.getNode();
1667 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001668 }
Chris Lattner0b144872004-01-27 22:03:40 +00001669 }
1670#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001671 bool isGlobalsGraph = !GlobalsGraph;
1672
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001673 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001674 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001675
1676 // Do not remove *any* global nodes in the globals graph.
1677 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001678 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001679 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001680 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001681 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001682
Chris Lattner28897e12004-02-08 00:53:26 +00001683 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001684 // This is a useless node if it has no mod/ref info (checked above),
1685 // outgoing edges (which it cannot, as it is not modified in this
1686 // context), and it has no incoming edges. If it is a global node it may
1687 // have all of these properties and still have incoming edges, due to the
1688 // scalar map, so we check those now.
1689 //
Chris Lattner28897e12004-02-08 00:53:26 +00001690 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1691 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001692
Chris Lattner17a93e22004-01-29 03:32:15 +00001693 // Loop through and make sure all of the globals are referring directly
1694 // to the node...
1695 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1696 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001697 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001698 }
1699
Chris Lattnerbd92b732003-06-19 21:15:11 +00001700 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001701 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001702 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1703 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001704 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001705 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001706 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001707 }
1708 }
1709
Chris Lattner28897e12004-02-08 00:53:26 +00001710 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001711 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001712 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001713 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001714 } else {
1715 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001716 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001717 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001718
1719 removeIdenticalCalls(FunctionCalls);
1720 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001721}
1722
1723
Chris Lattner5c7380e2003-01-29 21:10:20 +00001724/// markReachableNodes - This method recursively traverses the specified
1725/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1726/// to the set, which allows it to only traverse visited nodes once.
1727///
Chris Lattnera9548d92005-01-30 23:51:02 +00001728void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001729 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001730 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001731 if (ReachableNodes.insert(this).second) // Is newly reachable?
Chris Lattner6be07942005-02-09 03:20:43 +00001732 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
1733 I != E; ++I)
1734 I->getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001735}
1736
Chris Lattnera9548d92005-01-30 23:51:02 +00001737void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001738 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001739 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001740
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001741 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1742 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001743}
1744
Chris Lattnera1220af2003-02-01 06:17:02 +00001745// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1746// looking for a node that is marked alive. If an alive node is found, return
1747// true, otherwise return false. If an alive node is reachable, this node is
1748// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001749//
Chris Lattnera9548d92005-01-30 23:51:02 +00001750static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
1751 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00001752 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001753 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001754 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001755
Chris Lattner85cfe012003-07-03 02:03:53 +00001756 // If this is a global node, it will end up in the globals graph anyway, so we
1757 // don't need to worry about it.
1758 if (IgnoreGlobals && N->isGlobalNode()) return false;
1759
Chris Lattneraa8146f2002-11-10 06:59:55 +00001760 // If we know that this node is alive, return so!
1761 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001762
Chris Lattneraa8146f2002-11-10 06:59:55 +00001763 // Otherwise, we don't think the node is alive yet, check for infinite
1764 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001765 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001766 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001767
Chris Lattner6be07942005-02-09 03:20:43 +00001768 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1769 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001770 N->markReachableNodes(Alive);
1771 return true;
1772 }
1773 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001774}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001775
Chris Lattnera1220af2003-02-01 06:17:02 +00001776// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1777// alive nodes.
1778//
Chris Lattnera9548d92005-01-30 23:51:02 +00001779static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
1780 hash_set<const DSNode*> &Alive,
1781 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00001782 bool IgnoreGlobals) {
1783 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1784 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001785 return true;
1786 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001787 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001788 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001789 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001790 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1791 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001792 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001793 return false;
1794}
1795
Chris Lattnere2219762002-07-18 18:22:40 +00001796// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1797// subgraphs that are unreachable. This often occurs because the data
1798// structure doesn't "escape" into it's caller, and thus should be eliminated
1799// from the caller's graph entirely. This is only appropriate to use when
1800// inlining graphs.
1801//
Chris Lattner394471f2003-01-23 22:05:33 +00001802void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001803 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001804
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001805 // Reduce the amount of work we have to do... remove dummy nodes left over by
1806 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001807 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001808
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001809 TIME_REGION(X, "removeDeadNodes");
1810
Misha Brukman2f2d0652003-09-11 18:14:24 +00001811 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001812
1813 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattnera9548d92005-01-30 23:51:02 +00001814 hash_set<const DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001815 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001816
Chris Lattner0b144872004-01-27 22:03:40 +00001817 // Copy and merge all information about globals to the GlobalsGraph if this is
1818 // not a final pass (where unreachable globals are removed).
1819 //
1820 // Strip all alloca bits since the current function is only for the BU pass.
1821 // Strip all incomplete bits since they are short-lived properties and they
1822 // will be correctly computed when rematerializing nodes into the functions.
1823 //
1824 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1825 DSGraph::StripIncompleteBit);
1826
Chris Lattneraa8146f2002-11-10 06:59:55 +00001827 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner00948c02004-01-28 02:05:05 +00001828 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
Chris Lattner62482e52004-01-28 09:15:42 +00001829 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001830 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00001831 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001832 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001833 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001834
1835 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001836 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1837 DSGraph::ScalarMapTy::iterator SMI =
1838 GlobalsGraph->getScalarMap().find(I->first);
1839 if (SMI != GlobalsGraph->getScalarMap().end())
1840 GGCloner.merge(SMI->second, I->second);
1841 else
1842 GGCloner.getClonedNH(I->second);
1843 }
Chris Lattner0b144872004-01-27 22:03:40 +00001844 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001845 } else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001846 DSNode *N = I->second.getNode();
1847#if 0
Chris Lattner0b144872004-01-27 22:03:40 +00001848 // Check to see if this is a worthless node generated for non-pointer
1849 // values, such as integers. Consider an addition of long types: A+B.
1850 // Assuming we can track all uses of the value in this context, and it is
1851 // NOT used as a pointer, we can delete the node. We will be able to
1852 // detect this situation if the node pointed to ONLY has Unknown bit set
1853 // in the node. In this case, the node is not incomplete, does not point
1854 // to any other nodes (no mod/ref bits set), and is therefore
1855 // uninteresting for data structure analysis. If we run across one of
1856 // these, prune the scalar pointing to it.
1857 //
Chris Lattner0b144872004-01-27 22:03:40 +00001858 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1859 ScalarMap.erase(I++);
1860 else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001861#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001862 N->markReachableNodes(Alive);
1863 ++I;
Chris Lattnera88a55c2004-01-28 02:41:32 +00001864 //}
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001865 }
Chris Lattner00948c02004-01-28 02:05:05 +00001866 }
Chris Lattnere2219762002-07-18 18:22:40 +00001867
Chris Lattner0b144872004-01-27 22:03:40 +00001868 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001869 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1870 I != E; ++I)
1871 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001872
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001873 // Mark any nodes reachable by primary calls as alive...
Chris Lattnera9548d92005-01-30 23:51:02 +00001874 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
1875 I->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001876
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001877
1878 // Now find globals and aux call nodes that are already live or reach a live
1879 // value (which makes them live in turn), and continue till no more are found.
1880 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001881 bool Iterate;
Chris Lattnera9548d92005-01-30 23:51:02 +00001882 hash_set<const DSNode*> Visited;
1883 hash_set<const DSCallSite*> AuxFCallsAlive;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001884 do {
1885 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001886 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001887 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001888 // unreachable globals in the list.
1889 //
1890 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001891 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001892 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1893 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1894 Flags & DSGraph::RemoveUnreachableGlobals)) {
1895 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1896 GlobalNodes.pop_back(); // erase efficiently
1897 Iterate = true;
1898 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001899
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001900 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1901 // call nodes that get resolved will be difficult to remove from that graph.
1902 // The final unresolved call nodes must be handled specially at the end of
1903 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattnera9548d92005-01-30 23:51:02 +00001904 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
1905 if (AuxFCallsAlive.insert(&*CI).second &&
1906 (CI->isIndirectCall()
1907 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001908 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001909 CI->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001910 Iterate = true;
1911 }
1912 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001913
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001914 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001915 unsigned CurIdx = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00001916 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
1917 E = AuxFunctionCalls.end(); CI != E; )
1918 if (AuxFCallsAlive.count(&*CI))
1919 ++CI;
1920 else {
1921 // Copy and merge global nodes and dead aux call nodes into the
1922 // GlobalsGraph, and all nodes reachable from those nodes. Update their
1923 // target pointers using the GGCloner.
1924 //
1925 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1926 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001927
Chris Lattnera9548d92005-01-30 23:51:02 +00001928 AuxFunctionCalls.erase(CI++);
1929 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001930
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001931 // We are finally done with the GGCloner so we can destroy it.
1932 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001933
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001934 // At this point, any nodes which are visited, but not alive, are nodes
1935 // which can be removed. Loop over all nodes, eliminating completely
1936 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001937 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001938 std::vector<DSNode*> DeadNodes;
1939 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00001940 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
1941 DSNode *N = NI++;
1942 assert(!N->isForwarding() && "Forwarded node in nodes list?");
1943
1944 if (!Alive.count(N)) {
1945 Nodes.remove(N);
1946 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001947 DeadNodes.push_back(N);
1948 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00001949 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00001950 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00001951 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001952
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001953 // Remove all unreachable globals from the ScalarMap.
1954 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1955 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001956 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001957 if (!Alive.count(GlobalNodes[i].second))
1958 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00001959 else
1960 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001961
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001962 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001963 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1964 delete DeadNodes[i];
1965
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001966 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001967}
1968
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001969void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
1970 assert(std::find(N->getGlobals().begin(), N->getGlobals().end(), GV) !=
1971 N->getGlobals().end() && "Global value not in node!");
1972}
1973
Chris Lattner2c7725a2004-03-03 20:55:27 +00001974void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
1975 if (CS.isIndirectCall()) {
1976 AssertNodeInGraph(CS.getCalleeNode());
1977#if 0
1978 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
1979 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
1980 std::cerr << "WARNING: WIERD CALL SITE FOUND!\n";
1981#endif
1982 }
1983 AssertNodeInGraph(CS.getRetVal().getNode());
1984 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
1985 AssertNodeInGraph(CS.getPtrArg(j).getNode());
1986}
1987
1988void DSGraph::AssertCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00001989 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
1990 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00001991}
1992void DSGraph::AssertAuxCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00001993 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
1994 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00001995}
1996
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001997void DSGraph::AssertGraphOK() const {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001998 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1999 (*NI)->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00002000
Chris Lattner8d327672003-06-30 03:36:09 +00002001 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002002 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00002003 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002004 AssertNodeInGraph(I->second.getNode());
2005 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00002006 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002007 "Global points to node, but node isn't global?");
2008 AssertNodeContainsGlobal(I->second.getNode(), GV);
2009 }
2010 }
2011 AssertCallNodesInGraph();
2012 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00002013
2014 // Check that all pointer arguments to any functions in this graph have
2015 // destinations.
2016 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2017 E = ReturnNodes.end();
2018 RI != E; ++RI) {
2019 Function &F = *RI->first;
2020 for (Function::aiterator AI = F.abegin(); AI != F.aend(); ++AI)
2021 if (isPointerType(AI->getType()))
2022 assert(!getNodeForValue(AI).isNull() &&
2023 "Pointer argument must be in the scalar map!");
2024 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002025}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002026
Chris Lattner400433d2003-11-11 05:08:59 +00002027/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00002028/// nodes reachable from the two graphs, computing the mapping of nodes from the
2029/// first to the second graph. This mapping may be many-to-one (i.e. the first
2030/// graph may have multiple nodes representing one node in the second graph),
2031/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00002032///
2033void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00002034 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2035 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00002036 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2037 if (N1 == 0 || N2 == 0) return;
2038
2039 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002040 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002041 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002042 if (StrictChecking) {
2043 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2044 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2045 Entry.getNode()->isNodeCompletelyFolded()) &&
2046 "Inconsistent mapping detected!");
2047 }
Chris Lattner400433d2003-11-11 05:08:59 +00002048 return;
2049 }
2050
Chris Lattnerefffdc92004-07-07 06:12:52 +00002051 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002052
2053 // Loop over all of the fields that N1 and N2 have in common, recursively
2054 // mapping the edges together now.
2055 int N2Idx = NH2.getOffset()-NH1.getOffset();
2056 unsigned N2Size = N2->getSize();
2057 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
2058 if (unsigned(N2Idx)+i < N2Size)
2059 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
Chris Lattnerb1aaeee2004-03-03 05:34:31 +00002060 else
2061 computeNodeMapping(N1->getLink(i),
2062 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
Chris Lattner400433d2003-11-11 05:08:59 +00002063}