blob: bd1757dcfd9c83e20d25fe796828c3a7aaf3fdc3 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
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"
Chris Lattnerd8642122005-03-24 21:07:47 +000026#include "llvm/ADT/SCCIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000027#include "llvm/ADT/Statistic.h"
28#include "llvm/Support/Timer.h"
Chris Lattner72382102006-01-22 23:19:18 +000029#include <iostream>
Chris Lattner0d9bab82002-07-18 00:12:30 +000030#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Chris Lattnerb29dd0f2004-12-08 21:03:56 +000033#define COLLAPSE_ARRAYS_AGGRESSIVELY 0
34
Chris Lattner08db7192002-11-06 06:20:27 +000035namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000036 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
37 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
38 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
39 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000040 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
41 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Chris Lattner08db7192002-11-06 06:20:27 +000042};
43
Chris Lattner1e9d1472005-03-22 23:54:52 +000044#if 0
Chris Lattner93ddd7e2004-01-22 16:36:28 +000045#define TIME_REGION(VARNAME, DESC) \
46 NamedRegionTimer VARNAME(DESC)
47#else
48#define TIME_REGION(VARNAME, DESC)
49#endif
50
Chris Lattnerb1060432002-11-07 05:20:53 +000051using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000052
Chris Lattner6f967742004-10-30 04:05:01 +000053/// isForwarding - Return true if this NodeHandle is forwarding to another
54/// one.
55bool DSNodeHandle::isForwarding() const {
56 return N && N->isForwarding();
57}
58
Chris Lattner731b2d72003-02-13 19:09:00 +000059DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000060 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000061
62 // Handle node forwarding here!
63 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
64 Offset += N->ForwardNH.getOffset();
65
66 if (--N->NumReferrers == 0) {
67 // Removing the last referrer to the node, sever the forwarding link
68 N->stopForwarding();
69 }
70
71 N = Next;
72 N->NumReferrers++;
73 if (N->Size <= Offset) {
74 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
75 Offset = 0;
76 }
77 return N;
78}
79
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000080//===----------------------------------------------------------------------===//
Chris Lattner612f0b72005-03-22 00:09:45 +000081// DSScalarMap Implementation
82//===----------------------------------------------------------------------===//
83
84DSNodeHandle &DSScalarMap::AddGlobal(GlobalValue *GV) {
85 assert(ValueMap.count(GV) == 0 && "GV already exists!");
86
87 // If the node doesn't exist, check to see if it's a global that is
88 // equated to another global in the program.
89 EquivalenceClasses<GlobalValue*>::iterator ECI = GlobalECs.findValue(GV);
90 if (ECI != GlobalECs.end()) {
91 GlobalValue *Leader = *GlobalECs.findLeader(ECI);
92 if (Leader != GV) {
93 GV = Leader;
94 iterator I = ValueMap.find(GV);
95 if (I != ValueMap.end())
96 return I->second;
97 }
98 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +000099
Chris Lattner612f0b72005-03-22 00:09:45 +0000100 // Okay, this is either not an equivalenced global or it is the leader, it
101 // will be inserted into the scalar map now.
102 GlobalSet.insert(GV);
103
104 return ValueMap.insert(std::make_pair(GV, DSNodeHandle())).first->second;
105}
106
107
108//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000109// DSNode Implementation
110//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000111
Chris Lattnerbd92b732003-06-19 21:15:11 +0000112DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +0000113 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000114 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +0000115 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +0000116 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000117 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000118}
119
Chris Lattner0d9bab82002-07-18 00:12:30 +0000120// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +0000121DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +0000122 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattneraf2e3e02005-04-12 03:59:27 +0000123 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattnerf590ced2004-03-04 17:06:53 +0000124 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +0000125 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +0000126 } else
Chris Lattner0b144872004-01-27 22:03:40 +0000127 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +0000128 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000129 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000130}
131
Chris Lattner15869aa2003-11-02 22:27:28 +0000132/// getTargetData - Get the target data object used to construct this node.
133///
134const TargetData &DSNode::getTargetData() const {
135 return ParentGraph->getTargetData();
136}
137
Chris Lattner72d29a42003-02-11 23:11:51 +0000138void DSNode::assertOK() const {
139 assert((Ty != Type::VoidTy ||
140 Ty == Type::VoidTy && (Size == 0 ||
141 (NodeType & DSNode::Array))) &&
142 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000143
144 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000145 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000146 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000147 assert(SM.global_count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000148 assert(SM.find(Globals[i])->second.getNode() == this);
149 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000150}
151
152/// forwardNode - Mark this node as being obsolete, and all references to it
153/// should be forwarded to the specified node and offset.
154///
155void DSNode::forwardNode(DSNode *To, unsigned Offset) {
156 assert(this != To && "Cannot forward a node to itself!");
157 assert(ForwardNH.isNull() && "Already forwarding from this node!");
158 if (To->Size <= 1) Offset = 0;
159 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
160 "Forwarded offset is wrong!");
Chris Lattnerefffdc92004-07-07 06:12:52 +0000161 ForwardNH.setTo(To, Offset);
Chris Lattner72d29a42003-02-11 23:11:51 +0000162 NodeType = DEAD;
163 Size = 0;
164 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000165
166 // Remove this node from the parent graph's Nodes list.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000167 ParentGraph->unlinkNode(this);
Chris Lattner4ff0b962004-02-08 01:27:18 +0000168 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000169}
170
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000171// addGlobal - Add an entry for a global value to the Globals list. This also
172// marks the node with the 'G' flag if it does not already have it.
173//
174void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000175 // First, check to make sure this is the leader if the global is in an
176 // equivalence class.
177 GV = getParentGraph()->getScalarMap().getLeaderForGlobal(GV);
178
Chris Lattner0d9bab82002-07-18 00:12:30 +0000179 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000180 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000181 std::lower_bound(Globals.begin(), Globals.end(), GV);
182
183 if (I == Globals.end() || *I != GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000184 Globals.insert(I, GV);
185 NodeType |= GlobalNode;
186 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000187}
188
Chris Lattner7cdf3212005-03-20 03:29:54 +0000189// removeGlobal - Remove the specified global that is explicitly in the globals
190// list.
191void DSNode::removeGlobal(GlobalValue *GV) {
192 std::vector<GlobalValue*>::iterator I =
193 std::lower_bound(Globals.begin(), Globals.end(), GV);
194 assert(I != Globals.end() && *I == GV && "Global not in node!");
195 Globals.erase(I);
196}
197
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000198/// foldNodeCompletely - If we determine that this node has some funny
199/// behavior happening to it that we cannot represent, we fold it down to a
200/// single, completely pessimistic, node. This node is represented as a
201/// single byte with a single TypeEntry of "void".
202///
203void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000204 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000205
Chris Lattner08db7192002-11-06 06:20:27 +0000206 ++NumFolds;
207
Chris Lattner0b144872004-01-27 22:03:40 +0000208 // If this node has a size that is <= 1, we don't need to create a forwarding
209 // node.
210 if (getSize() <= 1) {
211 NodeType |= DSNode::Array;
212 Ty = Type::VoidTy;
213 Size = 1;
214 assert(Links.size() <= 1 && "Size is 1, but has more links?");
215 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000216 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000217 // Create the node we are going to forward to. This is required because
218 // some referrers may have an offset that is > 0. By forcing them to
219 // forward, the forwarder has the opportunity to correct the offset.
220 DSNode *DestNode = new DSNode(0, ParentGraph);
221 DestNode->NodeType = NodeType|DSNode::Array;
222 DestNode->Ty = Type::VoidTy;
223 DestNode->Size = 1;
224 DestNode->Globals.swap(Globals);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000225
Chris Lattner0b144872004-01-27 22:03:40 +0000226 // Start forwarding to the destination node...
227 forwardNode(DestNode, 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000228
Chris Lattner0b144872004-01-27 22:03:40 +0000229 if (!Links.empty()) {
230 DestNode->Links.reserve(1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000231
Chris Lattner0b144872004-01-27 22:03:40 +0000232 DSNodeHandle NH(DestNode);
233 DestNode->Links.push_back(Links[0]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000234
Chris Lattner0b144872004-01-27 22:03:40 +0000235 // If we have links, merge all of our outgoing links together...
236 for (unsigned i = Links.size()-1; i != 0; --i)
237 NH.getNode()->Links[0].mergeWith(Links[i]);
238 Links.clear();
239 } else {
240 DestNode->Links.resize(1);
241 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000242 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000243}
Chris Lattner076c1f92002-11-07 06:31:54 +0000244
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000245/// isNodeCompletelyFolded - Return true if this node has been completely
246/// folded down to something that can never be expanded, effectively losing
247/// all of the field sensitivity that may be present in the node.
248///
249bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000250 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000251}
252
Chris Lattner82c6c722005-03-20 02:41:38 +0000253/// addFullGlobalsList - Compute the full set of global values that are
254/// represented by this node. Unlike getGlobalsList(), this requires fair
255/// amount of work to compute, so don't treat this method call as free.
256void DSNode::addFullGlobalsList(std::vector<GlobalValue*> &List) const {
257 if (globals_begin() == globals_end()) return;
258
259 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
260
261 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
262 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
263 if (ECI == EC.end())
264 List.push_back(*I);
265 else
266 List.insert(List.end(), EC.member_begin(ECI), EC.member_end());
267 }
268}
269
270/// addFullFunctionList - Identical to addFullGlobalsList, but only return the
271/// functions in the full list.
272void DSNode::addFullFunctionList(std::vector<Function*> &List) const {
273 if (globals_begin() == globals_end()) return;
274
275 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
276
277 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
278 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
279 if (ECI == EC.end()) {
280 if (Function *F = dyn_cast<Function>(*I))
281 List.push_back(F);
282 } else {
283 for (EquivalenceClasses<GlobalValue*>::member_iterator MI =
284 EC.member_begin(ECI), E = EC.member_end(); MI != E; ++MI)
285 if (Function *F = dyn_cast<Function>(*MI))
286 List.push_back(F);
287 }
288 }
289}
290
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000291namespace {
292 /// TypeElementWalker Class - Used for implementation of physical subtyping...
293 ///
294 class TypeElementWalker {
295 struct StackState {
296 const Type *Ty;
297 unsigned Offset;
298 unsigned Idx;
299 StackState(const Type *T, unsigned Off = 0)
300 : Ty(T), Offset(Off), Idx(0) {}
301 };
302
303 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000304 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000305 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000306 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000307 Stack.push_back(T);
308 StepToLeaf();
309 }
310
311 bool isDone() const { return Stack.empty(); }
312 const Type *getCurrentType() const { return Stack.back().Ty; }
313 unsigned getCurrentOffset() const { return Stack.back().Offset; }
314
315 void StepToNextType() {
316 PopStackAndAdvance();
317 StepToLeaf();
318 }
319
320 private:
321 /// PopStackAndAdvance - Pop the current element off of the stack and
322 /// advance the underlying element to the next contained member.
323 void PopStackAndAdvance() {
324 assert(!Stack.empty() && "Cannot pop an empty stack!");
325 Stack.pop_back();
326 while (!Stack.empty()) {
327 StackState &SS = Stack.back();
328 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
329 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000330 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000331 const StructLayout *SL = TD.getStructLayout(ST);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000332 SS.Offset +=
Chris Lattner507bdf92005-01-12 04:51:37 +0000333 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000334 return;
335 }
336 Stack.pop_back(); // At the end of the structure
337 } else {
338 const ArrayType *AT = cast<ArrayType>(SS.Ty);
339 ++SS.Idx;
340 if (SS.Idx != AT->getNumElements()) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000341 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000342 return;
343 }
344 Stack.pop_back(); // At the end of the array
345 }
346 }
347 }
348
349 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
350 /// on the type stack.
351 void StepToLeaf() {
352 if (Stack.empty()) return;
353 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
354 StackState &SS = Stack.back();
355 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000356 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000357 assert(SS.Idx == 0);
358 PopStackAndAdvance();
359 } else {
360 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000361 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000362 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000363 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner507bdf92005-01-12 04:51:37 +0000364 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000365 }
366 } else {
367 const ArrayType *AT = cast<ArrayType>(SS.Ty);
368 if (AT->getNumElements() == 0) {
369 assert(SS.Idx == 0);
370 PopStackAndAdvance();
371 } else {
372 // Step into the array...
373 assert(SS.Idx < AT->getNumElements());
374 Stack.push_back(StackState(AT->getElementType(),
375 SS.Offset+SS.Idx*
Chris Lattner507bdf92005-01-12 04:51:37 +0000376 unsigned(TD.getTypeSize(AT->getElementType()))));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000377 }
378 }
379 }
380 }
381 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000382} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000383
384/// ElementTypesAreCompatible - Check to see if the specified types are
385/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000386/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
387/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000388///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000389static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000390 bool AllowLargerT1, const TargetData &TD){
391 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000392
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000393 while (!T1W.isDone() && !T2W.isDone()) {
394 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
395 return false;
396
397 const Type *T1 = T1W.getCurrentType();
398 const Type *T2 = T2W.getCurrentType();
399 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
400 return false;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000401
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000402 T1W.StepToNextType();
403 T2W.StepToNextType();
404 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000405
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000406 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000407}
408
409
Chris Lattner08db7192002-11-06 06:20:27 +0000410/// mergeTypeInfo - This method merges the specified type into the current node
411/// at the specified offset. This may update the current node's type record if
412/// this gives more information to the node, it may do nothing to the node if
413/// this information is already known, or it may merge the node completely (and
414/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000415///
Chris Lattner08db7192002-11-06 06:20:27 +0000416/// This method returns true if the node is completely folded, otherwise false.
417///
Chris Lattner088b6392003-03-03 17:13:31 +0000418bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
419 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000420 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000421 // Check to make sure the Size member is up-to-date. Size can be one of the
422 // following:
423 // Size = 0, Ty = Void: Nothing is known about this node.
424 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
425 // Size = 1, Ty = Void, Array = 1: The node is collapsed
426 // Otherwise, sizeof(Ty) = Size
427 //
Chris Lattner18552922002-11-18 21:44:46 +0000428 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
429 (Size == 0 && !Ty->isSized() && !isArray()) ||
430 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
431 (Size == 0 && !Ty->isSized() && !isArray()) ||
432 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000433 "Size member of DSNode doesn't match the type structure!");
434 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000435
Chris Lattner18552922002-11-18 21:44:46 +0000436 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000437 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000438
Chris Lattner08db7192002-11-06 06:20:27 +0000439 // Return true immediately if the node is completely folded.
440 if (isNodeCompletelyFolded()) return true;
441
Chris Lattner23f83dc2002-11-08 22:49:57 +0000442 // If this is an array type, eliminate the outside arrays because they won't
443 // be used anyway. This greatly reduces the size of large static arrays used
444 // as global variables, for example.
445 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000446 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000447 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
448 // FIXME: we might want to keep small arrays, but must be careful about
449 // things like: [2 x [10000 x int*]]
450 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000451 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000452 }
453
Chris Lattner08db7192002-11-06 06:20:27 +0000454 // Figure out how big the new type we're merging in is...
Chris Lattner507bdf92005-01-12 04:51:37 +0000455 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000456
457 // Otherwise check to see if we can fold this type into the current node. If
458 // we can't, we fold the node completely, if we can, we potentially update our
459 // internal state.
460 //
Chris Lattner18552922002-11-18 21:44:46 +0000461 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000462 // If this is the first type that this node has seen, just accept it without
463 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000464 assert(Offset == 0 && !isArray() &&
465 "Cannot have an offset into a void node!");
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000466
467 // If this node would have to have an unreasonable number of fields, just
468 // collapse it. This can occur for fortran common blocks, which have stupid
469 // things like { [100000000 x double], [1000000 x double] }.
470 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
Chris Lattner1e9d1472005-03-22 23:54:52 +0000471 if (NumFields > 256) {
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000472 foldNodeCompletely();
473 return true;
474 }
475
Chris Lattner18552922002-11-18 21:44:46 +0000476 Ty = NewTy;
477 NodeType &= ~Array;
478 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000479 Size = NewTySize;
480
481 // Calculate the number of outgoing links from this node.
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000482 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000483 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000484 }
Chris Lattner08db7192002-11-06 06:20:27 +0000485
486 // Handle node expansion case here...
487 if (Offset+NewTySize > Size) {
488 // It is illegal to grow this node if we have treated it as an array of
489 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000490 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000491 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000492 return true;
493 }
494
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000495 // If this node would have to have an unreasonable number of fields, just
496 // collapse it. This can occur for fortran common blocks, which have stupid
497 // things like { [100000000 x double], [1000000 x double] }.
498 unsigned NumFields = (NewTySize+Offset+DS::PointerSize-1) >> DS::PointerShift;
499 if (NumFields > 256) {
500 foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000501 return true;
502 }
503
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000504 if (Offset) {
505 //handle some common cases:
506 // Ty: struct { t1, t2, t3, t4, ..., tn}
507 // NewTy: struct { offset, stuff...}
508 // try merge with NewTy: struct {t1, t2, stuff...} if offset lands exactly on a field in Ty
509 if (isa<StructType>(NewTy) && isa<StructType>(Ty)) {
510 DEBUG(std::cerr << "Ty: " << *Ty << "\nNewTy: " << *NewTy << "@" << Offset << "\n");
511 unsigned O = 0;
512 const StructType *STy = cast<StructType>(Ty);
513 const StructLayout &SL = *TD.getStructLayout(STy);
514 unsigned i = SL.getElementContainingOffset(Offset);
515 //Either we hit it exactly or give up
516 if (SL.MemberOffsets[i] != Offset) {
517 if (FoldIfIncompatible) foldNodeCompletely();
518 return true;
519 }
520 std::vector<const Type*> nt;
521 for (unsigned x = 0; x < i; ++x)
522 nt.push_back(STy->getElementType(x));
523 STy = cast<StructType>(NewTy);
524 nt.insert(nt.end(), STy->element_begin(), STy->element_end());
525 //and merge
526 STy = StructType::get(nt);
527 DEBUG(std::cerr << "Trying with: " << *STy << "\n");
528 return mergeTypeInfo(STy, 0);
529 }
530
531 std::cerr << "UNIMP: Trying to merge a growth type into "
532 << "offset != 0: Collapsing!\n";
533 abort();
534 if (FoldIfIncompatible) foldNodeCompletely();
535 return true;
536
537 }
538
539
Chris Lattner08db7192002-11-06 06:20:27 +0000540 // Okay, the situation is nice and simple, we are trying to merge a type in
541 // at offset 0 that is bigger than our current type. Implement this by
542 // switching to the new type and then merge in the smaller one, which should
543 // hit the other code path here. If the other code path decides it's not
544 // ok, it will collapse the node as appropriate.
545 //
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000546
Chris Lattner94f84702005-03-17 19:56:56 +0000547 const Type *OldTy = Ty;
548 Ty = NewTy;
549 NodeType &= ~Array;
550 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000551 Size = NewTySize;
552
553 // Must grow links to be the appropriate size...
Chris Lattner94f84702005-03-17 19:56:56 +0000554 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000555
556 // Merge in the old type now... which is guaranteed to be smaller than the
557 // "current" type.
558 return mergeTypeInfo(OldTy, 0);
559 }
560
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000561 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000562 "Cannot merge something into a part of our type that doesn't exist!");
563
Chris Lattner18552922002-11-18 21:44:46 +0000564 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000565 // type that starts at offset Offset.
566 //
567 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000568 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000569 while (O < Offset) {
570 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
571
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000572 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000573 case Type::StructTyID: {
574 const StructType *STy = cast<StructType>(SubType);
575 const StructLayout &SL = *TD.getStructLayout(STy);
Chris Lattner2787e032005-03-13 19:05:05 +0000576 unsigned i = SL.getElementContainingOffset(Offset-O);
Chris Lattner08db7192002-11-06 06:20:27 +0000577
578 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000579 SubType = STy->getElementType(i);
Chris Lattner507bdf92005-01-12 04:51:37 +0000580 O += (unsigned)SL.MemberOffsets[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000581 break;
582 }
583 case Type::ArrayTyID: {
584 SubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000585 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000586 unsigned Remainder = (Offset-O) % ElSize;
587 O = Offset-Remainder;
588 break;
589 }
590 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000591 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000592 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000593 }
594 }
595
596 assert(O == Offset && "Could not achieve the correct offset!");
597
598 // If we found our type exactly, early exit
599 if (SubType == NewTy) return false;
600
Misha Brukman96a8bd72004-04-29 04:05:30 +0000601 // Differing function types don't require us to merge. They are not values
602 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000603 if (isa<FunctionType>(SubType) &&
604 isa<FunctionType>(NewTy)) return false;
605
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000606 unsigned SubTypeSize = SubType->isSized() ?
Chris Lattner507bdf92005-01-12 04:51:37 +0000607 (unsigned)TD.getTypeSize(SubType) : 0;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000608
609 // Ok, we are getting desperate now. Check for physical subtyping, where we
610 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000611 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000612 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000613 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000614 return false;
615
Chris Lattner08db7192002-11-06 06:20:27 +0000616 // Okay, so we found the leader type at the offset requested. Search the list
617 // of types that starts at this offset. If SubType is currently an array or
618 // structure, the type desired may actually be the first element of the
619 // composite type...
620 //
Chris Lattner18552922002-11-18 21:44:46 +0000621 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000622 while (SubType != NewTy) {
623 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000624 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000625 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000626 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000627 case Type::StructTyID: {
628 const StructType *STy = cast<StructType>(SubType);
629 const StructLayout &SL = *TD.getStructLayout(STy);
630 if (SL.MemberOffsets.size() > 1)
Chris Lattner507bdf92005-01-12 04:51:37 +0000631 NextPadSize = (unsigned)SL.MemberOffsets[1];
Chris Lattner18552922002-11-18 21:44:46 +0000632 else
633 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000634 NextSubType = STy->getElementType(0);
Chris Lattner507bdf92005-01-12 04:51:37 +0000635 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000636 break;
Chris Lattner18552922002-11-18 21:44:46 +0000637 }
Chris Lattner08db7192002-11-06 06:20:27 +0000638 case Type::ArrayTyID:
639 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000640 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner18552922002-11-18 21:44:46 +0000641 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000642 break;
643 default: ;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000644 // fall out
Chris Lattner08db7192002-11-06 06:20:27 +0000645 }
646
647 if (NextSubType == 0)
648 break; // In the default case, break out of the loop
649
Chris Lattner18552922002-11-18 21:44:46 +0000650 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000651 break; // Don't allow shrinking to a smaller type than NewTySize
652 SubType = NextSubType;
653 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000654 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000655 }
656
657 // If we found the type exactly, return it...
658 if (SubType == NewTy)
659 return false;
660
661 // Check to see if we have a compatible, but different type...
662 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000663 // Check to see if this type is obviously convertible... int -> uint f.e.
664 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000665 return false;
666
667 // Check to see if we have a pointer & integer mismatch going on here,
668 // loading a pointer as a long, for example.
669 //
670 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
671 NewTy->isInteger() && isa<PointerType>(SubType))
672 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000673 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
674 // We are accessing the field, plus some structure padding. Ignore the
675 // structure padding.
676 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000677 }
678
Chris Lattner58f98d02003-07-02 04:38:49 +0000679 Module *M = 0;
Chris Lattnera5f47ea2005-03-15 16:55:04 +0000680 if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
681 M = getParentGraph()->retnodes_begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000682 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
683 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
684 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
685 << "SubType: ";
686 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000687
Chris Lattner088b6392003-03-03 17:13:31 +0000688 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000689 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000690}
691
Chris Lattner08db7192002-11-06 06:20:27 +0000692
693
Misha Brukman96a8bd72004-04-29 04:05:30 +0000694/// addEdgeTo - Add an edge from the current node to the specified node. This
695/// can cause merging of nodes in the graph.
696///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000697void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000698 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000699
Chris Lattner08db7192002-11-06 06:20:27 +0000700 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000701 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000702 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000703 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000704 } else { // No merging to perform...
705 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000706 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000707}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000708
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000709
Misha Brukman96a8bd72004-04-29 04:05:30 +0000710/// MergeSortedVectors - Efficiently merge a vector into another vector where
711/// duplicates are not allowed and both are sorted. This assumes that 'T's are
712/// efficiently copyable and have sane comparison semantics.
713///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000714static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
715 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000716 // By far, the most common cases will be the simple ones. In these cases,
717 // avoid having to allocate a temporary vector...
718 //
719 if (Src.empty()) { // Nothing to merge in...
720 return;
721 } else if (Dest.empty()) { // Just copy the result in...
722 Dest = Src;
723 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000724 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000725 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000726 std::lower_bound(Dest.begin(), Dest.end(), V);
727 if (I == Dest.end() || *I != Src[0]) // If not already contained...
728 Dest.insert(I, Src[0]);
729 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000730 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000731 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000732 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000733 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
734 if (I == Dest.end() || *I != Tmp) // If not already contained...
735 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000736
737 } else {
738 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000739 std::vector<GlobalValue*> Old(Dest);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000740
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000741 // Make space for all of the type entries now...
742 Dest.resize(Dest.size()+Src.size());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000743
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000744 // Merge the two sorted ranges together... into Dest.
745 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000746
747 // Now erase any duplicate entries that may have accumulated into the
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000748 // vectors (because they were in both of the input sets)
749 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
750 }
751}
752
Chris Lattner0b144872004-01-27 22:03:40 +0000753void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
754 MergeSortedVectors(Globals, RHS);
755}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000756
Chris Lattner0b144872004-01-27 22:03:40 +0000757// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000758// This function does the hard work of merging two nodes, CurNodeH
759// and NH after filtering out trivial cases and making sure that
760// CurNodeH.offset >= NH.offset.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000761//
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000762// ***WARNING***
763// Since merging may cause either node to go away, we must always
764// use the node-handles to refer to the nodes. These node handles are
765// automatically updated during merging, so will always provide access
766// to the correct node after a merge.
767//
768void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
769 assert(CurNodeH.getOffset() >= NH.getOffset() &&
770 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000771 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
772 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000773
774 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
775 // respect to NH.Offset) is now zero. NOffset is the distance from the base
776 // of our object that N starts from.
777 //
778 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
779 unsigned NSize = NH.getNode()->getSize();
780
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000781 // If the two nodes are of different size, and the smaller node has the array
782 // bit set, collapse!
783 if (NSize != CurNodeH.getNode()->getSize()) {
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000784#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000785 if (NSize < CurNodeH.getNode()->getSize()) {
786 if (NH.getNode()->isArray())
787 NH.getNode()->foldNodeCompletely();
788 } else if (CurNodeH.getNode()->isArray()) {
789 NH.getNode()->foldNodeCompletely();
790 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000791#endif
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000792 }
793
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000794 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000795 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000796 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000797 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000798
799 // If we are merging a node with a completely folded node, then both nodes are
800 // now completely folded.
801 //
802 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
803 if (!NH.getNode()->isNodeCompletelyFolded()) {
804 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000805 assert(NH.getNode() && NH.getOffset() == 0 &&
806 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000807 NOffset = NH.getOffset();
808 NSize = NH.getNode()->getSize();
809 assert(NOffset == 0 && NSize == 1);
810 }
811 } else if (NH.getNode()->isNodeCompletelyFolded()) {
812 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000813 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
814 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000815 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000816 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000817 assert(NOffset == 0 && NSize == 1);
818 }
819
Chris Lattner72d29a42003-02-11 23:11:51 +0000820 DSNode *N = NH.getNode();
821 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000822 assert(!CurNodeH.getNode()->isDeadNode());
823
Chris Lattner0b144872004-01-27 22:03:40 +0000824 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000825 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000826
Chris Lattner72d29a42003-02-11 23:11:51 +0000827 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000828 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000829 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000830
Chris Lattner72d29a42003-02-11 23:11:51 +0000831 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
832 //
833 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
834 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000835 if (Link.getNode()) {
836 // Compute the offset into the current node at which to
837 // merge this link. In the common case, this is a linear
838 // relation to the offset in the original node (with
839 // wrapping), but if the current node gets collapsed due to
840 // recursive merging, we must make sure to merge in all remaining
841 // links at offset zero.
842 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000843 DSNode *CN = CurNodeH.getNode();
844 if (CN->Size != 1)
845 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
846 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000847 }
848 }
849
850 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000851 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000852
853 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000854 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000855 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000856
857 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000858 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000859 }
860}
861
862
Misha Brukman96a8bd72004-04-29 04:05:30 +0000863/// mergeWith - Merge this node and the specified node, moving all links to and
864/// from the argument node into the current node, deleting the node argument.
865/// Offset indicates what offset the specified node is to be merged into the
866/// current node.
867///
868/// The specified node may be a null pointer (in which case, we update it to
869/// point to this node).
870///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000871void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
872 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000873 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000874 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000875
Chris Lattner5254a8d2004-01-22 16:31:08 +0000876 // If the RHS is a null node, make it point to this node!
877 if (N == 0) {
878 NH.mergeWith(DSNodeHandle(this, Offset));
879 return;
880 }
881
Chris Lattnerbd92b732003-06-19 21:15:11 +0000882 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000883 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
884
Chris Lattner02606632002-11-04 06:48:26 +0000885 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000886 // We cannot merge two pieces of the same node together, collapse the node
887 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000888 DEBUG(std::cerr << "Attempting to merge two chunks of"
889 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000890 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000891 return;
892 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000893
Chris Lattner5190ce82002-11-12 07:20:45 +0000894 // If both nodes are not at offset 0, make sure that we are merging the node
895 // at an later offset into the node with the zero offset.
896 //
897 if (Offset < NH.getOffset()) {
898 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
899 return;
900 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
901 // If the offsets are the same, merge the smaller node into the bigger node
902 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
903 return;
904 }
905
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000906 // Ok, now we can merge the two nodes. Use a static helper that works with
907 // two node handles, since "this" may get merged away at intermediate steps.
908 DSNodeHandle CurNodeH(this, Offset);
909 DSNodeHandle NHCopy(NH);
910 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000911}
912
Chris Lattner0b144872004-01-27 22:03:40 +0000913
914//===----------------------------------------------------------------------===//
915// ReachabilityCloner Implementation
916//===----------------------------------------------------------------------===//
917
918DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
919 if (SrcNH.isNull()) return DSNodeHandle();
920 const DSNode *SN = SrcNH.getNode();
921
922 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000923 if (!NH.isNull()) { // Node already mapped?
924 DSNode *NHN = NH.getNode();
925 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
926 }
Chris Lattner0b144872004-01-27 22:03:40 +0000927
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000928 // If SrcNH has globals and the destination graph has one of the same globals,
929 // merge this node with the destination node, which is much more efficient.
Chris Lattner82c6c722005-03-20 02:41:38 +0000930 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000931 DSScalarMap &DestSM = Dest.getScalarMap();
Chris Lattner82c6c722005-03-20 02:41:38 +0000932 for (DSNode::globals_iterator I = SN->globals_begin(),E = SN->globals_end();
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000933 I != E; ++I) {
934 GlobalValue *GV = *I;
935 DSScalarMap::iterator GI = DestSM.find(GV);
936 if (GI != DestSM.end() && !GI->second.isNull()) {
937 // We found one, use merge instead!
938 merge(GI->second, Src.getNodeForValue(GV));
939 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000940 DSNode *NHN = NH.getNode();
941 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000942 }
943 }
944 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000945
Chris Lattner0b144872004-01-27 22:03:40 +0000946 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
947 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000948 NH = DN;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000949
Chris Lattner0b144872004-01-27 22:03:40 +0000950 // Next, recursively clone all outgoing links as necessary. Note that
951 // adding these links can cause the node to collapse itself at any time, and
952 // the current node may be merged with arbitrary other nodes. For this
953 // reason, we must always go through NH.
954 DN = 0;
955 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
956 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
957 if (!SrcEdge.isNull()) {
958 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
959 // Compute the offset into the current node at which to
960 // merge this link. In the common case, this is a linear
961 // relation to the offset in the original node (with
962 // wrapping), but if the current node gets collapsed due to
963 // recursive merging, we must make sure to merge in all remaining
964 // links at offset zero.
965 unsigned MergeOffset = 0;
966 DSNode *CN = NH.getNode();
967 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +0000968 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +0000969 CN->addEdgeTo(MergeOffset, DestEdge);
970 }
971 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000972
Chris Lattner0b144872004-01-27 22:03:40 +0000973 // If this node contains any globals, make sure they end up in the scalar
974 // map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +0000975 for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
Chris Lattner0b144872004-01-27 22:03:40 +0000976 I != E; ++I) {
977 GlobalValue *GV = *I;
978 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
979 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
980 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
981 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000982 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000983 }
Chris Lattner82c6c722005-03-20 02:41:38 +0000984 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +0000985
986 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
987}
988
989void ReachabilityCloner::merge(const DSNodeHandle &NH,
990 const DSNodeHandle &SrcNH) {
991 if (SrcNH.isNull()) return; // Noop
992 if (NH.isNull()) {
993 // If there is no destination node, just clone the source and assign the
994 // destination node to be it.
995 NH.mergeWith(getClonedNH(SrcNH));
996 return;
997 }
998
999 // Okay, at this point, we know that we have both a destination and a source
1000 // node that need to be merged. Check to see if the source node has already
1001 // been cloned.
1002 const DSNode *SN = SrcNH.getNode();
1003 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +00001004 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +00001005 DSNode *SCNHN = SCNH.getNode();
1006 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +00001007 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001008 return; // Nothing to do!
1009 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001010
Chris Lattner0b144872004-01-27 22:03:40 +00001011 // Okay, so the source node has not already been cloned. Instead of creating
1012 // a new DSNode, only to merge it into the one we already have, try to perform
1013 // the merge in-place. The only case we cannot handle here is when the offset
1014 // into the existing node is less than the offset into the virtual node we are
1015 // merging in. In this case, we have to extend the existing node, which
1016 // requires an allocation anyway.
1017 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
1018 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +00001019 if (!DN->isNodeCompletelyFolded()) {
1020 // Make sure the destination node is folded if the source node is folded.
1021 if (SN->isNodeCompletelyFolded()) {
1022 DN->foldNodeCompletely();
1023 DN = NH.getNode();
1024 } else if (SN->getSize() != DN->getSize()) {
1025 // If the two nodes are of different size, and the smaller node has the
1026 // array bit set, collapse!
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001027#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner0b144872004-01-27 22:03:40 +00001028 if (SN->getSize() < DN->getSize()) {
1029 if (SN->isArray()) {
1030 DN->foldNodeCompletely();
1031 DN = NH.getNode();
1032 }
1033 } else if (DN->isArray()) {
1034 DN->foldNodeCompletely();
1035 DN = NH.getNode();
1036 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001037#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001038 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001039
1040 // Merge the type entries of the two nodes together...
Chris Lattner0b144872004-01-27 22:03:40 +00001041 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
1042 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
1043 DN = NH.getNode();
1044 }
1045 }
1046
1047 assert(!DN->isDeadNode());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001048
Chris Lattner0b144872004-01-27 22:03:40 +00001049 // Merge the NodeType information.
1050 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
1051
1052 // Before we start merging outgoing links and updating the scalar map, make
1053 // sure it is known that this is the representative node for the src node.
1054 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
1055
1056 // If the source node contains any globals, make sure they end up in the
1057 // scalar map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +00001058 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattner0b144872004-01-27 22:03:40 +00001059 // Update the globals in the destination node itself.
Chris Lattner82c6c722005-03-20 02:41:38 +00001060 DN->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001061
1062 // Update the scalar map for the graph we are merging the source node
1063 // into.
Chris Lattner82c6c722005-03-20 02:41:38 +00001064 for (DSNode::globals_iterator I = SN->globals_begin(),
1065 E = SN->globals_end(); I != E; ++I) {
Chris Lattner0b144872004-01-27 22:03:40 +00001066 GlobalValue *GV = *I;
1067 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1068 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1069 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1070 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +00001071 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001072 }
Chris Lattner82c6c722005-03-20 02:41:38 +00001073 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001074 }
1075 } else {
1076 // We cannot handle this case without allocating a temporary node. Fall
1077 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +00001078 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
1079 NewDN->maskNodeTypes(BitsToKeep);
1080
1081 unsigned NHOffset = NH.getOffset();
1082 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001083
Chris Lattner0b144872004-01-27 22:03:40 +00001084 assert(NH.getNode() &&
1085 (NH.getOffset() > NHOffset ||
1086 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
1087 "Merging did not adjust the offset!");
1088
1089 // Before we start merging outgoing links and updating the scalar map, make
1090 // sure it is known that this is the representative node for the src node.
1091 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +00001092
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001093 // If the source node contained any globals, make sure to create entries
Chris Lattneread9eb72004-01-29 08:36:22 +00001094 // in the scalar map for them!
Chris Lattner82c6c722005-03-20 02:41:38 +00001095 for (DSNode::globals_iterator I = SN->globals_begin(),
1096 E = SN->globals_end(); I != E; ++I) {
Chris Lattneread9eb72004-01-29 08:36:22 +00001097 GlobalValue *GV = *I;
1098 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1099 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1100 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1101 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
1102 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1103 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001104 }
Chris Lattner0b144872004-01-27 22:03:40 +00001105 }
1106
1107
1108 // Next, recursively merge all outgoing links as necessary. Note that
1109 // adding these links can cause the destination node to collapse itself at
1110 // any time, and the current node may be merged with arbitrary other nodes.
1111 // For this reason, we must always go through NH.
1112 DN = 0;
1113 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1114 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1115 if (!SrcEdge.isNull()) {
1116 // Compute the offset into the current node at which to
1117 // merge this link. In the common case, this is a linear
1118 // relation to the offset in the original node (with
1119 // wrapping), but if the current node gets collapsed due to
1120 // recursive merging, we must make sure to merge in all remaining
1121 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +00001122 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +00001123 unsigned MergeOffset =
1124 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001125
Chris Lattnerf590ced2004-03-04 17:06:53 +00001126 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1127 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001128 // Perform the recursive merging. Make sure to create a temporary NH,
1129 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001130 merge(Tmp, SrcEdge);
1131 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001132 Tmp.mergeWith(getClonedNH(SrcEdge));
1133 // Merging this could cause all kinds of recursive things to happen,
1134 // culminating in the current node being eliminated. Since this is
1135 // possible, make sure to reaquire the link from 'CN'.
1136
1137 unsigned MergeOffset = 0;
1138 CN = SCNH.getNode();
1139 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1140 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001141 }
Chris Lattner0b144872004-01-27 22:03:40 +00001142 }
1143 }
1144}
1145
1146/// mergeCallSite - Merge the nodes reachable from the specified src call
1147/// site into the nodes reachable from DestCS.
Chris Lattnerb3439372005-03-21 20:28:50 +00001148void ReachabilityCloner::mergeCallSite(DSCallSite &DestCS,
Chris Lattner0b144872004-01-27 22:03:40 +00001149 const DSCallSite &SrcCS) {
1150 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1151 unsigned MinArgs = DestCS.getNumPtrArgs();
1152 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001153
Chris Lattner0b144872004-01-27 22:03:40 +00001154 for (unsigned a = 0; a != MinArgs; ++a)
1155 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
Chris Lattner3f90a942005-03-21 09:39:51 +00001156
1157 for (unsigned a = MinArgs, e = SrcCS.getNumPtrArgs(); a != e; ++a)
Chris Lattnerb3439372005-03-21 20:28:50 +00001158 DestCS.addPtrArg(getClonedNH(SrcCS.getPtrArg(a)));
Chris Lattner0b144872004-01-27 22:03:40 +00001159}
1160
1161
Chris Lattner9de906c2002-10-20 22:11:44 +00001162//===----------------------------------------------------------------------===//
1163// DSCallSite Implementation
1164//===----------------------------------------------------------------------===//
1165
Vikram S. Adve26b98262002-10-20 21:41:02 +00001166// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001167Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001168 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001169}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001170
Chris Lattner0b144872004-01-27 22:03:40 +00001171void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1172 ReachabilityCloner &RC) {
1173 NH = RC.getClonedNH(Src);
1174}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001175
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001176//===----------------------------------------------------------------------===//
1177// DSGraph Implementation
1178//===----------------------------------------------------------------------===//
1179
Chris Lattnera9d65662003-06-30 05:57:30 +00001180/// getFunctionNames - Return a space separated list of the name of the
1181/// functions in this graph (if any)
1182std::string DSGraph::getFunctionNames() const {
1183 switch (getReturnNodes().size()) {
1184 case 0: return "Globals graph";
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001185 case 1: return retnodes_begin()->first->getName();
Chris Lattnera9d65662003-06-30 05:57:30 +00001186 default:
1187 std::string Return;
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001188 for (DSGraph::retnodes_iterator I = retnodes_begin();
1189 I != retnodes_end(); ++I)
Chris Lattnera9d65662003-06-30 05:57:30 +00001190 Return += I->first->getName() + " ";
1191 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1192 return Return;
1193 }
1194}
1195
1196
Chris Lattnerf09ecff2005-03-21 22:49:53 +00001197DSGraph::DSGraph(const DSGraph &G, EquivalenceClasses<GlobalValue*> &ECs,
1198 unsigned CloneFlags)
Chris Lattnerf4f62272005-03-19 22:23:45 +00001199 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001200 PrintAuxCalls = false;
Chris Lattnera2197132005-03-22 00:36:51 +00001201 cloneInto(G, CloneFlags);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001202}
1203
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001204DSGraph::~DSGraph() {
1205 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001206 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001207 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001208 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001209
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001210 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001211 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
Chris Lattner84b80a22005-03-16 22:42:19 +00001212 NI->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001213
Chris Lattner28897e12004-02-08 00:53:26 +00001214 // Free all of the nodes.
1215 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001216}
1217
Chris Lattner0d9bab82002-07-18 00:12:30 +00001218// dump - Allow inspection of graph in a debugger.
1219void DSGraph::dump() const { print(std::cerr); }
1220
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001221
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001222/// remapLinks - Change all of the Links in the current node according to the
1223/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001224///
Chris Lattner8d327672003-06-30 03:36:09 +00001225void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001226 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1227 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001228 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001229 if (ONMI != OldNodeMap.end()) {
1230 DSNode *ONMIN = ONMI->second.getNode();
1231 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1232 }
Chris Lattner2f561382004-01-22 16:56:13 +00001233 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001234}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001235
Chris Lattnerd672ab92005-02-15 18:40:55 +00001236/// addObjectToGraph - This method can be used to add global, stack, and heap
1237/// objects to the graph. This can be used when updating DSGraphs due to the
1238/// introduction of new temporary objects. The new object is not pointed to
1239/// and does not point to any other objects in the graph.
1240DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1241 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1242 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1243 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
Chris Lattner7a0c7752005-02-15 18:48:48 +00001244 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
Chris Lattnerd672ab92005-02-15 18:40:55 +00001245 ScalarMap[Ptr] = N;
1246
1247 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1248 N->addGlobal(GV);
1249 } else if (MallocInst *MI = dyn_cast<MallocInst>(Ptr)) {
1250 N->setHeapNodeMarker();
1251 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr)) {
1252 N->setAllocaNodeMarker();
1253 } else {
1254 assert(0 && "Illegal memory object input!");
1255 }
1256 return N;
1257}
1258
1259
Chris Lattner5a540632003-06-30 03:15:25 +00001260/// cloneInto - Clone the specified DSGraph into the current graph. The
Chris Lattner3c920fa2005-03-22 00:21:05 +00001261/// translated ScalarMap for the old function is filled into the ScalarMap
1262/// for the graph, and the translated ReturnNodes map is returned into
1263/// ReturnNodes.
Chris Lattner5a540632003-06-30 03:15:25 +00001264///
1265/// The CloneFlags member controls various aspects of the cloning process.
1266///
Chris Lattnera2197132005-03-22 00:36:51 +00001267void DSGraph::cloneInto(const DSGraph &G, unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001268 TIME_REGION(X, "cloneInto");
Chris Lattner33312f72002-11-08 01:21:07 +00001269 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001270
Chris Lattnera2197132005-03-22 00:36:51 +00001271 NodeMapTy OldNodeMap;
1272
Chris Lattner1e883692003-02-03 20:08:51 +00001273 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001274 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1275 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1276 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001277 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001278
Chris Lattner84b80a22005-03-16 22:42:19 +00001279 for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1280 assert(!I->isForwarding() &&
Chris Lattnerd85645f2004-02-21 22:28:26 +00001281 "Forward nodes shouldn't be in node list!");
Chris Lattner84b80a22005-03-16 22:42:19 +00001282 DSNode *New = new DSNode(*I, this);
Chris Lattnerd85645f2004-02-21 22:28:26 +00001283 New->maskNodeTypes(~BitsToClear);
Chris Lattner84b80a22005-03-16 22:42:19 +00001284 OldNodeMap[I] = New;
Chris Lattnerd85645f2004-02-21 22:28:26 +00001285 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001286
Chris Lattner18552922002-11-18 21:44:46 +00001287#ifndef NDEBUG
1288 Timer::addPeakMemoryMeasurement();
1289#endif
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001290
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001291 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001292 // Note that we don't loop over the node's list to do this. The problem is
1293 // that remaping links can cause recursive merging to happen, which means
1294 // that node_iterator's can get easily invalidated! Because of this, we
1295 // loop over the OldNodeMap, which contains all of the new nodes as the
1296 // .second element of the map elements. Also note that if we remap a node
1297 // more than once, we won't break anything.
1298 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1299 I != E; ++I)
1300 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001301
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001302 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001303 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001304 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001305 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner3bc703b2005-03-22 01:42:59 +00001306 DSNodeHandle &H = ScalarMap.getRawEntryRef(I->first);
Chris Lattner6f967742004-10-30 04:05:01 +00001307 DSNode *MappedNodeN = MappedNode.getNode();
1308 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001309 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001310 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001311
Chris Lattner679e8e12002-11-08 21:27:12 +00001312 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001313 // Copy the function calls list.
1314 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1315 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001316 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001317
Chris Lattneracf491f2002-11-08 22:27:09 +00001318 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001319 // Copy the auxiliary function calls list.
1320 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1321 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattner679e8e12002-11-08 21:27:12 +00001322 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001323
Chris Lattner5a540632003-06-30 03:15:25 +00001324 // Map the return node pointers over...
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001325 for (retnodes_iterator I = G.retnodes_begin(),
1326 E = G.retnodes_end(); I != E; ++I) {
Chris Lattner5a540632003-06-30 03:15:25 +00001327 const DSNodeHandle &Ret = I->second;
1328 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001329 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattnerd65145b2005-03-22 00:29:44 +00001330 ReturnNodes.insert(std::make_pair(I->first,
1331 DSNodeHandle(MappedRetN,
1332 MappedRet.getOffset()+Ret.getOffset())));
Chris Lattner5a540632003-06-30 03:15:25 +00001333 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001334}
1335
Chris Lattner5734e432005-03-24 23:46:04 +00001336/// spliceFrom - Logically perform the operation of cloning the RHS graph into
1337/// this graph, then clearing the RHS graph. Instead of performing this as
1338/// two seperate operations, do it as a single, much faster, one.
1339///
1340void DSGraph::spliceFrom(DSGraph &RHS) {
1341 // Change all of the nodes in RHS to think we are their parent.
1342 for (NodeListTy::iterator I = RHS.Nodes.begin(), E = RHS.Nodes.end();
1343 I != E; ++I)
1344 I->setParentGraph(this);
1345 // Take all of the nodes.
1346 Nodes.splice(Nodes.end(), RHS.Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001347
Chris Lattner5734e432005-03-24 23:46:04 +00001348 // Take all of the calls.
1349 FunctionCalls.splice(FunctionCalls.end(), RHS.FunctionCalls);
1350 AuxFunctionCalls.splice(AuxFunctionCalls.end(), RHS.AuxFunctionCalls);
1351
1352 // Take all of the return nodes.
Chris Lattnerce7068d2005-03-25 00:02:41 +00001353 if (ReturnNodes.empty()) {
1354 ReturnNodes.swap(RHS.ReturnNodes);
1355 } else {
1356 ReturnNodes.insert(RHS.ReturnNodes.begin(), RHS.ReturnNodes.end());
1357 RHS.ReturnNodes.clear();
1358 }
Chris Lattner5734e432005-03-24 23:46:04 +00001359
1360 // Merge the scalar map in.
1361 ScalarMap.spliceFrom(RHS.ScalarMap);
1362}
1363
1364/// spliceFrom - Copy all entries from RHS, then clear RHS.
1365///
1366void DSScalarMap::spliceFrom(DSScalarMap &RHS) {
1367 // Special case if this is empty.
1368 if (ValueMap.empty()) {
1369 ValueMap.swap(RHS.ValueMap);
1370 GlobalSet.swap(RHS.GlobalSet);
1371 } else {
1372 GlobalSet.insert(RHS.GlobalSet.begin(), RHS.GlobalSet.end());
1373 for (ValueMapTy::iterator I = RHS.ValueMap.begin(), E = RHS.ValueMap.end();
1374 I != E; ++I)
1375 ValueMap[I->first].mergeWith(I->second);
1376 RHS.ValueMap.clear();
1377 }
1378}
1379
1380
Chris Lattnerbb753c42005-02-03 18:40:25 +00001381/// getFunctionArgumentsForCall - Given a function that is currently in this
1382/// graph, return the DSNodeHandles that correspond to the pointer-compatible
1383/// function arguments. The vector is filled in with the return value (or
1384/// null if it is not pointer compatible), followed by all of the
1385/// pointer-compatible arguments.
1386void DSGraph::getFunctionArgumentsForCall(Function *F,
1387 std::vector<DSNodeHandle> &Args) const {
1388 Args.push_back(getReturnNodeFor(*F));
Chris Lattnereb394922005-03-23 16:43:11 +00001389 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1390 AI != E; ++AI)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001391 if (isPointerType(AI->getType())) {
1392 Args.push_back(getNodeForValue(AI));
1393 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1394 }
1395}
1396
Chris Lattner4da120e2005-03-24 23:06:02 +00001397namespace {
1398 // HackedGraphSCCFinder - This is used to find nodes that have a path from the
1399 // node to a node cloned by the ReachabilityCloner object contained. To be
1400 // extra obnoxious it ignores edges from nodes that are globals, and truncates
1401 // search at RC marked nodes. This is designed as an object so that
1402 // intermediate results can be memoized across invocations of
1403 // PathExistsToClonedNode.
1404 struct HackedGraphSCCFinder {
1405 ReachabilityCloner &RC;
1406 unsigned CurNodeId;
1407 std::vector<const DSNode*> SCCStack;
1408 std::map<const DSNode*, std::pair<unsigned, bool> > NodeInfo;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001409
Chris Lattner4da120e2005-03-24 23:06:02 +00001410 HackedGraphSCCFinder(ReachabilityCloner &rc) : RC(rc), CurNodeId(1) {
1411 // Remove null pointer as a special case.
1412 NodeInfo[0] = std::make_pair(0, false);
Chris Lattnerd8642122005-03-24 21:07:47 +00001413 }
1414
Chris Lattner4da120e2005-03-24 23:06:02 +00001415 std::pair<unsigned, bool> &VisitForSCCs(const DSNode *N);
1416
1417 bool PathExistsToClonedNode(const DSNode *N) {
1418 return VisitForSCCs(N).second;
1419 }
1420
1421 bool PathExistsToClonedNode(const DSCallSite &CS) {
1422 if (PathExistsToClonedNode(CS.getRetVal().getNode()))
1423 return true;
1424 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1425 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode()))
1426 return true;
1427 return false;
1428 }
1429 };
1430}
1431
1432std::pair<unsigned, bool> &HackedGraphSCCFinder::
1433VisitForSCCs(const DSNode *N) {
1434 std::map<const DSNode*, std::pair<unsigned, bool> >::iterator
1435 NodeInfoIt = NodeInfo.lower_bound(N);
1436 if (NodeInfoIt != NodeInfo.end() && NodeInfoIt->first == N)
1437 return NodeInfoIt->second;
1438
1439 unsigned Min = CurNodeId++;
1440 unsigned MyId = Min;
1441 std::pair<unsigned, bool> &ThisNodeInfo =
1442 NodeInfo.insert(NodeInfoIt,
1443 std::make_pair(N, std::make_pair(MyId, false)))->second;
1444
1445 // Base case: if we find a global, this doesn't reach the cloned graph
1446 // portion.
1447 if (N->isGlobalNode()) {
1448 ThisNodeInfo.second = false;
1449 return ThisNodeInfo;
Chris Lattnerd8642122005-03-24 21:07:47 +00001450 }
1451
Chris Lattner4da120e2005-03-24 23:06:02 +00001452 // Base case: if this does reach the cloned graph portion... it does. :)
1453 if (RC.hasClonedNode(N)) {
1454 ThisNodeInfo.second = true;
1455 return ThisNodeInfo;
1456 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001457
Chris Lattner4da120e2005-03-24 23:06:02 +00001458 SCCStack.push_back(N);
Chris Lattnerd8642122005-03-24 21:07:47 +00001459
Chris Lattner4da120e2005-03-24 23:06:02 +00001460 // Otherwise, check all successors.
1461 bool AnyDirectSuccessorsReachClonedNodes = false;
1462 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
Chris Lattner63320cc2005-04-25 19:16:17 +00001463 EI != EE; ++EI)
1464 if (DSNode *Succ = EI->getNode()) {
1465 std::pair<unsigned, bool> &SuccInfo = VisitForSCCs(Succ);
1466 if (SuccInfo.first < Min) Min = SuccInfo.first;
1467 AnyDirectSuccessorsReachClonedNodes |= SuccInfo.second;
1468 }
Chris Lattner4da120e2005-03-24 23:06:02 +00001469
1470 if (Min != MyId)
1471 return ThisNodeInfo; // Part of a large SCC. Leave self on stack.
1472
1473 if (SCCStack.back() == N) { // Special case single node SCC.
1474 SCCStack.pop_back();
1475 ThisNodeInfo.second = AnyDirectSuccessorsReachClonedNodes;
1476 return ThisNodeInfo;
1477 }
1478
1479 // Find out if any direct successors of any node reach cloned nodes.
1480 if (!AnyDirectSuccessorsReachClonedNodes)
1481 for (unsigned i = SCCStack.size()-1; SCCStack[i] != N; --i)
1482 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1483 EI != EE; ++EI)
1484 if (DSNode *N = EI->getNode())
1485 if (NodeInfo[N].second) {
1486 AnyDirectSuccessorsReachClonedNodes = true;
1487 goto OutOfLoop;
1488 }
1489OutOfLoop:
1490 // If any successor reaches a cloned node, mark all nodes in this SCC as
1491 // reaching the cloned node.
1492 if (AnyDirectSuccessorsReachClonedNodes)
1493 while (SCCStack.back() != N) {
1494 NodeInfo[SCCStack.back()].second = true;
1495 SCCStack.pop_back();
1496 }
1497 SCCStack.pop_back();
1498 ThisNodeInfo.second = true;
1499 return ThisNodeInfo;
1500}
Chris Lattnerd8642122005-03-24 21:07:47 +00001501
Chris Lattnere8594442005-02-04 19:58:28 +00001502/// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1503/// nodes from G2 into 'this' graph, merging the bindings specified by the
1504/// call site (in this graph) with the bindings specified by the vector in G2.
1505/// The two DSGraphs must be different.
Chris Lattner076c1f92002-11-07 06:31:54 +00001506///
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001507void DSGraph::mergeInGraph(const DSCallSite &CS,
Chris Lattnere8594442005-02-04 19:58:28 +00001508 std::vector<DSNodeHandle> &Args,
Chris Lattner9f930552003-06-30 05:27:18 +00001509 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001510 TIME_REGION(X, "mergeInGraph");
1511
Chris Lattnerc14f59c2005-03-23 20:12:08 +00001512 assert((CloneFlags & DontCloneCallNodes) &&
1513 "Doesn't support copying of call nodes!");
1514
Chris Lattner076c1f92002-11-07 06:31:54 +00001515 // If this is not a recursive call, clone the graph into this graph...
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001516 if (&Graph == this) {
Chris Lattnerbb753c42005-02-03 18:40:25 +00001517 // Merge the return value with the return value of the context.
1518 Args[0].mergeWith(CS.getRetVal());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001519
Chris Lattnerbb753c42005-02-03 18:40:25 +00001520 // Resolve all of the function arguments.
1521 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001522 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001523 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001524
Chris Lattnerbb753c42005-02-03 18:40:25 +00001525 // Add the link from the argument scalar to the provided value.
1526 Args[i+1].mergeWith(CS.getPtrArg(i));
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001527 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001528 return;
Chris Lattner076c1f92002-11-07 06:31:54 +00001529 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001530
1531 // Clone the callee's graph into the current graph, keeping track of where
1532 // scalars in the old graph _used_ to point, and of the new nodes matching
1533 // nodes of the old graph.
1534 ReachabilityCloner RC(*this, Graph, CloneFlags);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001535
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001536 // Map the return node pointer over.
1537 if (!CS.getRetVal().isNull())
1538 RC.merge(CS.getRetVal(), Args[0]);
1539
1540 // Map over all of the arguments.
1541 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1542 if (i == Args.size()-1)
1543 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001544
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001545 // Add the link from the argument scalar to the provided value.
1546 RC.merge(CS.getPtrArg(i), Args[i+1]);
1547 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001548
Chris Lattnerd8642122005-03-24 21:07:47 +00001549 // We generally don't want to copy global nodes or aux calls from the callee
1550 // graph to the caller graph. However, we have to copy them if there is a
1551 // path from the node to a node we have already copied which does not go
1552 // through another global. Compute the set of node that can reach globals and
1553 // aux call nodes to copy over, then do it.
1554 std::vector<const DSCallSite*> AuxCallToCopy;
1555 std::vector<GlobalValue*> GlobalsToCopy;
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001556
Chris Lattnerd8642122005-03-24 21:07:47 +00001557 // NodesReachCopiedNodes - Memoize results for efficiency. Contains a
1558 // true/false value for every visited node that reaches a copied node without
1559 // going through a global.
Chris Lattner4da120e2005-03-24 23:06:02 +00001560 HackedGraphSCCFinder SCCFinder(RC);
Chris Lattnerd8642122005-03-24 21:07:47 +00001561
1562 if (!(CloneFlags & DontCloneAuxCallNodes))
1563 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
Chris Lattner4da120e2005-03-24 23:06:02 +00001564 if (SCCFinder.PathExistsToClonedNode(*I))
Chris Lattnerd8642122005-03-24 21:07:47 +00001565 AuxCallToCopy.push_back(&*I);
1566
Chris Lattner4da120e2005-03-24 23:06:02 +00001567 const DSScalarMap &GSM = Graph.getScalarMap();
Chris Lattnerd8642122005-03-24 21:07:47 +00001568 for (DSScalarMap::global_iterator GI = GSM.global_begin(),
Chris Lattner09adbbc92005-03-24 21:17:27 +00001569 E = GSM.global_end(); GI != E; ++GI) {
1570 DSNode *GlobalNode = Graph.getNodeForValue(*GI).getNode();
1571 for (DSNode::edge_iterator EI = GlobalNode->edge_begin(),
1572 EE = GlobalNode->edge_end(); EI != EE; ++EI)
Chris Lattner4da120e2005-03-24 23:06:02 +00001573 if (SCCFinder.PathExistsToClonedNode(EI->getNode())) {
Chris Lattner09adbbc92005-03-24 21:17:27 +00001574 GlobalsToCopy.push_back(*GI);
1575 break;
1576 }
1577 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001578
1579 // Copy aux calls that are needed.
1580 for (unsigned i = 0, e = AuxCallToCopy.size(); i != e; ++i)
1581 AuxFunctionCalls.push_back(DSCallSite(*AuxCallToCopy[i], RC));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001582
Chris Lattnerd8642122005-03-24 21:07:47 +00001583 // Copy globals that are needed.
1584 for (unsigned i = 0, e = GlobalsToCopy.size(); i != e; ++i)
1585 RC.getClonedNH(Graph.getNodeForValue(GlobalsToCopy[i]));
Chris Lattner076c1f92002-11-07 06:31:54 +00001586}
1587
Chris Lattnere8594442005-02-04 19:58:28 +00001588
1589
1590/// mergeInGraph - The method is used for merging graphs together. If the
1591/// argument graph is not *this, it makes a clone of the specified graph, then
1592/// merges the nodes specified in the call site with the formal arguments in the
1593/// graph.
1594///
1595void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1596 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattnere8594442005-02-04 19:58:28 +00001597 // Set up argument bindings.
1598 std::vector<DSNodeHandle> Args;
1599 Graph.getFunctionArgumentsForCall(&F, Args);
1600
1601 mergeInGraph(CS, Args, Graph, CloneFlags);
1602}
1603
Chris Lattner58f98d02003-07-02 04:38:49 +00001604/// getCallSiteForArguments - Get the arguments and return value bindings for
1605/// the specified function in the current graph.
1606///
1607DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1608 std::vector<DSNodeHandle> Args;
1609
Chris Lattnere4d5c442005-03-15 04:54:21 +00001610 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner58f98d02003-07-02 04:38:49 +00001611 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001612 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001613
Chris Lattner808a7ae2003-09-20 16:34:13 +00001614 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001615}
1616
Chris Lattner85fb1be2004-03-09 19:37:06 +00001617/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1618/// the context of this graph, return the DSCallSite for it.
1619DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1620 DSNodeHandle RetVal;
1621 Instruction *I = CS.getInstruction();
1622 if (isPointerType(I->getType()))
1623 RetVal = getNodeForValue(I);
1624
1625 std::vector<DSNodeHandle> Args;
1626 Args.reserve(CS.arg_end()-CS.arg_begin());
1627
1628 // Calculate the arguments vector...
1629 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1630 if (isPointerType((*I)->getType()))
Chris Lattner94f84702005-03-17 19:56:56 +00001631 if (isa<ConstantPointerNull>(*I))
1632 Args.push_back(DSNodeHandle());
1633 else
1634 Args.push_back(getNodeForValue(*I));
Chris Lattner85fb1be2004-03-09 19:37:06 +00001635
1636 // Add a new function call entry...
1637 if (Function *F = CS.getCalledFunction())
1638 return DSCallSite(CS, RetVal, F, Args);
1639 else
1640 return DSCallSite(CS, RetVal,
1641 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1642}
1643
Chris Lattner58f98d02003-07-02 04:38:49 +00001644
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001645
Chris Lattner0d9bab82002-07-18 00:12:30 +00001646// markIncompleteNodes - Mark the specified node as having contents that are not
1647// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001648// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001649// must recursively traverse the data structure graph, marking all reachable
1650// nodes as incomplete.
1651//
1652static void markIncompleteNode(DSNode *N) {
1653 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001654 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001655
1656 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001657 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001658
Misha Brukman2f2d0652003-09-11 18:14:24 +00001659 // Recursively process children...
Chris Lattner6be07942005-02-09 03:20:43 +00001660 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1661 if (DSNode *DSN = I->getNode())
Chris Lattner08db7192002-11-06 06:20:27 +00001662 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001663}
1664
Chris Lattnere71ffc22002-11-11 03:36:55 +00001665static void markIncomplete(DSCallSite &Call) {
1666 // Then the return value is certainly incomplete!
1667 markIncompleteNode(Call.getRetVal().getNode());
1668
1669 // All objects pointed to by function arguments are incomplete!
1670 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1671 markIncompleteNode(Call.getPtrArg(i).getNode());
1672}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001673
1674// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1675// modified by other functions that have not been resolved yet. This marks
1676// nodes that are reachable through three sources of "unknownness":
1677//
1678// Global Variables, Function Calls, and Incoming Arguments
1679//
1680// For any node that may have unknown components (because something outside the
1681// scope of current analysis may have modified it), the 'Incomplete' flag is
1682// added to the NodeType.
1683//
Chris Lattner394471f2003-01-23 22:05:33 +00001684void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001685 // Mark any incoming arguments as incomplete.
Chris Lattner5a540632003-06-30 03:15:25 +00001686 if (Flags & DSGraph::MarkFormalArgs)
1687 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1688 FI != E; ++FI) {
1689 Function &F = *FI->first;
Chris Lattner9342a932005-03-29 19:16:59 +00001690 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1691 I != E; ++I)
Chris Lattnerb5ecd2e2005-03-13 20:22:10 +00001692 if (isPointerType(I->getType()))
1693 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattnera4319e52005-03-12 14:58:28 +00001694 markIncompleteNode(FI->second.getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001695 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001696
Chris Lattnera9548d92005-01-30 23:51:02 +00001697 // Mark stuff passed into functions calls as being incomplete.
Chris Lattnere71ffc22002-11-11 03:36:55 +00001698 if (!shouldPrintAuxCalls())
Chris Lattnera9548d92005-01-30 23:51:02 +00001699 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1700 E = FunctionCalls.end(); I != E; ++I)
1701 markIncomplete(*I);
Chris Lattnere71ffc22002-11-11 03:36:55 +00001702 else
Chris Lattnera9548d92005-01-30 23:51:02 +00001703 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1704 E = AuxFunctionCalls.end(); I != E; ++I)
1705 markIncomplete(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001706
Chris Lattnere2bc7b22005-03-13 20:36:01 +00001707 // Mark all global nodes as incomplete.
1708 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1709 E = ScalarMap.global_end(); I != E; ++I)
1710 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1711 if (!GV->hasInitializer() || // Always mark external globals incomp.
1712 (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1713 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001714}
1715
Chris Lattneraa8146f2002-11-10 06:59:55 +00001716static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1717 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001718 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001719 // No interesting info?
1720 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001721 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001722 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001723}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001724
Chris Lattneraa8146f2002-11-10 06:59:55 +00001725static inline bool nodeContainsExternalFunction(const DSNode *N) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001726 std::vector<Function*> Funcs;
1727 N->addFullFunctionList(Funcs);
1728 for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
1729 if (Funcs[i]->isExternal()) return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001730 return false;
1731}
1732
Chris Lattnera9548d92005-01-30 23:51:02 +00001733static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001734 // Remove trivially identical function calls
Chris Lattnera9548d92005-01-30 23:51:02 +00001735 Calls.sort(); // Sort by callee as primary key!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001736
1737 // Scan the call list cleaning it up as necessary...
Chris Lattner1e9d1472005-03-22 23:54:52 +00001738 DSNodeHandle LastCalleeNode;
Chris Lattner923fc052003-02-05 21:59:58 +00001739 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001740 unsigned NumDuplicateCalls = 0;
1741 bool LastCalleeContainsExternalFunction = false;
Chris Lattner857eb062004-10-30 05:41:23 +00001742
Chris Lattnera9548d92005-01-30 23:51:02 +00001743 unsigned NumDeleted = 0;
1744 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1745 I != E;) {
1746 DSCallSite &CS = *I;
1747 std::list<DSCallSite>::iterator OldIt = I++;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001748
Chris Lattner1e9d1472005-03-22 23:54:52 +00001749 if (!CS.isIndirectCall()) {
1750 LastCalleeNode = 0;
1751 } else {
1752 DSNode *Callee = CS.getCalleeNode();
1753
1754 // If the Callee is a useless edge, this must be an unreachable call site,
1755 // eliminate it.
1756 if (Callee->getNumReferrers() == 1 && Callee->isComplete() &&
1757 Callee->getGlobalsList().empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001758#ifndef NDEBUG
Chris Lattner1e9d1472005-03-22 23:54:52 +00001759 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001760#endif
Chris Lattner1e9d1472005-03-22 23:54:52 +00001761 Calls.erase(OldIt);
1762 ++NumDeleted;
1763 continue;
1764 }
1765
1766 // If the last call site in the list has the same callee as this one, and
1767 // if the callee contains an external function, it will never be
1768 // resolvable, just merge the call sites.
1769 if (!LastCalleeNode.isNull() && LastCalleeNode.getNode() == Callee) {
1770 LastCalleeContainsExternalFunction =
1771 nodeContainsExternalFunction(Callee);
1772
1773 std::list<DSCallSite>::iterator PrevIt = OldIt;
1774 --PrevIt;
1775 PrevIt->mergeWith(CS);
1776
1777 // No need to keep this call anymore.
1778 Calls.erase(OldIt);
1779 ++NumDeleted;
1780 continue;
1781 } else {
1782 LastCalleeNode = Callee;
1783 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001784 }
1785
1786 // If the return value or any arguments point to a void node with no
1787 // information at all in it, and the call node is the only node to point
1788 // to it, remove the edge to the node (killing the node).
1789 //
1790 killIfUselessEdge(CS.getRetVal());
1791 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1792 killIfUselessEdge(CS.getPtrArg(a));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001793
Chris Lattner0b144872004-01-27 22:03:40 +00001794#if 0
Chris Lattnera9548d92005-01-30 23:51:02 +00001795 // If this call site calls the same function as the last call site, and if
1796 // the function pointer contains an external function, this node will
1797 // never be resolved. Merge the arguments of the call node because no
1798 // information will be lost.
1799 //
1800 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1801 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1802 ++NumDuplicateCalls;
1803 if (NumDuplicateCalls == 1) {
1804 if (LastCalleeNode)
1805 LastCalleeContainsExternalFunction =
1806 nodeContainsExternalFunction(LastCalleeNode);
1807 else
1808 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001809 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001810
Chris Lattnera9548d92005-01-30 23:51:02 +00001811 // It is not clear why, but enabling this code makes DSA really
1812 // sensitive to node forwarding. Basically, with this enabled, DSA
1813 // performs different number of inlinings based on which nodes are
1814 // forwarding or not. This is clearly a problem, so this code is
1815 // disabled until this can be resolved.
1816#if 1
1817 if (LastCalleeContainsExternalFunction
1818#if 0
1819 ||
1820 // This should be more than enough context sensitivity!
1821 // FIXME: Evaluate how many times this is tripped!
1822 NumDuplicateCalls > 20
1823#endif
1824 ) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001825
Chris Lattnera9548d92005-01-30 23:51:02 +00001826 std::list<DSCallSite>::iterator PrevIt = OldIt;
1827 --PrevIt;
1828 PrevIt->mergeWith(CS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001829
Chris Lattnera9548d92005-01-30 23:51:02 +00001830 // No need to keep this call anymore.
1831 Calls.erase(OldIt);
1832 ++NumDeleted;
1833 continue;
1834 }
1835#endif
1836 } else {
1837 if (CS.isDirectCall()) {
1838 LastCalleeFunc = CS.getCalleeFunc();
1839 LastCalleeNode = 0;
1840 } else {
1841 LastCalleeNode = CS.getCalleeNode();
1842 LastCalleeFunc = 0;
1843 }
1844 NumDuplicateCalls = 0;
1845 }
1846#endif
1847
1848 if (I != Calls.end() && CS == *I) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001849 LastCalleeNode = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00001850 Calls.erase(OldIt);
1851 ++NumDeleted;
1852 continue;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001853 }
1854 }
Chris Lattner857eb062004-10-30 05:41:23 +00001855
Chris Lattnera9548d92005-01-30 23:51:02 +00001856 // Resort now that we simplified things.
1857 Calls.sort();
Chris Lattner857eb062004-10-30 05:41:23 +00001858
Chris Lattnera9548d92005-01-30 23:51:02 +00001859 // Now that we are in sorted order, eliminate duplicates.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001860 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1861 if (CI != CE)
Chris Lattnera9548d92005-01-30 23:51:02 +00001862 while (1) {
Chris Lattnerf9aace22005-01-31 00:10:58 +00001863 std::list<DSCallSite>::iterator OldIt = CI++;
1864 if (CI == CE) break;
Chris Lattnera9548d92005-01-30 23:51:02 +00001865
1866 // If this call site is now the same as the previous one, we can delete it
1867 // as a duplicate.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001868 if (*OldIt == *CI) {
1869 Calls.erase(CI);
1870 CI = OldIt;
Chris Lattnera9548d92005-01-30 23:51:02 +00001871 ++NumDeleted;
1872 }
1873 }
1874
1875 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001876
Chris Lattner33312f72002-11-08 01:21:07 +00001877 // Track the number of call nodes merged away...
Chris Lattnera9548d92005-01-30 23:51:02 +00001878 NumCallNodesMerged += NumDeleted;
Chris Lattner33312f72002-11-08 01:21:07 +00001879
Chris Lattnera9548d92005-01-30 23:51:02 +00001880 DEBUG(if (NumDeleted)
1881 std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001882}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001883
Chris Lattneraa8146f2002-11-10 06:59:55 +00001884
Chris Lattnere2219762002-07-18 18:22:40 +00001885// removeTriviallyDeadNodes - After the graph has been constructed, this method
1886// removes all unreachable nodes that are created because they got merged with
1887// other nodes in the graph. These nodes will all be trivially unreachable, so
1888// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001889//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001890void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001891 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001892
Chris Lattner5ace1e42004-07-08 07:25:51 +00001893#if 0
1894 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1895 /// substantially!
1896
Chris Lattnerbab8c282003-09-20 21:34:07 +00001897 // Loop over all of the nodes in the graph, calling getNode on each field.
1898 // This will cause all nodes to update their forwarding edges, causing
1899 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001900 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001901 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
Chris Lattner84b80a22005-03-16 22:42:19 +00001902 DSNode &N = *NI;
1903 for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1904 N.getLink(l*N.getPointerSize()).getNode();
Chris Lattnerbab8c282003-09-20 21:34:07 +00001905 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001906 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001907
Chris Lattner0b144872004-01-27 22:03:40 +00001908 // NOTE: This code is disabled. Though it should, in theory, allow us to
1909 // remove more nodes down below, the scan of the scalar map is incredibly
1910 // expensive for certain programs (with large SCCs). In the future, if we can
1911 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001912 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1913
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001914 // Likewise, forward any edges from the scalar nodes. While we are at it,
1915 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001916 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001917 I->second.getNode();
1918 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001919 }
Chris Lattner0b144872004-01-27 22:03:40 +00001920 }
1921#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001922 bool isGlobalsGraph = !GlobalsGraph;
1923
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001924 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001925 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001926
1927 // Do not remove *any* global nodes in the globals graph.
1928 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001929 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001930 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001931 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001932 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001933
Chris Lattner28897e12004-02-08 00:53:26 +00001934 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001935 // This is a useless node if it has no mod/ref info (checked above),
1936 // outgoing edges (which it cannot, as it is not modified in this
1937 // context), and it has no incoming edges. If it is a global node it may
1938 // have all of these properties and still have incoming edges, due to the
1939 // scalar map, so we check those now.
1940 //
Chris Lattner82c6c722005-03-20 02:41:38 +00001941 if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1942 const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
Chris Lattner72d29a42003-02-11 23:11:51 +00001943
Chris Lattner17a93e22004-01-29 03:32:15 +00001944 // Loop through and make sure all of the globals are referring directly
1945 // to the node...
1946 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1947 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001948 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001949 }
1950
Chris Lattnerbd92b732003-06-19 21:15:11 +00001951 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001952 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001953 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1954 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001955 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001956 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001957 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001958 }
1959 }
1960
Chris Lattner28897e12004-02-08 00:53:26 +00001961 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001962 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001963 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001964 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001965 } else {
1966 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001967 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001968 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001969
1970 removeIdenticalCalls(FunctionCalls);
1971 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001972}
1973
1974
Chris Lattner5c7380e2003-01-29 21:10:20 +00001975/// markReachableNodes - This method recursively traverses the specified
1976/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1977/// to the set, which allows it to only traverse visited nodes once.
1978///
Chris Lattnera9548d92005-01-30 23:51:02 +00001979void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001980 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001981 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001982 if (ReachableNodes.insert(this).second) // Is newly reachable?
Chris Lattner6be07942005-02-09 03:20:43 +00001983 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
1984 I != E; ++I)
1985 I->getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001986}
1987
Chris Lattnera9548d92005-01-30 23:51:02 +00001988void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001989 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001990 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001991
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001992 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1993 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001994}
1995
Chris Lattnera1220af2003-02-01 06:17:02 +00001996// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1997// looking for a node that is marked alive. If an alive node is found, return
1998// true, otherwise return false. If an alive node is reachable, this node is
1999// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00002000//
Chris Lattnera9548d92005-01-30 23:51:02 +00002001static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
2002 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00002003 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002004 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00002005 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002006
Chris Lattner85cfe012003-07-03 02:03:53 +00002007 // If this is a global node, it will end up in the globals graph anyway, so we
2008 // don't need to worry about it.
2009 if (IgnoreGlobals && N->isGlobalNode()) return false;
2010
Chris Lattneraa8146f2002-11-10 06:59:55 +00002011 // If we know that this node is alive, return so!
2012 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002013
Chris Lattneraa8146f2002-11-10 06:59:55 +00002014 // Otherwise, we don't think the node is alive yet, check for infinite
2015 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00002016 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00002017 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00002018
Chris Lattner6be07942005-02-09 03:20:43 +00002019 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
2020 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00002021 N->markReachableNodes(Alive);
2022 return true;
2023 }
2024 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002025}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002026
Chris Lattnera1220af2003-02-01 06:17:02 +00002027// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
2028// alive nodes.
2029//
Chris Lattnera9548d92005-01-30 23:51:02 +00002030static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
2031 hash_set<const DSNode*> &Alive,
2032 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00002033 bool IgnoreGlobals) {
2034 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
2035 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00002036 return true;
2037 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00002038 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002039 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002040 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00002041 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
2042 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002043 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002044 return false;
2045}
2046
Chris Lattnere2219762002-07-18 18:22:40 +00002047// removeDeadNodes - Use a more powerful reachability analysis to eliminate
2048// subgraphs that are unreachable. This often occurs because the data
2049// structure doesn't "escape" into it's caller, and thus should be eliminated
2050// from the caller's graph entirely. This is only appropriate to use when
2051// inlining graphs.
2052//
Chris Lattner394471f2003-01-23 22:05:33 +00002053void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00002054 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00002055
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002056 // Reduce the amount of work we have to do... remove dummy nodes left over by
2057 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00002058 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002059
Chris Lattner93ddd7e2004-01-22 16:36:28 +00002060 TIME_REGION(X, "removeDeadNodes");
2061
Misha Brukman2f2d0652003-09-11 18:14:24 +00002062 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00002063
2064 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattnera9548d92005-01-30 23:51:02 +00002065 hash_set<const DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002066 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00002067
Chris Lattner0b144872004-01-27 22:03:40 +00002068 // Copy and merge all information about globals to the GlobalsGraph if this is
2069 // not a final pass (where unreachable globals are removed).
2070 //
2071 // Strip all alloca bits since the current function is only for the BU pass.
2072 // Strip all incomplete bits since they are short-lived properties and they
2073 // will be correctly computed when rematerializing nodes into the functions.
2074 //
2075 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
2076 DSGraph::StripIncompleteBit);
2077
Chris Lattneraa8146f2002-11-10 06:59:55 +00002078 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattnerf4f62272005-03-19 22:23:45 +00002079{ TIME_REGION(Y, "removeDeadNodes:scalarscan");
2080 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
2081 I != E; ++I)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002082 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00002083 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002084 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002085 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00002086
2087 // Make sure that all globals are cloned over as roots.
Chris Lattner021decc2005-04-02 19:17:18 +00002088 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && GlobalsGraph) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002089 DSGraph::ScalarMapTy::iterator SMI =
Chris Lattner00948c02004-01-28 02:05:05 +00002090 GlobalsGraph->getScalarMap().find(I->first);
2091 if (SMI != GlobalsGraph->getScalarMap().end())
2092 GGCloner.merge(SMI->second, I->second);
2093 else
2094 GGCloner.getClonedNH(I->second);
2095 }
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002096 } else {
Chris Lattnerf4f62272005-03-19 22:23:45 +00002097 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002098 }
Chris Lattnerf4f62272005-03-19 22:23:45 +00002099}
Chris Lattnere2219762002-07-18 18:22:40 +00002100
Chris Lattner0b144872004-01-27 22:03:40 +00002101 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00002102 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
2103 I != E; ++I)
2104 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002105
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002106 // Mark any nodes reachable by primary calls as alive...
Chris Lattnera9548d92005-01-30 23:51:02 +00002107 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2108 I->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002109
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002110
2111 // Now find globals and aux call nodes that are already live or reach a live
2112 // value (which makes them live in turn), and continue till no more are found.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002113 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002114 bool Iterate;
Chris Lattnera9548d92005-01-30 23:51:02 +00002115 hash_set<const DSNode*> Visited;
2116 hash_set<const DSCallSite*> AuxFCallsAlive;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002117 do {
2118 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00002119 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00002120 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002121 // unreachable globals in the list.
2122 //
2123 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002124 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00002125 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002126 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
Chris Lattner0b144872004-01-27 22:03:40 +00002127 Flags & DSGraph::RemoveUnreachableGlobals)) {
2128 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
2129 GlobalNodes.pop_back(); // erase efficiently
2130 Iterate = true;
2131 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002132
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002133 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
2134 // call nodes that get resolved will be difficult to remove from that graph.
2135 // The final unresolved call nodes must be handled specially at the end of
2136 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattnera9548d92005-01-30 23:51:02 +00002137 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
Chris Lattnerd7642c42005-02-24 18:48:07 +00002138 if (!AuxFCallsAlive.count(&*CI) &&
Chris Lattnera9548d92005-01-30 23:51:02 +00002139 (CI->isIndirectCall()
2140 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002141 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattnera9548d92005-01-30 23:51:02 +00002142 CI->markReachableNodes(Alive);
Chris Lattnerd7642c42005-02-24 18:48:07 +00002143 AuxFCallsAlive.insert(&*CI);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002144 Iterate = true;
2145 }
2146 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00002147
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002148 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002149 unsigned CurIdx = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00002150 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
2151 E = AuxFunctionCalls.end(); CI != E; )
2152 if (AuxFCallsAlive.count(&*CI))
2153 ++CI;
2154 else {
2155 // Copy and merge global nodes and dead aux call nodes into the
2156 // GlobalsGraph, and all nodes reachable from those nodes. Update their
2157 // target pointers using the GGCloner.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002158 //
Chris Lattnera9548d92005-01-30 23:51:02 +00002159 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2160 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002161
Chris Lattnera9548d92005-01-30 23:51:02 +00002162 AuxFunctionCalls.erase(CI++);
2163 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002164
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002165 // We are finally done with the GGCloner so we can destroy it.
2166 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002167
Vikram S. Adve40c600e2003-07-22 12:08:58 +00002168 // At this point, any nodes which are visited, but not alive, are nodes
2169 // which can be removed. Loop over all nodes, eliminating completely
2170 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002171 //
Chris Lattner72d29a42003-02-11 23:11:51 +00002172 std::vector<DSNode*> DeadNodes;
2173 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00002174 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2175 DSNode *N = NI++;
2176 assert(!N->isForwarding() && "Forwarded node in nodes list?");
2177
2178 if (!Alive.count(N)) {
2179 Nodes.remove(N);
2180 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002181 DeadNodes.push_back(N);
2182 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00002183 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00002184 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00002185 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002186
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002187 // Remove all unreachable globals from the ScalarMap.
2188 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2189 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00002190 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002191 if (!Alive.count(GlobalNodes[i].second))
2192 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00002193 else
2194 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002195
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002196 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00002197 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2198 delete DeadNodes[i];
2199
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002200 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00002201}
2202
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002203void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
Chris Lattner82c6c722005-03-20 02:41:38 +00002204 assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2205 N->globals_end() && "Global value not in node!");
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002206}
2207
Chris Lattner2c7725a2004-03-03 20:55:27 +00002208void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2209 if (CS.isIndirectCall()) {
2210 AssertNodeInGraph(CS.getCalleeNode());
2211#if 0
2212 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2213 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002214 std::cerr << "WARNING: WEIRD CALL SITE FOUND!\n";
Chris Lattner2c7725a2004-03-03 20:55:27 +00002215#endif
2216 }
2217 AssertNodeInGraph(CS.getRetVal().getNode());
2218 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2219 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2220}
2221
2222void DSGraph::AssertCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002223 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2224 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002225}
2226void DSGraph::AssertAuxCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002227 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2228 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002229}
2230
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002231void DSGraph::AssertGraphOK() const {
Chris Lattner84b80a22005-03-16 22:42:19 +00002232 for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2233 NI->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00002234
Chris Lattner8d327672003-06-30 03:36:09 +00002235 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002236 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00002237 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002238 AssertNodeInGraph(I->second.getNode());
2239 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00002240 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002241 "Global points to node, but node isn't global?");
2242 AssertNodeContainsGlobal(I->second.getNode(), GV);
2243 }
2244 }
2245 AssertCallNodesInGraph();
2246 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00002247
2248 // Check that all pointer arguments to any functions in this graph have
2249 // destinations.
2250 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2251 E = ReturnNodes.end();
2252 RI != E; ++RI) {
2253 Function &F = *RI->first;
Chris Lattnere4d5c442005-03-15 04:54:21 +00002254 for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
Chris Lattner7d8d4712004-10-31 17:45:40 +00002255 if (isPointerType(AI->getType()))
2256 assert(!getNodeForValue(AI).isNull() &&
2257 "Pointer argument must be in the scalar map!");
2258 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002259}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002260
Chris Lattner400433d2003-11-11 05:08:59 +00002261/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00002262/// nodes reachable from the two graphs, computing the mapping of nodes from the
2263/// first to the second graph. This mapping may be many-to-one (i.e. the first
2264/// graph may have multiple nodes representing one node in the second graph),
2265/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00002266///
2267void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00002268 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2269 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00002270 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2271 if (N1 == 0 || N2 == 0) return;
2272
2273 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002274 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002275 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002276 if (StrictChecking) {
2277 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2278 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2279 Entry.getNode()->isNodeCompletelyFolded()) &&
2280 "Inconsistent mapping detected!");
2281 }
Chris Lattner400433d2003-11-11 05:08:59 +00002282 return;
2283 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002284
Chris Lattnerefffdc92004-07-07 06:12:52 +00002285 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002286
2287 // Loop over all of the fields that N1 and N2 have in common, recursively
2288 // mapping the edges together now.
2289 int N2Idx = NH2.getOffset()-NH1.getOffset();
2290 unsigned N2Size = N2->getSize();
Chris Lattner841957e2005-03-15 04:40:24 +00002291 if (N2Size == 0) return; // No edges to map to.
2292
Chris Lattner4d5af8e2005-03-15 21:36:50 +00002293 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2294 const DSNodeHandle &N1NH = N1->getLink(i);
2295 // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2296 // aligned right).
2297 if (!N1NH.isNull()) {
2298 if (unsigned(N2Idx)+i < N2Size)
2299 computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2300 else
2301 computeNodeMapping(N1NH,
2302 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2303 }
2304 }
Chris Lattner400433d2003-11-11 05:08:59 +00002305}
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002306
2307
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002308/// computeGToGGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002309/// nodes in this graph.
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002310void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002311 DSGraph &GG = *getGlobalsGraph();
2312
2313 DSScalarMap &SM = getScalarMap();
2314 for (DSScalarMap::global_iterator I = SM.global_begin(),
2315 E = SM.global_end(); I != E; ++I)
2316 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2317}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002318
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002319/// computeGGToGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002320/// nodes in this graph. Note that any uses of this method are probably bugs,
2321/// unless it is known that the globals graph has been merged into this graph!
2322void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2323 NodeMapTy NodeMap;
2324 computeGToGGMapping(NodeMap);
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002325
Chris Lattner36a13cd2005-03-15 17:52:18 +00002326 while (!NodeMap.empty()) {
2327 InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2328 NodeMap.begin()->first));
2329 NodeMap.erase(NodeMap.begin());
2330 }
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002331}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002332
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002333
2334/// computeCalleeCallerMapping - Given a call from a function in the current
2335/// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2336/// mapping of nodes from the callee to nodes in the caller.
2337void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2338 DSGraph &CalleeGraph,
2339 NodeMapTy &NodeMap) {
2340
2341 DSCallSite CalleeArgs =
2342 CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002343
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002344 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2345
2346 unsigned NumArgs = CS.getNumPtrArgs();
2347 if (NumArgs > CalleeArgs.getNumPtrArgs())
2348 NumArgs = CalleeArgs.getNumPtrArgs();
2349
2350 for (unsigned i = 0; i != NumArgs; ++i)
2351 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002352
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002353 // Map the nodes that are pointed to by globals.
2354 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2355 DSScalarMap &CallerSM = getScalarMap();
2356
2357 if (CalleeSM.global_size() >= CallerSM.global_size()) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002358 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002359 E = CallerSM.global_end(); GI != E; ++GI)
2360 if (CalleeSM.global_count(*GI))
2361 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2362 } else {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002363 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002364 E = CalleeSM.global_end(); GI != E; ++GI)
2365 if (CallerSM.global_count(*GI))
2366 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2367 }
2368}