blob: 43170fdc24277883ec006bab03fea2000a8ead14 [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 Lattner94f84702005-03-17 19:56:56 +000015#include "llvm/Constants.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000016#include "llvm/Function.h"
Chris Lattnercf14e712004-02-25 23:36:08 +000017#include "llvm/GlobalVariable.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000019#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000020#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000021#include "llvm/Assembly/Writer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000022#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/ADT/DepthFirstIterator.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000028#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattnerb29dd0f2004-12-08 21:03:56 +000031#define COLLAPSE_ARRAYS_AGGRESSIVELY 0
32
Chris Lattner08db7192002-11-06 06:20:27 +000033namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000034 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
35 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
36 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
37 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000038 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
39 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Chris Lattner08db7192002-11-06 06:20:27 +000040};
41
Chris Lattnera88a55c2004-01-28 02:41:32 +000042#if 1
Chris Lattner93ddd7e2004-01-22 16:36:28 +000043#define TIME_REGION(VARNAME, DESC) \
44 NamedRegionTimer VARNAME(DESC)
45#else
46#define TIME_REGION(VARNAME, DESC)
47#endif
48
Chris Lattnerb1060432002-11-07 05:20:53 +000049using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000050
Chris Lattner6f967742004-10-30 04:05:01 +000051/// isForwarding - Return true if this NodeHandle is forwarding to another
52/// one.
53bool DSNodeHandle::isForwarding() const {
54 return N && N->isForwarding();
55}
56
Chris Lattner731b2d72003-02-13 19:09:00 +000057DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000058 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000059
60 // Handle node forwarding here!
61 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
62 Offset += N->ForwardNH.getOffset();
63
64 if (--N->NumReferrers == 0) {
65 // Removing the last referrer to the node, sever the forwarding link
66 N->stopForwarding();
67 }
68
69 N = Next;
70 N->NumReferrers++;
71 if (N->Size <= Offset) {
72 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
73 Offset = 0;
74 }
75 return N;
76}
77
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000078//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000079// DSNode Implementation
80//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000081
Chris Lattnerbd92b732003-06-19 21:15:11 +000082DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000083 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000084 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000085 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +000086 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000087 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000088}
89
Chris Lattner0d9bab82002-07-18 00:12:30 +000090// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +000091DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +000092 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattnerf590ced2004-03-04 17:06:53 +000093 Ty(N.Ty), NodeType(N.NodeType) {
94 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +000095 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +000096 Globals = N.Globals;
97 } else
Chris Lattner0b144872004-01-27 22:03:40 +000098 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +000099 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000100 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000101}
102
Chris Lattner15869aa2003-11-02 22:27:28 +0000103/// getTargetData - Get the target data object used to construct this node.
104///
105const TargetData &DSNode::getTargetData() const {
106 return ParentGraph->getTargetData();
107}
108
Chris Lattner72d29a42003-02-11 23:11:51 +0000109void DSNode::assertOK() const {
110 assert((Ty != Type::VoidTy ||
111 Ty == Type::VoidTy && (Size == 0 ||
112 (NodeType & DSNode::Array))) &&
113 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000114
115 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000116 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000117 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnera88a55c2004-01-28 02:41:32 +0000118 assert(SM.count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000119 assert(SM.find(Globals[i])->second.getNode() == this);
120 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000121}
122
123/// forwardNode - Mark this node as being obsolete, and all references to it
124/// should be forwarded to the specified node and offset.
125///
126void DSNode::forwardNode(DSNode *To, unsigned Offset) {
127 assert(this != To && "Cannot forward a node to itself!");
128 assert(ForwardNH.isNull() && "Already forwarding from this node!");
129 if (To->Size <= 1) Offset = 0;
130 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
131 "Forwarded offset is wrong!");
Chris Lattnerefffdc92004-07-07 06:12:52 +0000132 ForwardNH.setTo(To, Offset);
Chris Lattner72d29a42003-02-11 23:11:51 +0000133 NodeType = DEAD;
134 Size = 0;
135 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000136
137 // Remove this node from the parent graph's Nodes list.
138 ParentGraph->unlinkNode(this);
139 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000140}
141
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000142// addGlobal - Add an entry for a global value to the Globals list. This also
143// marks the node with the 'G' flag if it does not already have it.
144//
145void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000146 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000147 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000148 std::lower_bound(Globals.begin(), Globals.end(), GV);
149
150 if (I == Globals.end() || *I != GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000151 Globals.insert(I, GV);
152 NodeType |= GlobalNode;
153 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000154}
155
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000156/// foldNodeCompletely - If we determine that this node has some funny
157/// behavior happening to it that we cannot represent, we fold it down to a
158/// single, completely pessimistic, node. This node is represented as a
159/// single byte with a single TypeEntry of "void".
160///
161void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000162 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000163
Chris Lattner08db7192002-11-06 06:20:27 +0000164 ++NumFolds;
165
Chris Lattner0b144872004-01-27 22:03:40 +0000166 // If this node has a size that is <= 1, we don't need to create a forwarding
167 // node.
168 if (getSize() <= 1) {
169 NodeType |= DSNode::Array;
170 Ty = Type::VoidTy;
171 Size = 1;
172 assert(Links.size() <= 1 && "Size is 1, but has more links?");
173 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000174 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000175 // Create the node we are going to forward to. This is required because
176 // some referrers may have an offset that is > 0. By forcing them to
177 // forward, the forwarder has the opportunity to correct the offset.
178 DSNode *DestNode = new DSNode(0, ParentGraph);
179 DestNode->NodeType = NodeType|DSNode::Array;
180 DestNode->Ty = Type::VoidTy;
181 DestNode->Size = 1;
182 DestNode->Globals.swap(Globals);
183
184 // Start forwarding to the destination node...
185 forwardNode(DestNode, 0);
186
187 if (!Links.empty()) {
188 DestNode->Links.reserve(1);
189
190 DSNodeHandle NH(DestNode);
191 DestNode->Links.push_back(Links[0]);
192
193 // If we have links, merge all of our outgoing links together...
194 for (unsigned i = Links.size()-1; i != 0; --i)
195 NH.getNode()->Links[0].mergeWith(Links[i]);
196 Links.clear();
197 } else {
198 DestNode->Links.resize(1);
199 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000200 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000201}
Chris Lattner076c1f92002-11-07 06:31:54 +0000202
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000203/// isNodeCompletelyFolded - Return true if this node has been completely
204/// folded down to something that can never be expanded, effectively losing
205/// all of the field sensitivity that may be present in the node.
206///
207bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000208 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000209}
210
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000211namespace {
212 /// TypeElementWalker Class - Used for implementation of physical subtyping...
213 ///
214 class TypeElementWalker {
215 struct StackState {
216 const Type *Ty;
217 unsigned Offset;
218 unsigned Idx;
219 StackState(const Type *T, unsigned Off = 0)
220 : Ty(T), Offset(Off), Idx(0) {}
221 };
222
223 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000224 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000225 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000226 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000227 Stack.push_back(T);
228 StepToLeaf();
229 }
230
231 bool isDone() const { return Stack.empty(); }
232 const Type *getCurrentType() const { return Stack.back().Ty; }
233 unsigned getCurrentOffset() const { return Stack.back().Offset; }
234
235 void StepToNextType() {
236 PopStackAndAdvance();
237 StepToLeaf();
238 }
239
240 private:
241 /// PopStackAndAdvance - Pop the current element off of the stack and
242 /// advance the underlying element to the next contained member.
243 void PopStackAndAdvance() {
244 assert(!Stack.empty() && "Cannot pop an empty stack!");
245 Stack.pop_back();
246 while (!Stack.empty()) {
247 StackState &SS = Stack.back();
248 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
249 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000250 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000251 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattner507bdf92005-01-12 04:51:37 +0000252 SS.Offset +=
253 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000254 return;
255 }
256 Stack.pop_back(); // At the end of the structure
257 } else {
258 const ArrayType *AT = cast<ArrayType>(SS.Ty);
259 ++SS.Idx;
260 if (SS.Idx != AT->getNumElements()) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000261 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000262 return;
263 }
264 Stack.pop_back(); // At the end of the array
265 }
266 }
267 }
268
269 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
270 /// on the type stack.
271 void StepToLeaf() {
272 if (Stack.empty()) return;
273 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
274 StackState &SS = Stack.back();
275 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000276 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000277 assert(SS.Idx == 0);
278 PopStackAndAdvance();
279 } else {
280 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000281 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000282 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000283 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner507bdf92005-01-12 04:51:37 +0000284 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000285 }
286 } else {
287 const ArrayType *AT = cast<ArrayType>(SS.Ty);
288 if (AT->getNumElements() == 0) {
289 assert(SS.Idx == 0);
290 PopStackAndAdvance();
291 } else {
292 // Step into the array...
293 assert(SS.Idx < AT->getNumElements());
294 Stack.push_back(StackState(AT->getElementType(),
295 SS.Offset+SS.Idx*
Chris Lattner507bdf92005-01-12 04:51:37 +0000296 unsigned(TD.getTypeSize(AT->getElementType()))));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000297 }
298 }
299 }
300 }
301 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000302} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000303
304/// ElementTypesAreCompatible - Check to see if the specified types are
305/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000306/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
307/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000308///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000309static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000310 bool AllowLargerT1, const TargetData &TD){
311 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000312
313 while (!T1W.isDone() && !T2W.isDone()) {
314 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
315 return false;
316
317 const Type *T1 = T1W.getCurrentType();
318 const Type *T2 = T2W.getCurrentType();
319 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
320 return false;
321
322 T1W.StepToNextType();
323 T2W.StepToNextType();
324 }
325
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000326 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000327}
328
329
Chris Lattner08db7192002-11-06 06:20:27 +0000330/// mergeTypeInfo - This method merges the specified type into the current node
331/// at the specified offset. This may update the current node's type record if
332/// this gives more information to the node, it may do nothing to the node if
333/// this information is already known, or it may merge the node completely (and
334/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000335///
Chris Lattner08db7192002-11-06 06:20:27 +0000336/// This method returns true if the node is completely folded, otherwise false.
337///
Chris Lattner088b6392003-03-03 17:13:31 +0000338bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
339 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000340 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000341 // Check to make sure the Size member is up-to-date. Size can be one of the
342 // following:
343 // Size = 0, Ty = Void: Nothing is known about this node.
344 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
345 // Size = 1, Ty = Void, Array = 1: The node is collapsed
346 // Otherwise, sizeof(Ty) = Size
347 //
Chris Lattner18552922002-11-18 21:44:46 +0000348 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
349 (Size == 0 && !Ty->isSized() && !isArray()) ||
350 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
351 (Size == 0 && !Ty->isSized() && !isArray()) ||
352 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000353 "Size member of DSNode doesn't match the type structure!");
354 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000355
Chris Lattner18552922002-11-18 21:44:46 +0000356 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000357 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000358
Chris Lattner08db7192002-11-06 06:20:27 +0000359 // Return true immediately if the node is completely folded.
360 if (isNodeCompletelyFolded()) return true;
361
Chris Lattner23f83dc2002-11-08 22:49:57 +0000362 // If this is an array type, eliminate the outside arrays because they won't
363 // be used anyway. This greatly reduces the size of large static arrays used
364 // as global variables, for example.
365 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000366 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000367 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
368 // FIXME: we might want to keep small arrays, but must be careful about
369 // things like: [2 x [10000 x int*]]
370 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000371 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000372 }
373
Chris Lattner08db7192002-11-06 06:20:27 +0000374 // Figure out how big the new type we're merging in is...
Chris Lattner507bdf92005-01-12 04:51:37 +0000375 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000376
377 // Otherwise check to see if we can fold this type into the current node. If
378 // we can't, we fold the node completely, if we can, we potentially update our
379 // internal state.
380 //
Chris Lattner18552922002-11-18 21:44:46 +0000381 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000382 // If this is the first type that this node has seen, just accept it without
383 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000384 assert(Offset == 0 && !isArray() &&
385 "Cannot have an offset into a void node!");
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000386
387 // If this node would have to have an unreasonable number of fields, just
388 // collapse it. This can occur for fortran common blocks, which have stupid
389 // things like { [100000000 x double], [1000000 x double] }.
390 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
391 if (NumFields > 64) {
392 foldNodeCompletely();
393 return true;
394 }
395
Chris Lattner18552922002-11-18 21:44:46 +0000396 Ty = NewTy;
397 NodeType &= ~Array;
398 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000399 Size = NewTySize;
400
401 // Calculate the number of outgoing links from this node.
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000402 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000403 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000404 }
Chris Lattner08db7192002-11-06 06:20:27 +0000405
406 // Handle node expansion case here...
407 if (Offset+NewTySize > Size) {
408 // It is illegal to grow this node if we have treated it as an array of
409 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000410 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000411 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000412 return true;
413 }
414
415 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000416 std::cerr << "UNIMP: Trying to merge a growth type into "
417 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000418 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000419 return true;
420 }
421
422 // Okay, the situation is nice and simple, we are trying to merge a type in
423 // at offset 0 that is bigger than our current type. Implement this by
424 // switching to the new type and then merge in the smaller one, which should
425 // hit the other code path here. If the other code path decides it's not
426 // ok, it will collapse the node as appropriate.
427 //
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000428
429 // If this node would have to have an unreasonable number of fields, just
430 // collapse it. This can occur for fortran common blocks, which have stupid
431 // things like { [100000000 x double], [1000000 x double] }.
432 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
433 if (NumFields > 64) {
434 foldNodeCompletely();
435 return true;
436 }
437
Chris Lattner94f84702005-03-17 19:56:56 +0000438 const Type *OldTy = Ty;
439 Ty = NewTy;
440 NodeType &= ~Array;
441 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000442 Size = NewTySize;
443
444 // Must grow links to be the appropriate size...
Chris Lattner94f84702005-03-17 19:56:56 +0000445 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000446
447 // Merge in the old type now... which is guaranteed to be smaller than the
448 // "current" type.
449 return mergeTypeInfo(OldTy, 0);
450 }
451
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000452 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000453 "Cannot merge something into a part of our type that doesn't exist!");
454
Chris Lattner18552922002-11-18 21:44:46 +0000455 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000456 // type that starts at offset Offset.
457 //
458 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000459 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000460 while (O < Offset) {
461 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
462
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000463 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000464 case Type::StructTyID: {
465 const StructType *STy = cast<StructType>(SubType);
466 const StructLayout &SL = *TD.getStructLayout(STy);
Chris Lattner2787e032005-03-13 19:05:05 +0000467 unsigned i = SL.getElementContainingOffset(Offset-O);
Chris Lattner08db7192002-11-06 06:20:27 +0000468
469 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000470 SubType = STy->getElementType(i);
Chris Lattner507bdf92005-01-12 04:51:37 +0000471 O += (unsigned)SL.MemberOffsets[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000472 break;
473 }
474 case Type::ArrayTyID: {
475 SubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000476 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000477 unsigned Remainder = (Offset-O) % ElSize;
478 O = Offset-Remainder;
479 break;
480 }
481 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000482 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000483 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000484 }
485 }
486
487 assert(O == Offset && "Could not achieve the correct offset!");
488
489 // If we found our type exactly, early exit
490 if (SubType == NewTy) return false;
491
Misha Brukman96a8bd72004-04-29 04:05:30 +0000492 // Differing function types don't require us to merge. They are not values
493 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000494 if (isa<FunctionType>(SubType) &&
495 isa<FunctionType>(NewTy)) return false;
496
Chris Lattner507bdf92005-01-12 04:51:37 +0000497 unsigned SubTypeSize = SubType->isSized() ?
498 (unsigned)TD.getTypeSize(SubType) : 0;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000499
500 // Ok, we are getting desperate now. Check for physical subtyping, where we
501 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000502 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000503 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000504 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000505 return false;
506
Chris Lattner08db7192002-11-06 06:20:27 +0000507 // Okay, so we found the leader type at the offset requested. Search the list
508 // of types that starts at this offset. If SubType is currently an array or
509 // structure, the type desired may actually be the first element of the
510 // composite type...
511 //
Chris Lattner18552922002-11-18 21:44:46 +0000512 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000513 while (SubType != NewTy) {
514 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000515 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000516 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000517 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000518 case Type::StructTyID: {
519 const StructType *STy = cast<StructType>(SubType);
520 const StructLayout &SL = *TD.getStructLayout(STy);
521 if (SL.MemberOffsets.size() > 1)
Chris Lattner507bdf92005-01-12 04:51:37 +0000522 NextPadSize = (unsigned)SL.MemberOffsets[1];
Chris Lattner18552922002-11-18 21:44:46 +0000523 else
524 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000525 NextSubType = STy->getElementType(0);
Chris Lattner507bdf92005-01-12 04:51:37 +0000526 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000527 break;
Chris Lattner18552922002-11-18 21:44:46 +0000528 }
Chris Lattner08db7192002-11-06 06:20:27 +0000529 case Type::ArrayTyID:
530 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000531 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner18552922002-11-18 21:44:46 +0000532 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000533 break;
534 default: ;
535 // fall out
536 }
537
538 if (NextSubType == 0)
539 break; // In the default case, break out of the loop
540
Chris Lattner18552922002-11-18 21:44:46 +0000541 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000542 break; // Don't allow shrinking to a smaller type than NewTySize
543 SubType = NextSubType;
544 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000545 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000546 }
547
548 // If we found the type exactly, return it...
549 if (SubType == NewTy)
550 return false;
551
552 // Check to see if we have a compatible, but different type...
553 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000554 // Check to see if this type is obviously convertible... int -> uint f.e.
555 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000556 return false;
557
558 // Check to see if we have a pointer & integer mismatch going on here,
559 // loading a pointer as a long, for example.
560 //
561 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
562 NewTy->isInteger() && isa<PointerType>(SubType))
563 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000564 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
565 // We are accessing the field, plus some structure padding. Ignore the
566 // structure padding.
567 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000568 }
569
Chris Lattner58f98d02003-07-02 04:38:49 +0000570 Module *M = 0;
Chris Lattnera5f47ea2005-03-15 16:55:04 +0000571 if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
572 M = getParentGraph()->retnodes_begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000573 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
574 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
575 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
576 << "SubType: ";
577 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000578
Chris Lattner088b6392003-03-03 17:13:31 +0000579 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000580 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000581}
582
Chris Lattner08db7192002-11-06 06:20:27 +0000583
584
Misha Brukman96a8bd72004-04-29 04:05:30 +0000585/// addEdgeTo - Add an edge from the current node to the specified node. This
586/// can cause merging of nodes in the graph.
587///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000588void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000589 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000590
Chris Lattner08db7192002-11-06 06:20:27 +0000591 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000592 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000593 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000594 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000595 } else { // No merging to perform...
596 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000597 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000598}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000599
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000600
Misha Brukman96a8bd72004-04-29 04:05:30 +0000601/// MergeSortedVectors - Efficiently merge a vector into another vector where
602/// duplicates are not allowed and both are sorted. This assumes that 'T's are
603/// efficiently copyable and have sane comparison semantics.
604///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000605static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
606 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000607 // By far, the most common cases will be the simple ones. In these cases,
608 // avoid having to allocate a temporary vector...
609 //
610 if (Src.empty()) { // Nothing to merge in...
611 return;
612 } else if (Dest.empty()) { // Just copy the result in...
613 Dest = Src;
614 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000615 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000616 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000617 std::lower_bound(Dest.begin(), Dest.end(), V);
618 if (I == Dest.end() || *I != Src[0]) // If not already contained...
619 Dest.insert(I, Src[0]);
620 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000621 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000622 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000623 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000624 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
625 if (I == Dest.end() || *I != Tmp) // If not already contained...
626 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000627
628 } else {
629 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000630 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000631
632 // Make space for all of the type entries now...
633 Dest.resize(Dest.size()+Src.size());
634
635 // Merge the two sorted ranges together... into Dest.
636 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
637
638 // Now erase any duplicate entries that may have accumulated into the
639 // vectors (because they were in both of the input sets)
640 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
641 }
642}
643
Chris Lattner0b144872004-01-27 22:03:40 +0000644void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
645 MergeSortedVectors(Globals, RHS);
646}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000647
Chris Lattner0b144872004-01-27 22:03:40 +0000648// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000649// This function does the hard work of merging two nodes, CurNodeH
650// and NH after filtering out trivial cases and making sure that
651// CurNodeH.offset >= NH.offset.
652//
653// ***WARNING***
654// Since merging may cause either node to go away, we must always
655// use the node-handles to refer to the nodes. These node handles are
656// automatically updated during merging, so will always provide access
657// to the correct node after a merge.
658//
659void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
660 assert(CurNodeH.getOffset() >= NH.getOffset() &&
661 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000662 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
663 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000664
665 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
666 // respect to NH.Offset) is now zero. NOffset is the distance from the base
667 // of our object that N starts from.
668 //
669 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
670 unsigned NSize = NH.getNode()->getSize();
671
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000672 // If the two nodes are of different size, and the smaller node has the array
673 // bit set, collapse!
674 if (NSize != CurNodeH.getNode()->getSize()) {
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000675#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000676 if (NSize < CurNodeH.getNode()->getSize()) {
677 if (NH.getNode()->isArray())
678 NH.getNode()->foldNodeCompletely();
679 } else if (CurNodeH.getNode()->isArray()) {
680 NH.getNode()->foldNodeCompletely();
681 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000682#endif
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000683 }
684
685 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000686 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000687 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000688 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000689
690 // If we are merging a node with a completely folded node, then both nodes are
691 // now completely folded.
692 //
693 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
694 if (!NH.getNode()->isNodeCompletelyFolded()) {
695 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000696 assert(NH.getNode() && NH.getOffset() == 0 &&
697 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000698 NOffset = NH.getOffset();
699 NSize = NH.getNode()->getSize();
700 assert(NOffset == 0 && NSize == 1);
701 }
702 } else if (NH.getNode()->isNodeCompletelyFolded()) {
703 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000704 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
705 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000706 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000707 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000708 assert(NOffset == 0 && NSize == 1);
709 }
710
Chris Lattner72d29a42003-02-11 23:11:51 +0000711 DSNode *N = NH.getNode();
712 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000713 assert(!CurNodeH.getNode()->isDeadNode());
714
Chris Lattner0b144872004-01-27 22:03:40 +0000715 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000716 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000717
Chris Lattner72d29a42003-02-11 23:11:51 +0000718 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000719 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000720 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000721
Chris Lattner72d29a42003-02-11 23:11:51 +0000722 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
723 //
724 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
725 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000726 if (Link.getNode()) {
727 // Compute the offset into the current node at which to
728 // merge this link. In the common case, this is a linear
729 // relation to the offset in the original node (with
730 // wrapping), but if the current node gets collapsed due to
731 // recursive merging, we must make sure to merge in all remaining
732 // links at offset zero.
733 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000734 DSNode *CN = CurNodeH.getNode();
735 if (CN->Size != 1)
736 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
737 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000738 }
739 }
740
741 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000742 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000743
744 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000745 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000746 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000747
748 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000749 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000750 }
751}
752
753
Misha Brukman96a8bd72004-04-29 04:05:30 +0000754/// mergeWith - Merge this node and the specified node, moving all links to and
755/// from the argument node into the current node, deleting the node argument.
756/// Offset indicates what offset the specified node is to be merged into the
757/// current node.
758///
759/// The specified node may be a null pointer (in which case, we update it to
760/// point to this node).
761///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000762void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
763 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000764 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000765 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000766
Chris Lattner5254a8d2004-01-22 16:31:08 +0000767 // If the RHS is a null node, make it point to this node!
768 if (N == 0) {
769 NH.mergeWith(DSNodeHandle(this, Offset));
770 return;
771 }
772
Chris Lattnerbd92b732003-06-19 21:15:11 +0000773 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000774 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
775
Chris Lattner02606632002-11-04 06:48:26 +0000776 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000777 // We cannot merge two pieces of the same node together, collapse the node
778 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000779 DEBUG(std::cerr << "Attempting to merge two chunks of"
780 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000781 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000782 return;
783 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000784
Chris Lattner5190ce82002-11-12 07:20:45 +0000785 // If both nodes are not at offset 0, make sure that we are merging the node
786 // at an later offset into the node with the zero offset.
787 //
788 if (Offset < NH.getOffset()) {
789 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
790 return;
791 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
792 // If the offsets are the same, merge the smaller node into the bigger node
793 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
794 return;
795 }
796
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000797 // Ok, now we can merge the two nodes. Use a static helper that works with
798 // two node handles, since "this" may get merged away at intermediate steps.
799 DSNodeHandle CurNodeH(this, Offset);
800 DSNodeHandle NHCopy(NH);
801 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000802}
803
Chris Lattner0b144872004-01-27 22:03:40 +0000804
805//===----------------------------------------------------------------------===//
806// ReachabilityCloner Implementation
807//===----------------------------------------------------------------------===//
808
809DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
810 if (SrcNH.isNull()) return DSNodeHandle();
811 const DSNode *SN = SrcNH.getNode();
812
813 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000814 if (!NH.isNull()) { // Node already mapped?
815 DSNode *NHN = NH.getNode();
816 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
817 }
Chris Lattner0b144872004-01-27 22:03:40 +0000818
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000819 // If SrcNH has globals and the destination graph has one of the same globals,
820 // merge this node with the destination node, which is much more efficient.
821 if (SN->global_begin() != SN->global_end()) {
822 DSScalarMap &DestSM = Dest.getScalarMap();
823 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
824 I != E; ++I) {
825 GlobalValue *GV = *I;
826 DSScalarMap::iterator GI = DestSM.find(GV);
827 if (GI != DestSM.end() && !GI->second.isNull()) {
828 // We found one, use merge instead!
829 merge(GI->second, Src.getNodeForValue(GV));
830 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000831 DSNode *NHN = NH.getNode();
832 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000833 }
834 }
835 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000836
Chris Lattner0b144872004-01-27 22:03:40 +0000837 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
838 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000839 NH = DN;
Chris Lattner0b144872004-01-27 22:03:40 +0000840
841 // Next, recursively clone all outgoing links as necessary. Note that
842 // adding these links can cause the node to collapse itself at any time, and
843 // the current node may be merged with arbitrary other nodes. For this
844 // reason, we must always go through NH.
845 DN = 0;
846 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
847 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
848 if (!SrcEdge.isNull()) {
849 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
850 // Compute the offset into the current node at which to
851 // merge this link. In the common case, this is a linear
852 // relation to the offset in the original node (with
853 // wrapping), but if the current node gets collapsed due to
854 // recursive merging, we must make sure to merge in all remaining
855 // links at offset zero.
856 unsigned MergeOffset = 0;
857 DSNode *CN = NH.getNode();
858 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +0000859 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +0000860 CN->addEdgeTo(MergeOffset, DestEdge);
861 }
862 }
863
864 // If this node contains any globals, make sure they end up in the scalar
865 // map with the correct offset.
866 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
867 I != E; ++I) {
868 GlobalValue *GV = *I;
869 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
870 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
871 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
872 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000873 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000874
875 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
876 Dest.getInlinedGlobals().insert(GV);
877 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000878 NH.getNode()->mergeGlobals(SN->getGlobals());
Chris Lattner0b144872004-01-27 22:03:40 +0000879
880 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
881}
882
883void ReachabilityCloner::merge(const DSNodeHandle &NH,
884 const DSNodeHandle &SrcNH) {
885 if (SrcNH.isNull()) return; // Noop
886 if (NH.isNull()) {
887 // If there is no destination node, just clone the source and assign the
888 // destination node to be it.
889 NH.mergeWith(getClonedNH(SrcNH));
890 return;
891 }
892
893 // Okay, at this point, we know that we have both a destination and a source
894 // node that need to be merged. Check to see if the source node has already
895 // been cloned.
896 const DSNode *SN = SrcNH.getNode();
897 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +0000898 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +0000899 DSNode *SCNHN = SCNH.getNode();
900 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +0000901 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000902 return; // Nothing to do!
903 }
Chris Lattner6f967742004-10-30 04:05:01 +0000904
Chris Lattner0b144872004-01-27 22:03:40 +0000905 // Okay, so the source node has not already been cloned. Instead of creating
906 // a new DSNode, only to merge it into the one we already have, try to perform
907 // the merge in-place. The only case we cannot handle here is when the offset
908 // into the existing node is less than the offset into the virtual node we are
909 // merging in. In this case, we have to extend the existing node, which
910 // requires an allocation anyway.
911 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
912 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000913 if (!DN->isNodeCompletelyFolded()) {
914 // Make sure the destination node is folded if the source node is folded.
915 if (SN->isNodeCompletelyFolded()) {
916 DN->foldNodeCompletely();
917 DN = NH.getNode();
918 } else if (SN->getSize() != DN->getSize()) {
919 // If the two nodes are of different size, and the smaller node has the
920 // array bit set, collapse!
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000921#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner0b144872004-01-27 22:03:40 +0000922 if (SN->getSize() < DN->getSize()) {
923 if (SN->isArray()) {
924 DN->foldNodeCompletely();
925 DN = NH.getNode();
926 }
927 } else if (DN->isArray()) {
928 DN->foldNodeCompletely();
929 DN = NH.getNode();
930 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000931#endif
Chris Lattner0b144872004-01-27 22:03:40 +0000932 }
933
934 // Merge the type entries of the two nodes together...
935 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
936 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
937 DN = NH.getNode();
938 }
939 }
940
941 assert(!DN->isDeadNode());
942
943 // Merge the NodeType information.
944 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
945
946 // Before we start merging outgoing links and updating the scalar map, make
947 // sure it is known that this is the representative node for the src node.
948 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
949
950 // If the source node contains any globals, make sure they end up in the
951 // scalar map with the correct offset.
952 if (SN->global_begin() != SN->global_end()) {
953 // Update the globals in the destination node itself.
954 DN->mergeGlobals(SN->getGlobals());
955
956 // Update the scalar map for the graph we are merging the source node
957 // into.
958 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
959 I != E; ++I) {
960 GlobalValue *GV = *I;
961 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
962 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
963 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
964 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +0000965 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000966
967 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
968 Dest.getInlinedGlobals().insert(GV);
969 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000970 NH.getNode()->mergeGlobals(SN->getGlobals());
Chris Lattner0b144872004-01-27 22:03:40 +0000971 }
972 } else {
973 // We cannot handle this case without allocating a temporary node. Fall
974 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +0000975 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
976 NewDN->maskNodeTypes(BitsToKeep);
977
978 unsigned NHOffset = NH.getOffset();
979 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +0000980
Chris Lattner0b144872004-01-27 22:03:40 +0000981 assert(NH.getNode() &&
982 (NH.getOffset() > NHOffset ||
983 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
984 "Merging did not adjust the offset!");
985
986 // Before we start merging outgoing links and updating the scalar map, make
987 // sure it is known that this is the representative node for the src node.
988 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +0000989
990 // If the source node contained any globals, make sure to create entries
991 // in the scalar map for them!
992 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
993 I != E; ++I) {
994 GlobalValue *GV = *I;
995 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
996 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
997 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
998 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
999 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1000 DestGNH.getOffset()+SrcGNH.getOffset()));
1001
1002 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1003 Dest.getInlinedGlobals().insert(GV);
1004 }
Chris Lattner0b144872004-01-27 22:03:40 +00001005 }
1006
1007
1008 // Next, recursively merge all outgoing links as necessary. Note that
1009 // adding these links can cause the destination node to collapse itself at
1010 // any time, and the current node may be merged with arbitrary other nodes.
1011 // For this reason, we must always go through NH.
1012 DN = 0;
1013 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1014 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1015 if (!SrcEdge.isNull()) {
1016 // Compute the offset into the current node at which to
1017 // merge this link. In the common case, this is a linear
1018 // relation to the offset in the original node (with
1019 // wrapping), but if the current node gets collapsed due to
1020 // recursive merging, we must make sure to merge in all remaining
1021 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +00001022 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +00001023 unsigned MergeOffset =
1024 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +00001025
Chris Lattnerf590ced2004-03-04 17:06:53 +00001026 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1027 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001028 // Perform the recursive merging. Make sure to create a temporary NH,
1029 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001030 merge(Tmp, SrcEdge);
1031 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001032 Tmp.mergeWith(getClonedNH(SrcEdge));
1033 // Merging this could cause all kinds of recursive things to happen,
1034 // culminating in the current node being eliminated. Since this is
1035 // possible, make sure to reaquire the link from 'CN'.
1036
1037 unsigned MergeOffset = 0;
1038 CN = SCNH.getNode();
1039 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1040 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001041 }
Chris Lattner0b144872004-01-27 22:03:40 +00001042 }
1043 }
1044}
1045
1046/// mergeCallSite - Merge the nodes reachable from the specified src call
1047/// site into the nodes reachable from DestCS.
1048void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
1049 const DSCallSite &SrcCS) {
1050 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1051 unsigned MinArgs = DestCS.getNumPtrArgs();
1052 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1053
1054 for (unsigned a = 0; a != MinArgs; ++a)
1055 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1056}
1057
1058
Chris Lattner9de906c2002-10-20 22:11:44 +00001059//===----------------------------------------------------------------------===//
1060// DSCallSite Implementation
1061//===----------------------------------------------------------------------===//
1062
Vikram S. Adve26b98262002-10-20 21:41:02 +00001063// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001064Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001065 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001066}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001067
Chris Lattner0b144872004-01-27 22:03:40 +00001068void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1069 ReachabilityCloner &RC) {
1070 NH = RC.getClonedNH(Src);
1071}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001072
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001073//===----------------------------------------------------------------------===//
1074// DSGraph Implementation
1075//===----------------------------------------------------------------------===//
1076
Chris Lattnera9d65662003-06-30 05:57:30 +00001077/// getFunctionNames - Return a space separated list of the name of the
1078/// functions in this graph (if any)
1079std::string DSGraph::getFunctionNames() const {
1080 switch (getReturnNodes().size()) {
1081 case 0: return "Globals graph";
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001082 case 1: return retnodes_begin()->first->getName();
Chris Lattnera9d65662003-06-30 05:57:30 +00001083 default:
1084 std::string Return;
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001085 for (DSGraph::retnodes_iterator I = retnodes_begin();
1086 I != retnodes_end(); ++I)
Chris Lattnera9d65662003-06-30 05:57:30 +00001087 Return += I->first->getName() + " ";
1088 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1089 return Return;
1090 }
1091}
1092
1093
Chris Lattner15869aa2003-11-02 22:27:28 +00001094DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001095 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001096 NodeMapTy NodeMap;
1097 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001098}
1099
Chris Lattner5a540632003-06-30 03:15:25 +00001100DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001101 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001102 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001103 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001104}
1105
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001106DSGraph::~DSGraph() {
1107 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001108 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001109 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001110 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001111 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001112
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001113 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001114 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
Chris Lattner84b80a22005-03-16 22:42:19 +00001115 NI->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001116
Chris Lattner28897e12004-02-08 00:53:26 +00001117 // Free all of the nodes.
1118 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001119}
1120
Chris Lattner0d9bab82002-07-18 00:12:30 +00001121// dump - Allow inspection of graph in a debugger.
1122void DSGraph::dump() const { print(std::cerr); }
1123
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001124
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001125/// remapLinks - Change all of the Links in the current node according to the
1126/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001127///
Chris Lattner8d327672003-06-30 03:36:09 +00001128void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001129 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1130 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001131 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001132 if (ONMI != OldNodeMap.end()) {
1133 DSNode *ONMIN = ONMI->second.getNode();
1134 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1135 }
Chris Lattner2f561382004-01-22 16:56:13 +00001136 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001137}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001138
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001139/// updateFromGlobalGraph - This function rematerializes global nodes and
1140/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001141/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1142/// are already up-to-date in the current graph. In practice, in the TD pass,
1143/// this is likely to be a large fraction of the live global nodes in each
1144/// function (since most live nodes are likely to have been brought up-to-date
1145/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001146///
1147void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001148 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001149 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1150
1151 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001152 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1153 E = getScalarMap().global_end(); I != E; ++I)
1154 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001155 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001156 if (It != GlobalsGraph->ScalarMap.end())
1157 RC.merge(getNodeForValue(*I), It->second);
1158 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001159}
1160
Chris Lattnerd672ab92005-02-15 18:40:55 +00001161/// addObjectToGraph - This method can be used to add global, stack, and heap
1162/// objects to the graph. This can be used when updating DSGraphs due to the
1163/// introduction of new temporary objects. The new object is not pointed to
1164/// and does not point to any other objects in the graph.
1165DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1166 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1167 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1168 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
Chris Lattner7a0c7752005-02-15 18:48:48 +00001169 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
Chris Lattnerd672ab92005-02-15 18:40:55 +00001170 ScalarMap[Ptr] = N;
1171
1172 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1173 N->addGlobal(GV);
1174 } else if (MallocInst *MI = dyn_cast<MallocInst>(Ptr)) {
1175 N->setHeapNodeMarker();
1176 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr)) {
1177 N->setAllocaNodeMarker();
1178 } else {
1179 assert(0 && "Illegal memory object input!");
1180 }
1181 return N;
1182}
1183
1184
Chris Lattner5a540632003-06-30 03:15:25 +00001185/// cloneInto - Clone the specified DSGraph into the current graph. The
1186/// translated ScalarMap for the old function is filled into the OldValMap
1187/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1188///
1189/// The CloneFlags member controls various aspects of the cloning process.
1190///
Chris Lattner62482e52004-01-28 09:15:42 +00001191void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001192 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1193 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001194 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001195 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001196 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001197
Chris Lattner1e883692003-02-03 20:08:51 +00001198 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001199 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1200 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1201 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001202 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001203
Chris Lattner84b80a22005-03-16 22:42:19 +00001204 for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1205 assert(!I->isForwarding() &&
Chris Lattnerd85645f2004-02-21 22:28:26 +00001206 "Forward nodes shouldn't be in node list!");
Chris Lattner84b80a22005-03-16 22:42:19 +00001207 DSNode *New = new DSNode(*I, this);
Chris Lattnerd85645f2004-02-21 22:28:26 +00001208 New->maskNodeTypes(~BitsToClear);
Chris Lattner84b80a22005-03-16 22:42:19 +00001209 OldNodeMap[I] = New;
Chris Lattnerd85645f2004-02-21 22:28:26 +00001210 }
1211
Chris Lattner18552922002-11-18 21:44:46 +00001212#ifndef NDEBUG
1213 Timer::addPeakMemoryMeasurement();
1214#endif
Chris Lattnerd85645f2004-02-21 22:28:26 +00001215
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001216 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001217 // Note that we don't loop over the node's list to do this. The problem is
1218 // that remaping links can cause recursive merging to happen, which means
1219 // that node_iterator's can get easily invalidated! Because of this, we
1220 // loop over the OldNodeMap, which contains all of the new nodes as the
1221 // .second element of the map elements. Also note that if we remap a node
1222 // more than once, we won't break anything.
1223 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1224 I != E; ++I)
1225 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001226
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001227 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001228 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001229 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001230 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001231 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner6f967742004-10-30 04:05:01 +00001232 DSNode *MappedNodeN = MappedNode.getNode();
1233 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001234 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001235
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001236 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001237 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1238 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001239 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1240 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001241 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001242 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001243
Chris Lattner679e8e12002-11-08 21:27:12 +00001244 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001245 // Copy the function calls list.
1246 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1247 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001248 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001249
Chris Lattneracf491f2002-11-08 22:27:09 +00001250 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001251 // Copy the auxiliary function calls list.
1252 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1253 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattner679e8e12002-11-08 21:27:12 +00001254 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001255
Chris Lattner5a540632003-06-30 03:15:25 +00001256 // Map the return node pointers over...
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001257 for (retnodes_iterator I = G.retnodes_begin(),
1258 E = G.retnodes_end(); I != E; ++I) {
Chris Lattner5a540632003-06-30 03:15:25 +00001259 const DSNodeHandle &Ret = I->second;
1260 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001261 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattner5a540632003-06-30 03:15:25 +00001262 OldReturnNodes.insert(std::make_pair(I->first,
Chris Lattner6f967742004-10-30 04:05:01 +00001263 DSNodeHandle(MappedRetN,
Chris Lattner5a540632003-06-30 03:15:25 +00001264 MappedRet.getOffset()+Ret.getOffset())));
1265 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001266}
1267
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001268static bool PathExistsToClonedNode(const DSNode *N, ReachabilityCloner &RC) {
Chris Lattner2f346902004-03-04 03:57:53 +00001269 if (N)
1270 for (df_iterator<const DSNode*> I = df_begin(N), E = df_end(N); I != E; ++I)
1271 if (RC.hasClonedNode(*I))
1272 return true;
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001273 return false;
1274}
1275
Chris Lattner2f346902004-03-04 03:57:53 +00001276static bool PathExistsToClonedNode(const DSCallSite &CS,
1277 ReachabilityCloner &RC) {
1278 if (PathExistsToClonedNode(CS.getRetVal().getNode(), RC))
1279 return true;
1280 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1281 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode(), RC))
1282 return true;
1283 return false;
1284}
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001285
Chris Lattnerbb753c42005-02-03 18:40:25 +00001286/// getFunctionArgumentsForCall - Given a function that is currently in this
1287/// graph, return the DSNodeHandles that correspond to the pointer-compatible
1288/// function arguments. The vector is filled in with the return value (or
1289/// null if it is not pointer compatible), followed by all of the
1290/// pointer-compatible arguments.
1291void DSGraph::getFunctionArgumentsForCall(Function *F,
1292 std::vector<DSNodeHandle> &Args) const {
1293 Args.push_back(getReturnNodeFor(*F));
Chris Lattnere4d5c442005-03-15 04:54:21 +00001294 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; ++AI)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001295 if (isPointerType(AI->getType())) {
1296 Args.push_back(getNodeForValue(AI));
1297 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1298 }
1299}
1300
Chris Lattnere8594442005-02-04 19:58:28 +00001301/// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1302/// nodes from G2 into 'this' graph, merging the bindings specified by the
1303/// call site (in this graph) with the bindings specified by the vector in G2.
1304/// The two DSGraphs must be different.
Chris Lattner076c1f92002-11-07 06:31:54 +00001305///
Chris Lattnere8594442005-02-04 19:58:28 +00001306void DSGraph::mergeInGraph(const DSCallSite &CS,
1307 std::vector<DSNodeHandle> &Args,
Chris Lattner9f930552003-06-30 05:27:18 +00001308 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001309 TIME_REGION(X, "mergeInGraph");
1310
Chris Lattner076c1f92002-11-07 06:31:54 +00001311 // If this is not a recursive call, clone the graph into this graph...
1312 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001313 // Clone the callee's graph into the current graph, keeping track of where
1314 // scalars in the old graph _used_ to point, and of the new nodes matching
1315 // nodes of the old graph.
1316 ReachabilityCloner RC(*this, Graph, CloneFlags);
1317
Chris Lattner0b144872004-01-27 22:03:40 +00001318 // Map the return node pointer over.
Chris Lattner0ad91702004-02-22 00:53:54 +00001319 if (!CS.getRetVal().isNull())
Chris Lattnerbb753c42005-02-03 18:40:25 +00001320 RC.merge(CS.getRetVal(), Args[0]);
Chris Lattnerf590ced2004-03-04 17:06:53 +00001321
Chris Lattnerbb753c42005-02-03 18:40:25 +00001322 // Map over all of the arguments.
1323 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001324 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001325 break;
Chris Lattnerbb753c42005-02-03 18:40:25 +00001326
1327 // Add the link from the argument scalar to the provided value.
1328 RC.merge(CS.getPtrArg(i), Args[i+1]);
1329 }
1330
Chris Lattner2f346902004-03-04 03:57:53 +00001331 // If requested, copy all of the calls.
Chris Lattner0b144872004-01-27 22:03:40 +00001332 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001333 // Copy the function calls list.
1334 for (fc_iterator I = Graph.fc_begin(), E = Graph.fc_end(); I != E; ++I)
1335 FunctionCalls.push_back(DSCallSite(*I, RC));
Chris Lattner0b144872004-01-27 22:03:40 +00001336 }
Chris Lattner2f346902004-03-04 03:57:53 +00001337
1338 // If the user has us copying aux calls (the normal case), set up a data
1339 // structure to keep track of which ones we've copied over.
Chris Lattnera9548d92005-01-30 23:51:02 +00001340 std::set<const DSCallSite*> CopiedAuxCall;
Chris Lattner0b144872004-01-27 22:03:40 +00001341
Chris Lattner0321b682004-02-27 20:05:15 +00001342 // Clone over all globals that appear in the caller and callee graphs.
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001343 hash_set<GlobalVariable*> NonCopiedGlobals;
Chris Lattner0321b682004-02-27 20:05:15 +00001344 for (DSScalarMap::global_iterator GI = Graph.getScalarMap().global_begin(),
1345 E = Graph.getScalarMap().global_end(); GI != E; ++GI)
1346 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*GI))
1347 if (ScalarMap.count(GV))
1348 RC.merge(ScalarMap[GV], Graph.getNodeForValue(GV));
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001349 else
1350 NonCopiedGlobals.insert(GV);
1351
1352 // If the global does not appear in the callers graph we generally don't
1353 // want to copy the node. However, if there is a path from the node global
1354 // node to a node that we did copy in the graph, we *must* copy it to
1355 // maintain the connection information. Every time we decide to include a
1356 // new global, this might make other globals live, so we must iterate
1357 // unfortunately.
Chris Lattner2f346902004-03-04 03:57:53 +00001358 bool MadeChange = true;
1359 while (MadeChange) {
1360 MadeChange = false;
1361 for (hash_set<GlobalVariable*>::iterator I = NonCopiedGlobals.begin();
1362 I != NonCopiedGlobals.end();) {
1363 DSNode *GlobalNode = Graph.getNodeForValue(*I).getNode();
1364 if (RC.hasClonedNode(GlobalNode)) {
1365 // Already cloned it, remove from set.
1366 NonCopiedGlobals.erase(I++);
1367 MadeChange = true;
1368 } else if (PathExistsToClonedNode(GlobalNode, RC)) {
1369 RC.getClonedNH(Graph.getNodeForValue(*I));
1370 NonCopiedGlobals.erase(I++);
1371 MadeChange = true;
1372 } else {
1373 ++I;
1374 }
1375 }
1376
1377 // If requested, copy any aux calls that can reach copied nodes.
1378 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001379 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
1380 if (CopiedAuxCall.insert(&*I).second &&
1381 PathExistsToClonedNode(*I, RC)) {
1382 AuxFunctionCalls.push_back(DSCallSite(*I, RC));
Chris Lattner2f346902004-03-04 03:57:53 +00001383 MadeChange = true;
1384 }
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001385 }
1386 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001387
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001388 } else {
Chris Lattnerbb753c42005-02-03 18:40:25 +00001389 // Merge the return value with the return value of the context.
1390 Args[0].mergeWith(CS.getRetVal());
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001391
Chris Lattnerbb753c42005-02-03 18:40:25 +00001392 // Resolve all of the function arguments.
1393 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001394 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001395 break;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001396
Chris Lattnerbb753c42005-02-03 18:40:25 +00001397 // Add the link from the argument scalar to the provided value.
1398 Args[i+1].mergeWith(CS.getPtrArg(i));
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001399 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001400 }
1401}
1402
Chris Lattnere8594442005-02-04 19:58:28 +00001403
1404
1405/// mergeInGraph - The method is used for merging graphs together. If the
1406/// argument graph is not *this, it makes a clone of the specified graph, then
1407/// merges the nodes specified in the call site with the formal arguments in the
1408/// graph.
1409///
1410void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1411 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattnere8594442005-02-04 19:58:28 +00001412 // Set up argument bindings.
1413 std::vector<DSNodeHandle> Args;
1414 Graph.getFunctionArgumentsForCall(&F, Args);
1415
1416 mergeInGraph(CS, Args, Graph, CloneFlags);
1417}
1418
Chris Lattner58f98d02003-07-02 04:38:49 +00001419/// getCallSiteForArguments - Get the arguments and return value bindings for
1420/// the specified function in the current graph.
1421///
1422DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1423 std::vector<DSNodeHandle> Args;
1424
Chris Lattnere4d5c442005-03-15 04:54:21 +00001425 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner58f98d02003-07-02 04:38:49 +00001426 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001427 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001428
Chris Lattner808a7ae2003-09-20 16:34:13 +00001429 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001430}
1431
Chris Lattner85fb1be2004-03-09 19:37:06 +00001432/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1433/// the context of this graph, return the DSCallSite for it.
1434DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1435 DSNodeHandle RetVal;
1436 Instruction *I = CS.getInstruction();
1437 if (isPointerType(I->getType()))
1438 RetVal = getNodeForValue(I);
1439
1440 std::vector<DSNodeHandle> Args;
1441 Args.reserve(CS.arg_end()-CS.arg_begin());
1442
1443 // Calculate the arguments vector...
1444 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1445 if (isPointerType((*I)->getType()))
Chris Lattner94f84702005-03-17 19:56:56 +00001446 if (isa<ConstantPointerNull>(*I))
1447 Args.push_back(DSNodeHandle());
1448 else
1449 Args.push_back(getNodeForValue(*I));
Chris Lattner85fb1be2004-03-09 19:37:06 +00001450
1451 // Add a new function call entry...
1452 if (Function *F = CS.getCalledFunction())
1453 return DSCallSite(CS, RetVal, F, Args);
1454 else
1455 return DSCallSite(CS, RetVal,
1456 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1457}
1458
Chris Lattner58f98d02003-07-02 04:38:49 +00001459
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001460
Chris Lattner0d9bab82002-07-18 00:12:30 +00001461// markIncompleteNodes - Mark the specified node as having contents that are not
1462// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001463// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001464// must recursively traverse the data structure graph, marking all reachable
1465// nodes as incomplete.
1466//
1467static void markIncompleteNode(DSNode *N) {
1468 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001469 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001470
1471 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001472 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001473
Misha Brukman2f2d0652003-09-11 18:14:24 +00001474 // Recursively process children...
Chris Lattner6be07942005-02-09 03:20:43 +00001475 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1476 if (DSNode *DSN = I->getNode())
Chris Lattner08db7192002-11-06 06:20:27 +00001477 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001478}
1479
Chris Lattnere71ffc22002-11-11 03:36:55 +00001480static void markIncomplete(DSCallSite &Call) {
1481 // Then the return value is certainly incomplete!
1482 markIncompleteNode(Call.getRetVal().getNode());
1483
1484 // All objects pointed to by function arguments are incomplete!
1485 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1486 markIncompleteNode(Call.getPtrArg(i).getNode());
1487}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001488
1489// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1490// modified by other functions that have not been resolved yet. This marks
1491// nodes that are reachable through three sources of "unknownness":
1492//
1493// Global Variables, Function Calls, and Incoming Arguments
1494//
1495// For any node that may have unknown components (because something outside the
1496// scope of current analysis may have modified it), the 'Incomplete' flag is
1497// added to the NodeType.
1498//
Chris Lattner394471f2003-01-23 22:05:33 +00001499void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001500 // Mark any incoming arguments as incomplete.
Chris Lattner5a540632003-06-30 03:15:25 +00001501 if (Flags & DSGraph::MarkFormalArgs)
1502 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1503 FI != E; ++FI) {
1504 Function &F = *FI->first;
Chris Lattnere4d5c442005-03-15 04:54:21 +00001505 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattnerb5ecd2e2005-03-13 20:22:10 +00001506 if (isPointerType(I->getType()))
1507 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattnera4319e52005-03-12 14:58:28 +00001508 markIncompleteNode(FI->second.getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001509 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001510
Chris Lattnera9548d92005-01-30 23:51:02 +00001511 // Mark stuff passed into functions calls as being incomplete.
Chris Lattnere71ffc22002-11-11 03:36:55 +00001512 if (!shouldPrintAuxCalls())
Chris Lattnera9548d92005-01-30 23:51:02 +00001513 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1514 E = FunctionCalls.end(); I != E; ++I)
1515 markIncomplete(*I);
Chris Lattnere71ffc22002-11-11 03:36:55 +00001516 else
Chris Lattnera9548d92005-01-30 23:51:02 +00001517 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1518 E = AuxFunctionCalls.end(); I != E; ++I)
1519 markIncomplete(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001520
Chris Lattnere2bc7b22005-03-13 20:36:01 +00001521 // Mark all global nodes as incomplete.
1522 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1523 E = ScalarMap.global_end(); I != E; ++I)
1524 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1525 if (!GV->hasInitializer() || // Always mark external globals incomp.
1526 (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1527 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001528}
1529
Chris Lattneraa8146f2002-11-10 06:59:55 +00001530static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1531 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001532 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001533 // No interesting info?
1534 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001535 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001536 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001537}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001538
Chris Lattneraa8146f2002-11-10 06:59:55 +00001539static inline bool nodeContainsExternalFunction(const DSNode *N) {
1540 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1541 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
Chris Lattner857eb062004-10-30 05:41:23 +00001542 if (Globals[i]->isExternal() && isa<Function>(Globals[i]))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001543 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001544 return false;
1545}
1546
Chris Lattnera9548d92005-01-30 23:51:02 +00001547static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001548 // Remove trivially identical function calls
Chris Lattnera9548d92005-01-30 23:51:02 +00001549 Calls.sort(); // Sort by callee as primary key!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001550
1551 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001552 DSNode *LastCalleeNode = 0;
1553 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001554 unsigned NumDuplicateCalls = 0;
1555 bool LastCalleeContainsExternalFunction = false;
Chris Lattner857eb062004-10-30 05:41:23 +00001556
Chris Lattnera9548d92005-01-30 23:51:02 +00001557 unsigned NumDeleted = 0;
1558 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1559 I != E;) {
1560 DSCallSite &CS = *I;
1561 std::list<DSCallSite>::iterator OldIt = I++;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001562
Chris Lattnere4258442002-11-11 21:35:38 +00001563 // If the Callee is a useless edge, this must be an unreachable call site,
1564 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001565 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerabcdf802004-02-26 03:43:43 +00001566 CS.getCalleeNode()->isComplete() &&
Chris Lattneraf6926a2004-02-26 03:45:03 +00001567 CS.getCalleeNode()->getGlobals().empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001568#ifndef NDEBUG
Chris Lattnerabcdf802004-02-26 03:43:43 +00001569 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001570#endif
Chris Lattnera9548d92005-01-30 23:51:02 +00001571 Calls.erase(OldIt);
1572 ++NumDeleted;
1573 continue;
1574 }
1575
1576 // If the return value or any arguments point to a void node with no
1577 // information at all in it, and the call node is the only node to point
1578 // to it, remove the edge to the node (killing the node).
1579 //
1580 killIfUselessEdge(CS.getRetVal());
1581 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1582 killIfUselessEdge(CS.getPtrArg(a));
1583
Chris Lattner0b144872004-01-27 22:03:40 +00001584#if 0
Chris Lattnera9548d92005-01-30 23:51:02 +00001585 // If this call site calls the same function as the last call site, and if
1586 // the function pointer contains an external function, this node will
1587 // never be resolved. Merge the arguments of the call node because no
1588 // information will be lost.
1589 //
1590 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1591 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1592 ++NumDuplicateCalls;
1593 if (NumDuplicateCalls == 1) {
1594 if (LastCalleeNode)
1595 LastCalleeContainsExternalFunction =
1596 nodeContainsExternalFunction(LastCalleeNode);
1597 else
1598 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001599 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001600
1601 // It is not clear why, but enabling this code makes DSA really
1602 // sensitive to node forwarding. Basically, with this enabled, DSA
1603 // performs different number of inlinings based on which nodes are
1604 // forwarding or not. This is clearly a problem, so this code is
1605 // disabled until this can be resolved.
1606#if 1
1607 if (LastCalleeContainsExternalFunction
1608#if 0
1609 ||
1610 // This should be more than enough context sensitivity!
1611 // FIXME: Evaluate how many times this is tripped!
1612 NumDuplicateCalls > 20
1613#endif
1614 ) {
1615
1616 std::list<DSCallSite>::iterator PrevIt = OldIt;
1617 --PrevIt;
1618 PrevIt->mergeWith(CS);
1619
1620 // No need to keep this call anymore.
1621 Calls.erase(OldIt);
1622 ++NumDeleted;
1623 continue;
1624 }
1625#endif
1626 } else {
1627 if (CS.isDirectCall()) {
1628 LastCalleeFunc = CS.getCalleeFunc();
1629 LastCalleeNode = 0;
1630 } else {
1631 LastCalleeNode = CS.getCalleeNode();
1632 LastCalleeFunc = 0;
1633 }
1634 NumDuplicateCalls = 0;
1635 }
1636#endif
1637
1638 if (I != Calls.end() && CS == *I) {
1639 Calls.erase(OldIt);
1640 ++NumDeleted;
1641 continue;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001642 }
1643 }
Chris Lattner857eb062004-10-30 05:41:23 +00001644
Chris Lattnera9548d92005-01-30 23:51:02 +00001645 // Resort now that we simplified things.
1646 Calls.sort();
Chris Lattner857eb062004-10-30 05:41:23 +00001647
Chris Lattnera9548d92005-01-30 23:51:02 +00001648 // Now that we are in sorted order, eliminate duplicates.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001649 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1650 if (CI != CE)
Chris Lattnera9548d92005-01-30 23:51:02 +00001651 while (1) {
Chris Lattnerf9aace22005-01-31 00:10:58 +00001652 std::list<DSCallSite>::iterator OldIt = CI++;
1653 if (CI == CE) break;
Chris Lattnera9548d92005-01-30 23:51:02 +00001654
1655 // If this call site is now the same as the previous one, we can delete it
1656 // as a duplicate.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001657 if (*OldIt == *CI) {
1658 Calls.erase(CI);
1659 CI = OldIt;
Chris Lattnera9548d92005-01-30 23:51:02 +00001660 ++NumDeleted;
1661 }
1662 }
1663
1664 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001665
Chris Lattner33312f72002-11-08 01:21:07 +00001666 // Track the number of call nodes merged away...
Chris Lattnera9548d92005-01-30 23:51:02 +00001667 NumCallNodesMerged += NumDeleted;
Chris Lattner33312f72002-11-08 01:21:07 +00001668
Chris Lattnera9548d92005-01-30 23:51:02 +00001669 DEBUG(if (NumDeleted)
1670 std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001671}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001672
Chris Lattneraa8146f2002-11-10 06:59:55 +00001673
Chris Lattnere2219762002-07-18 18:22:40 +00001674// removeTriviallyDeadNodes - After the graph has been constructed, this method
1675// removes all unreachable nodes that are created because they got merged with
1676// other nodes in the graph. These nodes will all be trivially unreachable, so
1677// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001678//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001679void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001680 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001681
Chris Lattner5ace1e42004-07-08 07:25:51 +00001682#if 0
1683 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1684 /// substantially!
1685
Chris Lattnerbab8c282003-09-20 21:34:07 +00001686 // Loop over all of the nodes in the graph, calling getNode on each field.
1687 // This will cause all nodes to update their forwarding edges, causing
1688 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001689 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001690 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
Chris Lattner84b80a22005-03-16 22:42:19 +00001691 DSNode &N = *NI;
1692 for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1693 N.getLink(l*N.getPointerSize()).getNode();
Chris Lattnerbab8c282003-09-20 21:34:07 +00001694 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001695 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001696
Chris Lattner0b144872004-01-27 22:03:40 +00001697 // NOTE: This code is disabled. Though it should, in theory, allow us to
1698 // remove more nodes down below, the scan of the scalar map is incredibly
1699 // expensive for certain programs (with large SCCs). In the future, if we can
1700 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001701 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1702
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001703 // Likewise, forward any edges from the scalar nodes. While we are at it,
1704 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001705 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001706 I->second.getNode();
1707 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001708 }
Chris Lattner0b144872004-01-27 22:03:40 +00001709 }
1710#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001711 bool isGlobalsGraph = !GlobalsGraph;
1712
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001713 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001714 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001715
1716 // Do not remove *any* global nodes in the globals graph.
1717 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001718 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001719 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001720 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001721 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001722
Chris Lattner28897e12004-02-08 00:53:26 +00001723 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001724 // This is a useless node if it has no mod/ref info (checked above),
1725 // outgoing edges (which it cannot, as it is not modified in this
1726 // context), and it has no incoming edges. If it is a global node it may
1727 // have all of these properties and still have incoming edges, due to the
1728 // scalar map, so we check those now.
1729 //
Chris Lattner28897e12004-02-08 00:53:26 +00001730 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1731 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001732
Chris Lattner17a93e22004-01-29 03:32:15 +00001733 // Loop through and make sure all of the globals are referring directly
1734 // to the node...
1735 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1736 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001737 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001738 }
1739
Chris Lattnerbd92b732003-06-19 21:15:11 +00001740 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001741 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001742 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1743 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001744 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001745 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001746 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001747 }
1748 }
1749
Chris Lattner28897e12004-02-08 00:53:26 +00001750 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001751 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001752 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001753 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001754 } else {
1755 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001756 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001757 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001758
1759 removeIdenticalCalls(FunctionCalls);
1760 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001761}
1762
1763
Chris Lattner5c7380e2003-01-29 21:10:20 +00001764/// markReachableNodes - This method recursively traverses the specified
1765/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1766/// to the set, which allows it to only traverse visited nodes once.
1767///
Chris Lattnera9548d92005-01-30 23:51:02 +00001768void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001769 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001770 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001771 if (ReachableNodes.insert(this).second) // Is newly reachable?
Chris Lattner6be07942005-02-09 03:20:43 +00001772 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
1773 I != E; ++I)
1774 I->getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001775}
1776
Chris Lattnera9548d92005-01-30 23:51:02 +00001777void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001778 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001779 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001780
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001781 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1782 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001783}
1784
Chris Lattnera1220af2003-02-01 06:17:02 +00001785// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1786// looking for a node that is marked alive. If an alive node is found, return
1787// true, otherwise return false. If an alive node is reachable, this node is
1788// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001789//
Chris Lattnera9548d92005-01-30 23:51:02 +00001790static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
1791 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00001792 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001793 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001794 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001795
Chris Lattner85cfe012003-07-03 02:03:53 +00001796 // If this is a global node, it will end up in the globals graph anyway, so we
1797 // don't need to worry about it.
1798 if (IgnoreGlobals && N->isGlobalNode()) return false;
1799
Chris Lattneraa8146f2002-11-10 06:59:55 +00001800 // If we know that this node is alive, return so!
1801 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001802
Chris Lattneraa8146f2002-11-10 06:59:55 +00001803 // Otherwise, we don't think the node is alive yet, check for infinite
1804 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001805 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001806 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001807
Chris Lattner6be07942005-02-09 03:20:43 +00001808 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1809 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001810 N->markReachableNodes(Alive);
1811 return true;
1812 }
1813 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001814}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001815
Chris Lattnera1220af2003-02-01 06:17:02 +00001816// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1817// alive nodes.
1818//
Chris Lattnera9548d92005-01-30 23:51:02 +00001819static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
1820 hash_set<const DSNode*> &Alive,
1821 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00001822 bool IgnoreGlobals) {
1823 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1824 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001825 return true;
1826 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001827 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001828 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001829 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001830 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1831 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001832 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001833 return false;
1834}
1835
Chris Lattnere2219762002-07-18 18:22:40 +00001836// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1837// subgraphs that are unreachable. This often occurs because the data
1838// structure doesn't "escape" into it's caller, and thus should be eliminated
1839// from the caller's graph entirely. This is only appropriate to use when
1840// inlining graphs.
1841//
Chris Lattner394471f2003-01-23 22:05:33 +00001842void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001843 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001844
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001845 // Reduce the amount of work we have to do... remove dummy nodes left over by
1846 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001847 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001848
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001849 TIME_REGION(X, "removeDeadNodes");
1850
Misha Brukman2f2d0652003-09-11 18:14:24 +00001851 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001852
1853 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattnera9548d92005-01-30 23:51:02 +00001854 hash_set<const DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001855 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001856
Chris Lattner0b144872004-01-27 22:03:40 +00001857 // Copy and merge all information about globals to the GlobalsGraph if this is
1858 // not a final pass (where unreachable globals are removed).
1859 //
1860 // Strip all alloca bits since the current function is only for the BU pass.
1861 // Strip all incomplete bits since they are short-lived properties and they
1862 // will be correctly computed when rematerializing nodes into the functions.
1863 //
1864 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1865 DSGraph::StripIncompleteBit);
1866
Chris Lattneraa8146f2002-11-10 06:59:55 +00001867 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner00948c02004-01-28 02:05:05 +00001868 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
Chris Lattner62482e52004-01-28 09:15:42 +00001869 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001870 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00001871 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001872 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001873 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001874
1875 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001876 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1877 DSGraph::ScalarMapTy::iterator SMI =
1878 GlobalsGraph->getScalarMap().find(I->first);
1879 if (SMI != GlobalsGraph->getScalarMap().end())
1880 GGCloner.merge(SMI->second, I->second);
1881 else
1882 GGCloner.getClonedNH(I->second);
1883 }
Chris Lattner0b144872004-01-27 22:03:40 +00001884 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001885 } else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001886 DSNode *N = I->second.getNode();
1887#if 0
Chris Lattner0b144872004-01-27 22:03:40 +00001888 // Check to see if this is a worthless node generated for non-pointer
1889 // values, such as integers. Consider an addition of long types: A+B.
1890 // Assuming we can track all uses of the value in this context, and it is
1891 // NOT used as a pointer, we can delete the node. We will be able to
1892 // detect this situation if the node pointed to ONLY has Unknown bit set
1893 // in the node. In this case, the node is not incomplete, does not point
1894 // to any other nodes (no mod/ref bits set), and is therefore
1895 // uninteresting for data structure analysis. If we run across one of
1896 // these, prune the scalar pointing to it.
1897 //
Chris Lattner0b144872004-01-27 22:03:40 +00001898 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1899 ScalarMap.erase(I++);
1900 else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001901#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001902 N->markReachableNodes(Alive);
1903 ++I;
Chris Lattnera88a55c2004-01-28 02:41:32 +00001904 //}
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001905 }
Chris Lattner00948c02004-01-28 02:05:05 +00001906 }
Chris Lattnere2219762002-07-18 18:22:40 +00001907
Chris Lattner0b144872004-01-27 22:03:40 +00001908 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001909 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1910 I != E; ++I)
1911 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001912
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001913 // Mark any nodes reachable by primary calls as alive...
Chris Lattnera9548d92005-01-30 23:51:02 +00001914 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
1915 I->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001916
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001917
1918 // Now find globals and aux call nodes that are already live or reach a live
1919 // value (which makes them live in turn), and continue till no more are found.
1920 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001921 bool Iterate;
Chris Lattnera9548d92005-01-30 23:51:02 +00001922 hash_set<const DSNode*> Visited;
1923 hash_set<const DSCallSite*> AuxFCallsAlive;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001924 do {
1925 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001926 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001927 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001928 // unreachable globals in the list.
1929 //
1930 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001931 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001932 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1933 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1934 Flags & DSGraph::RemoveUnreachableGlobals)) {
1935 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1936 GlobalNodes.pop_back(); // erase efficiently
1937 Iterate = true;
1938 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001939
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001940 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1941 // call nodes that get resolved will be difficult to remove from that graph.
1942 // The final unresolved call nodes must be handled specially at the end of
1943 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattnera9548d92005-01-30 23:51:02 +00001944 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
Chris Lattnerd7642c42005-02-24 18:48:07 +00001945 if (!AuxFCallsAlive.count(&*CI) &&
Chris Lattnera9548d92005-01-30 23:51:02 +00001946 (CI->isIndirectCall()
1947 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001948 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001949 CI->markReachableNodes(Alive);
Chris Lattnerd7642c42005-02-24 18:48:07 +00001950 AuxFCallsAlive.insert(&*CI);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001951 Iterate = true;
1952 }
1953 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001954
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001955 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001956 unsigned CurIdx = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00001957 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
1958 E = AuxFunctionCalls.end(); CI != E; )
1959 if (AuxFCallsAlive.count(&*CI))
1960 ++CI;
1961 else {
1962 // Copy and merge global nodes and dead aux call nodes into the
1963 // GlobalsGraph, and all nodes reachable from those nodes. Update their
1964 // target pointers using the GGCloner.
1965 //
1966 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1967 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001968
Chris Lattnera9548d92005-01-30 23:51:02 +00001969 AuxFunctionCalls.erase(CI++);
1970 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001971
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001972 // We are finally done with the GGCloner so we can destroy it.
1973 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001974
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001975 // At this point, any nodes which are visited, but not alive, are nodes
1976 // which can be removed. Loop over all nodes, eliminating completely
1977 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001978 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001979 std::vector<DSNode*> DeadNodes;
1980 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00001981 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
1982 DSNode *N = NI++;
1983 assert(!N->isForwarding() && "Forwarded node in nodes list?");
1984
1985 if (!Alive.count(N)) {
1986 Nodes.remove(N);
1987 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001988 DeadNodes.push_back(N);
1989 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00001990 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00001991 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00001992 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001993
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001994 // Remove all unreachable globals from the ScalarMap.
1995 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1996 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001997 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001998 if (!Alive.count(GlobalNodes[i].second))
1999 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00002000 else
2001 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002002
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002003 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00002004 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2005 delete DeadNodes[i];
2006
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002007 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00002008}
2009
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002010void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
2011 assert(std::find(N->getGlobals().begin(), N->getGlobals().end(), GV) !=
2012 N->getGlobals().end() && "Global value not in node!");
2013}
2014
Chris Lattner2c7725a2004-03-03 20:55:27 +00002015void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2016 if (CS.isIndirectCall()) {
2017 AssertNodeInGraph(CS.getCalleeNode());
2018#if 0
2019 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2020 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
Chris Lattnerf8db8a02005-02-27 06:15:51 +00002021 std::cerr << "WARNING: WEIRD CALL SITE FOUND!\n";
Chris Lattner2c7725a2004-03-03 20:55:27 +00002022#endif
2023 }
2024 AssertNodeInGraph(CS.getRetVal().getNode());
2025 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2026 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2027}
2028
2029void DSGraph::AssertCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002030 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2031 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002032}
2033void DSGraph::AssertAuxCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002034 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2035 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002036}
2037
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002038void DSGraph::AssertGraphOK() const {
Chris Lattner84b80a22005-03-16 22:42:19 +00002039 for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2040 NI->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00002041
Chris Lattner8d327672003-06-30 03:36:09 +00002042 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002043 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00002044 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002045 AssertNodeInGraph(I->second.getNode());
2046 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00002047 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002048 "Global points to node, but node isn't global?");
2049 AssertNodeContainsGlobal(I->second.getNode(), GV);
2050 }
2051 }
2052 AssertCallNodesInGraph();
2053 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00002054
2055 // Check that all pointer arguments to any functions in this graph have
2056 // destinations.
2057 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2058 E = ReturnNodes.end();
2059 RI != E; ++RI) {
2060 Function &F = *RI->first;
Chris Lattnere4d5c442005-03-15 04:54:21 +00002061 for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
Chris Lattner7d8d4712004-10-31 17:45:40 +00002062 if (isPointerType(AI->getType()))
2063 assert(!getNodeForValue(AI).isNull() &&
2064 "Pointer argument must be in the scalar map!");
2065 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002066}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002067
Chris Lattner400433d2003-11-11 05:08:59 +00002068/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00002069/// nodes reachable from the two graphs, computing the mapping of nodes from the
2070/// first to the second graph. This mapping may be many-to-one (i.e. the first
2071/// graph may have multiple nodes representing one node in the second graph),
2072/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00002073///
2074void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00002075 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2076 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00002077 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2078 if (N1 == 0 || N2 == 0) return;
2079
2080 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002081 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002082 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002083 if (StrictChecking) {
2084 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2085 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2086 Entry.getNode()->isNodeCompletelyFolded()) &&
2087 "Inconsistent mapping detected!");
2088 }
Chris Lattner400433d2003-11-11 05:08:59 +00002089 return;
2090 }
2091
Chris Lattnerefffdc92004-07-07 06:12:52 +00002092 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002093
2094 // Loop over all of the fields that N1 and N2 have in common, recursively
2095 // mapping the edges together now.
2096 int N2Idx = NH2.getOffset()-NH1.getOffset();
2097 unsigned N2Size = N2->getSize();
Chris Lattner841957e2005-03-15 04:40:24 +00002098 if (N2Size == 0) return; // No edges to map to.
2099
Chris Lattner4d5af8e2005-03-15 21:36:50 +00002100 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2101 const DSNodeHandle &N1NH = N1->getLink(i);
2102 // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2103 // aligned right).
2104 if (!N1NH.isNull()) {
2105 if (unsigned(N2Idx)+i < N2Size)
2106 computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2107 else
2108 computeNodeMapping(N1NH,
2109 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2110 }
2111 }
Chris Lattner400433d2003-11-11 05:08:59 +00002112}
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002113
2114
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002115/// computeGToGGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002116/// nodes in this graph.
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002117void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002118 DSGraph &GG = *getGlobalsGraph();
2119
2120 DSScalarMap &SM = getScalarMap();
2121 for (DSScalarMap::global_iterator I = SM.global_begin(),
2122 E = SM.global_end(); I != E; ++I)
2123 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2124}
2125
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002126/// computeGGToGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002127/// nodes in this graph. Note that any uses of this method are probably bugs,
2128/// unless it is known that the globals graph has been merged into this graph!
2129void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2130 NodeMapTy NodeMap;
2131 computeGToGGMapping(NodeMap);
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002132
Chris Lattner36a13cd2005-03-15 17:52:18 +00002133 while (!NodeMap.empty()) {
2134 InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2135 NodeMap.begin()->first));
2136 NodeMap.erase(NodeMap.begin());
2137 }
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002138}
2139
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002140
2141/// computeCalleeCallerMapping - Given a call from a function in the current
2142/// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2143/// mapping of nodes from the callee to nodes in the caller.
2144void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2145 DSGraph &CalleeGraph,
2146 NodeMapTy &NodeMap) {
2147
2148 DSCallSite CalleeArgs =
2149 CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
2150
2151 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2152
2153 unsigned NumArgs = CS.getNumPtrArgs();
2154 if (NumArgs > CalleeArgs.getNumPtrArgs())
2155 NumArgs = CalleeArgs.getNumPtrArgs();
2156
2157 for (unsigned i = 0; i != NumArgs; ++i)
2158 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
2159
2160 // Map the nodes that are pointed to by globals.
2161 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2162 DSScalarMap &CallerSM = getScalarMap();
2163
2164 if (CalleeSM.global_size() >= CallerSM.global_size()) {
2165 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
2166 E = CallerSM.global_end(); GI != E; ++GI)
2167 if (CalleeSM.global_count(*GI))
2168 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2169 } else {
2170 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
2171 E = CalleeSM.global_end(); GI != E; ++GI)
2172 if (CallerSM.global_count(*GI))
2173 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2174 }
2175}