blob: be53dab3b836986a16367acac7368e59c78e88bb [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);
252 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
253 return;
254 }
255 Stack.pop_back(); // At the end of the structure
256 } else {
257 const ArrayType *AT = cast<ArrayType>(SS.Ty);
258 ++SS.Idx;
259 if (SS.Idx != AT->getNumElements()) {
260 SS.Offset += TD.getTypeSize(AT->getElementType());
261 return;
262 }
263 Stack.pop_back(); // At the end of the array
264 }
265 }
266 }
267
268 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
269 /// on the type stack.
270 void StepToLeaf() {
271 if (Stack.empty()) return;
272 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
273 StackState &SS = Stack.back();
274 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000275 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000276 assert(SS.Idx == 0);
277 PopStackAndAdvance();
278 } else {
279 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000280 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000281 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000282 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000283 SS.Offset+SL->MemberOffsets[SS.Idx]));
284 }
285 } else {
286 const ArrayType *AT = cast<ArrayType>(SS.Ty);
287 if (AT->getNumElements() == 0) {
288 assert(SS.Idx == 0);
289 PopStackAndAdvance();
290 } else {
291 // Step into the array...
292 assert(SS.Idx < AT->getNumElements());
293 Stack.push_back(StackState(AT->getElementType(),
294 SS.Offset+SS.Idx*
295 TD.getTypeSize(AT->getElementType())));
296 }
297 }
298 }
299 }
300 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000301} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000302
303/// ElementTypesAreCompatible - Check to see if the specified types are
304/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000305/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
306/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000307///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000308static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000309 bool AllowLargerT1, const TargetData &TD){
310 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000311
312 while (!T1W.isDone() && !T2W.isDone()) {
313 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
314 return false;
315
316 const Type *T1 = T1W.getCurrentType();
317 const Type *T2 = T2W.getCurrentType();
318 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
319 return false;
320
321 T1W.StepToNextType();
322 T2W.StepToNextType();
323 }
324
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000325 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000326}
327
328
Chris Lattner08db7192002-11-06 06:20:27 +0000329/// mergeTypeInfo - This method merges the specified type into the current node
330/// at the specified offset. This may update the current node's type record if
331/// this gives more information to the node, it may do nothing to the node if
332/// this information is already known, or it may merge the node completely (and
333/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000334///
Chris Lattner08db7192002-11-06 06:20:27 +0000335/// This method returns true if the node is completely folded, otherwise false.
336///
Chris Lattner088b6392003-03-03 17:13:31 +0000337bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
338 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000339 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000340 // Check to make sure the Size member is up-to-date. Size can be one of the
341 // following:
342 // Size = 0, Ty = Void: Nothing is known about this node.
343 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
344 // Size = 1, Ty = Void, Array = 1: The node is collapsed
345 // Otherwise, sizeof(Ty) = Size
346 //
Chris Lattner18552922002-11-18 21:44:46 +0000347 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
348 (Size == 0 && !Ty->isSized() && !isArray()) ||
349 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
350 (Size == 0 && !Ty->isSized() && !isArray()) ||
351 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000352 "Size member of DSNode doesn't match the type structure!");
353 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000354
Chris Lattner18552922002-11-18 21:44:46 +0000355 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000356 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000357
Chris Lattner08db7192002-11-06 06:20:27 +0000358 // Return true immediately if the node is completely folded.
359 if (isNodeCompletelyFolded()) return true;
360
Chris Lattner23f83dc2002-11-08 22:49:57 +0000361 // If this is an array type, eliminate the outside arrays because they won't
362 // be used anyway. This greatly reduces the size of large static arrays used
363 // as global variables, for example.
364 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000365 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000366 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
367 // FIXME: we might want to keep small arrays, but must be careful about
368 // things like: [2 x [10000 x int*]]
369 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000370 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000371 }
372
Chris Lattner08db7192002-11-06 06:20:27 +0000373 // Figure out how big the new type we're merging in is...
374 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
375
376 // Otherwise check to see if we can fold this type into the current node. If
377 // we can't, we fold the node completely, if we can, we potentially update our
378 // internal state.
379 //
Chris Lattner18552922002-11-18 21:44:46 +0000380 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000381 // If this is the first type that this node has seen, just accept it without
382 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000383 assert(Offset == 0 && !isArray() &&
384 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000385 Ty = NewTy;
386 NodeType &= ~Array;
387 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000388 Size = NewTySize;
389
390 // Calculate the number of outgoing links from this node.
391 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
392 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000393 }
Chris Lattner08db7192002-11-06 06:20:27 +0000394
395 // Handle node expansion case here...
396 if (Offset+NewTySize > Size) {
397 // It is illegal to grow this node if we have treated it as an array of
398 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000399 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000400 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000401 return true;
402 }
403
404 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000405 std::cerr << "UNIMP: Trying to merge a growth type into "
406 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000407 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000408 return true;
409 }
410
411 // Okay, the situation is nice and simple, we are trying to merge a type in
412 // at offset 0 that is bigger than our current type. Implement this by
413 // switching to the new type and then merge in the smaller one, which should
414 // hit the other code path here. If the other code path decides it's not
415 // ok, it will collapse the node as appropriate.
416 //
Chris Lattner18552922002-11-18 21:44:46 +0000417 const Type *OldTy = Ty;
418 Ty = NewTy;
419 NodeType &= ~Array;
420 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000421 Size = NewTySize;
422
423 // Must grow links to be the appropriate size...
424 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
425
426 // Merge in the old type now... which is guaranteed to be smaller than the
427 // "current" type.
428 return mergeTypeInfo(OldTy, 0);
429 }
430
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000431 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000432 "Cannot merge something into a part of our type that doesn't exist!");
433
Chris Lattner18552922002-11-18 21:44:46 +0000434 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000435 // type that starts at offset Offset.
436 //
437 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000438 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000439 while (O < Offset) {
440 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
441
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000442 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000443 case Type::StructTyID: {
444 const StructType *STy = cast<StructType>(SubType);
445 const StructLayout &SL = *TD.getStructLayout(STy);
446
447 unsigned i = 0, e = SL.MemberOffsets.size();
448 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
449 /* empty */;
450
451 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000452 SubType = STy->getElementType(i);
Chris Lattner08db7192002-11-06 06:20:27 +0000453 O += SL.MemberOffsets[i];
454 break;
455 }
456 case Type::ArrayTyID: {
457 SubType = cast<ArrayType>(SubType)->getElementType();
458 unsigned ElSize = TD.getTypeSize(SubType);
459 unsigned Remainder = (Offset-O) % ElSize;
460 O = Offset-Remainder;
461 break;
462 }
463 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000464 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000465 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000466 }
467 }
468
469 assert(O == Offset && "Could not achieve the correct offset!");
470
471 // If we found our type exactly, early exit
472 if (SubType == NewTy) return false;
473
Misha Brukman96a8bd72004-04-29 04:05:30 +0000474 // Differing function types don't require us to merge. They are not values
475 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000476 if (isa<FunctionType>(SubType) &&
477 isa<FunctionType>(NewTy)) return false;
478
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000479 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
480
481 // Ok, we are getting desperate now. Check for physical subtyping, where we
482 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000483 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000484 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000485 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000486 return false;
487
Chris Lattner08db7192002-11-06 06:20:27 +0000488 // Okay, so we found the leader type at the offset requested. Search the list
489 // of types that starts at this offset. If SubType is currently an array or
490 // structure, the type desired may actually be the first element of the
491 // composite type...
492 //
Chris Lattner18552922002-11-18 21:44:46 +0000493 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000494 while (SubType != NewTy) {
495 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000496 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000497 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000498 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000499 case Type::StructTyID: {
500 const StructType *STy = cast<StructType>(SubType);
501 const StructLayout &SL = *TD.getStructLayout(STy);
502 if (SL.MemberOffsets.size() > 1)
503 NextPadSize = SL.MemberOffsets[1];
504 else
505 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000506 NextSubType = STy->getElementType(0);
Chris Lattner18552922002-11-18 21:44:46 +0000507 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000508 break;
Chris Lattner18552922002-11-18 21:44:46 +0000509 }
Chris Lattner08db7192002-11-06 06:20:27 +0000510 case Type::ArrayTyID:
511 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000512 NextSubTypeSize = TD.getTypeSize(NextSubType);
513 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000514 break;
515 default: ;
516 // fall out
517 }
518
519 if (NextSubType == 0)
520 break; // In the default case, break out of the loop
521
Chris Lattner18552922002-11-18 21:44:46 +0000522 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000523 break; // Don't allow shrinking to a smaller type than NewTySize
524 SubType = NextSubType;
525 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000526 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000527 }
528
529 // If we found the type exactly, return it...
530 if (SubType == NewTy)
531 return false;
532
533 // Check to see if we have a compatible, but different type...
534 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000535 // Check to see if this type is obviously convertible... int -> uint f.e.
536 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000537 return false;
538
539 // Check to see if we have a pointer & integer mismatch going on here,
540 // loading a pointer as a long, for example.
541 //
542 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
543 NewTy->isInteger() && isa<PointerType>(SubType))
544 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000545 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
546 // We are accessing the field, plus some structure padding. Ignore the
547 // structure padding.
548 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000549 }
550
Chris Lattner58f98d02003-07-02 04:38:49 +0000551 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000552 if (getParentGraph()->getReturnNodes().size())
553 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000554 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
555 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
556 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
557 << "SubType: ";
558 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000559
Chris Lattner088b6392003-03-03 17:13:31 +0000560 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000561 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000562}
563
Chris Lattner08db7192002-11-06 06:20:27 +0000564
565
Misha Brukman96a8bd72004-04-29 04:05:30 +0000566/// addEdgeTo - Add an edge from the current node to the specified node. This
567/// can cause merging of nodes in the graph.
568///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000569void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000570 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000571
Chris Lattner08db7192002-11-06 06:20:27 +0000572 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000573 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000574 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000575 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000576 } else { // No merging to perform...
577 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000578 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000579}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000580
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000581
Misha Brukman96a8bd72004-04-29 04:05:30 +0000582/// MergeSortedVectors - Efficiently merge a vector into another vector where
583/// duplicates are not allowed and both are sorted. This assumes that 'T's are
584/// efficiently copyable and have sane comparison semantics.
585///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000586static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
587 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000588 // By far, the most common cases will be the simple ones. In these cases,
589 // avoid having to allocate a temporary vector...
590 //
591 if (Src.empty()) { // Nothing to merge in...
592 return;
593 } else if (Dest.empty()) { // Just copy the result in...
594 Dest = Src;
595 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000596 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000597 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000598 std::lower_bound(Dest.begin(), Dest.end(), V);
599 if (I == Dest.end() || *I != Src[0]) // If not already contained...
600 Dest.insert(I, Src[0]);
601 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000602 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000603 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000604 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000605 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
606 if (I == Dest.end() || *I != Tmp) // If not already contained...
607 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000608
609 } else {
610 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000611 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000612
613 // Make space for all of the type entries now...
614 Dest.resize(Dest.size()+Src.size());
615
616 // Merge the two sorted ranges together... into Dest.
617 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
618
619 // Now erase any duplicate entries that may have accumulated into the
620 // vectors (because they were in both of the input sets)
621 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
622 }
623}
624
Chris Lattner0b144872004-01-27 22:03:40 +0000625void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
626 MergeSortedVectors(Globals, RHS);
627}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000628
Chris Lattner0b144872004-01-27 22:03:40 +0000629// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000630// This function does the hard work of merging two nodes, CurNodeH
631// and NH after filtering out trivial cases and making sure that
632// CurNodeH.offset >= NH.offset.
633//
634// ***WARNING***
635// Since merging may cause either node to go away, we must always
636// use the node-handles to refer to the nodes. These node handles are
637// automatically updated during merging, so will always provide access
638// to the correct node after a merge.
639//
640void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
641 assert(CurNodeH.getOffset() >= NH.getOffset() &&
642 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000643 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
644 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000645
646 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
647 // respect to NH.Offset) is now zero. NOffset is the distance from the base
648 // of our object that N starts from.
649 //
650 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
651 unsigned NSize = NH.getNode()->getSize();
652
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000653 // If the two nodes are of different size, and the smaller node has the array
654 // bit set, collapse!
655 if (NSize != CurNodeH.getNode()->getSize()) {
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000656#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000657 if (NSize < CurNodeH.getNode()->getSize()) {
658 if (NH.getNode()->isArray())
659 NH.getNode()->foldNodeCompletely();
660 } else if (CurNodeH.getNode()->isArray()) {
661 NH.getNode()->foldNodeCompletely();
662 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000663#endif
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000664 }
665
666 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000667 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000668 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000669 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000670
671 // If we are merging a node with a completely folded node, then both nodes are
672 // now completely folded.
673 //
674 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
675 if (!NH.getNode()->isNodeCompletelyFolded()) {
676 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000677 assert(NH.getNode() && NH.getOffset() == 0 &&
678 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000679 NOffset = NH.getOffset();
680 NSize = NH.getNode()->getSize();
681 assert(NOffset == 0 && NSize == 1);
682 }
683 } else if (NH.getNode()->isNodeCompletelyFolded()) {
684 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000685 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
686 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000687 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000688 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000689 assert(NOffset == 0 && NSize == 1);
690 }
691
Chris Lattner72d29a42003-02-11 23:11:51 +0000692 DSNode *N = NH.getNode();
693 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000694 assert(!CurNodeH.getNode()->isDeadNode());
695
Chris Lattner0b144872004-01-27 22:03:40 +0000696 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000697 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000698
Chris Lattner72d29a42003-02-11 23:11:51 +0000699 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000700 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000701 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000702
Chris Lattner72d29a42003-02-11 23:11:51 +0000703 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
704 //
705 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
706 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000707 if (Link.getNode()) {
708 // Compute the offset into the current node at which to
709 // merge this link. In the common case, this is a linear
710 // relation to the offset in the original node (with
711 // wrapping), but if the current node gets collapsed due to
712 // recursive merging, we must make sure to merge in all remaining
713 // links at offset zero.
714 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000715 DSNode *CN = CurNodeH.getNode();
716 if (CN->Size != 1)
717 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
718 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000719 }
720 }
721
722 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000723 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000724
725 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000726 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000727 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000728
729 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000730 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000731 }
732}
733
734
Misha Brukman96a8bd72004-04-29 04:05:30 +0000735/// mergeWith - Merge this node and the specified node, moving all links to and
736/// from the argument node into the current node, deleting the node argument.
737/// Offset indicates what offset the specified node is to be merged into the
738/// current node.
739///
740/// The specified node may be a null pointer (in which case, we update it to
741/// point to this node).
742///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000743void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
744 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000745 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000746 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000747
Chris Lattner5254a8d2004-01-22 16:31:08 +0000748 // If the RHS is a null node, make it point to this node!
749 if (N == 0) {
750 NH.mergeWith(DSNodeHandle(this, Offset));
751 return;
752 }
753
Chris Lattnerbd92b732003-06-19 21:15:11 +0000754 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000755 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
756
Chris Lattner02606632002-11-04 06:48:26 +0000757 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000758 // We cannot merge two pieces of the same node together, collapse the node
759 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000760 DEBUG(std::cerr << "Attempting to merge two chunks of"
761 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000762 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000763 return;
764 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000765
Chris Lattner5190ce82002-11-12 07:20:45 +0000766 // If both nodes are not at offset 0, make sure that we are merging the node
767 // at an later offset into the node with the zero offset.
768 //
769 if (Offset < NH.getOffset()) {
770 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
771 return;
772 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
773 // If the offsets are the same, merge the smaller node into the bigger node
774 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
775 return;
776 }
777
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000778 // Ok, now we can merge the two nodes. Use a static helper that works with
779 // two node handles, since "this" may get merged away at intermediate steps.
780 DSNodeHandle CurNodeH(this, Offset);
781 DSNodeHandle NHCopy(NH);
782 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000783}
784
Chris Lattner0b144872004-01-27 22:03:40 +0000785
786//===----------------------------------------------------------------------===//
787// ReachabilityCloner Implementation
788//===----------------------------------------------------------------------===//
789
790DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
791 if (SrcNH.isNull()) return DSNodeHandle();
792 const DSNode *SN = SrcNH.getNode();
793
794 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000795 if (!NH.isNull()) { // Node already mapped?
796 DSNode *NHN = NH.getNode();
797 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
798 }
Chris Lattner0b144872004-01-27 22:03:40 +0000799
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000800 // If SrcNH has globals and the destination graph has one of the same globals,
801 // merge this node with the destination node, which is much more efficient.
802 if (SN->global_begin() != SN->global_end()) {
803 DSScalarMap &DestSM = Dest.getScalarMap();
804 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
805 I != E; ++I) {
806 GlobalValue *GV = *I;
807 DSScalarMap::iterator GI = DestSM.find(GV);
808 if (GI != DestSM.end() && !GI->second.isNull()) {
809 // We found one, use merge instead!
810 merge(GI->second, Src.getNodeForValue(GV));
811 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000812 DSNode *NHN = NH.getNode();
813 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000814 }
815 }
816 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000817
Chris Lattner0b144872004-01-27 22:03:40 +0000818 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
819 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000820 NH = DN;
Chris Lattner0b144872004-01-27 22:03:40 +0000821
822 // Next, recursively clone all outgoing links as necessary. Note that
823 // adding these links can cause the node to collapse itself at any time, and
824 // the current node may be merged with arbitrary other nodes. For this
825 // reason, we must always go through NH.
826 DN = 0;
827 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
828 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
829 if (!SrcEdge.isNull()) {
830 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
831 // Compute the offset into the current node at which to
832 // merge this link. In the common case, this is a linear
833 // relation to the offset in the original node (with
834 // wrapping), but if the current node gets collapsed due to
835 // recursive merging, we must make sure to merge in all remaining
836 // links at offset zero.
837 unsigned MergeOffset = 0;
838 DSNode *CN = NH.getNode();
839 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +0000840 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +0000841 CN->addEdgeTo(MergeOffset, DestEdge);
842 }
843 }
844
845 // If this node contains any globals, make sure they end up in the scalar
846 // map with the correct offset.
847 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
848 I != E; ++I) {
849 GlobalValue *GV = *I;
850 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
851 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
852 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
853 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000854 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000855
856 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
857 Dest.getInlinedGlobals().insert(GV);
858 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000859 NH.getNode()->mergeGlobals(SN->getGlobals());
Chris Lattner0b144872004-01-27 22:03:40 +0000860
861 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
862}
863
864void ReachabilityCloner::merge(const DSNodeHandle &NH,
865 const DSNodeHandle &SrcNH) {
866 if (SrcNH.isNull()) return; // Noop
867 if (NH.isNull()) {
868 // If there is no destination node, just clone the source and assign the
869 // destination node to be it.
870 NH.mergeWith(getClonedNH(SrcNH));
871 return;
872 }
873
874 // Okay, at this point, we know that we have both a destination and a source
875 // node that need to be merged. Check to see if the source node has already
876 // been cloned.
877 const DSNode *SN = SrcNH.getNode();
878 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +0000879 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +0000880 DSNode *SCNHN = SCNH.getNode();
881 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +0000882 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000883 return; // Nothing to do!
884 }
Chris Lattner6f967742004-10-30 04:05:01 +0000885
Chris Lattner0b144872004-01-27 22:03:40 +0000886 // Okay, so the source node has not already been cloned. Instead of creating
887 // a new DSNode, only to merge it into the one we already have, try to perform
888 // the merge in-place. The only case we cannot handle here is when the offset
889 // into the existing node is less than the offset into the virtual node we are
890 // merging in. In this case, we have to extend the existing node, which
891 // requires an allocation anyway.
892 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
893 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000894 if (!DN->isNodeCompletelyFolded()) {
895 // Make sure the destination node is folded if the source node is folded.
896 if (SN->isNodeCompletelyFolded()) {
897 DN->foldNodeCompletely();
898 DN = NH.getNode();
899 } else if (SN->getSize() != DN->getSize()) {
900 // If the two nodes are of different size, and the smaller node has the
901 // array bit set, collapse!
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000902#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner0b144872004-01-27 22:03:40 +0000903 if (SN->getSize() < DN->getSize()) {
904 if (SN->isArray()) {
905 DN->foldNodeCompletely();
906 DN = NH.getNode();
907 }
908 } else if (DN->isArray()) {
909 DN->foldNodeCompletely();
910 DN = NH.getNode();
911 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000912#endif
Chris Lattner0b144872004-01-27 22:03:40 +0000913 }
914
915 // Merge the type entries of the two nodes together...
916 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
917 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
918 DN = NH.getNode();
919 }
920 }
921
922 assert(!DN->isDeadNode());
923
924 // Merge the NodeType information.
925 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
926
927 // Before we start merging outgoing links and updating the scalar map, make
928 // sure it is known that this is the representative node for the src node.
929 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
930
931 // If the source node contains any globals, make sure they end up in the
932 // scalar map with the correct offset.
933 if (SN->global_begin() != SN->global_end()) {
934 // Update the globals in the destination node itself.
935 DN->mergeGlobals(SN->getGlobals());
936
937 // Update the scalar map for the graph we are merging the source node
938 // into.
939 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
940 I != E; ++I) {
941 GlobalValue *GV = *I;
942 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
943 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
944 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
945 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +0000946 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000947
948 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
949 Dest.getInlinedGlobals().insert(GV);
950 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000951 NH.getNode()->mergeGlobals(SN->getGlobals());
Chris Lattner0b144872004-01-27 22:03:40 +0000952 }
953 } else {
954 // We cannot handle this case without allocating a temporary node. Fall
955 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +0000956 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
957 NewDN->maskNodeTypes(BitsToKeep);
958
959 unsigned NHOffset = NH.getOffset();
960 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +0000961
Chris Lattner0b144872004-01-27 22:03:40 +0000962 assert(NH.getNode() &&
963 (NH.getOffset() > NHOffset ||
964 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
965 "Merging did not adjust the offset!");
966
967 // Before we start merging outgoing links and updating the scalar map, make
968 // sure it is known that this is the representative node for the src node.
969 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +0000970
971 // If the source node contained any globals, make sure to create entries
972 // in the scalar map for them!
973 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
974 I != E; ++I) {
975 GlobalValue *GV = *I;
976 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
977 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
978 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
979 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
980 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
981 DestGNH.getOffset()+SrcGNH.getOffset()));
982
983 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
984 Dest.getInlinedGlobals().insert(GV);
985 }
Chris Lattner0b144872004-01-27 22:03:40 +0000986 }
987
988
989 // Next, recursively merge all outgoing links as necessary. Note that
990 // adding these links can cause the destination node to collapse itself at
991 // any time, and the current node may be merged with arbitrary other nodes.
992 // For this reason, we must always go through NH.
993 DN = 0;
994 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
995 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
996 if (!SrcEdge.isNull()) {
997 // Compute the offset into the current node at which to
998 // merge this link. In the common case, this is a linear
999 // relation to the offset in the original node (with
1000 // wrapping), but if the current node gets collapsed due to
1001 // recursive merging, we must make sure to merge in all remaining
1002 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +00001003 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +00001004 unsigned MergeOffset =
1005 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +00001006
Chris Lattnerf590ced2004-03-04 17:06:53 +00001007 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1008 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001009 // Perform the recursive merging. Make sure to create a temporary NH,
1010 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001011 merge(Tmp, SrcEdge);
1012 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001013 Tmp.mergeWith(getClonedNH(SrcEdge));
1014 // Merging this could cause all kinds of recursive things to happen,
1015 // culminating in the current node being eliminated. Since this is
1016 // possible, make sure to reaquire the link from 'CN'.
1017
1018 unsigned MergeOffset = 0;
1019 CN = SCNH.getNode();
1020 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1021 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001022 }
Chris Lattner0b144872004-01-27 22:03:40 +00001023 }
1024 }
1025}
1026
1027/// mergeCallSite - Merge the nodes reachable from the specified src call
1028/// site into the nodes reachable from DestCS.
1029void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
1030 const DSCallSite &SrcCS) {
1031 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1032 unsigned MinArgs = DestCS.getNumPtrArgs();
1033 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1034
1035 for (unsigned a = 0; a != MinArgs; ++a)
1036 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1037}
1038
1039
Chris Lattner9de906c2002-10-20 22:11:44 +00001040//===----------------------------------------------------------------------===//
1041// DSCallSite Implementation
1042//===----------------------------------------------------------------------===//
1043
Vikram S. Adve26b98262002-10-20 21:41:02 +00001044// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001045Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001046 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001047}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001048
Chris Lattner0b144872004-01-27 22:03:40 +00001049void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1050 ReachabilityCloner &RC) {
1051 NH = RC.getClonedNH(Src);
1052}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001053
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001054//===----------------------------------------------------------------------===//
1055// DSGraph Implementation
1056//===----------------------------------------------------------------------===//
1057
Chris Lattnera9d65662003-06-30 05:57:30 +00001058/// getFunctionNames - Return a space separated list of the name of the
1059/// functions in this graph (if any)
1060std::string DSGraph::getFunctionNames() const {
1061 switch (getReturnNodes().size()) {
1062 case 0: return "Globals graph";
1063 case 1: return getReturnNodes().begin()->first->getName();
1064 default:
1065 std::string Return;
1066 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1067 I != getReturnNodes().end(); ++I)
1068 Return += I->first->getName() + " ";
1069 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1070 return Return;
1071 }
1072}
1073
1074
Chris Lattner15869aa2003-11-02 22:27:28 +00001075DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001076 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001077 NodeMapTy NodeMap;
1078 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001079}
1080
Chris Lattner5a540632003-06-30 03:15:25 +00001081DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001082 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001083 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001084 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001085}
1086
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001087DSGraph::~DSGraph() {
1088 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001089 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001090 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001091 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001092 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001093
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001094 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001095 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1096 (*NI)->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001097
Chris Lattner28897e12004-02-08 00:53:26 +00001098 // Free all of the nodes.
1099 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001100}
1101
Chris Lattner0d9bab82002-07-18 00:12:30 +00001102// dump - Allow inspection of graph in a debugger.
1103void DSGraph::dump() const { print(std::cerr); }
1104
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001105
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001106/// remapLinks - Change all of the Links in the current node according to the
1107/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001108///
Chris Lattner8d327672003-06-30 03:36:09 +00001109void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001110 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1111 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001112 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001113 if (ONMI != OldNodeMap.end()) {
1114 DSNode *ONMIN = ONMI->second.getNode();
1115 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1116 }
Chris Lattner2f561382004-01-22 16:56:13 +00001117 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001118}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001119
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001120/// updateFromGlobalGraph - This function rematerializes global nodes and
1121/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001122/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1123/// are already up-to-date in the current graph. In practice, in the TD pass,
1124/// this is likely to be a large fraction of the live global nodes in each
1125/// function (since most live nodes are likely to have been brought up-to-date
1126/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001127///
1128void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001129 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001130 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1131
1132 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001133 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1134 E = getScalarMap().global_end(); I != E; ++I)
1135 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001136 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001137 if (It != GlobalsGraph->ScalarMap.end())
1138 RC.merge(getNodeForValue(*I), It->second);
1139 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001140}
1141
Chris Lattner5a540632003-06-30 03:15:25 +00001142/// cloneInto - Clone the specified DSGraph into the current graph. The
1143/// translated ScalarMap for the old function is filled into the OldValMap
1144/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1145///
1146/// The CloneFlags member controls various aspects of the cloning process.
1147///
Chris Lattner62482e52004-01-28 09:15:42 +00001148void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001149 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1150 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001151 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001152 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001153 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001154
Chris Lattner1e883692003-02-03 20:08:51 +00001155 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001156 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1157 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1158 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001159 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001160
Chris Lattnerd85645f2004-02-21 22:28:26 +00001161 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1162 assert(!(*I)->isForwarding() &&
1163 "Forward nodes shouldn't be in node list!");
1164 DSNode *New = new DSNode(**I, this);
1165 New->maskNodeTypes(~BitsToClear);
1166 OldNodeMap[*I] = New;
1167 }
1168
Chris Lattner18552922002-11-18 21:44:46 +00001169#ifndef NDEBUG
1170 Timer::addPeakMemoryMeasurement();
1171#endif
Chris Lattnerd85645f2004-02-21 22:28:26 +00001172
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001173 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001174 // Note that we don't loop over the node's list to do this. The problem is
1175 // that remaping links can cause recursive merging to happen, which means
1176 // that node_iterator's can get easily invalidated! Because of this, we
1177 // loop over the OldNodeMap, which contains all of the new nodes as the
1178 // .second element of the map elements. Also note that if we remap a node
1179 // more than once, we won't break anything.
1180 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1181 I != E; ++I)
1182 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001183
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001184 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001185 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001186 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001187 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001188 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner6f967742004-10-30 04:05:01 +00001189 DSNode *MappedNodeN = MappedNode.getNode();
1190 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001191 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001192
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001193 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001194 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1195 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001196 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1197 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001198 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001199 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001200
Chris Lattner679e8e12002-11-08 21:27:12 +00001201 if (!(CloneFlags & DontCloneCallNodes)) {
1202 // Copy the function calls list...
1203 unsigned FC = FunctionCalls.size(); // FirstCall
1204 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1205 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1206 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[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)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +00001210 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +00001211 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +00001212 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1213 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1214 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1215 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001216
Chris Lattner5a540632003-06-30 03:15:25 +00001217 // Map the return node pointers over...
1218 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1219 E = G.getReturnNodes().end(); I != E; ++I) {
1220 const DSNodeHandle &Ret = I->second;
1221 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001222 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattner5a540632003-06-30 03:15:25 +00001223 OldReturnNodes.insert(std::make_pair(I->first,
Chris Lattner6f967742004-10-30 04:05:01 +00001224 DSNodeHandle(MappedRetN,
Chris Lattner5a540632003-06-30 03:15:25 +00001225 MappedRet.getOffset()+Ret.getOffset())));
1226 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001227}
1228
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001229static bool PathExistsToClonedNode(const DSNode *N, ReachabilityCloner &RC) {
Chris Lattner2f346902004-03-04 03:57:53 +00001230 if (N)
1231 for (df_iterator<const DSNode*> I = df_begin(N), E = df_end(N); I != E; ++I)
1232 if (RC.hasClonedNode(*I))
1233 return true;
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001234 return false;
1235}
1236
Chris Lattner2f346902004-03-04 03:57:53 +00001237static bool PathExistsToClonedNode(const DSCallSite &CS,
1238 ReachabilityCloner &RC) {
1239 if (PathExistsToClonedNode(CS.getRetVal().getNode(), RC))
1240 return true;
1241 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1242 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode(), RC))
1243 return true;
1244 return false;
1245}
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001246
Chris Lattner076c1f92002-11-07 06:31:54 +00001247/// mergeInGraph - The method is used for merging graphs together. If the
1248/// argument graph is not *this, it makes a clone of the specified graph, then
1249/// merges the nodes specified in the call site with the formal arguments in the
1250/// graph.
1251///
Chris Lattner9f930552003-06-30 05:27:18 +00001252void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1253 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001254 TIME_REGION(X, "mergeInGraph");
1255
Chris Lattner2c7725a2004-03-03 20:55:27 +00001256 // Fastpath for a noop inline.
1257 if (CS.getNumPtrArgs() == 0 && CS.getRetVal().isNull())
1258 return;
1259
Chris Lattner076c1f92002-11-07 06:31:54 +00001260 // If this is not a recursive call, clone the graph into this graph...
1261 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001262 // Clone the callee's graph into the current graph, keeping track of where
1263 // scalars in the old graph _used_ to point, and of the new nodes matching
1264 // nodes of the old graph.
1265 ReachabilityCloner RC(*this, Graph, CloneFlags);
1266
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001267 // Set up argument bindings
1268 Function::aiterator AI = F.abegin();
1269 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1270 // Advance the argument iterator to the first pointer argument...
1271 while (AI != F.aend() && !isPointerType(AI->getType())) {
1272 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001273#ifndef NDEBUG // FIXME: We should merge vararg arguments!
1274 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001275 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001276#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001277 }
1278 if (AI == F.aend()) break;
1279
1280 // Add the link from the argument scalar to the provided value.
Chris Lattner0b144872004-01-27 22:03:40 +00001281 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
Chris Lattner076c1f92002-11-07 06:31:54 +00001282 }
1283
Chris Lattner0b144872004-01-27 22:03:40 +00001284 // Map the return node pointer over.
Chris Lattner0ad91702004-02-22 00:53:54 +00001285 if (!CS.getRetVal().isNull())
Chris Lattner0b144872004-01-27 22:03:40 +00001286 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
Chris Lattnerf590ced2004-03-04 17:06:53 +00001287
Chris Lattner2f346902004-03-04 03:57:53 +00001288 // If requested, copy all of the calls.
Chris Lattner0b144872004-01-27 22:03:40 +00001289 if (!(CloneFlags & DontCloneCallNodes)) {
1290 // Copy the function calls list...
1291 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1292 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1293 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1294 }
Chris Lattner2f346902004-03-04 03:57:53 +00001295
1296 // If the user has us copying aux calls (the normal case), set up a data
1297 // structure to keep track of which ones we've copied over.
1298 std::vector<bool> CopiedAuxCall;
Chris Lattner0b144872004-01-27 22:03:40 +00001299 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001300 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1301 Graph.AuxFunctionCalls.size());
Chris Lattner2f346902004-03-04 03:57:53 +00001302 CopiedAuxCall.resize(Graph.AuxFunctionCalls.size());
Chris Lattner0b144872004-01-27 22:03:40 +00001303 }
1304
Chris Lattner0321b682004-02-27 20:05:15 +00001305 // Clone over all globals that appear in the caller and callee graphs.
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001306 hash_set<GlobalVariable*> NonCopiedGlobals;
Chris Lattner0321b682004-02-27 20:05:15 +00001307 for (DSScalarMap::global_iterator GI = Graph.getScalarMap().global_begin(),
1308 E = Graph.getScalarMap().global_end(); GI != E; ++GI)
1309 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*GI))
1310 if (ScalarMap.count(GV))
1311 RC.merge(ScalarMap[GV], Graph.getNodeForValue(GV));
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001312 else
1313 NonCopiedGlobals.insert(GV);
1314
1315 // If the global does not appear in the callers graph we generally don't
1316 // want to copy the node. However, if there is a path from the node global
1317 // node to a node that we did copy in the graph, we *must* copy it to
1318 // maintain the connection information. Every time we decide to include a
1319 // new global, this might make other globals live, so we must iterate
1320 // unfortunately.
Chris Lattner2f346902004-03-04 03:57:53 +00001321 bool MadeChange = true;
1322 while (MadeChange) {
1323 MadeChange = false;
1324 for (hash_set<GlobalVariable*>::iterator I = NonCopiedGlobals.begin();
1325 I != NonCopiedGlobals.end();) {
1326 DSNode *GlobalNode = Graph.getNodeForValue(*I).getNode();
1327 if (RC.hasClonedNode(GlobalNode)) {
1328 // Already cloned it, remove from set.
1329 NonCopiedGlobals.erase(I++);
1330 MadeChange = true;
1331 } else if (PathExistsToClonedNode(GlobalNode, RC)) {
1332 RC.getClonedNH(Graph.getNodeForValue(*I));
1333 NonCopiedGlobals.erase(I++);
1334 MadeChange = true;
1335 } else {
1336 ++I;
1337 }
1338 }
1339
1340 // If requested, copy any aux calls that can reach copied nodes.
1341 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1342 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1343 if (!CopiedAuxCall[i] &&
1344 PathExistsToClonedNode(Graph.AuxFunctionCalls[i], RC)) {
1345 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i],
1346 RC));
1347 CopiedAuxCall[i] = true;
1348 MadeChange = true;
1349 }
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001350 }
1351 }
1352
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001353 } else {
1354 DSNodeHandle RetVal = getReturnNodeFor(F);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001355
1356 // Merge the return value with the return value of the context...
1357 RetVal.mergeWith(CS.getRetVal());
1358
1359 // Resolve all of the function arguments...
1360 Function::aiterator AI = F.abegin();
1361
1362 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1363 // Advance the argument iterator to the first pointer argument...
1364 while (AI != F.aend() && !isPointerType(AI->getType())) {
1365 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001366#ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1367 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001368 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1369#endif
1370 }
1371 if (AI == F.aend()) break;
1372
1373 // Add the link from the argument scalar to the provided value
Chris Lattner0b144872004-01-27 22:03:40 +00001374 DSNodeHandle &NH = getNodeForValue(AI);
Chris Lattner6f967742004-10-30 04:05:01 +00001375 assert(!NH.isNull() && "Pointer argument without scalarmap entry?");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001376 NH.mergeWith(CS.getPtrArg(i));
1377 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001378 }
1379}
1380
Chris Lattner58f98d02003-07-02 04:38:49 +00001381/// getCallSiteForArguments - Get the arguments and return value bindings for
1382/// the specified function in the current graph.
1383///
1384DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1385 std::vector<DSNodeHandle> Args;
1386
1387 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1388 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001389 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001390
Chris Lattner808a7ae2003-09-20 16:34:13 +00001391 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001392}
1393
Chris Lattner85fb1be2004-03-09 19:37:06 +00001394/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1395/// the context of this graph, return the DSCallSite for it.
1396DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1397 DSNodeHandle RetVal;
1398 Instruction *I = CS.getInstruction();
1399 if (isPointerType(I->getType()))
1400 RetVal = getNodeForValue(I);
1401
1402 std::vector<DSNodeHandle> Args;
1403 Args.reserve(CS.arg_end()-CS.arg_begin());
1404
1405 // Calculate the arguments vector...
1406 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1407 if (isPointerType((*I)->getType()))
1408 Args.push_back(getNodeForValue(*I));
1409
1410 // Add a new function call entry...
1411 if (Function *F = CS.getCalledFunction())
1412 return DSCallSite(CS, RetVal, F, Args);
1413 else
1414 return DSCallSite(CS, RetVal,
1415 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1416}
1417
Chris Lattner58f98d02003-07-02 04:38:49 +00001418
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001419
Chris Lattner0d9bab82002-07-18 00:12:30 +00001420// markIncompleteNodes - Mark the specified node as having contents that are not
1421// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001422// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001423// must recursively traverse the data structure graph, marking all reachable
1424// nodes as incomplete.
1425//
1426static void markIncompleteNode(DSNode *N) {
1427 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001428 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001429
1430 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001431 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001432
Misha Brukman2f2d0652003-09-11 18:14:24 +00001433 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001434 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1435 if (DSNode *DSN = N->getLink(i).getNode())
1436 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001437}
1438
Chris Lattnere71ffc22002-11-11 03:36:55 +00001439static void markIncomplete(DSCallSite &Call) {
1440 // Then the return value is certainly incomplete!
1441 markIncompleteNode(Call.getRetVal().getNode());
1442
1443 // All objects pointed to by function arguments are incomplete!
1444 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1445 markIncompleteNode(Call.getPtrArg(i).getNode());
1446}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001447
1448// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1449// modified by other functions that have not been resolved yet. This marks
1450// nodes that are reachable through three sources of "unknownness":
1451//
1452// Global Variables, Function Calls, and Incoming Arguments
1453//
1454// For any node that may have unknown components (because something outside the
1455// scope of current analysis may have modified it), the 'Incomplete' flag is
1456// added to the NodeType.
1457//
Chris Lattner394471f2003-01-23 22:05:33 +00001458void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001459 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001460 if (Flags & DSGraph::MarkFormalArgs)
1461 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1462 FI != E; ++FI) {
1463 Function &F = *FI->first;
1464 if (F.getName() != "main")
1465 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001466 if (isPointerType(I->getType()))
1467 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001468 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001469
1470 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001471 if (!shouldPrintAuxCalls())
1472 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1473 markIncomplete(FunctionCalls[i]);
1474 else
1475 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1476 markIncomplete(AuxFunctionCalls[i]);
1477
Chris Lattner0d9bab82002-07-18 00:12:30 +00001478
Chris Lattner93d7a212003-02-09 18:41:49 +00001479 // Mark all global nodes as incomplete...
1480 if ((Flags & DSGraph::IgnoreGlobals) == 0)
Chris Lattner51c06ab2004-02-25 23:08:00 +00001481 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1482 E = ScalarMap.global_end(); I != E; ++I)
Chris Lattnercf14e712004-02-25 23:36:08 +00001483 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
Chris Lattnerd84d3502004-03-08 03:52:24 +00001484 if (!GV->isConstant() || !GV->hasInitializer())
Chris Lattnercf14e712004-02-25 23:36:08 +00001485 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001486}
1487
Chris Lattneraa8146f2002-11-10 06:59:55 +00001488static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1489 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001490 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001491 // No interesting info?
1492 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001493 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001494 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001495}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001496
Chris Lattneraa8146f2002-11-10 06:59:55 +00001497static inline bool nodeContainsExternalFunction(const DSNode *N) {
1498 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1499 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
Chris Lattner857eb062004-10-30 05:41:23 +00001500 if (Globals[i]->isExternal() && isa<Function>(Globals[i]))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001501 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001502 return false;
1503}
1504
Chris Lattner5a540632003-06-30 03:15:25 +00001505static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001506 // Remove trivially identical function calls
1507 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001508 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1509
Chris Lattner0b144872004-01-27 22:03:40 +00001510#if 1
Chris Lattneraa8146f2002-11-10 06:59:55 +00001511 // 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
1517 std::vector<unsigned> CallsToDelete;
1518
Chris Lattnere4258442002-11-11 21:35:38 +00001519 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001520 DSCallSite &CS = Calls[i];
1521
Chris Lattnere4258442002-11-11 21:35:38 +00001522 // If the Callee is a useless edge, this must be an unreachable call site,
1523 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001524 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerabcdf802004-02-26 03:43:43 +00001525 CS.getCalleeNode()->isComplete() &&
Chris Lattneraf6926a2004-02-26 03:45:03 +00001526 CS.getCalleeNode()->getGlobals().empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001527#ifndef NDEBUG
Chris Lattnerabcdf802004-02-26 03:43:43 +00001528 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001529#endif
Chris Lattner857eb062004-10-30 05:41:23 +00001530 CallsToDelete.push_back(i);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001531 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001532 // If the return value or any arguments point to a void node with no
1533 // information at all in it, and the call node is the only node to point
1534 // to it, remove the edge to the node (killing the node).
1535 //
1536 killIfUselessEdge(CS.getRetVal());
1537 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1538 killIfUselessEdge(CS.getPtrArg(a));
1539
1540 // If this call site calls the same function as the last call site, and if
1541 // the function pointer contains an external function, this node will
1542 // never be resolved. Merge the arguments of the call node because no
1543 // information will be lost.
1544 //
Chris Lattner923fc052003-02-05 21:59:58 +00001545 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1546 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001547 ++NumDuplicateCalls;
1548 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001549 if (LastCalleeNode)
1550 LastCalleeContainsExternalFunction =
1551 nodeContainsExternalFunction(LastCalleeNode);
1552 else
1553 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001554 }
Chris Lattner0b144872004-01-27 22:03:40 +00001555
1556 // It is not clear why, but enabling this code makes DSA really
1557 // sensitive to node forwarding. Basically, with this enabled, DSA
1558 // performs different number of inlinings based on which nodes are
1559 // forwarding or not. This is clearly a problem, so this code is
1560 // disabled until this can be resolved.
Chris Lattner58f98d02003-07-02 04:38:49 +00001561#if 1
Chris Lattner0b144872004-01-27 22:03:40 +00001562 if (LastCalleeContainsExternalFunction
1563#if 0
1564 ||
Chris Lattnere4258442002-11-11 21:35:38 +00001565 // This should be more than enough context sensitivity!
1566 // FIXME: Evaluate how many times this is tripped!
Chris Lattner0b144872004-01-27 22:03:40 +00001567 NumDuplicateCalls > 20
1568#endif
1569 ) {
Chris Lattnere4258442002-11-11 21:35:38 +00001570 DSCallSite &OCS = Calls[i-1];
1571 OCS.mergeWith(CS);
1572
Chris Lattner857eb062004-10-30 05:41:23 +00001573 // No need to keep this call anymore.
1574 CallsToDelete.push_back(i);
Chris Lattnere4258442002-11-11 21:35:38 +00001575 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001576#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001577 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001578 if (CS.isDirectCall()) {
1579 LastCalleeFunc = CS.getCalleeFunc();
1580 LastCalleeNode = 0;
1581 } else {
1582 LastCalleeNode = CS.getCalleeNode();
1583 LastCalleeFunc = 0;
1584 }
Chris Lattnere4258442002-11-11 21:35:38 +00001585 NumDuplicateCalls = 0;
1586 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001587 }
1588 }
Chris Lattner0b144872004-01-27 22:03:40 +00001589#endif
Chris Lattner857eb062004-10-30 05:41:23 +00001590
1591 unsigned NumDeleted = 0;
1592 for (unsigned i = 0, e = CallsToDelete.size(); i != e; ++i)
1593 Calls.erase(Calls.begin()+CallsToDelete[i]-NumDeleted++);
1594
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001595 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001596
Chris Lattner33312f72002-11-08 01:21:07 +00001597 // Track the number of call nodes merged away...
1598 NumCallNodesMerged += NumFns-Calls.size();
1599
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001600 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001601 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001602}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001603
Chris Lattneraa8146f2002-11-10 06:59:55 +00001604
Chris Lattnere2219762002-07-18 18:22:40 +00001605// removeTriviallyDeadNodes - After the graph has been constructed, this method
1606// removes all unreachable nodes that are created because they got merged with
1607// other nodes in the graph. These nodes will all be trivially unreachable, so
1608// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001609//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001610void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001611 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001612
Chris Lattner5ace1e42004-07-08 07:25:51 +00001613#if 0
1614 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1615 /// substantially!
1616
Chris Lattnerbab8c282003-09-20 21:34:07 +00001617 // Loop over all of the nodes in the graph, calling getNode on each field.
1618 // This will cause all nodes to update their forwarding edges, causing
1619 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001620 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001621 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1622 DSNode *N = *NI;
Chris Lattnerbab8c282003-09-20 21:34:07 +00001623 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1624 N->getLink(l*N->getPointerSize()).getNode();
1625 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001626 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001627
Chris Lattner0b144872004-01-27 22:03:40 +00001628 // NOTE: This code is disabled. Though it should, in theory, allow us to
1629 // remove more nodes down below, the scan of the scalar map is incredibly
1630 // expensive for certain programs (with large SCCs). In the future, if we can
1631 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001632 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1633
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001634 // Likewise, forward any edges from the scalar nodes. While we are at it,
1635 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001636 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001637 I->second.getNode();
1638 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001639 }
Chris Lattner0b144872004-01-27 22:03:40 +00001640 }
1641#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001642 bool isGlobalsGraph = !GlobalsGraph;
1643
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001644 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001645 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001646
1647 // Do not remove *any* global nodes in the globals graph.
1648 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001649 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001650 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001651 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001652 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001653
Chris Lattner28897e12004-02-08 00:53:26 +00001654 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001655 // This is a useless node if it has no mod/ref info (checked above),
1656 // outgoing edges (which it cannot, as it is not modified in this
1657 // context), and it has no incoming edges. If it is a global node it may
1658 // have all of these properties and still have incoming edges, due to the
1659 // scalar map, so we check those now.
1660 //
Chris Lattner28897e12004-02-08 00:53:26 +00001661 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1662 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001663
Chris Lattner17a93e22004-01-29 03:32:15 +00001664 // Loop through and make sure all of the globals are referring directly
1665 // to the node...
1666 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1667 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001668 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001669 }
1670
Chris Lattnerbd92b732003-06-19 21:15:11 +00001671 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001672 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001673 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1674 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001675 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001676 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001677 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001678 }
1679 }
1680
Chris Lattner28897e12004-02-08 00:53:26 +00001681 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001682 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001683 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001684 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001685 } else {
1686 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001687 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001688 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001689
1690 removeIdenticalCalls(FunctionCalls);
1691 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001692}
1693
1694
Chris Lattner5c7380e2003-01-29 21:10:20 +00001695/// markReachableNodes - This method recursively traverses the specified
1696/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1697/// to the set, which allows it to only traverse visited nodes once.
1698///
Chris Lattner41c04f72003-02-01 04:52:08 +00001699void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001700 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001701 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001702 if (ReachableNodes.insert(this).second) // Is newly reachable?
1703 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1704 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001705}
1706
Chris Lattner41c04f72003-02-01 04:52:08 +00001707void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001708 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001709 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001710
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001711 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1712 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001713}
1714
Chris Lattnera1220af2003-02-01 06:17:02 +00001715// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1716// looking for a node that is marked alive. If an alive node is found, return
1717// true, otherwise return false. If an alive node is reachable, this node is
1718// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001719//
Chris Lattnera1220af2003-02-01 06:17:02 +00001720static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001721 hash_set<DSNode*> &Visited,
1722 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001723 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001724 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001725
Chris Lattner85cfe012003-07-03 02:03:53 +00001726 // If this is a global node, it will end up in the globals graph anyway, so we
1727 // don't need to worry about it.
1728 if (IgnoreGlobals && N->isGlobalNode()) return false;
1729
Chris Lattneraa8146f2002-11-10 06:59:55 +00001730 // If we know that this node is alive, return so!
1731 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001732
Chris Lattneraa8146f2002-11-10 06:59:55 +00001733 // Otherwise, we don't think the node is alive yet, check for infinite
1734 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001735 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001736 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001737
Chris Lattner08db7192002-11-06 06:20:27 +00001738 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001739 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1740 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001741 N->markReachableNodes(Alive);
1742 return true;
1743 }
1744 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001745}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001746
Chris Lattnera1220af2003-02-01 06:17:02 +00001747// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1748// alive nodes.
1749//
Chris Lattner41c04f72003-02-01 04:52:08 +00001750static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001751 hash_set<DSNode*> &Visited,
1752 bool IgnoreGlobals) {
1753 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1754 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001755 return true;
1756 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001757 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001758 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001759 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001760 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1761 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001762 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001763 return false;
1764}
1765
Chris Lattnere2219762002-07-18 18:22:40 +00001766// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1767// subgraphs that are unreachable. This often occurs because the data
1768// structure doesn't "escape" into it's caller, and thus should be eliminated
1769// from the caller's graph entirely. This is only appropriate to use when
1770// inlining graphs.
1771//
Chris Lattner394471f2003-01-23 22:05:33 +00001772void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001773 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001774
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001775 // Reduce the amount of work we have to do... remove dummy nodes left over by
1776 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001777 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001778
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001779 TIME_REGION(X, "removeDeadNodes");
1780
Misha Brukman2f2d0652003-09-11 18:14:24 +00001781 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001782
1783 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001784 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001785 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001786
Chris Lattner0b144872004-01-27 22:03:40 +00001787 // Copy and merge all information about globals to the GlobalsGraph if this is
1788 // not a final pass (where unreachable globals are removed).
1789 //
1790 // Strip all alloca bits since the current function is only for the BU pass.
1791 // Strip all incomplete bits since they are short-lived properties and they
1792 // will be correctly computed when rematerializing nodes into the functions.
1793 //
1794 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1795 DSGraph::StripIncompleteBit);
1796
Chris Lattneraa8146f2002-11-10 06:59:55 +00001797 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner00948c02004-01-28 02:05:05 +00001798 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
Chris Lattner62482e52004-01-28 09:15:42 +00001799 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001800 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00001801 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001802 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001803 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001804
1805 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001806 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1807 DSGraph::ScalarMapTy::iterator SMI =
1808 GlobalsGraph->getScalarMap().find(I->first);
1809 if (SMI != GlobalsGraph->getScalarMap().end())
1810 GGCloner.merge(SMI->second, I->second);
1811 else
1812 GGCloner.getClonedNH(I->second);
1813 }
Chris Lattner0b144872004-01-27 22:03:40 +00001814 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001815 } else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001816 DSNode *N = I->second.getNode();
1817#if 0
Chris Lattner0b144872004-01-27 22:03:40 +00001818 // Check to see if this is a worthless node generated for non-pointer
1819 // values, such as integers. Consider an addition of long types: A+B.
1820 // Assuming we can track all uses of the value in this context, and it is
1821 // NOT used as a pointer, we can delete the node. We will be able to
1822 // detect this situation if the node pointed to ONLY has Unknown bit set
1823 // in the node. In this case, the node is not incomplete, does not point
1824 // to any other nodes (no mod/ref bits set), and is therefore
1825 // uninteresting for data structure analysis. If we run across one of
1826 // these, prune the scalar pointing to it.
1827 //
Chris Lattner0b144872004-01-27 22:03:40 +00001828 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1829 ScalarMap.erase(I++);
1830 else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001831#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001832 N->markReachableNodes(Alive);
1833 ++I;
Chris Lattnera88a55c2004-01-28 02:41:32 +00001834 //}
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001835 }
Chris Lattner00948c02004-01-28 02:05:05 +00001836 }
Chris Lattnere2219762002-07-18 18:22:40 +00001837
Chris Lattner0b144872004-01-27 22:03:40 +00001838 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001839 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1840 I != E; ++I)
1841 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001842
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001843 // Mark any nodes reachable by primary calls as alive...
1844 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1845 FunctionCalls[i].markReachableNodes(Alive);
1846
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001847
1848 // Now find globals and aux call nodes that are already live or reach a live
1849 // value (which makes them live in turn), and continue till no more are found.
1850 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001851 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001852 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001853 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1854 do {
1855 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001856 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001857 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001858 // unreachable globals in the list.
1859 //
1860 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001861 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001862 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1863 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1864 Flags & DSGraph::RemoveUnreachableGlobals)) {
1865 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1866 GlobalNodes.pop_back(); // erase efficiently
1867 Iterate = true;
1868 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001869
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001870 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1871 // call nodes that get resolved will be difficult to remove from that graph.
1872 // The final unresolved call nodes must be handled specially at the end of
1873 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001874 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1875 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001876 (AuxFunctionCalls[i].isIndirectCall()
1877 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1878 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001879 AuxFunctionCalls[i].markReachableNodes(Alive);
1880 AuxFCallsAlive[i] = true;
1881 Iterate = true;
1882 }
1883 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001884
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001885 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001886 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001887 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1888 if (AuxFCallsAlive[i])
1889 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001890
1891 // Copy and merge all global nodes and dead aux call nodes into the
1892 // GlobalsGraph, and all nodes reachable from those nodes
1893 //
1894 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001895 // Copy the unreachable call nodes to the globals graph, updating their
1896 // target pointers using the GGCloner
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001897 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1898 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
Chris Lattner0b144872004-01-27 22:03:40 +00001899 GGCloner));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001900 }
1901 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001902 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1903 AuxFunctionCalls.end());
1904
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001905 // We are finally done with the GGCloner so we can destroy it.
1906 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001907
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001908 // At this point, any nodes which are visited, but not alive, are nodes
1909 // which can be removed. Loop over all nodes, eliminating completely
1910 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001911 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001912 std::vector<DSNode*> DeadNodes;
1913 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00001914 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
1915 DSNode *N = NI++;
1916 assert(!N->isForwarding() && "Forwarded node in nodes list?");
1917
1918 if (!Alive.count(N)) {
1919 Nodes.remove(N);
1920 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001921 DeadNodes.push_back(N);
1922 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00001923 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00001924 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00001925 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001926
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001927 // Remove all unreachable globals from the ScalarMap.
1928 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1929 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001930 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001931 if (!Alive.count(GlobalNodes[i].second))
1932 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00001933 else
1934 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001935
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001936 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001937 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1938 delete DeadNodes[i];
1939
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001940 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001941}
1942
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001943void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
1944 assert(std::find(N->getGlobals().begin(), N->getGlobals().end(), GV) !=
1945 N->getGlobals().end() && "Global value not in node!");
1946}
1947
Chris Lattner2c7725a2004-03-03 20:55:27 +00001948void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
1949 if (CS.isIndirectCall()) {
1950 AssertNodeInGraph(CS.getCalleeNode());
1951#if 0
1952 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
1953 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
1954 std::cerr << "WARNING: WIERD CALL SITE FOUND!\n";
1955#endif
1956 }
1957 AssertNodeInGraph(CS.getRetVal().getNode());
1958 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
1959 AssertNodeInGraph(CS.getPtrArg(j).getNode());
1960}
1961
1962void DSGraph::AssertCallNodesInGraph() const {
1963 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1964 AssertCallSiteInGraph(FunctionCalls[i]);
1965}
1966void DSGraph::AssertAuxCallNodesInGraph() const {
1967 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1968 AssertCallSiteInGraph(AuxFunctionCalls[i]);
1969}
1970
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001971void DSGraph::AssertGraphOK() const {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001972 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1973 (*NI)->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001974
Chris Lattner8d327672003-06-30 03:36:09 +00001975 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001976 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00001977 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001978 AssertNodeInGraph(I->second.getNode());
1979 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001980 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001981 "Global points to node, but node isn't global?");
1982 AssertNodeContainsGlobal(I->second.getNode(), GV);
1983 }
1984 }
1985 AssertCallNodesInGraph();
1986 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00001987
1988 // Check that all pointer arguments to any functions in this graph have
1989 // destinations.
1990 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
1991 E = ReturnNodes.end();
1992 RI != E; ++RI) {
1993 Function &F = *RI->first;
1994 for (Function::aiterator AI = F.abegin(); AI != F.aend(); ++AI)
1995 if (isPointerType(AI->getType()))
1996 assert(!getNodeForValue(AI).isNull() &&
1997 "Pointer argument must be in the scalar map!");
1998 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001999}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002000
Chris Lattner400433d2003-11-11 05:08:59 +00002001/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00002002/// nodes reachable from the two graphs, computing the mapping of nodes from the
2003/// first to the second graph. This mapping may be many-to-one (i.e. the first
2004/// graph may have multiple nodes representing one node in the second graph),
2005/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00002006///
2007void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00002008 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2009 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00002010 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2011 if (N1 == 0 || N2 == 0) return;
2012
2013 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002014 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002015 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002016 if (StrictChecking) {
2017 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2018 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2019 Entry.getNode()->isNodeCompletelyFolded()) &&
2020 "Inconsistent mapping detected!");
2021 }
Chris Lattner400433d2003-11-11 05:08:59 +00002022 return;
2023 }
2024
Chris Lattnerefffdc92004-07-07 06:12:52 +00002025 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002026
2027 // Loop over all of the fields that N1 and N2 have in common, recursively
2028 // mapping the edges together now.
2029 int N2Idx = NH2.getOffset()-NH1.getOffset();
2030 unsigned N2Size = N2->getSize();
2031 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
2032 if (unsigned(N2Idx)+i < N2Size)
2033 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
Chris Lattnerb1aaeee2004-03-03 05:34:31 +00002034 else
2035 computeNodeMapping(N1->getLink(i),
2036 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
Chris Lattner400433d2003-11-11 05:08:59 +00002037}