blob: 043579c72f52245889f83d281e83b99eed83bf3c [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00009//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerfccd06f2002-10-01 22:33:50 +000014#include "llvm/Analysis/DSGraph.h"
15#include "llvm/Function.h"
Vikram S. Adve26b98262002-10-20 21:41:02 +000016#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000017#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000018#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000019#include "llvm/Assembly/Writer.h"
Chris Lattner6806f562003-08-01 22:15:03 +000020#include "Support/Debug.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000021#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000022#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000023#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000024#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000025using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000026
Chris Lattner08db7192002-11-06 06:20:27 +000027namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000028 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
29 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000030};
31
Chris Lattnerb1060432002-11-07 05:20:53 +000032using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000033
Chris Lattner731b2d72003-02-13 19:09:00 +000034DSNode *DSNodeHandle::HandleForwarding() const {
35 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
36
37 // Handle node forwarding here!
38 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
39 Offset += N->ForwardNH.getOffset();
40
41 if (--N->NumReferrers == 0) {
42 // Removing the last referrer to the node, sever the forwarding link
43 N->stopForwarding();
44 }
45
46 N = Next;
47 N->NumReferrers++;
48 if (N->Size <= Offset) {
49 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
50 Offset = 0;
51 }
52 return N;
53}
54
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000055//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000056// DSNode Implementation
57//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000058
Chris Lattnerbd92b732003-06-19 21:15:11 +000059DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000060 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000061 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000062 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000063 G->getNodes().push_back(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000064}
65
Chris Lattner0d9bab82002-07-18 00:12:30 +000066// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner72d29a42003-02-11 23:11:51 +000067DSNode::DSNode(const DSNode &N, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000068 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner58f98d02003-07-02 04:38:49 +000069 Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner72d29a42003-02-11 23:11:51 +000070 G->getNodes().push_back(this);
Chris Lattner0d9bab82002-07-18 00:12:30 +000071}
72
Chris Lattner15869aa2003-11-02 22:27:28 +000073/// getTargetData - Get the target data object used to construct this node.
74///
75const TargetData &DSNode::getTargetData() const {
76 return ParentGraph->getTargetData();
77}
78
Chris Lattner72d29a42003-02-11 23:11:51 +000079void DSNode::assertOK() const {
80 assert((Ty != Type::VoidTy ||
81 Ty == Type::VoidTy && (Size == 0 ||
82 (NodeType & DSNode::Array))) &&
83 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +000084
85 assert(ParentGraph && "Node has no parent?");
86 const DSGraph::ScalarMapTy &SM = ParentGraph->getScalarMap();
87 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
88 assert(SM.find(Globals[i]) != SM.end());
89 assert(SM.find(Globals[i])->second.getNode() == this);
90 }
Chris Lattner72d29a42003-02-11 23:11:51 +000091}
92
93/// forwardNode - Mark this node as being obsolete, and all references to it
94/// should be forwarded to the specified node and offset.
95///
96void DSNode::forwardNode(DSNode *To, unsigned Offset) {
97 assert(this != To && "Cannot forward a node to itself!");
98 assert(ForwardNH.isNull() && "Already forwarding from this node!");
99 if (To->Size <= 1) Offset = 0;
100 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
101 "Forwarded offset is wrong!");
102 ForwardNH.setNode(To);
103 ForwardNH.setOffset(Offset);
104 NodeType = DEAD;
105 Size = 0;
106 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000107}
108
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000109// addGlobal - Add an entry for a global value to the Globals list. This also
110// marks the node with the 'G' flag if it does not already have it.
111//
112void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000113 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000114 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000115 std::lower_bound(Globals.begin(), Globals.end(), GV);
116
117 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000118 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000119 Globals.insert(I, GV);
120 NodeType |= GlobalNode;
121 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000122}
123
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000124/// foldNodeCompletely - If we determine that this node has some funny
125/// behavior happening to it that we cannot represent, we fold it down to a
126/// single, completely pessimistic, node. This node is represented as a
127/// single byte with a single TypeEntry of "void".
128///
129void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000130 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000131
Chris Lattner08db7192002-11-06 06:20:27 +0000132 ++NumFolds;
133
Chris Lattner72d29a42003-02-11 23:11:51 +0000134 // Create the node we are going to forward to...
Chris Lattner70793862003-07-02 23:57:05 +0000135 DSNode *DestNode = new DSNode(0, ParentGraph);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000136 DestNode->NodeType = NodeType|DSNode::Array;
Chris Lattner72d29a42003-02-11 23:11:51 +0000137 DestNode->Ty = Type::VoidTy;
138 DestNode->Size = 1;
139 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000140
Chris Lattner72d29a42003-02-11 23:11:51 +0000141 // Start forwarding to the destination node...
142 forwardNode(DestNode, 0);
143
144 if (Links.size()) {
145 DestNode->Links.push_back(Links[0]);
146 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000147
Chris Lattner72d29a42003-02-11 23:11:51 +0000148 // If we have links, merge all of our outgoing links together...
149 for (unsigned i = Links.size()-1; i != 0; --i)
150 NH.getNode()->Links[0].mergeWith(Links[i]);
151 Links.clear();
152 } else {
153 DestNode->Links.resize(1);
154 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000155}
Chris Lattner076c1f92002-11-07 06:31:54 +0000156
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000157/// isNodeCompletelyFolded - Return true if this node has been completely
158/// folded down to something that can never be expanded, effectively losing
159/// all of the field sensitivity that may be present in the node.
160///
161bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000162 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000163}
164
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000165namespace {
166 /// TypeElementWalker Class - Used for implementation of physical subtyping...
167 ///
168 class TypeElementWalker {
169 struct StackState {
170 const Type *Ty;
171 unsigned Offset;
172 unsigned Idx;
173 StackState(const Type *T, unsigned Off = 0)
174 : Ty(T), Offset(Off), Idx(0) {}
175 };
176
177 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000178 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000179 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000180 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000181 Stack.push_back(T);
182 StepToLeaf();
183 }
184
185 bool isDone() const { return Stack.empty(); }
186 const Type *getCurrentType() const { return Stack.back().Ty; }
187 unsigned getCurrentOffset() const { return Stack.back().Offset; }
188
189 void StepToNextType() {
190 PopStackAndAdvance();
191 StepToLeaf();
192 }
193
194 private:
195 /// PopStackAndAdvance - Pop the current element off of the stack and
196 /// advance the underlying element to the next contained member.
197 void PopStackAndAdvance() {
198 assert(!Stack.empty() && "Cannot pop an empty stack!");
199 Stack.pop_back();
200 while (!Stack.empty()) {
201 StackState &SS = Stack.back();
202 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
203 ++SS.Idx;
204 if (SS.Idx != ST->getElementTypes().size()) {
205 const StructLayout *SL = TD.getStructLayout(ST);
206 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
207 return;
208 }
209 Stack.pop_back(); // At the end of the structure
210 } else {
211 const ArrayType *AT = cast<ArrayType>(SS.Ty);
212 ++SS.Idx;
213 if (SS.Idx != AT->getNumElements()) {
214 SS.Offset += TD.getTypeSize(AT->getElementType());
215 return;
216 }
217 Stack.pop_back(); // At the end of the array
218 }
219 }
220 }
221
222 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
223 /// on the type stack.
224 void StepToLeaf() {
225 if (Stack.empty()) return;
226 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
227 StackState &SS = Stack.back();
228 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
229 if (ST->getElementTypes().empty()) {
230 assert(SS.Idx == 0);
231 PopStackAndAdvance();
232 } else {
233 // Step into the structure...
234 assert(SS.Idx < ST->getElementTypes().size());
235 const StructLayout *SL = TD.getStructLayout(ST);
236 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
237 SS.Offset+SL->MemberOffsets[SS.Idx]));
238 }
239 } else {
240 const ArrayType *AT = cast<ArrayType>(SS.Ty);
241 if (AT->getNumElements() == 0) {
242 assert(SS.Idx == 0);
243 PopStackAndAdvance();
244 } else {
245 // Step into the array...
246 assert(SS.Idx < AT->getNumElements());
247 Stack.push_back(StackState(AT->getElementType(),
248 SS.Offset+SS.Idx*
249 TD.getTypeSize(AT->getElementType())));
250 }
251 }
252 }
253 }
254 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000255} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000256
257/// ElementTypesAreCompatible - Check to see if the specified types are
258/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000259/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
260/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000261///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000262static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000263 bool AllowLargerT1, const TargetData &TD){
264 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000265
266 while (!T1W.isDone() && !T2W.isDone()) {
267 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
268 return false;
269
270 const Type *T1 = T1W.getCurrentType();
271 const Type *T2 = T2W.getCurrentType();
272 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
273 return false;
274
275 T1W.StepToNextType();
276 T2W.StepToNextType();
277 }
278
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000279 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000280}
281
282
Chris Lattner08db7192002-11-06 06:20:27 +0000283/// mergeTypeInfo - This method merges the specified type into the current node
284/// at the specified offset. This may update the current node's type record if
285/// this gives more information to the node, it may do nothing to the node if
286/// this information is already known, or it may merge the node completely (and
287/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000288///
Chris Lattner08db7192002-11-06 06:20:27 +0000289/// This method returns true if the node is completely folded, otherwise false.
290///
Chris Lattner088b6392003-03-03 17:13:31 +0000291bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
292 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000293 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000294 // Check to make sure the Size member is up-to-date. Size can be one of the
295 // following:
296 // Size = 0, Ty = Void: Nothing is known about this node.
297 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
298 // Size = 1, Ty = Void, Array = 1: The node is collapsed
299 // Otherwise, sizeof(Ty) = Size
300 //
Chris Lattner18552922002-11-18 21:44:46 +0000301 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
302 (Size == 0 && !Ty->isSized() && !isArray()) ||
303 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
304 (Size == 0 && !Ty->isSized() && !isArray()) ||
305 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000306 "Size member of DSNode doesn't match the type structure!");
307 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000308
Chris Lattner18552922002-11-18 21:44:46 +0000309 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000310 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000311
Chris Lattner08db7192002-11-06 06:20:27 +0000312 // Return true immediately if the node is completely folded.
313 if (isNodeCompletelyFolded()) return true;
314
Chris Lattner23f83dc2002-11-08 22:49:57 +0000315 // If this is an array type, eliminate the outside arrays because they won't
316 // be used anyway. This greatly reduces the size of large static arrays used
317 // as global variables, for example.
318 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000319 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000320 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
321 // FIXME: we might want to keep small arrays, but must be careful about
322 // things like: [2 x [10000 x int*]]
323 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000324 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000325 }
326
Chris Lattner08db7192002-11-06 06:20:27 +0000327 // Figure out how big the new type we're merging in is...
328 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
329
330 // Otherwise check to see if we can fold this type into the current node. If
331 // we can't, we fold the node completely, if we can, we potentially update our
332 // internal state.
333 //
Chris Lattner18552922002-11-18 21:44:46 +0000334 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000335 // If this is the first type that this node has seen, just accept it without
336 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000337 assert(Offset == 0 && !isArray() &&
338 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000339 Ty = NewTy;
340 NodeType &= ~Array;
341 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000342 Size = NewTySize;
343
344 // Calculate the number of outgoing links from this node.
345 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
346 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000347 }
Chris Lattner08db7192002-11-06 06:20:27 +0000348
349 // Handle node expansion case here...
350 if (Offset+NewTySize > Size) {
351 // It is illegal to grow this node if we have treated it as an array of
352 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000353 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000354 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000355 return true;
356 }
357
358 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000359 std::cerr << "UNIMP: Trying to merge a growth type into "
360 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000361 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000362 return true;
363 }
364
365 // Okay, the situation is nice and simple, we are trying to merge a type in
366 // at offset 0 that is bigger than our current type. Implement this by
367 // switching to the new type and then merge in the smaller one, which should
368 // hit the other code path here. If the other code path decides it's not
369 // ok, it will collapse the node as appropriate.
370 //
Chris Lattner18552922002-11-18 21:44:46 +0000371 const Type *OldTy = Ty;
372 Ty = NewTy;
373 NodeType &= ~Array;
374 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000375 Size = NewTySize;
376
377 // Must grow links to be the appropriate size...
378 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
379
380 // Merge in the old type now... which is guaranteed to be smaller than the
381 // "current" type.
382 return mergeTypeInfo(OldTy, 0);
383 }
384
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000385 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000386 "Cannot merge something into a part of our type that doesn't exist!");
387
Chris Lattner18552922002-11-18 21:44:46 +0000388 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000389 // type that starts at offset Offset.
390 //
391 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000392 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000393 while (O < Offset) {
394 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
395
396 switch (SubType->getPrimitiveID()) {
397 case Type::StructTyID: {
398 const StructType *STy = cast<StructType>(SubType);
399 const StructLayout &SL = *TD.getStructLayout(STy);
400
401 unsigned i = 0, e = SL.MemberOffsets.size();
402 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
403 /* empty */;
404
405 // The offset we are looking for must be in the i'th element...
406 SubType = STy->getElementTypes()[i];
407 O += SL.MemberOffsets[i];
408 break;
409 }
410 case Type::ArrayTyID: {
411 SubType = cast<ArrayType>(SubType)->getElementType();
412 unsigned ElSize = TD.getTypeSize(SubType);
413 unsigned Remainder = (Offset-O) % ElSize;
414 O = Offset-Remainder;
415 break;
416 }
417 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000418 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000419 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000420 }
421 }
422
423 assert(O == Offset && "Could not achieve the correct offset!");
424
425 // If we found our type exactly, early exit
426 if (SubType == NewTy) return false;
427
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000428 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
429
430 // Ok, we are getting desperate now. Check for physical subtyping, where we
431 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000432 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000433 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000434 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000435 return false;
436
Chris Lattner08db7192002-11-06 06:20:27 +0000437 // Okay, so we found the leader type at the offset requested. Search the list
438 // of types that starts at this offset. If SubType is currently an array or
439 // structure, the type desired may actually be the first element of the
440 // composite type...
441 //
Chris Lattner18552922002-11-18 21:44:46 +0000442 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000443 while (SubType != NewTy) {
444 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000445 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000446 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000447 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000448 case Type::StructTyID: {
449 const StructType *STy = cast<StructType>(SubType);
450 const StructLayout &SL = *TD.getStructLayout(STy);
451 if (SL.MemberOffsets.size() > 1)
452 NextPadSize = SL.MemberOffsets[1];
453 else
454 NextPadSize = SubTypeSize;
455 NextSubType = STy->getElementTypes()[0];
456 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000457 break;
Chris Lattner18552922002-11-18 21:44:46 +0000458 }
Chris Lattner08db7192002-11-06 06:20:27 +0000459 case Type::ArrayTyID:
460 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000461 NextSubTypeSize = TD.getTypeSize(NextSubType);
462 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000463 break;
464 default: ;
465 // fall out
466 }
467
468 if (NextSubType == 0)
469 break; // In the default case, break out of the loop
470
Chris Lattner18552922002-11-18 21:44:46 +0000471 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000472 break; // Don't allow shrinking to a smaller type than NewTySize
473 SubType = NextSubType;
474 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000475 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000476 }
477
478 // If we found the type exactly, return it...
479 if (SubType == NewTy)
480 return false;
481
482 // Check to see if we have a compatible, but different type...
483 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000484 // Check to see if this type is obviously convertible... int -> uint f.e.
485 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000486 return false;
487
488 // Check to see if we have a pointer & integer mismatch going on here,
489 // loading a pointer as a long, for example.
490 //
491 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
492 NewTy->isInteger() && isa<PointerType>(SubType))
493 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000494 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
495 // We are accessing the field, plus some structure padding. Ignore the
496 // structure padding.
497 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000498 }
499
Chris Lattner58f98d02003-07-02 04:38:49 +0000500 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000501 if (getParentGraph()->getReturnNodes().size())
502 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000503 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
504 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
505 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
506 << "SubType: ";
507 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000508
Chris Lattner088b6392003-03-03 17:13:31 +0000509 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000510 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000511}
512
Chris Lattner08db7192002-11-06 06:20:27 +0000513
514
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000515// addEdgeTo - Add an edge from the current node to the specified node. This
516// can cause merging of nodes in the graph.
517//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000518void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000519 if (NH.getNode() == 0) return; // Nothing to do
520
Chris Lattner08db7192002-11-06 06:20:27 +0000521 DSNodeHandle &ExistingEdge = getLink(Offset);
522 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000523 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000524 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000525 } else { // No merging to perform...
526 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000527 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000528}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000529
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000530
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000531// MergeSortedVectors - Efficiently merge a vector into another vector where
532// duplicates are not allowed and both are sorted. This assumes that 'T's are
533// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000534//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000535static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
536 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000537 // By far, the most common cases will be the simple ones. In these cases,
538 // avoid having to allocate a temporary vector...
539 //
540 if (Src.empty()) { // Nothing to merge in...
541 return;
542 } else if (Dest.empty()) { // Just copy the result in...
543 Dest = Src;
544 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000545 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000546 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000547 std::lower_bound(Dest.begin(), Dest.end(), V);
548 if (I == Dest.end() || *I != Src[0]) // If not already contained...
549 Dest.insert(I, Src[0]);
550 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000551 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000552 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000553 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000554 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
555 if (I == Dest.end() || *I != Tmp) // If not already contained...
556 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000557
558 } else {
559 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000560 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000561
562 // Make space for all of the type entries now...
563 Dest.resize(Dest.size()+Src.size());
564
565 // Merge the two sorted ranges together... into Dest.
566 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
567
568 // Now erase any duplicate entries that may have accumulated into the
569 // vectors (because they were in both of the input sets)
570 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
571 }
572}
573
574
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000575// MergeNodes() - Helper function for DSNode::mergeWith().
576// This function does the hard work of merging two nodes, CurNodeH
577// and NH after filtering out trivial cases and making sure that
578// CurNodeH.offset >= NH.offset.
579//
580// ***WARNING***
581// Since merging may cause either node to go away, we must always
582// use the node-handles to refer to the nodes. These node handles are
583// automatically updated during merging, so will always provide access
584// to the correct node after a merge.
585//
586void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
587 assert(CurNodeH.getOffset() >= NH.getOffset() &&
588 "This should have been enforced in the caller.");
589
590 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
591 // respect to NH.Offset) is now zero. NOffset is the distance from the base
592 // of our object that N starts from.
593 //
594 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
595 unsigned NSize = NH.getNode()->getSize();
596
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000597 // If the two nodes are of different size, and the smaller node has the array
598 // bit set, collapse!
599 if (NSize != CurNodeH.getNode()->getSize()) {
600 if (NSize < CurNodeH.getNode()->getSize()) {
601 if (NH.getNode()->isArray())
602 NH.getNode()->foldNodeCompletely();
603 } else if (CurNodeH.getNode()->isArray()) {
604 NH.getNode()->foldNodeCompletely();
605 }
606 }
607
608 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000609 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000610 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000611 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000612
613 // If we are merging a node with a completely folded node, then both nodes are
614 // now completely folded.
615 //
616 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
617 if (!NH.getNode()->isNodeCompletelyFolded()) {
618 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000619 assert(NH.getNode() && NH.getOffset() == 0 &&
620 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000621 NOffset = NH.getOffset();
622 NSize = NH.getNode()->getSize();
623 assert(NOffset == 0 && NSize == 1);
624 }
625 } else if (NH.getNode()->isNodeCompletelyFolded()) {
626 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000627 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
628 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000629 NOffset = NH.getOffset();
630 NSize = NH.getNode()->getSize();
631 assert(NOffset == 0 && NSize == 1);
632 }
633
Chris Lattner72d29a42003-02-11 23:11:51 +0000634 DSNode *N = NH.getNode();
635 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000636 assert(!CurNodeH.getNode()->isDeadNode());
637
638 // Merge the NodeType information...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000639 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000640
Chris Lattner72d29a42003-02-11 23:11:51 +0000641 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000642 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000643 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000644
Chris Lattner72d29a42003-02-11 23:11:51 +0000645 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
646 //
647 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
648 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000649 if (Link.getNode()) {
650 // Compute the offset into the current node at which to
651 // merge this link. In the common case, this is a linear
652 // relation to the offset in the original node (with
653 // wrapping), but if the current node gets collapsed due to
654 // recursive merging, we must make sure to merge in all remaining
655 // links at offset zero.
656 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000657 DSNode *CN = CurNodeH.getNode();
658 if (CN->Size != 1)
659 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
660 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000661 }
662 }
663
664 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000665 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000666
667 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000668 if (!N->Globals.empty()) {
669 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000670
671 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000672 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000673 }
674}
675
676
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000677// mergeWith - Merge this node and the specified node, moving all links to and
678// from the argument node into the current node, deleting the node argument.
679// Offset indicates what offset the specified node is to be merged into the
680// current node.
681//
Chris Lattner5254a8d2004-01-22 16:31:08 +0000682// The specified node may be a null pointer (in which case, we update it to
683// point to this node).
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000684//
685void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
686 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000687 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000688 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000689
Chris Lattner5254a8d2004-01-22 16:31:08 +0000690 // If the RHS is a null node, make it point to this node!
691 if (N == 0) {
692 NH.mergeWith(DSNodeHandle(this, Offset));
693 return;
694 }
695
Chris Lattnerbd92b732003-06-19 21:15:11 +0000696 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000697 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
698
Chris Lattner02606632002-11-04 06:48:26 +0000699 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000700 // We cannot merge two pieces of the same node together, collapse the node
701 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000702 DEBUG(std::cerr << "Attempting to merge two chunks of"
703 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000704 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000705 return;
706 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000707
Chris Lattner5190ce82002-11-12 07:20:45 +0000708 // If both nodes are not at offset 0, make sure that we are merging the node
709 // at an later offset into the node with the zero offset.
710 //
711 if (Offset < NH.getOffset()) {
712 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
713 return;
714 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
715 // If the offsets are the same, merge the smaller node into the bigger node
716 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
717 return;
718 }
719
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000720 // Ok, now we can merge the two nodes. Use a static helper that works with
721 // two node handles, since "this" may get merged away at intermediate steps.
722 DSNodeHandle CurNodeH(this, Offset);
723 DSNodeHandle NHCopy(NH);
724 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000725}
726
Chris Lattner9de906c2002-10-20 22:11:44 +0000727//===----------------------------------------------------------------------===//
728// DSCallSite Implementation
729//===----------------------------------------------------------------------===//
730
Vikram S. Adve26b98262002-10-20 21:41:02 +0000731// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000732Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000733 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000734}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000735
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000736
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000737//===----------------------------------------------------------------------===//
738// DSGraph Implementation
739//===----------------------------------------------------------------------===//
740
Chris Lattnera9d65662003-06-30 05:57:30 +0000741/// getFunctionNames - Return a space separated list of the name of the
742/// functions in this graph (if any)
743std::string DSGraph::getFunctionNames() const {
744 switch (getReturnNodes().size()) {
745 case 0: return "Globals graph";
746 case 1: return getReturnNodes().begin()->first->getName();
747 default:
748 std::string Return;
749 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
750 I != getReturnNodes().end(); ++I)
751 Return += I->first->getName() + " ";
752 Return.erase(Return.end()-1, Return.end()); // Remove last space character
753 return Return;
754 }
755}
756
757
Chris Lattner15869aa2003-11-02 22:27:28 +0000758DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000759 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000760 NodeMapTy NodeMap;
761 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000762 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattner0d9bab82002-07-18 00:12:30 +0000763}
764
Chris Lattner5a540632003-06-30 03:15:25 +0000765DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +0000766 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000767 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000768 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000769 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattnereff0da92002-10-21 15:32:34 +0000770}
771
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000772DSGraph::~DSGraph() {
773 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000774 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000775 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000776 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +0000777 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000778
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000779 // Drop all intra-node references, so that assertions don't fail...
780 std::for_each(Nodes.begin(), Nodes.end(),
781 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000782
783 // Delete all of the nodes themselves...
784 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
785}
786
Chris Lattner0d9bab82002-07-18 00:12:30 +0000787// dump - Allow inspection of graph in a debugger.
788void DSGraph::dump() const { print(std::cerr); }
789
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000790
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000791/// remapLinks - Change all of the Links in the current node according to the
792/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000793///
Chris Lattner8d327672003-06-30 03:36:09 +0000794void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000795 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
796 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
797 Links[i].setNode(H.getNode());
798 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
799 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000800}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000801
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000802
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000803/// cloneReachableNodes - Clone all reachable nodes from *Node into the
804/// current graph. This is a recursive function. The map OldNodeMap is a
805/// map from the original nodes to their clones.
806///
807void DSGraph::cloneReachableNodes(const DSNode* Node,
808 unsigned BitsToClear,
809 NodeMapTy& OldNodeMap,
810 NodeMapTy& CompletedNodeMap) {
811 if (CompletedNodeMap.find(Node) != CompletedNodeMap.end())
812 return;
813
814 DSNodeHandle& NH = OldNodeMap[Node];
815 if (NH.getNode() != NULL)
816 return;
817
818 // else Node has not yet been cloned: clone it and clear the specified bits
819 NH = new DSNode(*Node, this); // enters in OldNodeMap
820 NH.getNode()->maskNodeTypes(~BitsToClear);
821
822 // now recursively clone nodes pointed to by this node
823 for (unsigned i = 0, e = Node->getNumLinks(); i != e; ++i) {
824 const DSNodeHandle &Link = Node->getLink(i << DS::PointerShift);
825 if (const DSNode* nextNode = Link.getNode())
826 cloneReachableNodes(nextNode, BitsToClear, OldNodeMap, CompletedNodeMap);
827 }
828}
829
830void DSGraph::cloneReachableSubgraph(const DSGraph& G,
831 const hash_set<const DSNode*>& RootNodes,
832 NodeMapTy& OldNodeMap,
833 NodeMapTy& CompletedNodeMap,
834 unsigned CloneFlags) {
835 if (RootNodes.empty())
836 return;
837
838 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
839 assert(&G != this && "Cannot clone graph into itself!");
840 assert((*RootNodes.begin())->getParentGraph() == &G &&
841 "Root nodes do not belong to this graph!");
842
843 // Remove alloca or mod/ref bits as specified...
844 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
845 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
846 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
847 BitsToClear |= DSNode::DEAD; // Clear dead flag...
848
849 // Clone all nodes reachable from each root node, using a recursive helper
850 for (hash_set<const DSNode*>::const_iterator I = RootNodes.begin(),
851 E = RootNodes.end(); I != E; ++I)
852 cloneReachableNodes(*I, BitsToClear, OldNodeMap, CompletedNodeMap);
853
854 // Merge the map entries in OldNodeMap and CompletedNodeMap to remap links
855 NodeMapTy MergedMap(OldNodeMap);
856 MergedMap.insert(CompletedNodeMap.begin(), CompletedNodeMap.end());
857
858 // Rewrite the links in the newly created nodes (the nodes in OldNodeMap)
859 // to point into the current graph. MergedMap gives the full mapping.
860 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
861 I->second.getNode()->remapLinks(MergedMap);
862
863 // Now merge cloned global nodes with their copies in the current graph
864 // Just look through OldNodeMap to find such nodes!
865 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
866 if (I->first->isGlobalNode()) {
867 DSNodeHandle &GClone = I->second;
868 assert(GClone.getNode() != NULL && "NULL node in OldNodeMap?");
869 const std::vector<GlobalValue*> &Globals = I->first->getGlobals();
870 for (unsigned gi = 0, ge = Globals.size(); gi != ge; ++gi) {
871 DSNodeHandle &GH = ScalarMap[Globals[gi]];
872 GH.mergeWith(GClone);
873 }
874 }
875}
876
877
878/// updateFromGlobalGraph - This function rematerializes global nodes and
879/// nodes reachable from them from the globals graph into the current graph.
880/// It invokes cloneReachableSubgraph, using the globals in the current graph
881/// as the roots. It also uses the vector InlinedGlobals to avoid cloning and
882/// merging globals that are already up-to-date in the current graph. In
883/// practice, in the TD pass, this is likely to be a large fraction of the
884/// live global nodes in each function (since most live nodes are likely to
885/// have been brought up-to-date in at _some_ caller or callee).
886///
887void DSGraph::updateFromGlobalGraph() {
888
889 // Use a map to keep track of the mapping between nodes in the globals graph
890 // and this graph for up-to-date global nodes, which do not need to be cloned.
891 NodeMapTy CompletedMap;
892
893 // Put the live, non-up-to-date global nodes into a set and the up-to-date
894 // ones in the map above, mapping node in GlobalsGraph to the up-to-date node.
895 hash_set<const DSNode*> GlobalNodeSet;
896 for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
897 E = getScalarMap().end(); I != E; ++I)
898 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
899 DSNode* GNode = I->second.getNode();
900 assert(GNode && "No node for live global in current Graph?");
901 if (const DSNode* GGNode = GlobalsGraph->ScalarMap[GV].getNode())
902 if (InlinedGlobals.count(GV) == 0) // GNode is not up-to-date
903 GlobalNodeSet.insert(GGNode);
904 else { // GNode is up-to-date
905 CompletedMap[GGNode] = I->second;
906 assert(GGNode->getNumLinks() == GNode->getNumLinks() &&
907 "Links dont match in a node that is supposed to be up-to-date?"
908 "\nremapLinks() will not work if the links don't match!");
909 }
910 }
911
912 // Clone the subgraph reachable from the vector of nodes in GlobalNodes
913 // and merge the cloned global nodes with the corresponding ones, if any.
914 NodeMapTy OldNodeMap;
915 cloneReachableSubgraph(*GlobalsGraph, GlobalNodeSet, OldNodeMap,CompletedMap);
916
917 // Merging global nodes leaves behind unused nodes: get rid of them now.
918 OldNodeMap.clear(); // remove references before dead node cleanup
919 CompletedMap.clear(); // remove references before dead node cleanup
920 removeTriviallyDeadNodes();
921}
922
Chris Lattner5a540632003-06-30 03:15:25 +0000923/// cloneInto - Clone the specified DSGraph into the current graph. The
924/// translated ScalarMap for the old function is filled into the OldValMap
925/// member, and the translated ReturnNodes map is returned into ReturnNodes.
926///
927/// The CloneFlags member controls various aspects of the cloning process.
928///
929void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
930 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
931 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000932 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000933 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000934
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000935 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000936
937 // Duplicate all of the nodes, populating the node map...
938 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000939
940 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000941 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
942 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
943 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000944 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000945 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000946 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000947 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000948 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000949 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000950 }
Chris Lattner18552922002-11-18 21:44:46 +0000951#ifndef NDEBUG
952 Timer::addPeakMemoryMeasurement();
953#endif
954
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000955 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000956 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000957 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000958
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000959 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +0000960 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000961 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000962 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000963 DSNodeHandle &H = OldValMap[I->first];
964 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
965 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +0000966
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000967 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000968 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
969 ScalarMap[GV].mergeWith(H);
970 InlinedGlobals.insert(GV);
971 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000972 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000973
Chris Lattner679e8e12002-11-08 21:27:12 +0000974 if (!(CloneFlags & DontCloneCallNodes)) {
975 // Copy the function calls list...
976 unsigned FC = FunctionCalls.size(); // FirstCall
977 FunctionCalls.reserve(FC+G.FunctionCalls.size());
978 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
979 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000980 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000981
Chris Lattneracf491f2002-11-08 22:27:09 +0000982 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +0000983 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000984 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000985 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
986 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
987 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
988 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000989
Chris Lattner5a540632003-06-30 03:15:25 +0000990 // Map the return node pointers over...
991 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
992 E = G.getReturnNodes().end(); I != E; ++I) {
993 const DSNodeHandle &Ret = I->second;
994 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
995 OldReturnNodes.insert(std::make_pair(I->first,
996 DSNodeHandle(MappedRet.getNode(),
997 MappedRet.getOffset()+Ret.getOffset())));
998 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000999}
1000
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001001/// clonePartiallyInto - Clone the reachable subset of the specified DSGraph
1002/// into the current graph, for the specified function.
1003///
1004/// This differs from cloneInto in that it only clones nodes reachable from
1005/// globals, call nodes, the scalars specified in ValBindings, and the return
1006/// value of the specified function. This method merges the the cloned
1007/// version of the scalars and return value with the specified DSNodeHandles.
1008///
1009/// On return, OldNodeMap contains a mapping from the original nodes to the
1010/// newly cloned nodes, for the subset of nodes that were actually cloned.
1011///
1012/// The CloneFlags member controls various aspects of the cloning process.
1013///
1014void DSGraph::clonePartiallyInto(const DSGraph &G, Function &F,
1015 const DSNodeHandle &RetVal,
1016 const ScalarMapTy &ValBindings,
1017 NodeMapTy &OldNodeMap,
1018 unsigned CloneFlags) {
1019
1020 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
1021 assert(&G != this && "Cannot clone graph into itself!");
1022
1023 unsigned FN = Nodes.size(); // First new node...
1024
1025 /// FIXME: This currently clones the whole graph over, instead of doing it
1026 /// incrementally. This could be sped up quite a bit further!
1027
1028 // Duplicate all of the nodes, populating the node map...
1029 Nodes.reserve(FN+G.Nodes.size());
1030
1031 // Remove alloca or mod/ref bits as specified...
1032 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1033 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1034 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1035 BitsToClear |= DSNode::DEAD; // Clear dead flag...
1036
1037 GlobalSetTy ClonedGlobals;
1038 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
1039 DSNode *Old = G.Nodes[i];
1040 DSNode *New = new DSNode(*Old, this);
1041 New->maskNodeTypes(~BitsToClear);
1042 OldNodeMap[Old] = New;
1043
1044 ClonedGlobals.insert(New->getGlobals().begin(), New->getGlobals().end());
1045 }
1046#ifndef NDEBUG
1047 Timer::addPeakMemoryMeasurement();
1048#endif
1049
1050 // Rewrite the links in the new nodes to point into the current graph now.
1051 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
1052 Nodes[i]->remapLinks(OldNodeMap);
1053
1054 // Ensure that all global nodes end up in the scalar map, as appropriate.
1055 for (GlobalSetTy::iterator CI = ClonedGlobals.begin(),
1056 E = ClonedGlobals.end(); CI != E; ++CI) {
1057 const DSNodeHandle &NGH = G.ScalarMap.find(*CI)->second;
1058
1059 DSNodeHandle &MappedNode = OldNodeMap[NGH.getNode()];
1060 DSNodeHandle H(MappedNode.getNode(),NGH.getOffset()+MappedNode.getOffset());
1061 ScalarMap[*CI].mergeWith(H);
1062 InlinedGlobals.insert(*CI);
1063 }
1064
1065 // Merge the requested portion of the scalar map with the values specified.
1066 for (ScalarMapTy::const_iterator I = ValBindings.begin(),
1067 E = ValBindings.end(); I != E; ++I) {
1068 ScalarMapTy::const_iterator SMI = G.ScalarMap.find(I->first);
1069 assert(SMI != G.ScalarMap.end() && "Cannot map non-existant scalar!");
1070
1071 DSNodeHandle &MappedNode = OldNodeMap[SMI->second.getNode()];
1072 DSNodeHandle H(MappedNode.getNode(),
1073 SMI->second.getOffset()+MappedNode.getOffset());
1074 H.mergeWith(I->second);
1075 }
1076
1077 // Map the return node pointer over.
1078 if (RetVal.getNode()) {
1079 const DSNodeHandle &Ret = G.getReturnNodeFor(F);
1080 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1081 DSNodeHandle H(MappedRet.getNode(),
1082 MappedRet.getOffset()+Ret.getOffset());
1083 H.mergeWith(RetVal);
1084 }
1085
1086 // If requested, copy the calls or aux-calls lists.
1087 if (!(CloneFlags & DontCloneCallNodes)) {
1088 // Copy the function calls list...
1089 unsigned FC = FunctionCalls.size(); // FirstCall
1090 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1091 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1092 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
1093 }
1094
1095 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1096 // Copy the auxiliary function calls list...
1097 unsigned FC = AuxFunctionCalls.size(); // FirstCall
1098 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1099 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1100 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1101 }
1102}
1103
1104
1105
1106
Chris Lattner076c1f92002-11-07 06:31:54 +00001107/// mergeInGraph - The method is used for merging graphs together. If the
1108/// argument graph is not *this, it makes a clone of the specified graph, then
1109/// merges the nodes specified in the call site with the formal arguments in the
1110/// graph.
1111///
Chris Lattner9f930552003-06-30 05:27:18 +00001112void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1113 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner076c1f92002-11-07 06:31:54 +00001114 // If this is not a recursive call, clone the graph into this graph...
1115 if (&Graph != this) {
1116 // Clone the callee's graph into the current graph, keeping
1117 // track of where scalars in the old graph _used_ to point,
1118 // and of the new nodes matching nodes of the old graph.
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001119 ScalarMapTy ValueBindings;
Chris Lattner58f98d02003-07-02 04:38:49 +00001120
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001121 // Set up argument bindings
1122 Function::aiterator AI = F.abegin();
1123 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1124 // Advance the argument iterator to the first pointer argument...
1125 while (AI != F.aend() && !isPointerType(AI->getType())) {
1126 ++AI;
Chris Lattner076c1f92002-11-07 06:31:54 +00001127#ifndef NDEBUG
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001128 if (AI == F.aend())
1129 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001130#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001131 }
1132 if (AI == F.aend()) break;
1133
1134 // Add the link from the argument scalar to the provided value.
1135 ValueBindings[AI] = CS.getPtrArg(i);
Chris Lattner076c1f92002-11-07 06:31:54 +00001136 }
1137
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001138 NodeMapTy OldNodeMap;
1139 clonePartiallyInto(Graph, F, CS.getRetVal(), ValueBindings, OldNodeMap,
1140 CloneFlags);
1141
1142 } else {
1143 DSNodeHandle RetVal = getReturnNodeFor(F);
1144 ScalarMapTy &ScalarMap = getScalarMap();
1145
1146 // Merge the return value with the return value of the context...
1147 RetVal.mergeWith(CS.getRetVal());
1148
1149 // Resolve all of the function arguments...
1150 Function::aiterator AI = F.abegin();
1151
1152 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1153 // Advance the argument iterator to the first pointer argument...
1154 while (AI != F.aend() && !isPointerType(AI->getType())) {
1155 ++AI;
1156#ifndef NDEBUG
1157 if (AI == F.aend())
1158 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1159#endif
1160 }
1161 if (AI == F.aend()) break;
1162
1163 // Add the link from the argument scalar to the provided value
1164 assert(ScalarMap.count(AI) && "Argument not in scalar map?");
1165 DSNodeHandle &NH = ScalarMap[AI];
1166 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1167 NH.mergeWith(CS.getPtrArg(i));
1168 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001169 }
1170}
1171
Chris Lattner58f98d02003-07-02 04:38:49 +00001172/// getCallSiteForArguments - Get the arguments and return value bindings for
1173/// the specified function in the current graph.
1174///
1175DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1176 std::vector<DSNodeHandle> Args;
1177
1178 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1179 if (isPointerType(I->getType()))
1180 Args.push_back(getScalarMap().find(I)->second);
1181
Chris Lattner808a7ae2003-09-20 16:34:13 +00001182 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001183}
1184
1185
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001186
Chris Lattner0d9bab82002-07-18 00:12:30 +00001187// markIncompleteNodes - Mark the specified node as having contents that are not
1188// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001189// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001190// must recursively traverse the data structure graph, marking all reachable
1191// nodes as incomplete.
1192//
1193static void markIncompleteNode(DSNode *N) {
1194 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001195 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001196
1197 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001198 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001199
Misha Brukman2f2d0652003-09-11 18:14:24 +00001200 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001201 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1202 if (DSNode *DSN = N->getLink(i).getNode())
1203 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001204}
1205
Chris Lattnere71ffc22002-11-11 03:36:55 +00001206static void markIncomplete(DSCallSite &Call) {
1207 // Then the return value is certainly incomplete!
1208 markIncompleteNode(Call.getRetVal().getNode());
1209
1210 // All objects pointed to by function arguments are incomplete!
1211 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1212 markIncompleteNode(Call.getPtrArg(i).getNode());
1213}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001214
1215// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1216// modified by other functions that have not been resolved yet. This marks
1217// nodes that are reachable through three sources of "unknownness":
1218//
1219// Global Variables, Function Calls, and Incoming Arguments
1220//
1221// For any node that may have unknown components (because something outside the
1222// scope of current analysis may have modified it), the 'Incomplete' flag is
1223// added to the NodeType.
1224//
Chris Lattner394471f2003-01-23 22:05:33 +00001225void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001226 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001227 if (Flags & DSGraph::MarkFormalArgs)
1228 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1229 FI != E; ++FI) {
1230 Function &F = *FI->first;
1231 if (F.getName() != "main")
1232 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1233 if (isPointerType(I->getType()) &&
1234 ScalarMap.find(I) != ScalarMap.end())
1235 markIncompleteNode(ScalarMap[I].getNode());
1236 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001237
1238 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001239 if (!shouldPrintAuxCalls())
1240 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1241 markIncomplete(FunctionCalls[i]);
1242 else
1243 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1244 markIncomplete(AuxFunctionCalls[i]);
1245
Chris Lattner0d9bab82002-07-18 00:12:30 +00001246
Chris Lattner93d7a212003-02-09 18:41:49 +00001247 // Mark all global nodes as incomplete...
1248 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1249 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +00001250 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +00001251 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001252}
1253
Chris Lattneraa8146f2002-11-10 06:59:55 +00001254static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1255 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001256 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001257 // No interesting info?
1258 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001259 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001260 Edge.setNode(0); // Kill the edge!
1261}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001262
Chris Lattneraa8146f2002-11-10 06:59:55 +00001263static inline bool nodeContainsExternalFunction(const DSNode *N) {
1264 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1265 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1266 if (Globals[i]->isExternal())
1267 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001268 return false;
1269}
1270
Chris Lattner5a540632003-06-30 03:15:25 +00001271static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Chris Lattner18f07a12003-07-01 16:28:11 +00001272
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001273 // Remove trivially identical function calls
1274 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001275 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1276
1277 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001278 DSNode *LastCalleeNode = 0;
1279 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001280 unsigned NumDuplicateCalls = 0;
1281 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001282 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001283 DSCallSite &CS = Calls[i];
1284
Chris Lattnere4258442002-11-11 21:35:38 +00001285 // If the Callee is a useless edge, this must be an unreachable call site,
1286 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001287 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001288 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +00001289 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +00001290 CS.swap(Calls.back());
1291 Calls.pop_back();
1292 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001293 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001294 // If the return value or any arguments point to a void node with no
1295 // information at all in it, and the call node is the only node to point
1296 // to it, remove the edge to the node (killing the node).
1297 //
1298 killIfUselessEdge(CS.getRetVal());
1299 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1300 killIfUselessEdge(CS.getPtrArg(a));
1301
1302 // If this call site calls the same function as the last call site, and if
1303 // the function pointer contains an external function, this node will
1304 // never be resolved. Merge the arguments of the call node because no
1305 // information will be lost.
1306 //
Chris Lattner923fc052003-02-05 21:59:58 +00001307 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1308 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001309 ++NumDuplicateCalls;
1310 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001311 if (LastCalleeNode)
1312 LastCalleeContainsExternalFunction =
1313 nodeContainsExternalFunction(LastCalleeNode);
1314 else
1315 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001316 }
1317
Chris Lattner58f98d02003-07-02 04:38:49 +00001318#if 1
Chris Lattnere4258442002-11-11 21:35:38 +00001319 if (LastCalleeContainsExternalFunction ||
1320 // This should be more than enough context sensitivity!
1321 // FIXME: Evaluate how many times this is tripped!
1322 NumDuplicateCalls > 20) {
1323 DSCallSite &OCS = Calls[i-1];
1324 OCS.mergeWith(CS);
1325
1326 // The node will now be eliminated as a duplicate!
1327 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1328 CS = OCS;
1329 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1330 OCS = CS;
1331 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001332#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001333 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001334 if (CS.isDirectCall()) {
1335 LastCalleeFunc = CS.getCalleeFunc();
1336 LastCalleeNode = 0;
1337 } else {
1338 LastCalleeNode = CS.getCalleeNode();
1339 LastCalleeFunc = 0;
1340 }
Chris Lattnere4258442002-11-11 21:35:38 +00001341 NumDuplicateCalls = 0;
1342 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001343 }
1344 }
1345
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001346 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001347
Chris Lattner33312f72002-11-08 01:21:07 +00001348 // Track the number of call nodes merged away...
1349 NumCallNodesMerged += NumFns-Calls.size();
1350
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001351 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001352 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001353}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001354
Chris Lattneraa8146f2002-11-10 06:59:55 +00001355
Chris Lattnere2219762002-07-18 18:22:40 +00001356// removeTriviallyDeadNodes - After the graph has been constructed, this method
1357// removes all unreachable nodes that are created because they got merged with
1358// other nodes in the graph. These nodes will all be trivially unreachable, so
1359// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001360//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001361void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner5a540632003-06-30 03:15:25 +00001362 removeIdenticalCalls(FunctionCalls);
1363 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001364
Chris Lattnerbab8c282003-09-20 21:34:07 +00001365 // Loop over all of the nodes in the graph, calling getNode on each field.
1366 // This will cause all nodes to update their forwarding edges, causing
1367 // forwarded nodes to be delete-able.
1368 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1369 DSNode *N = Nodes[i];
1370 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1371 N->getLink(l*N->getPointerSize()).getNode();
1372 }
1373
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001374 // Likewise, forward any edges from the scalar nodes. While we are at it,
1375 // clean house a bit.
1376 for (ScalarMapTy::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1377 // Check to see if this is a worthless node generated for non-pointer
1378 // values, such as integers. Consider an addition of long types: A+B.
1379 // Assuming we can track all uses of the value in this context, and it is
1380 // NOT used as a pointer, we can delete the node. We will be able to detect
1381 // this situation if the node pointed to ONLY has Unknown bit set in the
1382 // node. In this case, the node is not incomplete, does not point to any
1383 // other nodes (no mod/ref bits set), and is therefore uninteresting for
1384 // data structure analysis. If we run across one of these, prune the scalar
1385 // pointing to it.
1386 //
1387 DSNode *N = I->second.getNode();
1388 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1389 ScalarMap.erase(I++);
1390 else
1391 ++I;
1392 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001393
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001394 bool isGlobalsGraph = !GlobalsGraph;
1395
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001396 for (unsigned i = 0; i != Nodes.size(); ++i) {
1397 DSNode *Node = Nodes[i];
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001398
1399 // Do not remove *any* global nodes in the globals graph.
1400 // This is a special case because such nodes may not have I, M, R flags set.
1401 if (Node->isGlobalNode() && isGlobalsGraph)
1402 continue;
1403
Chris Lattner72d50a02003-06-28 21:58:28 +00001404 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001405 // This is a useless node if it has no mod/ref info (checked above),
1406 // outgoing edges (which it cannot, as it is not modified in this
1407 // context), and it has no incoming edges. If it is a global node it may
1408 // have all of these properties and still have incoming edges, due to the
1409 // scalar map, so we check those now.
1410 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001411 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001412 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001413
1414 // Loop through and make sure all of the globals are referring directly
1415 // to the node...
1416 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1417 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1418 assert(N == Node && "ScalarMap doesn't match globals list!");
1419 }
1420
Chris Lattnerbd92b732003-06-19 21:15:11 +00001421 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001422 if (Node->getNumReferrers() == Globals.size()) {
1423 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1424 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001425 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001426 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001427 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001428
1429#ifdef SANER_CODE_FOR_CHECKING_IF_ALL_REFERRERS_ARE_FROM_SCALARMAP
1430 //
1431 // *** It seems to me that we should be able to simply check if
1432 // *** there are fewer or equal #referrers as #globals and make
1433 // *** sure that all those referrers are in the scalar map?
1434 //
1435 if (Node->getNumReferrers() <= Node->getGlobals().size()) {
1436 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1437
1438#ifndef NDEBUG
1439 // Loop through and make sure all of the globals are referring directly
1440 // to the node...
1441 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1442 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1443 assert(N == Node && "ScalarMap doesn't match globals list!");
1444 }
1445#endif
1446
1447 // Make sure NumReferrers still agrees. The node is truly dead.
1448 assert(Node->getNumReferrers() == Globals.size());
1449 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1450 ScalarMap.erase(Globals[j]);
1451 Node->makeNodeDead();
1452 }
1453#endif
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001454 }
1455
Chris Lattnerbd92b732003-06-19 21:15:11 +00001456 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001457 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001458 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001459 Nodes[i--] = Nodes.back();
1460 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001461 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001462 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001463}
1464
1465
Chris Lattner5c7380e2003-01-29 21:10:20 +00001466/// markReachableNodes - This method recursively traverses the specified
1467/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1468/// to the set, which allows it to only traverse visited nodes once.
1469///
Chris Lattner41c04f72003-02-01 04:52:08 +00001470void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001471 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001472 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001473 if (ReachableNodes.insert(this).second) // Is newly reachable?
1474 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1475 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001476}
1477
Chris Lattner41c04f72003-02-01 04:52:08 +00001478void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001479 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001480 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001481
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001482 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1483 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001484}
1485
Chris Lattnera1220af2003-02-01 06:17:02 +00001486// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1487// looking for a node that is marked alive. If an alive node is found, return
1488// true, otherwise return false. If an alive node is reachable, this node is
1489// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001490//
Chris Lattnera1220af2003-02-01 06:17:02 +00001491static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001492 hash_set<DSNode*> &Visited,
1493 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001494 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001495 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001496
Chris Lattner85cfe012003-07-03 02:03:53 +00001497 // If this is a global node, it will end up in the globals graph anyway, so we
1498 // don't need to worry about it.
1499 if (IgnoreGlobals && N->isGlobalNode()) return false;
1500
Chris Lattneraa8146f2002-11-10 06:59:55 +00001501 // If we know that this node is alive, return so!
1502 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001503
Chris Lattneraa8146f2002-11-10 06:59:55 +00001504 // Otherwise, we don't think the node is alive yet, check for infinite
1505 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001506 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001507 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001508
Chris Lattner08db7192002-11-06 06:20:27 +00001509 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001510 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1511 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001512 N->markReachableNodes(Alive);
1513 return true;
1514 }
1515 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001516}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001517
Chris Lattnera1220af2003-02-01 06:17:02 +00001518// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1519// alive nodes.
1520//
Chris Lattner41c04f72003-02-01 04:52:08 +00001521static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001522 hash_set<DSNode*> &Visited,
1523 bool IgnoreGlobals) {
1524 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1525 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001526 return true;
1527 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001528 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001529 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001530 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001531 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1532 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001533 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001534 return false;
1535}
1536
Chris Lattnere2219762002-07-18 18:22:40 +00001537// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1538// subgraphs that are unreachable. This often occurs because the data
1539// structure doesn't "escape" into it's caller, and thus should be eliminated
1540// from the caller's graph entirely. This is only appropriate to use when
1541// inlining graphs.
1542//
Chris Lattner394471f2003-01-23 22:05:33 +00001543void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001544 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001545
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001546 // Reduce the amount of work we have to do... remove dummy nodes left over by
1547 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001548 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001549
Misha Brukman2f2d0652003-09-11 18:14:24 +00001550 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001551
1552 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001553 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001554 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001555
Chris Lattneraa8146f2002-11-10 06:59:55 +00001556 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001557 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I != E;
1558 ++I)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001559 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001560 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001561 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001562 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001563 } else {
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001564 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001565 }
Chris Lattnere2219762002-07-18 18:22:40 +00001566
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001567 // The return value is alive as well...
Chris Lattner5a540632003-06-30 03:15:25 +00001568 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1569 I != E; ++I)
1570 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001571
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001572 // Mark any nodes reachable by primary calls as alive...
1573 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1574 FunctionCalls[i].markReachableNodes(Alive);
1575
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001576 // Copy and merge all information about globals to the GlobalsGraph
1577 // if this is not a final pass (where unreachable globals are removed)
1578 NodeMapTy GlobalNodeMap;
1579 hash_set<const DSNode*> GlobalNodeSet;
1580
1581 for (std::vector<std::pair<Value*, DSNode*> >::const_iterator
1582 I = GlobalNodes.begin(), E = GlobalNodes.end(); I != E; ++I)
1583 GlobalNodeSet.insert(I->second); // put global nodes into a set
1584
1585 // Now find globals and aux call nodes that are already live or reach a live
1586 // value (which makes them live in turn), and continue till no more are found.
1587 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001588 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001589 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001590 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1591 do {
1592 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001593 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001594 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001595 // unreachable globals in the list.
1596 //
1597 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001598 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1599 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1600 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1601 Flags & DSGraph::RemoveUnreachableGlobals)) {
1602 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1603 GlobalNodes.pop_back(); // erase efficiently
1604 Iterate = true;
1605 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001606
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001607 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1608 // call nodes that get resolved will be difficult to remove from that graph.
1609 // The final unresolved call nodes must be handled specially at the end of
1610 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001611 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1612 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001613 (AuxFunctionCalls[i].isIndirectCall()
1614 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1615 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001616 AuxFunctionCalls[i].markReachableNodes(Alive);
1617 AuxFCallsAlive[i] = true;
1618 Iterate = true;
1619 }
1620 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001621
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001622 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001623 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001624 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1625 if (AuxFCallsAlive[i])
1626 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001627
1628 // Copy and merge all global nodes and dead aux call nodes into the
1629 // GlobalsGraph, and all nodes reachable from those nodes
1630 //
1631 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1632
1633 // First, add the dead aux call nodes to the set of root nodes for cloning
1634 // -- return value at this call site, if any
1635 // -- actual arguments passed at this call site
1636 // -- callee node at this call site, if this is an indirect call
1637 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i) {
1638 if (const DSNode* RetNode = AuxFunctionCalls[i].getRetVal().getNode())
1639 GlobalNodeSet.insert(RetNode);
1640 for (unsigned j=0, N=AuxFunctionCalls[i].getNumPtrArgs(); j < N; ++j)
1641 if (const DSNode* ArgTarget=AuxFunctionCalls[i].getPtrArg(j).getNode())
1642 GlobalNodeSet.insert(ArgTarget);
1643 if (AuxFunctionCalls[i].isIndirectCall())
1644 GlobalNodeSet.insert(AuxFunctionCalls[i].getCalleeNode());
1645 }
1646
1647 // There are no "pre-completed" nodes so use any empty map for those.
1648 // Strip all alloca bits since the current function is only for the BU pass.
1649 // Strip all incomplete bits since they are short-lived properties and they
1650 // will be correctly computed when rematerializing nodes into the functions.
1651 //
1652 NodeMapTy CompletedMap;
1653 GlobalsGraph->cloneReachableSubgraph(*this, GlobalNodeSet,
1654 GlobalNodeMap, CompletedMap,
1655 (DSGraph::StripAllocaBit |
1656 DSGraph::StripIncompleteBit));
1657 }
1658
1659 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001660 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001661 assert(GlobalsGraph && "No globals graph available??");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001662
1663 // Copy the unreachable call nodes to the globals graph, updating
1664 // their target pointers using the GlobalNodeMap
1665 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1666 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1667 GlobalNodeMap));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001668 }
1669 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001670 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1671 AuxFunctionCalls.end());
1672
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001673 // We are finally done with the GlobalNodeMap so we can clear it and
1674 // then get rid of unused nodes in the GlobalsGraph produced by merging.
1675 GlobalNodeMap.clear();
1676 GlobalsGraph->removeTriviallyDeadNodes();
1677
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001678 // At this point, any nodes which are visited, but not alive, are nodes
1679 // which can be removed. Loop over all nodes, eliminating completely
1680 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001681 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001682 std::vector<DSNode*> DeadNodes;
1683 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001684 for (unsigned i = 0; i != Nodes.size(); ++i)
1685 if (!Alive.count(Nodes[i])) {
1686 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001687 Nodes[i--] = Nodes.back(); // move node to end of vector
1688 Nodes.pop_back(); // Erase node from alive list.
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001689 DeadNodes.push_back(N);
1690 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001691 } else {
1692 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001693 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001694
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001695 // Remove all unreachable globals from the ScalarMap.
1696 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1697 // In either case, the dead nodes will not be in the set Alive.
1698 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1699 assert(((Flags & DSGraph::RemoveUnreachableGlobals) ||
1700 !Alive.count(GlobalNodes[i].second)) && "huh? non-dead global");
1701 if (!Alive.count(GlobalNodes[i].second))
1702 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001703 }
1704
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001705 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001706 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1707 delete DeadNodes[i];
1708
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001709 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001710}
1711
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001712void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001713 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1714 Nodes[i]->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001715
Chris Lattner8d327672003-06-30 03:36:09 +00001716 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001717 E = ScalarMap.end(); I != E; ++I) {
1718 assert(I->second.getNode() && "Null node in scalarmap!");
1719 AssertNodeInGraph(I->second.getNode());
1720 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001721 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001722 "Global points to node, but node isn't global?");
1723 AssertNodeContainsGlobal(I->second.getNode(), GV);
1724 }
1725 }
1726 AssertCallNodesInGraph();
1727 AssertAuxCallNodesInGraph();
1728}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001729
Chris Lattner7ddb0132003-08-05 18:38:37 +00001730/// mergeInGlobalsGraph - This method is useful for clients to incorporate the
1731/// globals graph into the DS, BU or TD graph for a function. This code retains
1732/// all globals, i.e., does not delete unreachable globals after they are
1733/// inlined.
1734///
1735void DSGraph::mergeInGlobalsGraph() {
Sumant Kowshik108421a2003-08-05 17:04:41 +00001736 NodeMapTy GlobalNodeMap;
1737 ScalarMapTy OldValMap;
1738 ReturnNodesTy OldRetNodes;
Chris Lattner7ddb0132003-08-05 18:38:37 +00001739 cloneInto(*GlobalsGraph, OldValMap, OldRetNodes, GlobalNodeMap,
1740 DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes |
1741 DSGraph::DontCloneAuxCallNodes);
Sumant Kowshik108421a2003-08-05 17:04:41 +00001742
1743 // Now merge existing global nodes in the GlobalsGraph with their copies
1744 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1745 I != E; ++I)
1746 if (isa<GlobalValue>(I->first)) { // Found a global node
1747 DSNodeHandle &GH = I->second;
1748 DSNodeHandle &GGNodeH = GlobalsGraph->getScalarMap()[I->first];
1749 GH.mergeWith(GlobalNodeMap[GGNodeH.getNode()]);
1750 }
1751
1752 // Merging leaves behind unused nodes: get rid of them now.
1753 GlobalNodeMap.clear();
1754 OldValMap.clear();
1755 OldRetNodes.clear();
1756 removeTriviallyDeadNodes();
1757}
Chris Lattner400433d2003-11-11 05:08:59 +00001758
Brian Gaeked0fde302003-11-11 22:41:34 +00001759
Chris Lattner400433d2003-11-11 05:08:59 +00001760/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1761/// nodes reachable from the two graphs, computing the mapping of nodes from
1762/// the first to the second graph.
1763///
1764void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001765 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1766 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001767 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1768 if (N1 == 0 || N2 == 0) return;
1769
1770 DSNodeHandle &Entry = NodeMap[N1];
1771 if (Entry.getNode()) {
1772 // Termination of recursion!
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001773 assert(!StrictChecking ||
1774 (Entry.getNode() == N2 &&
1775 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
Chris Lattner400433d2003-11-11 05:08:59 +00001776 "Inconsistent mapping detected!");
1777 return;
1778 }
1779
1780 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001781 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001782
1783 // Loop over all of the fields that N1 and N2 have in common, recursively
1784 // mapping the edges together now.
1785 int N2Idx = NH2.getOffset()-NH1.getOffset();
1786 unsigned N2Size = N2->getSize();
1787 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1788 if (unsigned(N2Idx)+i < N2Size)
1789 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1790}