blob: c04a420faa5be9e97d5706cd292fc3eeacd7ace2 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00009//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerfccd06f2002-10-01 22:33:50 +000014#include "llvm/Analysis/DSGraph.h"
15#include "llvm/Function.h"
Chris Lattnercf14e712004-02-25 23:36:08 +000016#include "llvm/GlobalVariable.h"
Vikram S. Adve26b98262002-10-20 21:41:02 +000017#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000018#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000019#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000020#include "llvm/Assembly/Writer.h"
Chris Lattner0b144872004-01-27 22:03:40 +000021#include "Support/CommandLine.h"
Chris Lattner6806f562003-08-01 22:15:03 +000022#include "Support/Debug.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000023#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000024#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000025#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000026#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000027using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000028
Chris Lattner08db7192002-11-06 06:20:27 +000029namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000030 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
31 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
32 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
33 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000034 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
35 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Chris Lattner0b144872004-01-27 22:03:40 +000036
37 cl::opt<bool>
38 EnableDSNodeGlobalRootsHack("enable-dsa-globalrootshack", cl::Hidden,
39 cl::desc("Make DSA less aggressive when cloning graphs"));
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 Lattner731b2d72003-02-13 19:09:00 +000051DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000052 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000053
54 // Handle node forwarding here!
55 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
56 Offset += N->ForwardNH.getOffset();
57
58 if (--N->NumReferrers == 0) {
59 // Removing the last referrer to the node, sever the forwarding link
60 N->stopForwarding();
61 }
62
63 N = Next;
64 N->NumReferrers++;
65 if (N->Size <= Offset) {
66 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
67 Offset = 0;
68 }
69 return N;
70}
71
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000072//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000073// DSNode Implementation
74//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000075
Chris Lattnerbd92b732003-06-19 21:15:11 +000076DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000077 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000078 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000079 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +000080 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000081 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000082}
83
Chris Lattner0d9bab82002-07-18 00:12:30 +000084// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +000085DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +000086 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner0b144872004-01-27 22:03:40 +000087 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
88 if (!NullLinks)
89 Links = N.Links;
90 else
91 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +000092 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000093 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +000094}
95
Chris Lattner15869aa2003-11-02 22:27:28 +000096/// getTargetData - Get the target data object used to construct this node.
97///
98const TargetData &DSNode::getTargetData() const {
99 return ParentGraph->getTargetData();
100}
101
Chris Lattner72d29a42003-02-11 23:11:51 +0000102void DSNode::assertOK() const {
103 assert((Ty != Type::VoidTy ||
104 Ty == Type::VoidTy && (Size == 0 ||
105 (NodeType & DSNode::Array))) &&
106 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000107
108 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000109 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000110 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnera88a55c2004-01-28 02:41:32 +0000111 assert(SM.count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000112 assert(SM.find(Globals[i])->second.getNode() == this);
113 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000114}
115
116/// forwardNode - Mark this node as being obsolete, and all references to it
117/// should be forwarded to the specified node and offset.
118///
119void DSNode::forwardNode(DSNode *To, unsigned Offset) {
120 assert(this != To && "Cannot forward a node to itself!");
121 assert(ForwardNH.isNull() && "Already forwarding from this node!");
122 if (To->Size <= 1) Offset = 0;
123 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
124 "Forwarded offset is wrong!");
125 ForwardNH.setNode(To);
126 ForwardNH.setOffset(Offset);
127 NodeType = DEAD;
128 Size = 0;
129 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000130
131 // Remove this node from the parent graph's Nodes list.
132 ParentGraph->unlinkNode(this);
133 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000134}
135
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000136// addGlobal - Add an entry for a global value to the Globals list. This also
137// marks the node with the 'G' flag if it does not already have it.
138//
139void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000140 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000141 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000142 std::lower_bound(Globals.begin(), Globals.end(), GV);
143
144 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000145 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000146 Globals.insert(I, GV);
147 NodeType |= GlobalNode;
148 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000149}
150
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000151/// foldNodeCompletely - If we determine that this node has some funny
152/// behavior happening to it that we cannot represent, we fold it down to a
153/// single, completely pessimistic, node. This node is represented as a
154/// single byte with a single TypeEntry of "void".
155///
156void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000157 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000158
Chris Lattner08db7192002-11-06 06:20:27 +0000159 ++NumFolds;
160
Chris Lattner0b144872004-01-27 22:03:40 +0000161 // If this node has a size that is <= 1, we don't need to create a forwarding
162 // node.
163 if (getSize() <= 1) {
164 NodeType |= DSNode::Array;
165 Ty = Type::VoidTy;
166 Size = 1;
167 assert(Links.size() <= 1 && "Size is 1, but has more links?");
168 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000169 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000170 // Create the node we are going to forward to. This is required because
171 // some referrers may have an offset that is > 0. By forcing them to
172 // forward, the forwarder has the opportunity to correct the offset.
173 DSNode *DestNode = new DSNode(0, ParentGraph);
174 DestNode->NodeType = NodeType|DSNode::Array;
175 DestNode->Ty = Type::VoidTy;
176 DestNode->Size = 1;
177 DestNode->Globals.swap(Globals);
178
179 // Start forwarding to the destination node...
180 forwardNode(DestNode, 0);
181
182 if (!Links.empty()) {
183 DestNode->Links.reserve(1);
184
185 DSNodeHandle NH(DestNode);
186 DestNode->Links.push_back(Links[0]);
187
188 // If we have links, merge all of our outgoing links together...
189 for (unsigned i = Links.size()-1; i != 0; --i)
190 NH.getNode()->Links[0].mergeWith(Links[i]);
191 Links.clear();
192 } else {
193 DestNode->Links.resize(1);
194 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000195 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000196}
Chris Lattner076c1f92002-11-07 06:31:54 +0000197
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000198/// isNodeCompletelyFolded - Return true if this node has been completely
199/// folded down to something that can never be expanded, effectively losing
200/// all of the field sensitivity that may be present in the node.
201///
202bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000203 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000204}
205
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000206namespace {
207 /// TypeElementWalker Class - Used for implementation of physical subtyping...
208 ///
209 class TypeElementWalker {
210 struct StackState {
211 const Type *Ty;
212 unsigned Offset;
213 unsigned Idx;
214 StackState(const Type *T, unsigned Off = 0)
215 : Ty(T), Offset(Off), Idx(0) {}
216 };
217
218 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000219 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000220 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000221 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000222 Stack.push_back(T);
223 StepToLeaf();
224 }
225
226 bool isDone() const { return Stack.empty(); }
227 const Type *getCurrentType() const { return Stack.back().Ty; }
228 unsigned getCurrentOffset() const { return Stack.back().Offset; }
229
230 void StepToNextType() {
231 PopStackAndAdvance();
232 StepToLeaf();
233 }
234
235 private:
236 /// PopStackAndAdvance - Pop the current element off of the stack and
237 /// advance the underlying element to the next contained member.
238 void PopStackAndAdvance() {
239 assert(!Stack.empty() && "Cannot pop an empty stack!");
240 Stack.pop_back();
241 while (!Stack.empty()) {
242 StackState &SS = Stack.back();
243 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
244 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000245 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000246 const StructLayout *SL = TD.getStructLayout(ST);
247 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
248 return;
249 }
250 Stack.pop_back(); // At the end of the structure
251 } else {
252 const ArrayType *AT = cast<ArrayType>(SS.Ty);
253 ++SS.Idx;
254 if (SS.Idx != AT->getNumElements()) {
255 SS.Offset += TD.getTypeSize(AT->getElementType());
256 return;
257 }
258 Stack.pop_back(); // At the end of the array
259 }
260 }
261 }
262
263 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
264 /// on the type stack.
265 void StepToLeaf() {
266 if (Stack.empty()) return;
267 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
268 StackState &SS = Stack.back();
269 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000270 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000271 assert(SS.Idx == 0);
272 PopStackAndAdvance();
273 } else {
274 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000275 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000276 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000277 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000278 SS.Offset+SL->MemberOffsets[SS.Idx]));
279 }
280 } else {
281 const ArrayType *AT = cast<ArrayType>(SS.Ty);
282 if (AT->getNumElements() == 0) {
283 assert(SS.Idx == 0);
284 PopStackAndAdvance();
285 } else {
286 // Step into the array...
287 assert(SS.Idx < AT->getNumElements());
288 Stack.push_back(StackState(AT->getElementType(),
289 SS.Offset+SS.Idx*
290 TD.getTypeSize(AT->getElementType())));
291 }
292 }
293 }
294 }
295 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000296} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000297
298/// ElementTypesAreCompatible - Check to see if the specified types are
299/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000300/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
301/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000302///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000303static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000304 bool AllowLargerT1, const TargetData &TD){
305 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000306
307 while (!T1W.isDone() && !T2W.isDone()) {
308 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
309 return false;
310
311 const Type *T1 = T1W.getCurrentType();
312 const Type *T2 = T2W.getCurrentType();
313 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
314 return false;
315
316 T1W.StepToNextType();
317 T2W.StepToNextType();
318 }
319
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000320 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000321}
322
323
Chris Lattner08db7192002-11-06 06:20:27 +0000324/// mergeTypeInfo - This method merges the specified type into the current node
325/// at the specified offset. This may update the current node's type record if
326/// this gives more information to the node, it may do nothing to the node if
327/// this information is already known, or it may merge the node completely (and
328/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000329///
Chris Lattner08db7192002-11-06 06:20:27 +0000330/// This method returns true if the node is completely folded, otherwise false.
331///
Chris Lattner088b6392003-03-03 17:13:31 +0000332bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
333 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000334 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000335 // Check to make sure the Size member is up-to-date. Size can be one of the
336 // following:
337 // Size = 0, Ty = Void: Nothing is known about this node.
338 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
339 // Size = 1, Ty = Void, Array = 1: The node is collapsed
340 // Otherwise, sizeof(Ty) = Size
341 //
Chris Lattner18552922002-11-18 21:44:46 +0000342 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
343 (Size == 0 && !Ty->isSized() && !isArray()) ||
344 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
345 (Size == 0 && !Ty->isSized() && !isArray()) ||
346 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000347 "Size member of DSNode doesn't match the type structure!");
348 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000349
Chris Lattner18552922002-11-18 21:44:46 +0000350 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000351 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000352
Chris Lattner08db7192002-11-06 06:20:27 +0000353 // Return true immediately if the node is completely folded.
354 if (isNodeCompletelyFolded()) return true;
355
Chris Lattner23f83dc2002-11-08 22:49:57 +0000356 // If this is an array type, eliminate the outside arrays because they won't
357 // be used anyway. This greatly reduces the size of large static arrays used
358 // as global variables, for example.
359 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000360 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000361 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
362 // FIXME: we might want to keep small arrays, but must be careful about
363 // things like: [2 x [10000 x int*]]
364 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000365 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000366 }
367
Chris Lattner08db7192002-11-06 06:20:27 +0000368 // Figure out how big the new type we're merging in is...
369 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
370
371 // Otherwise check to see if we can fold this type into the current node. If
372 // we can't, we fold the node completely, if we can, we potentially update our
373 // internal state.
374 //
Chris Lattner18552922002-11-18 21:44:46 +0000375 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000376 // If this is the first type that this node has seen, just accept it without
377 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000378 assert(Offset == 0 && !isArray() &&
379 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000380 Ty = NewTy;
381 NodeType &= ~Array;
382 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000383 Size = NewTySize;
384
385 // Calculate the number of outgoing links from this node.
386 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
387 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000388 }
Chris Lattner08db7192002-11-06 06:20:27 +0000389
390 // Handle node expansion case here...
391 if (Offset+NewTySize > Size) {
392 // It is illegal to grow this node if we have treated it as an array of
393 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000394 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000395 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000396 return true;
397 }
398
399 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000400 std::cerr << "UNIMP: Trying to merge a growth type into "
401 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000402 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000403 return true;
404 }
405
406 // Okay, the situation is nice and simple, we are trying to merge a type in
407 // at offset 0 that is bigger than our current type. Implement this by
408 // switching to the new type and then merge in the smaller one, which should
409 // hit the other code path here. If the other code path decides it's not
410 // ok, it will collapse the node as appropriate.
411 //
Chris Lattner18552922002-11-18 21:44:46 +0000412 const Type *OldTy = Ty;
413 Ty = NewTy;
414 NodeType &= ~Array;
415 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000416 Size = NewTySize;
417
418 // Must grow links to be the appropriate size...
419 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
420
421 // Merge in the old type now... which is guaranteed to be smaller than the
422 // "current" type.
423 return mergeTypeInfo(OldTy, 0);
424 }
425
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000426 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000427 "Cannot merge something into a part of our type that doesn't exist!");
428
Chris Lattner18552922002-11-18 21:44:46 +0000429 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000430 // type that starts at offset Offset.
431 //
432 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000433 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000434 while (O < Offset) {
435 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
436
437 switch (SubType->getPrimitiveID()) {
438 case Type::StructTyID: {
439 const StructType *STy = cast<StructType>(SubType);
440 const StructLayout &SL = *TD.getStructLayout(STy);
441
442 unsigned i = 0, e = SL.MemberOffsets.size();
443 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
444 /* empty */;
445
446 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000447 SubType = STy->getElementType(i);
Chris Lattner08db7192002-11-06 06:20:27 +0000448 O += SL.MemberOffsets[i];
449 break;
450 }
451 case Type::ArrayTyID: {
452 SubType = cast<ArrayType>(SubType)->getElementType();
453 unsigned ElSize = TD.getTypeSize(SubType);
454 unsigned Remainder = (Offset-O) % ElSize;
455 O = Offset-Remainder;
456 break;
457 }
458 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000459 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000460 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000461 }
462 }
463
464 assert(O == Offset && "Could not achieve the correct offset!");
465
466 // If we found our type exactly, early exit
467 if (SubType == NewTy) return false;
468
Chris Lattner0b144872004-01-27 22:03:40 +0000469 // Differing function types don't require us to merge. They are not values anyway.
470 if (isa<FunctionType>(SubType) &&
471 isa<FunctionType>(NewTy)) return false;
472
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000473 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
474
475 // Ok, we are getting desperate now. Check for physical subtyping, where we
476 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000477 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000478 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000479 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000480 return false;
481
Chris Lattner08db7192002-11-06 06:20:27 +0000482 // Okay, so we found the leader type at the offset requested. Search the list
483 // of types that starts at this offset. If SubType is currently an array or
484 // structure, the type desired may actually be the first element of the
485 // composite type...
486 //
Chris Lattner18552922002-11-18 21:44:46 +0000487 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000488 while (SubType != NewTy) {
489 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000490 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000491 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000492 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000493 case Type::StructTyID: {
494 const StructType *STy = cast<StructType>(SubType);
495 const StructLayout &SL = *TD.getStructLayout(STy);
496 if (SL.MemberOffsets.size() > 1)
497 NextPadSize = SL.MemberOffsets[1];
498 else
499 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000500 NextSubType = STy->getElementType(0);
Chris Lattner18552922002-11-18 21:44:46 +0000501 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000502 break;
Chris Lattner18552922002-11-18 21:44:46 +0000503 }
Chris Lattner08db7192002-11-06 06:20:27 +0000504 case Type::ArrayTyID:
505 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000506 NextSubTypeSize = TD.getTypeSize(NextSubType);
507 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000508 break;
509 default: ;
510 // fall out
511 }
512
513 if (NextSubType == 0)
514 break; // In the default case, break out of the loop
515
Chris Lattner18552922002-11-18 21:44:46 +0000516 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000517 break; // Don't allow shrinking to a smaller type than NewTySize
518 SubType = NextSubType;
519 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000520 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000521 }
522
523 // If we found the type exactly, return it...
524 if (SubType == NewTy)
525 return false;
526
527 // Check to see if we have a compatible, but different type...
528 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000529 // Check to see if this type is obviously convertible... int -> uint f.e.
530 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000531 return false;
532
533 // Check to see if we have a pointer & integer mismatch going on here,
534 // loading a pointer as a long, for example.
535 //
536 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
537 NewTy->isInteger() && isa<PointerType>(SubType))
538 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000539 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
540 // We are accessing the field, plus some structure padding. Ignore the
541 // structure padding.
542 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000543 }
544
Chris Lattner58f98d02003-07-02 04:38:49 +0000545 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000546 if (getParentGraph()->getReturnNodes().size())
547 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000548 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
549 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
550 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
551 << "SubType: ";
552 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000553
Chris Lattner088b6392003-03-03 17:13:31 +0000554 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000555 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000556}
557
Chris Lattner08db7192002-11-06 06:20:27 +0000558
559
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000560// addEdgeTo - Add an edge from the current node to the specified node. This
561// can cause merging of nodes in the graph.
562//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000563void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000564 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000565
Chris Lattner08db7192002-11-06 06:20:27 +0000566 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000567 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000568 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000569 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000570 } else { // No merging to perform...
571 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000572 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000573}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000574
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000575
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000576// MergeSortedVectors - Efficiently merge a vector into another vector where
577// duplicates are not allowed and both are sorted. This assumes that 'T's are
578// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000579//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000580static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
581 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000582 // By far, the most common cases will be the simple ones. In these cases,
583 // avoid having to allocate a temporary vector...
584 //
585 if (Src.empty()) { // Nothing to merge in...
586 return;
587 } else if (Dest.empty()) { // Just copy the result in...
588 Dest = Src;
589 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000590 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000591 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000592 std::lower_bound(Dest.begin(), Dest.end(), V);
593 if (I == Dest.end() || *I != Src[0]) // If not already contained...
594 Dest.insert(I, Src[0]);
595 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000596 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000597 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000598 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000599 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
600 if (I == Dest.end() || *I != Tmp) // If not already contained...
601 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000602
603 } else {
604 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000605 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000606
607 // Make space for all of the type entries now...
608 Dest.resize(Dest.size()+Src.size());
609
610 // Merge the two sorted ranges together... into Dest.
611 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
612
613 // Now erase any duplicate entries that may have accumulated into the
614 // vectors (because they were in both of the input sets)
615 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
616 }
617}
618
Chris Lattner0b144872004-01-27 22:03:40 +0000619void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
620 MergeSortedVectors(Globals, RHS);
621}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000622
Chris Lattner0b144872004-01-27 22:03:40 +0000623// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000624// This function does the hard work of merging two nodes, CurNodeH
625// and NH after filtering out trivial cases and making sure that
626// CurNodeH.offset >= NH.offset.
627//
628// ***WARNING***
629// Since merging may cause either node to go away, we must always
630// use the node-handles to refer to the nodes. These node handles are
631// automatically updated during merging, so will always provide access
632// to the correct node after a merge.
633//
634void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
635 assert(CurNodeH.getOffset() >= NH.getOffset() &&
636 "This should have been enforced in the caller.");
637
638 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
639 // respect to NH.Offset) is now zero. NOffset is the distance from the base
640 // of our object that N starts from.
641 //
642 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
643 unsigned NSize = NH.getNode()->getSize();
644
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000645 // If the two nodes are of different size, and the smaller node has the array
646 // bit set, collapse!
647 if (NSize != CurNodeH.getNode()->getSize()) {
648 if (NSize < CurNodeH.getNode()->getSize()) {
649 if (NH.getNode()->isArray())
650 NH.getNode()->foldNodeCompletely();
651 } else if (CurNodeH.getNode()->isArray()) {
652 NH.getNode()->foldNodeCompletely();
653 }
654 }
655
656 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000657 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000658 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000659 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000660
661 // If we are merging a node with a completely folded node, then both nodes are
662 // now completely folded.
663 //
664 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
665 if (!NH.getNode()->isNodeCompletelyFolded()) {
666 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000667 assert(NH.getNode() && NH.getOffset() == 0 &&
668 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000669 NOffset = NH.getOffset();
670 NSize = NH.getNode()->getSize();
671 assert(NOffset == 0 && NSize == 1);
672 }
673 } else if (NH.getNode()->isNodeCompletelyFolded()) {
674 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000675 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
676 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000677 NOffset = NH.getOffset();
678 NSize = NH.getNode()->getSize();
679 assert(NOffset == 0 && NSize == 1);
680 }
681
Chris Lattner72d29a42003-02-11 23:11:51 +0000682 DSNode *N = NH.getNode();
683 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000684 assert(!CurNodeH.getNode()->isDeadNode());
685
Chris Lattner0b144872004-01-27 22:03:40 +0000686 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000687 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000688
Chris Lattner72d29a42003-02-11 23:11:51 +0000689 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000690 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000691 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000692
Chris Lattner72d29a42003-02-11 23:11:51 +0000693 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
694 //
695 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
696 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000697 if (Link.getNode()) {
698 // Compute the offset into the current node at which to
699 // merge this link. In the common case, this is a linear
700 // relation to the offset in the original node (with
701 // wrapping), but if the current node gets collapsed due to
702 // recursive merging, we must make sure to merge in all remaining
703 // links at offset zero.
704 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000705 DSNode *CN = CurNodeH.getNode();
706 if (CN->Size != 1)
707 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
708 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000709 }
710 }
711
712 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000713 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000714
715 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000716 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000717 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000718
719 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000720 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000721 }
722}
723
724
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000725// mergeWith - Merge this node and the specified node, moving all links to and
726// from the argument node into the current node, deleting the node argument.
727// Offset indicates what offset the specified node is to be merged into the
728// current node.
729//
Chris Lattner5254a8d2004-01-22 16:31:08 +0000730// The specified node may be a null pointer (in which case, we update it to
731// point to this node).
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000732//
733void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
734 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000735 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000736 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000737
Chris Lattner5254a8d2004-01-22 16:31:08 +0000738 // If the RHS is a null node, make it point to this node!
739 if (N == 0) {
740 NH.mergeWith(DSNodeHandle(this, Offset));
741 return;
742 }
743
Chris Lattnerbd92b732003-06-19 21:15:11 +0000744 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000745 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
746
Chris Lattner02606632002-11-04 06:48:26 +0000747 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000748 // We cannot merge two pieces of the same node together, collapse the node
749 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000750 DEBUG(std::cerr << "Attempting to merge two chunks of"
751 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000752 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000753 return;
754 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000755
Chris Lattner5190ce82002-11-12 07:20:45 +0000756 // If both nodes are not at offset 0, make sure that we are merging the node
757 // at an later offset into the node with the zero offset.
758 //
759 if (Offset < NH.getOffset()) {
760 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
761 return;
762 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
763 // If the offsets are the same, merge the smaller node into the bigger node
764 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
765 return;
766 }
767
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000768 // Ok, now we can merge the two nodes. Use a static helper that works with
769 // two node handles, since "this" may get merged away at intermediate steps.
770 DSNodeHandle CurNodeH(this, Offset);
771 DSNodeHandle NHCopy(NH);
772 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000773}
774
Chris Lattner0b144872004-01-27 22:03:40 +0000775
776//===----------------------------------------------------------------------===//
777// ReachabilityCloner Implementation
778//===----------------------------------------------------------------------===//
779
780DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
781 if (SrcNH.isNull()) return DSNodeHandle();
782 const DSNode *SN = SrcNH.getNode();
783
784 DSNodeHandle &NH = NodeMap[SN];
785 if (!NH.isNull()) // Node already mapped?
786 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
787
788 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
789 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000790 NH = DN;
Chris Lattner0b144872004-01-27 22:03:40 +0000791
792 // Next, recursively clone all outgoing links as necessary. Note that
793 // adding these links can cause the node to collapse itself at any time, and
794 // the current node may be merged with arbitrary other nodes. For this
795 // reason, we must always go through NH.
796 DN = 0;
797 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
798 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
799 if (!SrcEdge.isNull()) {
800 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
801 // Compute the offset into the current node at which to
802 // merge this link. In the common case, this is a linear
803 // relation to the offset in the original node (with
804 // wrapping), but if the current node gets collapsed due to
805 // recursive merging, we must make sure to merge in all remaining
806 // links at offset zero.
807 unsigned MergeOffset = 0;
808 DSNode *CN = NH.getNode();
809 if (CN->getSize() != 1)
810 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()
811 - SrcNH.getOffset()) %CN->getSize();
812 CN->addEdgeTo(MergeOffset, DestEdge);
813 }
814 }
815
816 // If this node contains any globals, make sure they end up in the scalar
817 // map with the correct offset.
818 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
819 I != E; ++I) {
820 GlobalValue *GV = *I;
821 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
822 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
823 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
824 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000825 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000826
827 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
828 Dest.getInlinedGlobals().insert(GV);
829 }
830
831 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
832}
833
834void ReachabilityCloner::merge(const DSNodeHandle &NH,
835 const DSNodeHandle &SrcNH) {
836 if (SrcNH.isNull()) return; // Noop
837 if (NH.isNull()) {
838 // If there is no destination node, just clone the source and assign the
839 // destination node to be it.
840 NH.mergeWith(getClonedNH(SrcNH));
841 return;
842 }
843
844 // Okay, at this point, we know that we have both a destination and a source
845 // node that need to be merged. Check to see if the source node has already
846 // been cloned.
847 const DSNode *SN = SrcNH.getNode();
848 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +0000849 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner0b144872004-01-27 22:03:40 +0000850 NH.mergeWith(DSNodeHandle(SCNH.getNode(),
851 SCNH.getOffset()+SrcNH.getOffset()));
852
853 return; // Nothing to do!
854 }
855
856 // Okay, so the source node has not already been cloned. Instead of creating
857 // a new DSNode, only to merge it into the one we already have, try to perform
858 // the merge in-place. The only case we cannot handle here is when the offset
859 // into the existing node is less than the offset into the virtual node we are
860 // merging in. In this case, we have to extend the existing node, which
861 // requires an allocation anyway.
862 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
863 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000864 if (!DN->isNodeCompletelyFolded()) {
865 // Make sure the destination node is folded if the source node is folded.
866 if (SN->isNodeCompletelyFolded()) {
867 DN->foldNodeCompletely();
868 DN = NH.getNode();
869 } else if (SN->getSize() != DN->getSize()) {
870 // If the two nodes are of different size, and the smaller node has the
871 // array bit set, collapse!
872 if (SN->getSize() < DN->getSize()) {
873 if (SN->isArray()) {
874 DN->foldNodeCompletely();
875 DN = NH.getNode();
876 }
877 } else if (DN->isArray()) {
878 DN->foldNodeCompletely();
879 DN = NH.getNode();
880 }
881 }
882
883 // Merge the type entries of the two nodes together...
884 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
885 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
886 DN = NH.getNode();
887 }
888 }
889
890 assert(!DN->isDeadNode());
891
892 // Merge the NodeType information.
893 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
894
895 // Before we start merging outgoing links and updating the scalar map, make
896 // sure it is known that this is the representative node for the src node.
897 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
898
899 // If the source node contains any globals, make sure they end up in the
900 // scalar map with the correct offset.
901 if (SN->global_begin() != SN->global_end()) {
902 // Update the globals in the destination node itself.
903 DN->mergeGlobals(SN->getGlobals());
904
905 // Update the scalar map for the graph we are merging the source node
906 // into.
907 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
908 I != E; ++I) {
909 GlobalValue *GV = *I;
910 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
911 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
912 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
913 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +0000914 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000915
916 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
917 Dest.getInlinedGlobals().insert(GV);
918 }
919 }
920 } else {
921 // We cannot handle this case without allocating a temporary node. Fall
922 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +0000923 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
924 NewDN->maskNodeTypes(BitsToKeep);
925
926 unsigned NHOffset = NH.getOffset();
927 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +0000928
Chris Lattner0b144872004-01-27 22:03:40 +0000929 assert(NH.getNode() &&
930 (NH.getOffset() > NHOffset ||
931 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
932 "Merging did not adjust the offset!");
933
934 // Before we start merging outgoing links and updating the scalar map, make
935 // sure it is known that this is the representative node for the src node.
936 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +0000937
938 // If the source node contained any globals, make sure to create entries
939 // in the scalar map for them!
940 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
941 I != E; ++I) {
942 GlobalValue *GV = *I;
943 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
944 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
945 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
946 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
947 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
948 DestGNH.getOffset()+SrcGNH.getOffset()));
949
950 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
951 Dest.getInlinedGlobals().insert(GV);
952 }
Chris Lattner0b144872004-01-27 22:03:40 +0000953 }
954
955
956 // Next, recursively merge all outgoing links as necessary. Note that
957 // adding these links can cause the destination node to collapse itself at
958 // any time, and the current node may be merged with arbitrary other nodes.
959 // For this reason, we must always go through NH.
960 DN = 0;
961 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
962 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
963 if (!SrcEdge.isNull()) {
964 // Compute the offset into the current node at which to
965 // merge this link. In the common case, this is a linear
966 // relation to the offset in the original node (with
967 // wrapping), but if the current node gets collapsed due to
968 // recursive merging, we must make sure to merge in all remaining
969 // links at offset zero.
970 unsigned MergeOffset = 0;
971 DSNode *CN = SCNH.getNode();
972 if (CN->getSize() != 1)
973 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
974
Chris Lattner0ad91702004-02-22 00:53:54 +0000975 DSNodeHandle &Link = CN->getLink(MergeOffset);
976 if (!Link.isNull()) {
977 // Perform the recursive merging. Make sure to create a temporary NH,
978 // because the Link can disappear in the process of recursive merging.
979 DSNodeHandle Tmp = Link;
980 merge(Tmp, SrcEdge);
981 } else {
982 merge(Link, SrcEdge);
983 }
Chris Lattner0b144872004-01-27 22:03:40 +0000984 }
985 }
986}
987
988/// mergeCallSite - Merge the nodes reachable from the specified src call
989/// site into the nodes reachable from DestCS.
990void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
991 const DSCallSite &SrcCS) {
992 merge(DestCS.getRetVal(), SrcCS.getRetVal());
993 unsigned MinArgs = DestCS.getNumPtrArgs();
994 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
995
996 for (unsigned a = 0; a != MinArgs; ++a)
997 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
998}
999
1000
Chris Lattner9de906c2002-10-20 22:11:44 +00001001//===----------------------------------------------------------------------===//
1002// DSCallSite Implementation
1003//===----------------------------------------------------------------------===//
1004
Vikram S. Adve26b98262002-10-20 21:41:02 +00001005// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001006Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001007 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001008}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001009
Chris Lattner0b144872004-01-27 22:03:40 +00001010void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1011 ReachabilityCloner &RC) {
1012 NH = RC.getClonedNH(Src);
1013}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001014
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001015//===----------------------------------------------------------------------===//
1016// DSGraph Implementation
1017//===----------------------------------------------------------------------===//
1018
Chris Lattnera9d65662003-06-30 05:57:30 +00001019/// getFunctionNames - Return a space separated list of the name of the
1020/// functions in this graph (if any)
1021std::string DSGraph::getFunctionNames() const {
1022 switch (getReturnNodes().size()) {
1023 case 0: return "Globals graph";
1024 case 1: return getReturnNodes().begin()->first->getName();
1025 default:
1026 std::string Return;
1027 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1028 I != getReturnNodes().end(); ++I)
1029 Return += I->first->getName() + " ";
1030 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1031 return Return;
1032 }
1033}
1034
1035
Chris Lattner15869aa2003-11-02 22:27:28 +00001036DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001037 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001038 NodeMapTy NodeMap;
1039 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001040}
1041
Chris Lattner5a540632003-06-30 03:15:25 +00001042DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001043 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001044 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001045 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001046}
1047
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001048DSGraph::~DSGraph() {
1049 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001050 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001051 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001052 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001053 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001054
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001055 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001056 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1057 (*NI)->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001058
Chris Lattner28897e12004-02-08 00:53:26 +00001059 // Free all of the nodes.
1060 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001061}
1062
Chris Lattner0d9bab82002-07-18 00:12:30 +00001063// dump - Allow inspection of graph in a debugger.
1064void DSGraph::dump() const { print(std::cerr); }
1065
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001066
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001067/// remapLinks - Change all of the Links in the current node according to the
1068/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001069///
Chris Lattner8d327672003-06-30 03:36:09 +00001070void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001071 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1072 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001073 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1074 if (ONMI != OldNodeMap.end()) {
1075 Links[i].setNode(ONMI->second.getNode());
1076 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1077 }
Chris Lattner2f561382004-01-22 16:56:13 +00001078 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001079}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001080
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001081/// updateFromGlobalGraph - This function rematerializes global nodes and
1082/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001083/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1084/// are already up-to-date in the current graph. In practice, in the TD pass,
1085/// this is likely to be a large fraction of the live global nodes in each
1086/// function (since most live nodes are likely to have been brought up-to-date
1087/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001088///
1089void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001090 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001091 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1092
1093 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001094 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1095 E = getScalarMap().global_end(); I != E; ++I)
1096 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001097 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001098 if (It != GlobalsGraph->ScalarMap.end())
1099 RC.merge(getNodeForValue(*I), It->second);
1100 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001101}
1102
Chris Lattner5a540632003-06-30 03:15:25 +00001103/// cloneInto - Clone the specified DSGraph into the current graph. The
1104/// translated ScalarMap for the old function is filled into the OldValMap
1105/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1106///
1107/// The CloneFlags member controls various aspects of the cloning process.
1108///
Chris Lattner62482e52004-01-28 09:15:42 +00001109void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001110 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1111 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001112 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001113 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001114 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001115
Chris Lattner1e883692003-02-03 20:08:51 +00001116 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001117 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1118 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1119 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001120 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001121
Chris Lattnerd85645f2004-02-21 22:28:26 +00001122 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1123 assert(!(*I)->isForwarding() &&
1124 "Forward nodes shouldn't be in node list!");
1125 DSNode *New = new DSNode(**I, this);
1126 New->maskNodeTypes(~BitsToClear);
1127 OldNodeMap[*I] = New;
1128 }
1129
Chris Lattner18552922002-11-18 21:44:46 +00001130#ifndef NDEBUG
1131 Timer::addPeakMemoryMeasurement();
1132#endif
Chris Lattnerd85645f2004-02-21 22:28:26 +00001133
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001134 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001135 // Note that we don't loop over the node's list to do this. The problem is
1136 // that remaping links can cause recursive merging to happen, which means
1137 // that node_iterator's can get easily invalidated! Because of this, we
1138 // loop over the OldNodeMap, which contains all of the new nodes as the
1139 // .second element of the map elements. Also note that if we remap a node
1140 // more than once, we won't break anything.
1141 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1142 I != E; ++I)
1143 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001144
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001145 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001146 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001147 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001148 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001149 DSNodeHandle &H = OldValMap[I->first];
1150 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1151 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001152
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001153 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001154 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1155 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001156 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1157 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001158 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001159 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001160
Chris Lattner679e8e12002-11-08 21:27:12 +00001161 if (!(CloneFlags & DontCloneCallNodes)) {
1162 // Copy the function calls list...
1163 unsigned FC = FunctionCalls.size(); // FirstCall
1164 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1165 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1166 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001167 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001168
Chris Lattneracf491f2002-11-08 22:27:09 +00001169 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +00001170 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +00001171 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +00001172 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1173 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1174 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1175 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001176
Chris Lattner5a540632003-06-30 03:15:25 +00001177 // Map the return node pointers over...
1178 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1179 E = G.getReturnNodes().end(); I != E; ++I) {
1180 const DSNodeHandle &Ret = I->second;
1181 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1182 OldReturnNodes.insert(std::make_pair(I->first,
1183 DSNodeHandle(MappedRet.getNode(),
1184 MappedRet.getOffset()+Ret.getOffset())));
1185 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001186}
1187
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001188
Chris Lattner076c1f92002-11-07 06:31:54 +00001189/// mergeInGraph - The method is used for merging graphs together. If the
1190/// argument graph is not *this, it makes a clone of the specified graph, then
1191/// merges the nodes specified in the call site with the formal arguments in the
1192/// graph.
1193///
Chris Lattner9f930552003-06-30 05:27:18 +00001194void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1195 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001196 TIME_REGION(X, "mergeInGraph");
1197
Chris Lattner076c1f92002-11-07 06:31:54 +00001198 // If this is not a recursive call, clone the graph into this graph...
1199 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001200 // Clone the callee's graph into the current graph, keeping track of where
1201 // scalars in the old graph _used_ to point, and of the new nodes matching
1202 // nodes of the old graph.
1203 ReachabilityCloner RC(*this, Graph, CloneFlags);
1204
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001205 // Set up argument bindings
1206 Function::aiterator AI = F.abegin();
1207 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1208 // Advance the argument iterator to the first pointer argument...
1209 while (AI != F.aend() && !isPointerType(AI->getType())) {
1210 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001211#ifndef NDEBUG // FIXME: We should merge vararg arguments!
1212 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001213 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001214#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001215 }
1216 if (AI == F.aend()) break;
1217
1218 // Add the link from the argument scalar to the provided value.
Chris Lattner0b144872004-01-27 22:03:40 +00001219 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
Chris Lattner076c1f92002-11-07 06:31:54 +00001220 }
1221
Chris Lattner0b144872004-01-27 22:03:40 +00001222 // Map the return node pointer over.
Chris Lattner0ad91702004-02-22 00:53:54 +00001223 if (!CS.getRetVal().isNull())
Chris Lattner0b144872004-01-27 22:03:40 +00001224 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
1225
1226 // If requested, copy the calls or aux-calls lists.
1227 if (!(CloneFlags & DontCloneCallNodes)) {
1228 // Copy the function calls list...
1229 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1230 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1231 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1232 }
1233
1234 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1235 // Copy the auxiliary function calls list...
1236 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1237 Graph.AuxFunctionCalls.size());
1238 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1239 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i], RC));
1240 }
1241
1242 // If the user requested it, add the nodes that we need to clone to the
1243 // RootNodes set.
1244 if (!EnableDSNodeGlobalRootsHack)
Chris Lattnerd85645f2004-02-21 22:28:26 +00001245 // FIXME: Why is this not iterating over the globals in the graph??
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001246 for (node_iterator NI = Graph.node_begin(), E = Graph.node_end();
1247 NI != E; ++NI)
1248 if (!(*NI)->getGlobals().empty())
1249 RC.getClonedNH(*NI);
Chris Lattner0b144872004-01-27 22:03:40 +00001250
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001251 } else {
1252 DSNodeHandle RetVal = getReturnNodeFor(F);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001253
1254 // Merge the return value with the return value of the context...
1255 RetVal.mergeWith(CS.getRetVal());
1256
1257 // Resolve all of the function arguments...
1258 Function::aiterator AI = F.abegin();
1259
1260 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1261 // Advance the argument iterator to the first pointer argument...
1262 while (AI != F.aend() && !isPointerType(AI->getType())) {
1263 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001264#ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1265 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001266 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1267#endif
1268 }
1269 if (AI == F.aend()) break;
1270
1271 // Add the link from the argument scalar to the provided value
Chris Lattner0b144872004-01-27 22:03:40 +00001272 DSNodeHandle &NH = getNodeForValue(AI);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001273 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1274 NH.mergeWith(CS.getPtrArg(i));
1275 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001276 }
1277}
1278
Chris Lattner58f98d02003-07-02 04:38:49 +00001279/// getCallSiteForArguments - Get the arguments and return value bindings for
1280/// the specified function in the current graph.
1281///
1282DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1283 std::vector<DSNodeHandle> Args;
1284
1285 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1286 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001287 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001288
Chris Lattner808a7ae2003-09-20 16:34:13 +00001289 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001290}
1291
1292
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001293
Chris Lattner0d9bab82002-07-18 00:12:30 +00001294// markIncompleteNodes - Mark the specified node as having contents that are not
1295// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001296// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001297// must recursively traverse the data structure graph, marking all reachable
1298// nodes as incomplete.
1299//
1300static void markIncompleteNode(DSNode *N) {
1301 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001302 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001303
1304 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001305 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001306
Misha Brukman2f2d0652003-09-11 18:14:24 +00001307 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001308 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1309 if (DSNode *DSN = N->getLink(i).getNode())
1310 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001311}
1312
Chris Lattnere71ffc22002-11-11 03:36:55 +00001313static void markIncomplete(DSCallSite &Call) {
1314 // Then the return value is certainly incomplete!
1315 markIncompleteNode(Call.getRetVal().getNode());
1316
1317 // All objects pointed to by function arguments are incomplete!
1318 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1319 markIncompleteNode(Call.getPtrArg(i).getNode());
1320}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001321
1322// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1323// modified by other functions that have not been resolved yet. This marks
1324// nodes that are reachable through three sources of "unknownness":
1325//
1326// Global Variables, Function Calls, and Incoming Arguments
1327//
1328// For any node that may have unknown components (because something outside the
1329// scope of current analysis may have modified it), the 'Incomplete' flag is
1330// added to the NodeType.
1331//
Chris Lattner394471f2003-01-23 22:05:33 +00001332void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001333 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001334 if (Flags & DSGraph::MarkFormalArgs)
1335 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1336 FI != E; ++FI) {
1337 Function &F = *FI->first;
1338 if (F.getName() != "main")
1339 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001340 if (isPointerType(I->getType()))
1341 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001342 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001343
1344 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001345 if (!shouldPrintAuxCalls())
1346 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1347 markIncomplete(FunctionCalls[i]);
1348 else
1349 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1350 markIncomplete(AuxFunctionCalls[i]);
1351
Chris Lattner0d9bab82002-07-18 00:12:30 +00001352
Chris Lattner93d7a212003-02-09 18:41:49 +00001353 // Mark all global nodes as incomplete...
1354 if ((Flags & DSGraph::IgnoreGlobals) == 0)
Chris Lattner51c06ab2004-02-25 23:08:00 +00001355 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1356 E = ScalarMap.global_end(); I != E; ++I)
Chris Lattnercf14e712004-02-25 23:36:08 +00001357 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1358 if (!GV->isConstant())
1359 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001360}
1361
Chris Lattneraa8146f2002-11-10 06:59:55 +00001362static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1363 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001364 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001365 // No interesting info?
1366 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001367 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001368 Edge.setNode(0); // Kill the edge!
1369}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001370
Chris Lattneraa8146f2002-11-10 06:59:55 +00001371static inline bool nodeContainsExternalFunction(const DSNode *N) {
1372 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1373 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1374 if (Globals[i]->isExternal())
1375 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001376 return false;
1377}
1378
Chris Lattner5a540632003-06-30 03:15:25 +00001379static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001380 // Remove trivially identical function calls
1381 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001382 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1383
Chris Lattner0b144872004-01-27 22:03:40 +00001384#if 1
Chris Lattneraa8146f2002-11-10 06:59:55 +00001385 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001386 DSNode *LastCalleeNode = 0;
1387 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001388 unsigned NumDuplicateCalls = 0;
1389 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001390 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001391 DSCallSite &CS = Calls[i];
1392
Chris Lattnere4258442002-11-11 21:35:38 +00001393 // If the Callee is a useless edge, this must be an unreachable call site,
1394 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001395 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerabcdf802004-02-26 03:43:43 +00001396 CS.getCalleeNode()->isComplete() &&
1397 CS.getCalleeNode()->getGlobals.empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001398#ifndef NDEBUG
Chris Lattnerabcdf802004-02-26 03:43:43 +00001399 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001400#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001401 CS.swap(Calls.back());
1402 Calls.pop_back();
1403 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001404 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001405 // If the return value or any arguments point to a void node with no
1406 // information at all in it, and the call node is the only node to point
1407 // to it, remove the edge to the node (killing the node).
1408 //
1409 killIfUselessEdge(CS.getRetVal());
1410 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1411 killIfUselessEdge(CS.getPtrArg(a));
1412
1413 // If this call site calls the same function as the last call site, and if
1414 // the function pointer contains an external function, this node will
1415 // never be resolved. Merge the arguments of the call node because no
1416 // information will be lost.
1417 //
Chris Lattner923fc052003-02-05 21:59:58 +00001418 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1419 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001420 ++NumDuplicateCalls;
1421 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001422 if (LastCalleeNode)
1423 LastCalleeContainsExternalFunction =
1424 nodeContainsExternalFunction(LastCalleeNode);
1425 else
1426 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001427 }
Chris Lattner0b144872004-01-27 22:03:40 +00001428
1429 // It is not clear why, but enabling this code makes DSA really
1430 // sensitive to node forwarding. Basically, with this enabled, DSA
1431 // performs different number of inlinings based on which nodes are
1432 // forwarding or not. This is clearly a problem, so this code is
1433 // disabled until this can be resolved.
Chris Lattner58f98d02003-07-02 04:38:49 +00001434#if 1
Chris Lattner0b144872004-01-27 22:03:40 +00001435 if (LastCalleeContainsExternalFunction
1436#if 0
1437 ||
Chris Lattnere4258442002-11-11 21:35:38 +00001438 // This should be more than enough context sensitivity!
1439 // FIXME: Evaluate how many times this is tripped!
Chris Lattner0b144872004-01-27 22:03:40 +00001440 NumDuplicateCalls > 20
1441#endif
1442 ) {
Chris Lattnere4258442002-11-11 21:35:38 +00001443 DSCallSite &OCS = Calls[i-1];
1444 OCS.mergeWith(CS);
1445
1446 // The node will now be eliminated as a duplicate!
1447 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1448 CS = OCS;
1449 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1450 OCS = CS;
1451 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001452#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001453 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001454 if (CS.isDirectCall()) {
1455 LastCalleeFunc = CS.getCalleeFunc();
1456 LastCalleeNode = 0;
1457 } else {
1458 LastCalleeNode = CS.getCalleeNode();
1459 LastCalleeFunc = 0;
1460 }
Chris Lattnere4258442002-11-11 21:35:38 +00001461 NumDuplicateCalls = 0;
1462 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001463 }
1464 }
Chris Lattner0b144872004-01-27 22:03:40 +00001465#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001466 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001467
Chris Lattner33312f72002-11-08 01:21:07 +00001468 // Track the number of call nodes merged away...
1469 NumCallNodesMerged += NumFns-Calls.size();
1470
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001471 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001472 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001473}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001474
Chris Lattneraa8146f2002-11-10 06:59:55 +00001475
Chris Lattnere2219762002-07-18 18:22:40 +00001476// removeTriviallyDeadNodes - After the graph has been constructed, this method
1477// removes all unreachable nodes that are created because they got merged with
1478// other nodes in the graph. These nodes will all be trivially unreachable, so
1479// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001480//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001481void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001482 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001483
Chris Lattnerbab8c282003-09-20 21:34:07 +00001484 // Loop over all of the nodes in the graph, calling getNode on each field.
1485 // This will cause all nodes to update their forwarding edges, causing
1486 // forwarded nodes to be delete-able.
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001487 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1488 DSNode *N = *NI;
Chris Lattnerbab8c282003-09-20 21:34:07 +00001489 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1490 N->getLink(l*N->getPointerSize()).getNode();
1491 }
1492
Chris Lattner0b144872004-01-27 22:03:40 +00001493 // NOTE: This code is disabled. Though it should, in theory, allow us to
1494 // remove more nodes down below, the scan of the scalar map is incredibly
1495 // expensive for certain programs (with large SCCs). In the future, if we can
1496 // make the scalar map scan more efficient, then we can reenable this.
1497#if 0
1498 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1499
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001500 // Likewise, forward any edges from the scalar nodes. While we are at it,
1501 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001502 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001503 I->second.getNode();
1504 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001505 }
Chris Lattner0b144872004-01-27 22:03:40 +00001506 }
1507#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001508 bool isGlobalsGraph = !GlobalsGraph;
1509
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001510 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001511 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001512
1513 // Do not remove *any* global nodes in the globals graph.
1514 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001515 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001516 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001517 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001518 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001519
Chris Lattner28897e12004-02-08 00:53:26 +00001520 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001521 // This is a useless node if it has no mod/ref info (checked above),
1522 // outgoing edges (which it cannot, as it is not modified in this
1523 // context), and it has no incoming edges. If it is a global node it may
1524 // have all of these properties and still have incoming edges, due to the
1525 // scalar map, so we check those now.
1526 //
Chris Lattner28897e12004-02-08 00:53:26 +00001527 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1528 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001529
Chris Lattner17a93e22004-01-29 03:32:15 +00001530 // Loop through and make sure all of the globals are referring directly
1531 // to the node...
1532 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1533 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001534 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001535 }
1536
Chris Lattnerbd92b732003-06-19 21:15:11 +00001537 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001538 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001539 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1540 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001541 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001542 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001543 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001544 }
1545 }
1546
Chris Lattner28897e12004-02-08 00:53:26 +00001547 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001548 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001549 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001550 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001551 } else {
1552 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001553 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001554 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001555
1556 removeIdenticalCalls(FunctionCalls);
1557 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001558}
1559
1560
Chris Lattner5c7380e2003-01-29 21:10:20 +00001561/// markReachableNodes - This method recursively traverses the specified
1562/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1563/// to the set, which allows it to only traverse visited nodes once.
1564///
Chris Lattner41c04f72003-02-01 04:52:08 +00001565void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001566 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001567 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001568 if (ReachableNodes.insert(this).second) // Is newly reachable?
1569 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1570 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001571}
1572
Chris Lattner41c04f72003-02-01 04:52:08 +00001573void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001574 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001575 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001576
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001577 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1578 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001579}
1580
Chris Lattnera1220af2003-02-01 06:17:02 +00001581// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1582// looking for a node that is marked alive. If an alive node is found, return
1583// true, otherwise return false. If an alive node is reachable, this node is
1584// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001585//
Chris Lattnera1220af2003-02-01 06:17:02 +00001586static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001587 hash_set<DSNode*> &Visited,
1588 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001589 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001590 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001591
Chris Lattner85cfe012003-07-03 02:03:53 +00001592 // If this is a global node, it will end up in the globals graph anyway, so we
1593 // don't need to worry about it.
1594 if (IgnoreGlobals && N->isGlobalNode()) return false;
1595
Chris Lattneraa8146f2002-11-10 06:59:55 +00001596 // If we know that this node is alive, return so!
1597 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001598
Chris Lattneraa8146f2002-11-10 06:59:55 +00001599 // Otherwise, we don't think the node is alive yet, check for infinite
1600 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001601 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001602 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001603
Chris Lattner08db7192002-11-06 06:20:27 +00001604 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001605 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1606 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001607 N->markReachableNodes(Alive);
1608 return true;
1609 }
1610 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001611}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001612
Chris Lattnera1220af2003-02-01 06:17:02 +00001613// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1614// alive nodes.
1615//
Chris Lattner41c04f72003-02-01 04:52:08 +00001616static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001617 hash_set<DSNode*> &Visited,
1618 bool IgnoreGlobals) {
1619 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1620 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001621 return true;
1622 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001623 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001624 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001625 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001626 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1627 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001628 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001629 return false;
1630}
1631
Chris Lattnere2219762002-07-18 18:22:40 +00001632// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1633// subgraphs that are unreachable. This often occurs because the data
1634// structure doesn't "escape" into it's caller, and thus should be eliminated
1635// from the caller's graph entirely. This is only appropriate to use when
1636// inlining graphs.
1637//
Chris Lattner394471f2003-01-23 22:05:33 +00001638void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001639 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001640
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001641 // Reduce the amount of work we have to do... remove dummy nodes left over by
1642 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001643 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001644
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001645 TIME_REGION(X, "removeDeadNodes");
1646
Misha Brukman2f2d0652003-09-11 18:14:24 +00001647 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001648
1649 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001650 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001651 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001652
Chris Lattner0b144872004-01-27 22:03:40 +00001653 // Copy and merge all information about globals to the GlobalsGraph if this is
1654 // not a final pass (where unreachable globals are removed).
1655 //
1656 // Strip all alloca bits since the current function is only for the BU pass.
1657 // Strip all incomplete bits since they are short-lived properties and they
1658 // will be correctly computed when rematerializing nodes into the functions.
1659 //
1660 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1661 DSGraph::StripIncompleteBit);
1662
Chris Lattneraa8146f2002-11-10 06:59:55 +00001663 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner00948c02004-01-28 02:05:05 +00001664 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
Chris Lattner62482e52004-01-28 09:15:42 +00001665 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001666 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001667 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001668 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001669 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001670
1671 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001672 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1673 DSGraph::ScalarMapTy::iterator SMI =
1674 GlobalsGraph->getScalarMap().find(I->first);
1675 if (SMI != GlobalsGraph->getScalarMap().end())
1676 GGCloner.merge(SMI->second, I->second);
1677 else
1678 GGCloner.getClonedNH(I->second);
1679 }
Chris Lattner0b144872004-01-27 22:03:40 +00001680 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001681 } else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001682 DSNode *N = I->second.getNode();
1683#if 0
Chris Lattner0b144872004-01-27 22:03:40 +00001684 // Check to see if this is a worthless node generated for non-pointer
1685 // values, such as integers. Consider an addition of long types: A+B.
1686 // Assuming we can track all uses of the value in this context, and it is
1687 // NOT used as a pointer, we can delete the node. We will be able to
1688 // detect this situation if the node pointed to ONLY has Unknown bit set
1689 // in the node. In this case, the node is not incomplete, does not point
1690 // to any other nodes (no mod/ref bits set), and is therefore
1691 // uninteresting for data structure analysis. If we run across one of
1692 // these, prune the scalar pointing to it.
1693 //
Chris Lattner0b144872004-01-27 22:03:40 +00001694 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1695 ScalarMap.erase(I++);
1696 else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001697#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001698 N->markReachableNodes(Alive);
1699 ++I;
Chris Lattnera88a55c2004-01-28 02:41:32 +00001700 //}
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001701 }
Chris Lattner00948c02004-01-28 02:05:05 +00001702 }
Chris Lattnere2219762002-07-18 18:22:40 +00001703
Chris Lattner0b144872004-01-27 22:03:40 +00001704 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001705 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1706 I != E; ++I)
1707 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001708
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001709 // Mark any nodes reachable by primary calls as alive...
1710 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1711 FunctionCalls[i].markReachableNodes(Alive);
1712
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001713
1714 // Now find globals and aux call nodes that are already live or reach a live
1715 // value (which makes them live in turn), and continue till no more are found.
1716 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001717 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001718 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001719 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1720 do {
1721 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001722 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001723 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001724 // unreachable globals in the list.
1725 //
1726 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001727 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001728 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1729 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1730 Flags & DSGraph::RemoveUnreachableGlobals)) {
1731 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1732 GlobalNodes.pop_back(); // erase efficiently
1733 Iterate = true;
1734 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001735
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001736 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1737 // call nodes that get resolved will be difficult to remove from that graph.
1738 // The final unresolved call nodes must be handled specially at the end of
1739 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001740 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1741 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001742 (AuxFunctionCalls[i].isIndirectCall()
1743 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1744 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001745 AuxFunctionCalls[i].markReachableNodes(Alive);
1746 AuxFCallsAlive[i] = true;
1747 Iterate = true;
1748 }
1749 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001750
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001751 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001752 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001753 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1754 if (AuxFCallsAlive[i])
1755 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001756
1757 // Copy and merge all global nodes and dead aux call nodes into the
1758 // GlobalsGraph, and all nodes reachable from those nodes
1759 //
1760 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001761 // Copy the unreachable call nodes to the globals graph, updating their
1762 // target pointers using the GGCloner
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001763 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1764 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
Chris Lattner0b144872004-01-27 22:03:40 +00001765 GGCloner));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001766 }
1767 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001768 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1769 AuxFunctionCalls.end());
1770
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001771 // We are finally done with the GGCloner so we can destroy it.
1772 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001773
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001774 // At this point, any nodes which are visited, but not alive, are nodes
1775 // which can be removed. Loop over all nodes, eliminating completely
1776 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001777 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001778 std::vector<DSNode*> DeadNodes;
1779 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00001780 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
1781 DSNode *N = NI++;
1782 assert(!N->isForwarding() && "Forwarded node in nodes list?");
1783
1784 if (!Alive.count(N)) {
1785 Nodes.remove(N);
1786 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001787 DeadNodes.push_back(N);
1788 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00001789 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00001790 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00001791 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001792
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001793 // Remove all unreachable globals from the ScalarMap.
1794 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1795 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001796 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001797 if (!Alive.count(GlobalNodes[i].second))
1798 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00001799 else
1800 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001801
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001802 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001803 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1804 delete DeadNodes[i];
1805
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001806 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001807}
1808
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001809void DSGraph::AssertGraphOK() const {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001810 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1811 (*NI)->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001812
Chris Lattner8d327672003-06-30 03:36:09 +00001813 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001814 E = ScalarMap.end(); I != E; ++I) {
1815 assert(I->second.getNode() && "Null node in scalarmap!");
1816 AssertNodeInGraph(I->second.getNode());
1817 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001818 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001819 "Global points to node, but node isn't global?");
1820 AssertNodeContainsGlobal(I->second.getNode(), GV);
1821 }
1822 }
1823 AssertCallNodesInGraph();
1824 AssertAuxCallNodesInGraph();
1825}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001826
Chris Lattner400433d2003-11-11 05:08:59 +00001827/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1828/// nodes reachable from the two graphs, computing the mapping of nodes from
1829/// the first to the second graph.
1830///
1831void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001832 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1833 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001834 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1835 if (N1 == 0 || N2 == 0) return;
1836
1837 DSNodeHandle &Entry = NodeMap[N1];
1838 if (Entry.getNode()) {
1839 // Termination of recursion!
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001840 assert(!StrictChecking ||
1841 (Entry.getNode() == N2 &&
1842 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
Chris Lattner400433d2003-11-11 05:08:59 +00001843 "Inconsistent mapping detected!");
1844 return;
1845 }
1846
1847 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001848 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001849
1850 // Loop over all of the fields that N1 and N2 have in common, recursively
1851 // mapping the edges together now.
1852 int N2Idx = NH2.getOffset()-NH1.getOffset();
1853 unsigned N2Size = N2->getSize();
1854 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1855 if (unsigned(N2Idx)+i < N2Size)
1856 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1857}