blob: 5cb6af6b194e79db81b666b09da1db358a05bd93 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00009//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner4dabb2c2004-07-07 06:32:21 +000014#include "llvm/Analysis/DataStructure/DSGraphTraits.h"
Chris Lattner94f84702005-03-17 19:56:56 +000015#include "llvm/Constants.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000016#include "llvm/Function.h"
Chris Lattnercf14e712004-02-25 23:36:08 +000017#include "llvm/GlobalVariable.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000019#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000020#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000021#include "llvm/Assembly/Writer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000022#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/ADT/DepthFirstIterator.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000028#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattnerb29dd0f2004-12-08 21:03:56 +000031#define COLLAPSE_ARRAYS_AGGRESSIVELY 0
32
Chris Lattner08db7192002-11-06 06:20:27 +000033namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000034 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
35 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
36 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
37 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000038 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
39 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Chris Lattner08db7192002-11-06 06:20:27 +000040};
41
Chris Lattnera88a55c2004-01-28 02:41:32 +000042#if 1
Chris Lattner93ddd7e2004-01-22 16:36:28 +000043#define TIME_REGION(VARNAME, DESC) \
44 NamedRegionTimer VARNAME(DESC)
45#else
46#define TIME_REGION(VARNAME, DESC)
47#endif
48
Chris Lattnerb1060432002-11-07 05:20:53 +000049using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000050
Chris Lattner6f967742004-10-30 04:05:01 +000051/// isForwarding - Return true if this NodeHandle is forwarding to another
52/// one.
53bool DSNodeHandle::isForwarding() const {
54 return N && N->isForwarding();
55}
56
Chris Lattner731b2d72003-02-13 19:09:00 +000057DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000058 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000059
60 // Handle node forwarding here!
61 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
62 Offset += N->ForwardNH.getOffset();
63
64 if (--N->NumReferrers == 0) {
65 // Removing the last referrer to the node, sever the forwarding link
66 N->stopForwarding();
67 }
68
69 N = Next;
70 N->NumReferrers++;
71 if (N->Size <= Offset) {
72 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
73 Offset = 0;
74 }
75 return N;
76}
77
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000078//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000079// DSNode Implementation
80//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000081
Chris Lattnerbd92b732003-06-19 21:15:11 +000082DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000083 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000084 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000085 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +000086 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000087 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000088}
89
Chris Lattner0d9bab82002-07-18 00:12:30 +000090// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +000091DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +000092 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattnerf590ced2004-03-04 17:06:53 +000093 Ty(N.Ty), NodeType(N.NodeType) {
94 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +000095 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +000096 Globals = N.Globals;
97 } else
Chris Lattner0b144872004-01-27 22:03:40 +000098 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +000099 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000100 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000101}
102
Chris Lattner15869aa2003-11-02 22:27:28 +0000103/// getTargetData - Get the target data object used to construct this node.
104///
105const TargetData &DSNode::getTargetData() const {
106 return ParentGraph->getTargetData();
107}
108
Chris Lattner72d29a42003-02-11 23:11:51 +0000109void DSNode::assertOK() const {
110 assert((Ty != Type::VoidTy ||
111 Ty == Type::VoidTy && (Size == 0 ||
112 (NodeType & DSNode::Array))) &&
113 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000114
115 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000116 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000117 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000118 assert(SM.global_count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000119 assert(SM.find(Globals[i])->second.getNode() == this);
120 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000121}
122
123/// forwardNode - Mark this node as being obsolete, and all references to it
124/// should be forwarded to the specified node and offset.
125///
126void DSNode::forwardNode(DSNode *To, unsigned Offset) {
127 assert(this != To && "Cannot forward a node to itself!");
128 assert(ForwardNH.isNull() && "Already forwarding from this node!");
129 if (To->Size <= 1) Offset = 0;
130 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
131 "Forwarded offset is wrong!");
Chris Lattnerefffdc92004-07-07 06:12:52 +0000132 ForwardNH.setTo(To, Offset);
Chris Lattner72d29a42003-02-11 23:11:51 +0000133 NodeType = DEAD;
134 Size = 0;
135 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000136
137 // Remove this node from the parent graph's Nodes list.
138 ParentGraph->unlinkNode(this);
139 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000140}
141
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000142// addGlobal - Add an entry for a global value to the Globals list. This also
143// marks the node with the 'G' flag if it does not already have it.
144//
145void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000146 // First, check to make sure this is the leader if the global is in an
147 // equivalence class.
148 GV = getParentGraph()->getScalarMap().getLeaderForGlobal(GV);
149
Chris Lattner0d9bab82002-07-18 00:12:30 +0000150 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000151 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000152 std::lower_bound(Globals.begin(), Globals.end(), GV);
153
154 if (I == Globals.end() || *I != GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000155 Globals.insert(I, GV);
156 NodeType |= GlobalNode;
157 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000158}
159
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000160/// foldNodeCompletely - If we determine that this node has some funny
161/// behavior happening to it that we cannot represent, we fold it down to a
162/// single, completely pessimistic, node. This node is represented as a
163/// single byte with a single TypeEntry of "void".
164///
165void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000166 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000167
Chris Lattner08db7192002-11-06 06:20:27 +0000168 ++NumFolds;
169
Chris Lattner0b144872004-01-27 22:03:40 +0000170 // If this node has a size that is <= 1, we don't need to create a forwarding
171 // node.
172 if (getSize() <= 1) {
173 NodeType |= DSNode::Array;
174 Ty = Type::VoidTy;
175 Size = 1;
176 assert(Links.size() <= 1 && "Size is 1, but has more links?");
177 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000178 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000179 // Create the node we are going to forward to. This is required because
180 // some referrers may have an offset that is > 0. By forcing them to
181 // forward, the forwarder has the opportunity to correct the offset.
182 DSNode *DestNode = new DSNode(0, ParentGraph);
183 DestNode->NodeType = NodeType|DSNode::Array;
184 DestNode->Ty = Type::VoidTy;
185 DestNode->Size = 1;
186 DestNode->Globals.swap(Globals);
187
188 // Start forwarding to the destination node...
189 forwardNode(DestNode, 0);
190
191 if (!Links.empty()) {
192 DestNode->Links.reserve(1);
193
194 DSNodeHandle NH(DestNode);
195 DestNode->Links.push_back(Links[0]);
196
197 // If we have links, merge all of our outgoing links together...
198 for (unsigned i = Links.size()-1; i != 0; --i)
199 NH.getNode()->Links[0].mergeWith(Links[i]);
200 Links.clear();
201 } else {
202 DestNode->Links.resize(1);
203 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000204 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000205}
Chris Lattner076c1f92002-11-07 06:31:54 +0000206
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000207/// isNodeCompletelyFolded - Return true if this node has been completely
208/// folded down to something that can never be expanded, effectively losing
209/// all of the field sensitivity that may be present in the node.
210///
211bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000212 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000213}
214
Chris Lattner82c6c722005-03-20 02:41:38 +0000215/// addFullGlobalsList - Compute the full set of global values that are
216/// represented by this node. Unlike getGlobalsList(), this requires fair
217/// amount of work to compute, so don't treat this method call as free.
218void DSNode::addFullGlobalsList(std::vector<GlobalValue*> &List) const {
219 if (globals_begin() == globals_end()) return;
220
221 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
222
223 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
224 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
225 if (ECI == EC.end())
226 List.push_back(*I);
227 else
228 List.insert(List.end(), EC.member_begin(ECI), EC.member_end());
229 }
230}
231
232/// addFullFunctionList - Identical to addFullGlobalsList, but only return the
233/// functions in the full list.
234void DSNode::addFullFunctionList(std::vector<Function*> &List) const {
235 if (globals_begin() == globals_end()) return;
236
237 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
238
239 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
240 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
241 if (ECI == EC.end()) {
242 if (Function *F = dyn_cast<Function>(*I))
243 List.push_back(F);
244 } else {
245 for (EquivalenceClasses<GlobalValue*>::member_iterator MI =
246 EC.member_begin(ECI), E = EC.member_end(); MI != E; ++MI)
247 if (Function *F = dyn_cast<Function>(*MI))
248 List.push_back(F);
249 }
250 }
251}
252
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000253namespace {
254 /// TypeElementWalker Class - Used for implementation of physical subtyping...
255 ///
256 class TypeElementWalker {
257 struct StackState {
258 const Type *Ty;
259 unsigned Offset;
260 unsigned Idx;
261 StackState(const Type *T, unsigned Off = 0)
262 : Ty(T), Offset(Off), Idx(0) {}
263 };
264
265 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000266 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000267 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000268 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000269 Stack.push_back(T);
270 StepToLeaf();
271 }
272
273 bool isDone() const { return Stack.empty(); }
274 const Type *getCurrentType() const { return Stack.back().Ty; }
275 unsigned getCurrentOffset() const { return Stack.back().Offset; }
276
277 void StepToNextType() {
278 PopStackAndAdvance();
279 StepToLeaf();
280 }
281
282 private:
283 /// PopStackAndAdvance - Pop the current element off of the stack and
284 /// advance the underlying element to the next contained member.
285 void PopStackAndAdvance() {
286 assert(!Stack.empty() && "Cannot pop an empty stack!");
287 Stack.pop_back();
288 while (!Stack.empty()) {
289 StackState &SS = Stack.back();
290 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
291 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000292 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000293 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattner507bdf92005-01-12 04:51:37 +0000294 SS.Offset +=
295 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000296 return;
297 }
298 Stack.pop_back(); // At the end of the structure
299 } else {
300 const ArrayType *AT = cast<ArrayType>(SS.Ty);
301 ++SS.Idx;
302 if (SS.Idx != AT->getNumElements()) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000303 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000304 return;
305 }
306 Stack.pop_back(); // At the end of the array
307 }
308 }
309 }
310
311 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
312 /// on the type stack.
313 void StepToLeaf() {
314 if (Stack.empty()) return;
315 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
316 StackState &SS = Stack.back();
317 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000318 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000319 assert(SS.Idx == 0);
320 PopStackAndAdvance();
321 } else {
322 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000323 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000324 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000325 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner507bdf92005-01-12 04:51:37 +0000326 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000327 }
328 } else {
329 const ArrayType *AT = cast<ArrayType>(SS.Ty);
330 if (AT->getNumElements() == 0) {
331 assert(SS.Idx == 0);
332 PopStackAndAdvance();
333 } else {
334 // Step into the array...
335 assert(SS.Idx < AT->getNumElements());
336 Stack.push_back(StackState(AT->getElementType(),
337 SS.Offset+SS.Idx*
Chris Lattner507bdf92005-01-12 04:51:37 +0000338 unsigned(TD.getTypeSize(AT->getElementType()))));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000339 }
340 }
341 }
342 }
343 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000344} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000345
346/// ElementTypesAreCompatible - Check to see if the specified types are
347/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000348/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
349/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000350///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000351static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000352 bool AllowLargerT1, const TargetData &TD){
353 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000354
355 while (!T1W.isDone() && !T2W.isDone()) {
356 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
357 return false;
358
359 const Type *T1 = T1W.getCurrentType();
360 const Type *T2 = T2W.getCurrentType();
361 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
362 return false;
363
364 T1W.StepToNextType();
365 T2W.StepToNextType();
366 }
367
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000368 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000369}
370
371
Chris Lattner08db7192002-11-06 06:20:27 +0000372/// mergeTypeInfo - This method merges the specified type into the current node
373/// at the specified offset. This may update the current node's type record if
374/// this gives more information to the node, it may do nothing to the node if
375/// this information is already known, or it may merge the node completely (and
376/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000377///
Chris Lattner08db7192002-11-06 06:20:27 +0000378/// This method returns true if the node is completely folded, otherwise false.
379///
Chris Lattner088b6392003-03-03 17:13:31 +0000380bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
381 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000382 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000383 // Check to make sure the Size member is up-to-date. Size can be one of the
384 // following:
385 // Size = 0, Ty = Void: Nothing is known about this node.
386 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
387 // Size = 1, Ty = Void, Array = 1: The node is collapsed
388 // Otherwise, sizeof(Ty) = Size
389 //
Chris Lattner18552922002-11-18 21:44:46 +0000390 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
391 (Size == 0 && !Ty->isSized() && !isArray()) ||
392 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
393 (Size == 0 && !Ty->isSized() && !isArray()) ||
394 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000395 "Size member of DSNode doesn't match the type structure!");
396 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000397
Chris Lattner18552922002-11-18 21:44:46 +0000398 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000399 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000400
Chris Lattner08db7192002-11-06 06:20:27 +0000401 // Return true immediately if the node is completely folded.
402 if (isNodeCompletelyFolded()) return true;
403
Chris Lattner23f83dc2002-11-08 22:49:57 +0000404 // If this is an array type, eliminate the outside arrays because they won't
405 // be used anyway. This greatly reduces the size of large static arrays used
406 // as global variables, for example.
407 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000408 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000409 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
410 // FIXME: we might want to keep small arrays, but must be careful about
411 // things like: [2 x [10000 x int*]]
412 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000413 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000414 }
415
Chris Lattner08db7192002-11-06 06:20:27 +0000416 // Figure out how big the new type we're merging in is...
Chris Lattner507bdf92005-01-12 04:51:37 +0000417 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000418
419 // Otherwise check to see if we can fold this type into the current node. If
420 // we can't, we fold the node completely, if we can, we potentially update our
421 // internal state.
422 //
Chris Lattner18552922002-11-18 21:44:46 +0000423 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000424 // If this is the first type that this node has seen, just accept it without
425 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000426 assert(Offset == 0 && !isArray() &&
427 "Cannot have an offset into a void node!");
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000428
429 // If this node would have to have an unreasonable number of fields, just
430 // collapse it. This can occur for fortran common blocks, which have stupid
431 // things like { [100000000 x double], [1000000 x double] }.
432 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
433 if (NumFields > 64) {
434 foldNodeCompletely();
435 return true;
436 }
437
Chris Lattner18552922002-11-18 21:44:46 +0000438 Ty = NewTy;
439 NodeType &= ~Array;
440 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000441 Size = NewTySize;
442
443 // Calculate the number of outgoing links from this node.
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000444 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000445 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000446 }
Chris Lattner08db7192002-11-06 06:20:27 +0000447
448 // Handle node expansion case here...
449 if (Offset+NewTySize > Size) {
450 // It is illegal to grow this node if we have treated it as an array of
451 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000452 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000453 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000454 return true;
455 }
456
457 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000458 std::cerr << "UNIMP: Trying to merge a growth type into "
459 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000460 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000461 return true;
462 }
463
464 // Okay, the situation is nice and simple, we are trying to merge a type in
465 // at offset 0 that is bigger than our current type. Implement this by
466 // switching to the new type and then merge in the smaller one, which should
467 // hit the other code path here. If the other code path decides it's not
468 // ok, it will collapse the node as appropriate.
469 //
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000470
471 // If this node would have to have an unreasonable number of fields, just
472 // collapse it. This can occur for fortran common blocks, which have stupid
473 // things like { [100000000 x double], [1000000 x double] }.
474 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
475 if (NumFields > 64) {
476 foldNodeCompletely();
477 return true;
478 }
479
Chris Lattner94f84702005-03-17 19:56:56 +0000480 const Type *OldTy = Ty;
481 Ty = NewTy;
482 NodeType &= ~Array;
483 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000484 Size = NewTySize;
485
486 // Must grow links to be the appropriate size...
Chris Lattner94f84702005-03-17 19:56:56 +0000487 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000488
489 // Merge in the old type now... which is guaranteed to be smaller than the
490 // "current" type.
491 return mergeTypeInfo(OldTy, 0);
492 }
493
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000494 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000495 "Cannot merge something into a part of our type that doesn't exist!");
496
Chris Lattner18552922002-11-18 21:44:46 +0000497 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000498 // type that starts at offset Offset.
499 //
500 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000501 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000502 while (O < Offset) {
503 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
504
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000505 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000506 case Type::StructTyID: {
507 const StructType *STy = cast<StructType>(SubType);
508 const StructLayout &SL = *TD.getStructLayout(STy);
Chris Lattner2787e032005-03-13 19:05:05 +0000509 unsigned i = SL.getElementContainingOffset(Offset-O);
Chris Lattner08db7192002-11-06 06:20:27 +0000510
511 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000512 SubType = STy->getElementType(i);
Chris Lattner507bdf92005-01-12 04:51:37 +0000513 O += (unsigned)SL.MemberOffsets[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000514 break;
515 }
516 case Type::ArrayTyID: {
517 SubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000518 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000519 unsigned Remainder = (Offset-O) % ElSize;
520 O = Offset-Remainder;
521 break;
522 }
523 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000524 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000525 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000526 }
527 }
528
529 assert(O == Offset && "Could not achieve the correct offset!");
530
531 // If we found our type exactly, early exit
532 if (SubType == NewTy) return false;
533
Misha Brukman96a8bd72004-04-29 04:05:30 +0000534 // Differing function types don't require us to merge. They are not values
535 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000536 if (isa<FunctionType>(SubType) &&
537 isa<FunctionType>(NewTy)) return false;
538
Chris Lattner507bdf92005-01-12 04:51:37 +0000539 unsigned SubTypeSize = SubType->isSized() ?
540 (unsigned)TD.getTypeSize(SubType) : 0;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000541
542 // Ok, we are getting desperate now. Check for physical subtyping, where we
543 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000544 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000545 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000546 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000547 return false;
548
Chris Lattner08db7192002-11-06 06:20:27 +0000549 // Okay, so we found the leader type at the offset requested. Search the list
550 // of types that starts at this offset. If SubType is currently an array or
551 // structure, the type desired may actually be the first element of the
552 // composite type...
553 //
Chris Lattner18552922002-11-18 21:44:46 +0000554 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000555 while (SubType != NewTy) {
556 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000557 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000558 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000559 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000560 case Type::StructTyID: {
561 const StructType *STy = cast<StructType>(SubType);
562 const StructLayout &SL = *TD.getStructLayout(STy);
563 if (SL.MemberOffsets.size() > 1)
Chris Lattner507bdf92005-01-12 04:51:37 +0000564 NextPadSize = (unsigned)SL.MemberOffsets[1];
Chris Lattner18552922002-11-18 21:44:46 +0000565 else
566 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000567 NextSubType = STy->getElementType(0);
Chris Lattner507bdf92005-01-12 04:51:37 +0000568 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000569 break;
Chris Lattner18552922002-11-18 21:44:46 +0000570 }
Chris Lattner08db7192002-11-06 06:20:27 +0000571 case Type::ArrayTyID:
572 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000573 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner18552922002-11-18 21:44:46 +0000574 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000575 break;
576 default: ;
577 // fall out
578 }
579
580 if (NextSubType == 0)
581 break; // In the default case, break out of the loop
582
Chris Lattner18552922002-11-18 21:44:46 +0000583 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000584 break; // Don't allow shrinking to a smaller type than NewTySize
585 SubType = NextSubType;
586 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000587 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000588 }
589
590 // If we found the type exactly, return it...
591 if (SubType == NewTy)
592 return false;
593
594 // Check to see if we have a compatible, but different type...
595 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000596 // Check to see if this type is obviously convertible... int -> uint f.e.
597 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000598 return false;
599
600 // Check to see if we have a pointer & integer mismatch going on here,
601 // loading a pointer as a long, for example.
602 //
603 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
604 NewTy->isInteger() && isa<PointerType>(SubType))
605 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000606 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
607 // We are accessing the field, plus some structure padding. Ignore the
608 // structure padding.
609 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000610 }
611
Chris Lattner58f98d02003-07-02 04:38:49 +0000612 Module *M = 0;
Chris Lattnera5f47ea2005-03-15 16:55:04 +0000613 if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
614 M = getParentGraph()->retnodes_begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000615 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
616 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
617 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
618 << "SubType: ";
619 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000620
Chris Lattner088b6392003-03-03 17:13:31 +0000621 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000622 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000623}
624
Chris Lattner08db7192002-11-06 06:20:27 +0000625
626
Misha Brukman96a8bd72004-04-29 04:05:30 +0000627/// addEdgeTo - Add an edge from the current node to the specified node. This
628/// can cause merging of nodes in the graph.
629///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000630void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000631 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000632
Chris Lattner08db7192002-11-06 06:20:27 +0000633 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000634 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000635 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000636 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000637 } else { // No merging to perform...
638 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000639 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000640}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000641
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000642
Misha Brukman96a8bd72004-04-29 04:05:30 +0000643/// MergeSortedVectors - Efficiently merge a vector into another vector where
644/// duplicates are not allowed and both are sorted. This assumes that 'T's are
645/// efficiently copyable and have sane comparison semantics.
646///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000647static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
648 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000649 // By far, the most common cases will be the simple ones. In these cases,
650 // avoid having to allocate a temporary vector...
651 //
652 if (Src.empty()) { // Nothing to merge in...
653 return;
654 } else if (Dest.empty()) { // Just copy the result in...
655 Dest = Src;
656 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000657 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000658 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000659 std::lower_bound(Dest.begin(), Dest.end(), V);
660 if (I == Dest.end() || *I != Src[0]) // If not already contained...
661 Dest.insert(I, Src[0]);
662 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000663 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000664 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000665 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000666 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
667 if (I == Dest.end() || *I != Tmp) // If not already contained...
668 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000669
670 } else {
671 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000672 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000673
674 // Make space for all of the type entries now...
675 Dest.resize(Dest.size()+Src.size());
676
677 // Merge the two sorted ranges together... into Dest.
678 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
679
680 // Now erase any duplicate entries that may have accumulated into the
681 // vectors (because they were in both of the input sets)
682 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
683 }
684}
685
Chris Lattner0b144872004-01-27 22:03:40 +0000686void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
687 MergeSortedVectors(Globals, RHS);
688}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000689
Chris Lattner0b144872004-01-27 22:03:40 +0000690// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000691// This function does the hard work of merging two nodes, CurNodeH
692// and NH after filtering out trivial cases and making sure that
693// CurNodeH.offset >= NH.offset.
694//
695// ***WARNING***
696// Since merging may cause either node to go away, we must always
697// use the node-handles to refer to the nodes. These node handles are
698// automatically updated during merging, so will always provide access
699// to the correct node after a merge.
700//
701void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
702 assert(CurNodeH.getOffset() >= NH.getOffset() &&
703 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000704 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
705 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000706
707 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
708 // respect to NH.Offset) is now zero. NOffset is the distance from the base
709 // of our object that N starts from.
710 //
711 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
712 unsigned NSize = NH.getNode()->getSize();
713
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000714 // If the two nodes are of different size, and the smaller node has the array
715 // bit set, collapse!
716 if (NSize != CurNodeH.getNode()->getSize()) {
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000717#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000718 if (NSize < CurNodeH.getNode()->getSize()) {
719 if (NH.getNode()->isArray())
720 NH.getNode()->foldNodeCompletely();
721 } else if (CurNodeH.getNode()->isArray()) {
722 NH.getNode()->foldNodeCompletely();
723 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000724#endif
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000725 }
726
727 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000728 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000729 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000730 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000731
732 // If we are merging a node with a completely folded node, then both nodes are
733 // now completely folded.
734 //
735 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
736 if (!NH.getNode()->isNodeCompletelyFolded()) {
737 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000738 assert(NH.getNode() && NH.getOffset() == 0 &&
739 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000740 NOffset = NH.getOffset();
741 NSize = NH.getNode()->getSize();
742 assert(NOffset == 0 && NSize == 1);
743 }
744 } else if (NH.getNode()->isNodeCompletelyFolded()) {
745 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000746 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
747 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000748 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000749 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000750 assert(NOffset == 0 && NSize == 1);
751 }
752
Chris Lattner72d29a42003-02-11 23:11:51 +0000753 DSNode *N = NH.getNode();
754 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000755 assert(!CurNodeH.getNode()->isDeadNode());
756
Chris Lattner0b144872004-01-27 22:03:40 +0000757 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000758 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000759
Chris Lattner72d29a42003-02-11 23:11:51 +0000760 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000761 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000762 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000763
Chris Lattner72d29a42003-02-11 23:11:51 +0000764 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
765 //
766 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
767 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000768 if (Link.getNode()) {
769 // Compute the offset into the current node at which to
770 // merge this link. In the common case, this is a linear
771 // relation to the offset in the original node (with
772 // wrapping), but if the current node gets collapsed due to
773 // recursive merging, we must make sure to merge in all remaining
774 // links at offset zero.
775 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000776 DSNode *CN = CurNodeH.getNode();
777 if (CN->Size != 1)
778 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
779 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000780 }
781 }
782
783 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000784 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000785
786 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000787 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000788 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000789
790 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000791 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000792 }
793}
794
795
Misha Brukman96a8bd72004-04-29 04:05:30 +0000796/// mergeWith - Merge this node and the specified node, moving all links to and
797/// from the argument node into the current node, deleting the node argument.
798/// Offset indicates what offset the specified node is to be merged into the
799/// current node.
800///
801/// The specified node may be a null pointer (in which case, we update it to
802/// point to this node).
803///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000804void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
805 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000806 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000807 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000808
Chris Lattner5254a8d2004-01-22 16:31:08 +0000809 // If the RHS is a null node, make it point to this node!
810 if (N == 0) {
811 NH.mergeWith(DSNodeHandle(this, Offset));
812 return;
813 }
814
Chris Lattnerbd92b732003-06-19 21:15:11 +0000815 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000816 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
817
Chris Lattner02606632002-11-04 06:48:26 +0000818 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000819 // We cannot merge two pieces of the same node together, collapse the node
820 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000821 DEBUG(std::cerr << "Attempting to merge two chunks of"
822 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000823 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000824 return;
825 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000826
Chris Lattner5190ce82002-11-12 07:20:45 +0000827 // If both nodes are not at offset 0, make sure that we are merging the node
828 // at an later offset into the node with the zero offset.
829 //
830 if (Offset < NH.getOffset()) {
831 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
832 return;
833 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
834 // If the offsets are the same, merge the smaller node into the bigger node
835 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
836 return;
837 }
838
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000839 // Ok, now we can merge the two nodes. Use a static helper that works with
840 // two node handles, since "this" may get merged away at intermediate steps.
841 DSNodeHandle CurNodeH(this, Offset);
842 DSNodeHandle NHCopy(NH);
843 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000844}
845
Chris Lattner0b144872004-01-27 22:03:40 +0000846
847//===----------------------------------------------------------------------===//
848// ReachabilityCloner Implementation
849//===----------------------------------------------------------------------===//
850
851DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
852 if (SrcNH.isNull()) return DSNodeHandle();
853 const DSNode *SN = SrcNH.getNode();
854
855 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000856 if (!NH.isNull()) { // Node already mapped?
857 DSNode *NHN = NH.getNode();
858 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
859 }
Chris Lattner0b144872004-01-27 22:03:40 +0000860
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000861 // If SrcNH has globals and the destination graph has one of the same globals,
862 // merge this node with the destination node, which is much more efficient.
Chris Lattner82c6c722005-03-20 02:41:38 +0000863 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000864 DSScalarMap &DestSM = Dest.getScalarMap();
Chris Lattner82c6c722005-03-20 02:41:38 +0000865 for (DSNode::globals_iterator I = SN->globals_begin(),E = SN->globals_end();
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000866 I != E; ++I) {
867 GlobalValue *GV = *I;
868 DSScalarMap::iterator GI = DestSM.find(GV);
869 if (GI != DestSM.end() && !GI->second.isNull()) {
870 // We found one, use merge instead!
871 merge(GI->second, Src.getNodeForValue(GV));
872 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000873 DSNode *NHN = NH.getNode();
874 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000875 }
876 }
877 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000878
Chris Lattner0b144872004-01-27 22:03:40 +0000879 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
880 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000881 NH = DN;
Chris Lattner0b144872004-01-27 22:03:40 +0000882
883 // Next, recursively clone all outgoing links as necessary. Note that
884 // adding these links can cause the node to collapse itself at any time, and
885 // the current node may be merged with arbitrary other nodes. For this
886 // reason, we must always go through NH.
887 DN = 0;
888 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
889 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
890 if (!SrcEdge.isNull()) {
891 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
892 // Compute the offset into the current node at which to
893 // merge this link. In the common case, this is a linear
894 // relation to the offset in the original node (with
895 // wrapping), but if the current node gets collapsed due to
896 // recursive merging, we must make sure to merge in all remaining
897 // links at offset zero.
898 unsigned MergeOffset = 0;
899 DSNode *CN = NH.getNode();
900 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +0000901 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +0000902 CN->addEdgeTo(MergeOffset, DestEdge);
903 }
904 }
905
906 // If this node contains any globals, make sure they end up in the scalar
907 // map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +0000908 for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
Chris Lattner0b144872004-01-27 22:03:40 +0000909 I != E; ++I) {
910 GlobalValue *GV = *I;
911 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
912 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
913 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
914 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000915 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000916
917 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
918 Dest.getInlinedGlobals().insert(GV);
919 }
Chris Lattner82c6c722005-03-20 02:41:38 +0000920 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +0000921
922 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
923}
924
925void ReachabilityCloner::merge(const DSNodeHandle &NH,
926 const DSNodeHandle &SrcNH) {
927 if (SrcNH.isNull()) return; // Noop
928 if (NH.isNull()) {
929 // If there is no destination node, just clone the source and assign the
930 // destination node to be it.
931 NH.mergeWith(getClonedNH(SrcNH));
932 return;
933 }
934
935 // Okay, at this point, we know that we have both a destination and a source
936 // node that need to be merged. Check to see if the source node has already
937 // been cloned.
938 const DSNode *SN = SrcNH.getNode();
939 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +0000940 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +0000941 DSNode *SCNHN = SCNH.getNode();
942 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +0000943 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000944 return; // Nothing to do!
945 }
Chris Lattner6f967742004-10-30 04:05:01 +0000946
Chris Lattner0b144872004-01-27 22:03:40 +0000947 // Okay, so the source node has not already been cloned. Instead of creating
948 // a new DSNode, only to merge it into the one we already have, try to perform
949 // the merge in-place. The only case we cannot handle here is when the offset
950 // into the existing node is less than the offset into the virtual node we are
951 // merging in. In this case, we have to extend the existing node, which
952 // requires an allocation anyway.
953 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
954 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000955 if (!DN->isNodeCompletelyFolded()) {
956 // Make sure the destination node is folded if the source node is folded.
957 if (SN->isNodeCompletelyFolded()) {
958 DN->foldNodeCompletely();
959 DN = NH.getNode();
960 } else if (SN->getSize() != DN->getSize()) {
961 // If the two nodes are of different size, and the smaller node has the
962 // array bit set, collapse!
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000963#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner0b144872004-01-27 22:03:40 +0000964 if (SN->getSize() < DN->getSize()) {
965 if (SN->isArray()) {
966 DN->foldNodeCompletely();
967 DN = NH.getNode();
968 }
969 } else if (DN->isArray()) {
970 DN->foldNodeCompletely();
971 DN = NH.getNode();
972 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000973#endif
Chris Lattner0b144872004-01-27 22:03:40 +0000974 }
975
976 // Merge the type entries of the two nodes together...
977 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
978 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
979 DN = NH.getNode();
980 }
981 }
982
983 assert(!DN->isDeadNode());
984
985 // Merge the NodeType information.
986 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
987
988 // Before we start merging outgoing links and updating the scalar map, make
989 // sure it is known that this is the representative node for the src node.
990 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
991
992 // If the source node contains any globals, make sure they end up in the
993 // scalar map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +0000994 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000995 // Update the globals in the destination node itself.
Chris Lattner82c6c722005-03-20 02:41:38 +0000996 DN->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +0000997
998 // Update the scalar map for the graph we are merging the source node
999 // into.
Chris Lattner82c6c722005-03-20 02:41:38 +00001000 for (DSNode::globals_iterator I = SN->globals_begin(),
1001 E = SN->globals_end(); I != E; ++I) {
Chris Lattner0b144872004-01-27 22:03:40 +00001002 GlobalValue *GV = *I;
1003 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1004 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1005 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1006 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +00001007 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001008
1009 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1010 Dest.getInlinedGlobals().insert(GV);
1011 }
Chris Lattner82c6c722005-03-20 02:41:38 +00001012 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001013 }
1014 } else {
1015 // We cannot handle this case without allocating a temporary node. Fall
1016 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +00001017 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
1018 NewDN->maskNodeTypes(BitsToKeep);
1019
1020 unsigned NHOffset = NH.getOffset();
1021 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001022
Chris Lattner0b144872004-01-27 22:03:40 +00001023 assert(NH.getNode() &&
1024 (NH.getOffset() > NHOffset ||
1025 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
1026 "Merging did not adjust the offset!");
1027
1028 // Before we start merging outgoing links and updating the scalar map, make
1029 // sure it is known that this is the representative node for the src node.
1030 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +00001031
1032 // If the source node contained any globals, make sure to create entries
1033 // in the scalar map for them!
Chris Lattner82c6c722005-03-20 02:41:38 +00001034 for (DSNode::globals_iterator I = SN->globals_begin(),
1035 E = SN->globals_end(); I != E; ++I) {
Chris Lattneread9eb72004-01-29 08:36:22 +00001036 GlobalValue *GV = *I;
1037 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1038 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1039 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1040 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
1041 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1042 DestGNH.getOffset()+SrcGNH.getOffset()));
1043
1044 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1045 Dest.getInlinedGlobals().insert(GV);
1046 }
Chris Lattner0b144872004-01-27 22:03:40 +00001047 }
1048
1049
1050 // Next, recursively merge all outgoing links as necessary. Note that
1051 // adding these links can cause the destination node to collapse itself at
1052 // any time, and the current node may be merged with arbitrary other nodes.
1053 // For this reason, we must always go through NH.
1054 DN = 0;
1055 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1056 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1057 if (!SrcEdge.isNull()) {
1058 // Compute the offset into the current node at which to
1059 // merge this link. In the common case, this is a linear
1060 // relation to the offset in the original node (with
1061 // wrapping), but if the current node gets collapsed due to
1062 // recursive merging, we must make sure to merge in all remaining
1063 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +00001064 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +00001065 unsigned MergeOffset =
1066 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +00001067
Chris Lattnerf590ced2004-03-04 17:06:53 +00001068 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1069 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001070 // Perform the recursive merging. Make sure to create a temporary NH,
1071 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001072 merge(Tmp, SrcEdge);
1073 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001074 Tmp.mergeWith(getClonedNH(SrcEdge));
1075 // Merging this could cause all kinds of recursive things to happen,
1076 // culminating in the current node being eliminated. Since this is
1077 // possible, make sure to reaquire the link from 'CN'.
1078
1079 unsigned MergeOffset = 0;
1080 CN = SCNH.getNode();
1081 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1082 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001083 }
Chris Lattner0b144872004-01-27 22:03:40 +00001084 }
1085 }
1086}
1087
1088/// mergeCallSite - Merge the nodes reachable from the specified src call
1089/// site into the nodes reachable from DestCS.
1090void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
1091 const DSCallSite &SrcCS) {
1092 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1093 unsigned MinArgs = DestCS.getNumPtrArgs();
1094 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1095
1096 for (unsigned a = 0; a != MinArgs; ++a)
1097 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1098}
1099
1100
Chris Lattner9de906c2002-10-20 22:11:44 +00001101//===----------------------------------------------------------------------===//
1102// DSCallSite Implementation
1103//===----------------------------------------------------------------------===//
1104
Vikram S. Adve26b98262002-10-20 21:41:02 +00001105// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001106Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001107 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001108}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001109
Chris Lattner0b144872004-01-27 22:03:40 +00001110void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1111 ReachabilityCloner &RC) {
1112 NH = RC.getClonedNH(Src);
1113}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001114
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001115//===----------------------------------------------------------------------===//
1116// DSGraph Implementation
1117//===----------------------------------------------------------------------===//
1118
Chris Lattnera9d65662003-06-30 05:57:30 +00001119/// getFunctionNames - Return a space separated list of the name of the
1120/// functions in this graph (if any)
1121std::string DSGraph::getFunctionNames() const {
1122 switch (getReturnNodes().size()) {
1123 case 0: return "Globals graph";
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001124 case 1: return retnodes_begin()->first->getName();
Chris Lattnera9d65662003-06-30 05:57:30 +00001125 default:
1126 std::string Return;
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001127 for (DSGraph::retnodes_iterator I = retnodes_begin();
1128 I != retnodes_end(); ++I)
Chris Lattnera9d65662003-06-30 05:57:30 +00001129 Return += I->first->getName() + " ";
1130 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1131 return Return;
1132 }
1133}
1134
1135
Chris Lattnerf4f62272005-03-19 22:23:45 +00001136DSGraph::DSGraph(const DSGraph &G, EquivalenceClasses<GlobalValue*> &ECs)
1137 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001138 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001139 NodeMapTy NodeMap;
1140 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001141}
1142
Chris Lattnerf4f62272005-03-19 22:23:45 +00001143DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap,
1144 EquivalenceClasses<GlobalValue*> &ECs)
1145 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001146 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001147 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001148}
1149
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001150DSGraph::~DSGraph() {
1151 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001152 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001153 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001154 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001155 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001156
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001157 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001158 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
Chris Lattner84b80a22005-03-16 22:42:19 +00001159 NI->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001160
Chris Lattner28897e12004-02-08 00:53:26 +00001161 // Free all of the nodes.
1162 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001163}
1164
Chris Lattner0d9bab82002-07-18 00:12:30 +00001165// dump - Allow inspection of graph in a debugger.
1166void DSGraph::dump() const { print(std::cerr); }
1167
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001168
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001169/// remapLinks - Change all of the Links in the current node according to the
1170/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001171///
Chris Lattner8d327672003-06-30 03:36:09 +00001172void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001173 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1174 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001175 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001176 if (ONMI != OldNodeMap.end()) {
1177 DSNode *ONMIN = ONMI->second.getNode();
1178 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1179 }
Chris Lattner2f561382004-01-22 16:56:13 +00001180 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001181}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001182
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001183/// updateFromGlobalGraph - This function rematerializes global nodes and
1184/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001185/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1186/// are already up-to-date in the current graph. In practice, in the TD pass,
1187/// this is likely to be a large fraction of the live global nodes in each
1188/// function (since most live nodes are likely to have been brought up-to-date
1189/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001190///
1191void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001192 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001193 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1194
1195 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001196 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1197 E = getScalarMap().global_end(); I != E; ++I)
1198 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001199 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001200 if (It != GlobalsGraph->ScalarMap.end())
1201 RC.merge(getNodeForValue(*I), It->second);
1202 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001203}
1204
Chris Lattnerd672ab92005-02-15 18:40:55 +00001205/// addObjectToGraph - This method can be used to add global, stack, and heap
1206/// objects to the graph. This can be used when updating DSGraphs due to the
1207/// introduction of new temporary objects. The new object is not pointed to
1208/// and does not point to any other objects in the graph.
1209DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1210 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1211 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1212 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
Chris Lattner7a0c7752005-02-15 18:48:48 +00001213 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
Chris Lattnerd672ab92005-02-15 18:40:55 +00001214 ScalarMap[Ptr] = N;
1215
1216 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1217 N->addGlobal(GV);
1218 } else if (MallocInst *MI = dyn_cast<MallocInst>(Ptr)) {
1219 N->setHeapNodeMarker();
1220 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr)) {
1221 N->setAllocaNodeMarker();
1222 } else {
1223 assert(0 && "Illegal memory object input!");
1224 }
1225 return N;
1226}
1227
1228
Chris Lattner5a540632003-06-30 03:15:25 +00001229/// cloneInto - Clone the specified DSGraph into the current graph. The
1230/// translated ScalarMap for the old function is filled into the OldValMap
1231/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1232///
1233/// The CloneFlags member controls various aspects of the cloning process.
1234///
Chris Lattner62482e52004-01-28 09:15:42 +00001235void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001236 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1237 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001238 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001239 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001240 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001241
Chris Lattner1e883692003-02-03 20:08:51 +00001242 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001243 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1244 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1245 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001246 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001247
Chris Lattner84b80a22005-03-16 22:42:19 +00001248 for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1249 assert(!I->isForwarding() &&
Chris Lattnerd85645f2004-02-21 22:28:26 +00001250 "Forward nodes shouldn't be in node list!");
Chris Lattner84b80a22005-03-16 22:42:19 +00001251 DSNode *New = new DSNode(*I, this);
Chris Lattnerd85645f2004-02-21 22:28:26 +00001252 New->maskNodeTypes(~BitsToClear);
Chris Lattner84b80a22005-03-16 22:42:19 +00001253 OldNodeMap[I] = New;
Chris Lattnerd85645f2004-02-21 22:28:26 +00001254 }
1255
Chris Lattner18552922002-11-18 21:44:46 +00001256#ifndef NDEBUG
1257 Timer::addPeakMemoryMeasurement();
1258#endif
Chris Lattnerd85645f2004-02-21 22:28:26 +00001259
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001260 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001261 // Note that we don't loop over the node's list to do this. The problem is
1262 // that remaping links can cause recursive merging to happen, which means
1263 // that node_iterator's can get easily invalidated! Because of this, we
1264 // loop over the OldNodeMap, which contains all of the new nodes as the
1265 // .second element of the map elements. Also note that if we remap a node
1266 // more than once, we won't break anything.
1267 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1268 I != E; ++I)
1269 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001270
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001271 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001272 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001273 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001274 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001275 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner6f967742004-10-30 04:05:01 +00001276 DSNode *MappedNodeN = MappedNode.getNode();
1277 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001278 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001279
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001280 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001281 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1282 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001283 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1284 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001285 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001286 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001287
Chris Lattner679e8e12002-11-08 21:27:12 +00001288 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001289 // Copy the function calls list.
1290 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1291 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001292 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001293
Chris Lattneracf491f2002-11-08 22:27:09 +00001294 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001295 // Copy the auxiliary function calls list.
1296 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1297 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattner679e8e12002-11-08 21:27:12 +00001298 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001299
Chris Lattner5a540632003-06-30 03:15:25 +00001300 // Map the return node pointers over...
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001301 for (retnodes_iterator I = G.retnodes_begin(),
1302 E = G.retnodes_end(); I != E; ++I) {
Chris Lattner5a540632003-06-30 03:15:25 +00001303 const DSNodeHandle &Ret = I->second;
1304 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001305 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattner5a540632003-06-30 03:15:25 +00001306 OldReturnNodes.insert(std::make_pair(I->first,
Chris Lattner6f967742004-10-30 04:05:01 +00001307 DSNodeHandle(MappedRetN,
Chris Lattner5a540632003-06-30 03:15:25 +00001308 MappedRet.getOffset()+Ret.getOffset())));
1309 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001310}
1311
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001312static bool PathExistsToClonedNode(const DSNode *N, ReachabilityCloner &RC) {
Chris Lattner2f346902004-03-04 03:57:53 +00001313 if (N)
1314 for (df_iterator<const DSNode*> I = df_begin(N), E = df_end(N); I != E; ++I)
1315 if (RC.hasClonedNode(*I))
1316 return true;
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001317 return false;
1318}
1319
Chris Lattner2f346902004-03-04 03:57:53 +00001320static bool PathExistsToClonedNode(const DSCallSite &CS,
1321 ReachabilityCloner &RC) {
1322 if (PathExistsToClonedNode(CS.getRetVal().getNode(), RC))
1323 return true;
1324 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1325 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode(), RC))
1326 return true;
1327 return false;
1328}
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001329
Chris Lattnerbb753c42005-02-03 18:40:25 +00001330/// getFunctionArgumentsForCall - Given a function that is currently in this
1331/// graph, return the DSNodeHandles that correspond to the pointer-compatible
1332/// function arguments. The vector is filled in with the return value (or
1333/// null if it is not pointer compatible), followed by all of the
1334/// pointer-compatible arguments.
1335void DSGraph::getFunctionArgumentsForCall(Function *F,
1336 std::vector<DSNodeHandle> &Args) const {
1337 Args.push_back(getReturnNodeFor(*F));
Chris Lattnere4d5c442005-03-15 04:54:21 +00001338 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; ++AI)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001339 if (isPointerType(AI->getType())) {
1340 Args.push_back(getNodeForValue(AI));
1341 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1342 }
1343}
1344
Chris Lattnere8594442005-02-04 19:58:28 +00001345/// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1346/// nodes from G2 into 'this' graph, merging the bindings specified by the
1347/// call site (in this graph) with the bindings specified by the vector in G2.
1348/// The two DSGraphs must be different.
Chris Lattner076c1f92002-11-07 06:31:54 +00001349///
Chris Lattnere8594442005-02-04 19:58:28 +00001350void DSGraph::mergeInGraph(const DSCallSite &CS,
1351 std::vector<DSNodeHandle> &Args,
Chris Lattner9f930552003-06-30 05:27:18 +00001352 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001353 TIME_REGION(X, "mergeInGraph");
1354
Chris Lattner076c1f92002-11-07 06:31:54 +00001355 // If this is not a recursive call, clone the graph into this graph...
1356 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001357 // Clone the callee's graph into the current graph, keeping track of where
1358 // scalars in the old graph _used_ to point, and of the new nodes matching
1359 // nodes of the old graph.
1360 ReachabilityCloner RC(*this, Graph, CloneFlags);
1361
Chris Lattner0b144872004-01-27 22:03:40 +00001362 // Map the return node pointer over.
Chris Lattner0ad91702004-02-22 00:53:54 +00001363 if (!CS.getRetVal().isNull())
Chris Lattnerbb753c42005-02-03 18:40:25 +00001364 RC.merge(CS.getRetVal(), Args[0]);
Chris Lattnerf590ced2004-03-04 17:06:53 +00001365
Chris Lattnerbb753c42005-02-03 18:40:25 +00001366 // Map over all of the arguments.
1367 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001368 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001369 break;
Chris Lattnerbb753c42005-02-03 18:40:25 +00001370
1371 // Add the link from the argument scalar to the provided value.
1372 RC.merge(CS.getPtrArg(i), Args[i+1]);
1373 }
1374
Chris Lattner2f346902004-03-04 03:57:53 +00001375 // If requested, copy all of the calls.
Chris Lattner0b144872004-01-27 22:03:40 +00001376 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001377 // Copy the function calls list.
1378 for (fc_iterator I = Graph.fc_begin(), E = Graph.fc_end(); I != E; ++I)
1379 FunctionCalls.push_back(DSCallSite(*I, RC));
Chris Lattner0b144872004-01-27 22:03:40 +00001380 }
Chris Lattner2f346902004-03-04 03:57:53 +00001381
1382 // If the user has us copying aux calls (the normal case), set up a data
1383 // structure to keep track of which ones we've copied over.
Chris Lattnera9548d92005-01-30 23:51:02 +00001384 std::set<const DSCallSite*> CopiedAuxCall;
Chris Lattner0b144872004-01-27 22:03:40 +00001385
Chris Lattner0321b682004-02-27 20:05:15 +00001386 // Clone over all globals that appear in the caller and callee graphs.
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001387 hash_set<GlobalVariable*> NonCopiedGlobals;
Chris Lattner0321b682004-02-27 20:05:15 +00001388 for (DSScalarMap::global_iterator GI = Graph.getScalarMap().global_begin(),
1389 E = Graph.getScalarMap().global_end(); GI != E; ++GI)
1390 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*GI))
1391 if (ScalarMap.count(GV))
1392 RC.merge(ScalarMap[GV], Graph.getNodeForValue(GV));
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001393 else
1394 NonCopiedGlobals.insert(GV);
1395
1396 // If the global does not appear in the callers graph we generally don't
1397 // want to copy the node. However, if there is a path from the node global
1398 // node to a node that we did copy in the graph, we *must* copy it to
1399 // maintain the connection information. Every time we decide to include a
1400 // new global, this might make other globals live, so we must iterate
1401 // unfortunately.
Chris Lattner2f346902004-03-04 03:57:53 +00001402 bool MadeChange = true;
1403 while (MadeChange) {
1404 MadeChange = false;
1405 for (hash_set<GlobalVariable*>::iterator I = NonCopiedGlobals.begin();
1406 I != NonCopiedGlobals.end();) {
1407 DSNode *GlobalNode = Graph.getNodeForValue(*I).getNode();
1408 if (RC.hasClonedNode(GlobalNode)) {
1409 // Already cloned it, remove from set.
1410 NonCopiedGlobals.erase(I++);
1411 MadeChange = true;
1412 } else if (PathExistsToClonedNode(GlobalNode, RC)) {
1413 RC.getClonedNH(Graph.getNodeForValue(*I));
1414 NonCopiedGlobals.erase(I++);
1415 MadeChange = true;
1416 } else {
1417 ++I;
1418 }
1419 }
1420
1421 // If requested, copy any aux calls that can reach copied nodes.
1422 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001423 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
1424 if (CopiedAuxCall.insert(&*I).second &&
1425 PathExistsToClonedNode(*I, RC)) {
1426 AuxFunctionCalls.push_back(DSCallSite(*I, RC));
Chris Lattner2f346902004-03-04 03:57:53 +00001427 MadeChange = true;
1428 }
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001429 }
1430 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001431
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001432 } else {
Chris Lattnerbb753c42005-02-03 18:40:25 +00001433 // Merge the return value with the return value of the context.
1434 Args[0].mergeWith(CS.getRetVal());
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001435
Chris Lattnerbb753c42005-02-03 18:40:25 +00001436 // Resolve all of the function arguments.
1437 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001438 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001439 break;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001440
Chris Lattnerbb753c42005-02-03 18:40:25 +00001441 // Add the link from the argument scalar to the provided value.
1442 Args[i+1].mergeWith(CS.getPtrArg(i));
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001443 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001444 }
1445}
1446
Chris Lattnere8594442005-02-04 19:58:28 +00001447
1448
1449/// mergeInGraph - The method is used for merging graphs together. If the
1450/// argument graph is not *this, it makes a clone of the specified graph, then
1451/// merges the nodes specified in the call site with the formal arguments in the
1452/// graph.
1453///
1454void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1455 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattnere8594442005-02-04 19:58:28 +00001456 // Set up argument bindings.
1457 std::vector<DSNodeHandle> Args;
1458 Graph.getFunctionArgumentsForCall(&F, Args);
1459
1460 mergeInGraph(CS, Args, Graph, CloneFlags);
1461}
1462
Chris Lattner58f98d02003-07-02 04:38:49 +00001463/// getCallSiteForArguments - Get the arguments and return value bindings for
1464/// the specified function in the current graph.
1465///
1466DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1467 std::vector<DSNodeHandle> Args;
1468
Chris Lattnere4d5c442005-03-15 04:54:21 +00001469 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner58f98d02003-07-02 04:38:49 +00001470 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001471 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001472
Chris Lattner808a7ae2003-09-20 16:34:13 +00001473 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001474}
1475
Chris Lattner85fb1be2004-03-09 19:37:06 +00001476/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1477/// the context of this graph, return the DSCallSite for it.
1478DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1479 DSNodeHandle RetVal;
1480 Instruction *I = CS.getInstruction();
1481 if (isPointerType(I->getType()))
1482 RetVal = getNodeForValue(I);
1483
1484 std::vector<DSNodeHandle> Args;
1485 Args.reserve(CS.arg_end()-CS.arg_begin());
1486
1487 // Calculate the arguments vector...
1488 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1489 if (isPointerType((*I)->getType()))
Chris Lattner94f84702005-03-17 19:56:56 +00001490 if (isa<ConstantPointerNull>(*I))
1491 Args.push_back(DSNodeHandle());
1492 else
1493 Args.push_back(getNodeForValue(*I));
Chris Lattner85fb1be2004-03-09 19:37:06 +00001494
1495 // Add a new function call entry...
1496 if (Function *F = CS.getCalledFunction())
1497 return DSCallSite(CS, RetVal, F, Args);
1498 else
1499 return DSCallSite(CS, RetVal,
1500 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1501}
1502
Chris Lattner58f98d02003-07-02 04:38:49 +00001503
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001504
Chris Lattner0d9bab82002-07-18 00:12:30 +00001505// markIncompleteNodes - Mark the specified node as having contents that are not
1506// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001507// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001508// must recursively traverse the data structure graph, marking all reachable
1509// nodes as incomplete.
1510//
1511static void markIncompleteNode(DSNode *N) {
1512 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001513 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001514
1515 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001516 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001517
Misha Brukman2f2d0652003-09-11 18:14:24 +00001518 // Recursively process children...
Chris Lattner6be07942005-02-09 03:20:43 +00001519 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1520 if (DSNode *DSN = I->getNode())
Chris Lattner08db7192002-11-06 06:20:27 +00001521 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001522}
1523
Chris Lattnere71ffc22002-11-11 03:36:55 +00001524static void markIncomplete(DSCallSite &Call) {
1525 // Then the return value is certainly incomplete!
1526 markIncompleteNode(Call.getRetVal().getNode());
1527
1528 // All objects pointed to by function arguments are incomplete!
1529 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1530 markIncompleteNode(Call.getPtrArg(i).getNode());
1531}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001532
1533// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1534// modified by other functions that have not been resolved yet. This marks
1535// nodes that are reachable through three sources of "unknownness":
1536//
1537// Global Variables, Function Calls, and Incoming Arguments
1538//
1539// For any node that may have unknown components (because something outside the
1540// scope of current analysis may have modified it), the 'Incomplete' flag is
1541// added to the NodeType.
1542//
Chris Lattner394471f2003-01-23 22:05:33 +00001543void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001544 // Mark any incoming arguments as incomplete.
Chris Lattner5a540632003-06-30 03:15:25 +00001545 if (Flags & DSGraph::MarkFormalArgs)
1546 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1547 FI != E; ++FI) {
1548 Function &F = *FI->first;
Chris Lattnere4d5c442005-03-15 04:54:21 +00001549 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattnerb5ecd2e2005-03-13 20:22:10 +00001550 if (isPointerType(I->getType()))
1551 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattnera4319e52005-03-12 14:58:28 +00001552 markIncompleteNode(FI->second.getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001553 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001554
Chris Lattnera9548d92005-01-30 23:51:02 +00001555 // Mark stuff passed into functions calls as being incomplete.
Chris Lattnere71ffc22002-11-11 03:36:55 +00001556 if (!shouldPrintAuxCalls())
Chris Lattnera9548d92005-01-30 23:51:02 +00001557 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1558 E = FunctionCalls.end(); I != E; ++I)
1559 markIncomplete(*I);
Chris Lattnere71ffc22002-11-11 03:36:55 +00001560 else
Chris Lattnera9548d92005-01-30 23:51:02 +00001561 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1562 E = AuxFunctionCalls.end(); I != E; ++I)
1563 markIncomplete(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001564
Chris Lattnere2bc7b22005-03-13 20:36:01 +00001565 // Mark all global nodes as incomplete.
1566 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1567 E = ScalarMap.global_end(); I != E; ++I)
1568 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1569 if (!GV->hasInitializer() || // Always mark external globals incomp.
1570 (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1571 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001572}
1573
Chris Lattneraa8146f2002-11-10 06:59:55 +00001574static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1575 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001576 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001577 // No interesting info?
1578 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001579 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001580 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001581}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001582
Chris Lattner82c6c722005-03-20 02:41:38 +00001583#if 0
Chris Lattneraa8146f2002-11-10 06:59:55 +00001584static inline bool nodeContainsExternalFunction(const DSNode *N) {
1585 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1586 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
Chris Lattner857eb062004-10-30 05:41:23 +00001587 if (Globals[i]->isExternal() && isa<Function>(Globals[i]))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001588 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001589 return false;
1590}
Chris Lattner82c6c722005-03-20 02:41:38 +00001591#endif
Chris Lattner0d9bab82002-07-18 00:12:30 +00001592
Chris Lattnera9548d92005-01-30 23:51:02 +00001593static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001594 // Remove trivially identical function calls
Chris Lattnera9548d92005-01-30 23:51:02 +00001595 Calls.sort(); // Sort by callee as primary key!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001596
1597 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001598 DSNode *LastCalleeNode = 0;
1599 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001600 unsigned NumDuplicateCalls = 0;
1601 bool LastCalleeContainsExternalFunction = false;
Chris Lattner857eb062004-10-30 05:41:23 +00001602
Chris Lattnera9548d92005-01-30 23:51:02 +00001603 unsigned NumDeleted = 0;
1604 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1605 I != E;) {
1606 DSCallSite &CS = *I;
1607 std::list<DSCallSite>::iterator OldIt = I++;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001608
Chris Lattnere4258442002-11-11 21:35:38 +00001609 // If the Callee is a useless edge, this must be an unreachable call site,
1610 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001611 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerabcdf802004-02-26 03:43:43 +00001612 CS.getCalleeNode()->isComplete() &&
Chris Lattner82c6c722005-03-20 02:41:38 +00001613 CS.getCalleeNode()->getGlobalsList().empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001614#ifndef NDEBUG
Chris Lattnerabcdf802004-02-26 03:43:43 +00001615 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001616#endif
Chris Lattnera9548d92005-01-30 23:51:02 +00001617 Calls.erase(OldIt);
1618 ++NumDeleted;
1619 continue;
1620 }
1621
1622 // If the return value or any arguments point to a void node with no
1623 // information at all in it, and the call node is the only node to point
1624 // to it, remove the edge to the node (killing the node).
1625 //
1626 killIfUselessEdge(CS.getRetVal());
1627 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1628 killIfUselessEdge(CS.getPtrArg(a));
1629
Chris Lattner0b144872004-01-27 22:03:40 +00001630#if 0
Chris Lattnera9548d92005-01-30 23:51:02 +00001631 // If this call site calls the same function as the last call site, and if
1632 // the function pointer contains an external function, this node will
1633 // never be resolved. Merge the arguments of the call node because no
1634 // information will be lost.
1635 //
1636 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1637 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1638 ++NumDuplicateCalls;
1639 if (NumDuplicateCalls == 1) {
1640 if (LastCalleeNode)
1641 LastCalleeContainsExternalFunction =
1642 nodeContainsExternalFunction(LastCalleeNode);
1643 else
1644 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001645 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001646
1647 // It is not clear why, but enabling this code makes DSA really
1648 // sensitive to node forwarding. Basically, with this enabled, DSA
1649 // performs different number of inlinings based on which nodes are
1650 // forwarding or not. This is clearly a problem, so this code is
1651 // disabled until this can be resolved.
1652#if 1
1653 if (LastCalleeContainsExternalFunction
1654#if 0
1655 ||
1656 // This should be more than enough context sensitivity!
1657 // FIXME: Evaluate how many times this is tripped!
1658 NumDuplicateCalls > 20
1659#endif
1660 ) {
1661
1662 std::list<DSCallSite>::iterator PrevIt = OldIt;
1663 --PrevIt;
1664 PrevIt->mergeWith(CS);
1665
1666 // No need to keep this call anymore.
1667 Calls.erase(OldIt);
1668 ++NumDeleted;
1669 continue;
1670 }
1671#endif
1672 } else {
1673 if (CS.isDirectCall()) {
1674 LastCalleeFunc = CS.getCalleeFunc();
1675 LastCalleeNode = 0;
1676 } else {
1677 LastCalleeNode = CS.getCalleeNode();
1678 LastCalleeFunc = 0;
1679 }
1680 NumDuplicateCalls = 0;
1681 }
1682#endif
1683
1684 if (I != Calls.end() && CS == *I) {
1685 Calls.erase(OldIt);
1686 ++NumDeleted;
1687 continue;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001688 }
1689 }
Chris Lattner857eb062004-10-30 05:41:23 +00001690
Chris Lattnera9548d92005-01-30 23:51:02 +00001691 // Resort now that we simplified things.
1692 Calls.sort();
Chris Lattner857eb062004-10-30 05:41:23 +00001693
Chris Lattnera9548d92005-01-30 23:51:02 +00001694 // Now that we are in sorted order, eliminate duplicates.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001695 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1696 if (CI != CE)
Chris Lattnera9548d92005-01-30 23:51:02 +00001697 while (1) {
Chris Lattnerf9aace22005-01-31 00:10:58 +00001698 std::list<DSCallSite>::iterator OldIt = CI++;
1699 if (CI == CE) break;
Chris Lattnera9548d92005-01-30 23:51:02 +00001700
1701 // If this call site is now the same as the previous one, we can delete it
1702 // as a duplicate.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001703 if (*OldIt == *CI) {
1704 Calls.erase(CI);
1705 CI = OldIt;
Chris Lattnera9548d92005-01-30 23:51:02 +00001706 ++NumDeleted;
1707 }
1708 }
1709
1710 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001711
Chris Lattner33312f72002-11-08 01:21:07 +00001712 // Track the number of call nodes merged away...
Chris Lattnera9548d92005-01-30 23:51:02 +00001713 NumCallNodesMerged += NumDeleted;
Chris Lattner33312f72002-11-08 01:21:07 +00001714
Chris Lattnera9548d92005-01-30 23:51:02 +00001715 DEBUG(if (NumDeleted)
1716 std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001717}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001718
Chris Lattneraa8146f2002-11-10 06:59:55 +00001719
Chris Lattnere2219762002-07-18 18:22:40 +00001720// removeTriviallyDeadNodes - After the graph has been constructed, this method
1721// removes all unreachable nodes that are created because they got merged with
1722// other nodes in the graph. These nodes will all be trivially unreachable, so
1723// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001724//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001725void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001726 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001727
Chris Lattner5ace1e42004-07-08 07:25:51 +00001728#if 0
1729 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1730 /// substantially!
1731
Chris Lattnerbab8c282003-09-20 21:34:07 +00001732 // Loop over all of the nodes in the graph, calling getNode on each field.
1733 // This will cause all nodes to update their forwarding edges, causing
1734 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001735 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001736 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
Chris Lattner84b80a22005-03-16 22:42:19 +00001737 DSNode &N = *NI;
1738 for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1739 N.getLink(l*N.getPointerSize()).getNode();
Chris Lattnerbab8c282003-09-20 21:34:07 +00001740 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001741 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001742
Chris Lattner0b144872004-01-27 22:03:40 +00001743 // NOTE: This code is disabled. Though it should, in theory, allow us to
1744 // remove more nodes down below, the scan of the scalar map is incredibly
1745 // expensive for certain programs (with large SCCs). In the future, if we can
1746 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001747 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1748
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001749 // Likewise, forward any edges from the scalar nodes. While we are at it,
1750 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001751 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001752 I->second.getNode();
1753 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001754 }
Chris Lattner0b144872004-01-27 22:03:40 +00001755 }
1756#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001757 bool isGlobalsGraph = !GlobalsGraph;
1758
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001759 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001760 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001761
1762 // Do not remove *any* global nodes in the globals graph.
1763 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001764 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001765 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001766 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001767 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001768
Chris Lattner28897e12004-02-08 00:53:26 +00001769 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001770 // This is a useless node if it has no mod/ref info (checked above),
1771 // outgoing edges (which it cannot, as it is not modified in this
1772 // context), and it has no incoming edges. If it is a global node it may
1773 // have all of these properties and still have incoming edges, due to the
1774 // scalar map, so we check those now.
1775 //
Chris Lattner82c6c722005-03-20 02:41:38 +00001776 if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1777 const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
Chris Lattner72d29a42003-02-11 23:11:51 +00001778
Chris Lattner17a93e22004-01-29 03:32:15 +00001779 // Loop through and make sure all of the globals are referring directly
1780 // to the node...
1781 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1782 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001783 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001784 }
1785
Chris Lattnerbd92b732003-06-19 21:15:11 +00001786 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001787 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001788 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1789 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001790 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001791 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001792 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001793 }
1794 }
1795
Chris Lattner28897e12004-02-08 00:53:26 +00001796 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001797 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001798 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001799 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001800 } else {
1801 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001802 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001803 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001804
1805 removeIdenticalCalls(FunctionCalls);
1806 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001807}
1808
1809
Chris Lattner5c7380e2003-01-29 21:10:20 +00001810/// markReachableNodes - This method recursively traverses the specified
1811/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1812/// to the set, which allows it to only traverse visited nodes once.
1813///
Chris Lattnera9548d92005-01-30 23:51:02 +00001814void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001815 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001816 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001817 if (ReachableNodes.insert(this).second) // Is newly reachable?
Chris Lattner6be07942005-02-09 03:20:43 +00001818 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
1819 I != E; ++I)
1820 I->getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001821}
1822
Chris Lattnera9548d92005-01-30 23:51:02 +00001823void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001824 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001825 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001826
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001827 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1828 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001829}
1830
Chris Lattnera1220af2003-02-01 06:17:02 +00001831// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1832// looking for a node that is marked alive. If an alive node is found, return
1833// true, otherwise return false. If an alive node is reachable, this node is
1834// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001835//
Chris Lattnera9548d92005-01-30 23:51:02 +00001836static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
1837 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00001838 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001839 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001840 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001841
Chris Lattner85cfe012003-07-03 02:03:53 +00001842 // If this is a global node, it will end up in the globals graph anyway, so we
1843 // don't need to worry about it.
1844 if (IgnoreGlobals && N->isGlobalNode()) return false;
1845
Chris Lattneraa8146f2002-11-10 06:59:55 +00001846 // If we know that this node is alive, return so!
1847 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001848
Chris Lattneraa8146f2002-11-10 06:59:55 +00001849 // Otherwise, we don't think the node is alive yet, check for infinite
1850 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001851 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001852 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001853
Chris Lattner6be07942005-02-09 03:20:43 +00001854 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1855 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001856 N->markReachableNodes(Alive);
1857 return true;
1858 }
1859 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001860}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001861
Chris Lattnera1220af2003-02-01 06:17:02 +00001862// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1863// alive nodes.
1864//
Chris Lattnera9548d92005-01-30 23:51:02 +00001865static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
1866 hash_set<const DSNode*> &Alive,
1867 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00001868 bool IgnoreGlobals) {
1869 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1870 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001871 return true;
1872 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001873 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001874 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001875 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001876 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1877 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001878 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001879 return false;
1880}
1881
Chris Lattnere2219762002-07-18 18:22:40 +00001882// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1883// subgraphs that are unreachable. This often occurs because the data
1884// structure doesn't "escape" into it's caller, and thus should be eliminated
1885// from the caller's graph entirely. This is only appropriate to use when
1886// inlining graphs.
1887//
Chris Lattner394471f2003-01-23 22:05:33 +00001888void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001889 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001890
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001891 // Reduce the amount of work we have to do... remove dummy nodes left over by
1892 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001893 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001894
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001895 TIME_REGION(X, "removeDeadNodes");
1896
Misha Brukman2f2d0652003-09-11 18:14:24 +00001897 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001898
1899 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattnera9548d92005-01-30 23:51:02 +00001900 hash_set<const DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001901 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001902
Chris Lattner0b144872004-01-27 22:03:40 +00001903 // Copy and merge all information about globals to the GlobalsGraph if this is
1904 // not a final pass (where unreachable globals are removed).
1905 //
1906 // Strip all alloca bits since the current function is only for the BU pass.
1907 // Strip all incomplete bits since they are short-lived properties and they
1908 // will be correctly computed when rematerializing nodes into the functions.
1909 //
1910 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1911 DSGraph::StripIncompleteBit);
1912
Chris Lattneraa8146f2002-11-10 06:59:55 +00001913 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattnerf4f62272005-03-19 22:23:45 +00001914{ TIME_REGION(Y, "removeDeadNodes:scalarscan");
1915 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1916 I != E; ++I)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001917 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00001918 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001919 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001920 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001921
1922 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001923 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1924 DSGraph::ScalarMapTy::iterator SMI =
1925 GlobalsGraph->getScalarMap().find(I->first);
1926 if (SMI != GlobalsGraph->getScalarMap().end())
1927 GGCloner.merge(SMI->second, I->second);
1928 else
1929 GGCloner.getClonedNH(I->second);
1930 }
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001931 } else {
Chris Lattnerf4f62272005-03-19 22:23:45 +00001932 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001933 }
Chris Lattnerf4f62272005-03-19 22:23:45 +00001934}
Chris Lattnere2219762002-07-18 18:22:40 +00001935
Chris Lattner0b144872004-01-27 22:03:40 +00001936 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001937 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1938 I != E; ++I)
1939 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001940
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001941 // Mark any nodes reachable by primary calls as alive...
Chris Lattnera9548d92005-01-30 23:51:02 +00001942 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
1943 I->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001944
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001945
1946 // Now find globals and aux call nodes that are already live or reach a live
1947 // value (which makes them live in turn), and continue till no more are found.
1948 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001949 bool Iterate;
Chris Lattnera9548d92005-01-30 23:51:02 +00001950 hash_set<const DSNode*> Visited;
1951 hash_set<const DSCallSite*> AuxFCallsAlive;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001952 do {
1953 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001954 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001955 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001956 // unreachable globals in the list.
1957 //
1958 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001959 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001960 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1961 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1962 Flags & DSGraph::RemoveUnreachableGlobals)) {
1963 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1964 GlobalNodes.pop_back(); // erase efficiently
1965 Iterate = true;
1966 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001967
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001968 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1969 // call nodes that get resolved will be difficult to remove from that graph.
1970 // The final unresolved call nodes must be handled specially at the end of
1971 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattnera9548d92005-01-30 23:51:02 +00001972 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
Chris Lattnerd7642c42005-02-24 18:48:07 +00001973 if (!AuxFCallsAlive.count(&*CI) &&
Chris Lattnera9548d92005-01-30 23:51:02 +00001974 (CI->isIndirectCall()
1975 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001976 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001977 CI->markReachableNodes(Alive);
Chris Lattnerd7642c42005-02-24 18:48:07 +00001978 AuxFCallsAlive.insert(&*CI);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001979 Iterate = true;
1980 }
1981 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001982
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001983 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001984 unsigned CurIdx = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00001985 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
1986 E = AuxFunctionCalls.end(); CI != E; )
1987 if (AuxFCallsAlive.count(&*CI))
1988 ++CI;
1989 else {
1990 // Copy and merge global nodes and dead aux call nodes into the
1991 // GlobalsGraph, and all nodes reachable from those nodes. Update their
1992 // target pointers using the GGCloner.
1993 //
1994 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1995 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001996
Chris Lattnera9548d92005-01-30 23:51:02 +00001997 AuxFunctionCalls.erase(CI++);
1998 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001999
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002000 // We are finally done with the GGCloner so we can destroy it.
2001 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002002
Vikram S. Adve40c600e2003-07-22 12:08:58 +00002003 // At this point, any nodes which are visited, but not alive, are nodes
2004 // which can be removed. Loop over all nodes, eliminating completely
2005 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002006 //
Chris Lattner72d29a42003-02-11 23:11:51 +00002007 std::vector<DSNode*> DeadNodes;
2008 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00002009 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2010 DSNode *N = NI++;
2011 assert(!N->isForwarding() && "Forwarded node in nodes list?");
2012
2013 if (!Alive.count(N)) {
2014 Nodes.remove(N);
2015 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002016 DeadNodes.push_back(N);
2017 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00002018 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00002019 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00002020 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002021
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002022 // Remove all unreachable globals from the ScalarMap.
2023 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2024 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00002025 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002026 if (!Alive.count(GlobalNodes[i].second))
2027 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00002028 else
2029 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002030
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002031 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00002032 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2033 delete DeadNodes[i];
2034
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002035 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00002036}
2037
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002038void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
Chris Lattner82c6c722005-03-20 02:41:38 +00002039 assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2040 N->globals_end() && "Global value not in node!");
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002041}
2042
Chris Lattner2c7725a2004-03-03 20:55:27 +00002043void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2044 if (CS.isIndirectCall()) {
2045 AssertNodeInGraph(CS.getCalleeNode());
2046#if 0
2047 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2048 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
Chris Lattnerf8db8a02005-02-27 06:15:51 +00002049 std::cerr << "WARNING: WEIRD CALL SITE FOUND!\n";
Chris Lattner2c7725a2004-03-03 20:55:27 +00002050#endif
2051 }
2052 AssertNodeInGraph(CS.getRetVal().getNode());
2053 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2054 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2055}
2056
2057void DSGraph::AssertCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002058 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2059 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002060}
2061void DSGraph::AssertAuxCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002062 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2063 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002064}
2065
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002066void DSGraph::AssertGraphOK() const {
Chris Lattner84b80a22005-03-16 22:42:19 +00002067 for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2068 NI->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00002069
Chris Lattner8d327672003-06-30 03:36:09 +00002070 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002071 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00002072 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002073 AssertNodeInGraph(I->second.getNode());
2074 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00002075 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002076 "Global points to node, but node isn't global?");
2077 AssertNodeContainsGlobal(I->second.getNode(), GV);
2078 }
2079 }
2080 AssertCallNodesInGraph();
2081 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00002082
2083 // Check that all pointer arguments to any functions in this graph have
2084 // destinations.
2085 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2086 E = ReturnNodes.end();
2087 RI != E; ++RI) {
2088 Function &F = *RI->first;
Chris Lattnere4d5c442005-03-15 04:54:21 +00002089 for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
Chris Lattner7d8d4712004-10-31 17:45:40 +00002090 if (isPointerType(AI->getType()))
2091 assert(!getNodeForValue(AI).isNull() &&
2092 "Pointer argument must be in the scalar map!");
2093 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002094}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002095
Chris Lattner400433d2003-11-11 05:08:59 +00002096/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00002097/// nodes reachable from the two graphs, computing the mapping of nodes from the
2098/// first to the second graph. This mapping may be many-to-one (i.e. the first
2099/// graph may have multiple nodes representing one node in the second graph),
2100/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00002101///
2102void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00002103 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2104 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00002105 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2106 if (N1 == 0 || N2 == 0) return;
2107
2108 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002109 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002110 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002111 if (StrictChecking) {
2112 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2113 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2114 Entry.getNode()->isNodeCompletelyFolded()) &&
2115 "Inconsistent mapping detected!");
2116 }
Chris Lattner400433d2003-11-11 05:08:59 +00002117 return;
2118 }
2119
Chris Lattnerefffdc92004-07-07 06:12:52 +00002120 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002121
2122 // Loop over all of the fields that N1 and N2 have in common, recursively
2123 // mapping the edges together now.
2124 int N2Idx = NH2.getOffset()-NH1.getOffset();
2125 unsigned N2Size = N2->getSize();
Chris Lattner841957e2005-03-15 04:40:24 +00002126 if (N2Size == 0) return; // No edges to map to.
2127
Chris Lattner4d5af8e2005-03-15 21:36:50 +00002128 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2129 const DSNodeHandle &N1NH = N1->getLink(i);
2130 // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2131 // aligned right).
2132 if (!N1NH.isNull()) {
2133 if (unsigned(N2Idx)+i < N2Size)
2134 computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2135 else
2136 computeNodeMapping(N1NH,
2137 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2138 }
2139 }
Chris Lattner400433d2003-11-11 05:08:59 +00002140}
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002141
2142
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002143/// computeGToGGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002144/// nodes in this graph.
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002145void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002146 DSGraph &GG = *getGlobalsGraph();
2147
2148 DSScalarMap &SM = getScalarMap();
2149 for (DSScalarMap::global_iterator I = SM.global_begin(),
2150 E = SM.global_end(); I != E; ++I)
2151 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2152}
2153
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002154/// computeGGToGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002155/// nodes in this graph. Note that any uses of this method are probably bugs,
2156/// unless it is known that the globals graph has been merged into this graph!
2157void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2158 NodeMapTy NodeMap;
2159 computeGToGGMapping(NodeMap);
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002160
Chris Lattner36a13cd2005-03-15 17:52:18 +00002161 while (!NodeMap.empty()) {
2162 InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2163 NodeMap.begin()->first));
2164 NodeMap.erase(NodeMap.begin());
2165 }
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002166}
2167
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002168
2169/// computeCalleeCallerMapping - Given a call from a function in the current
2170/// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2171/// mapping of nodes from the callee to nodes in the caller.
2172void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2173 DSGraph &CalleeGraph,
2174 NodeMapTy &NodeMap) {
2175
2176 DSCallSite CalleeArgs =
2177 CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
2178
2179 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2180
2181 unsigned NumArgs = CS.getNumPtrArgs();
2182 if (NumArgs > CalleeArgs.getNumPtrArgs())
2183 NumArgs = CalleeArgs.getNumPtrArgs();
2184
2185 for (unsigned i = 0; i != NumArgs; ++i)
2186 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
2187
2188 // Map the nodes that are pointed to by globals.
2189 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2190 DSScalarMap &CallerSM = getScalarMap();
2191
2192 if (CalleeSM.global_size() >= CallerSM.global_size()) {
2193 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
2194 E = CallerSM.global_end(); GI != E; ++GI)
2195 if (CalleeSM.global_count(*GI))
2196 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2197 } else {
2198 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
2199 E = CalleeSM.global_end(); GI != E; ++GI)
2200 if (CallerSM.global_count(*GI))
2201 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2202 }
2203}