blob: 6eee541aeb578b92c024ca686741981c2061ffe7 [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"
Bill Wendlinga5b31ca2006-11-28 23:33:06 +000028#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000029#include "llvm/Support/Timer.h"
Chris Lattner72382102006-01-22 23:19:18 +000030#include <iostream>
Chris Lattner0d9bab82002-07-18 00:12:30 +000031#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Chris Lattnerb29dd0f2004-12-08 21:03:56 +000034#define COLLAPSE_ARRAYS_AGGRESSIVELY 0
35
Chris Lattner08db7192002-11-06 06:20:27 +000036namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000037 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
38 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
39 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
40 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000041 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
42 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Andrew Lenharth0c3a0b62006-03-15 05:43:41 +000043 static cl::opt<unsigned>
44 DSAFieldLimit("dsa-field-limit", cl::Hidden,
45 cl::desc("Number of fields to track before collapsing a node"),
46 cl::init(256));
Chris Lattnerd74ea2b2006-05-24 17:04:05 +000047}
Chris Lattner08db7192002-11-06 06:20:27 +000048
Chris Lattner1e9d1472005-03-22 23:54:52 +000049#if 0
Chris Lattner93ddd7e2004-01-22 16:36:28 +000050#define TIME_REGION(VARNAME, DESC) \
51 NamedRegionTimer VARNAME(DESC)
52#else
53#define TIME_REGION(VARNAME, DESC)
54#endif
55
Chris Lattnerb1060432002-11-07 05:20:53 +000056using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000057
Chris Lattner6f967742004-10-30 04:05:01 +000058/// isForwarding - Return true if this NodeHandle is forwarding to another
59/// one.
60bool DSNodeHandle::isForwarding() const {
61 return N && N->isForwarding();
62}
63
Chris Lattner731b2d72003-02-13 19:09:00 +000064DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000065 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Andrew Lenharthdf983de2006-11-07 20:36:02 +000066 DEBUG(
67 { //assert not looping
68 DSNode* NH = N;
69 std::set<DSNode*> seen;
70 while(NH && NH->isForwarding()) {
71 assert(seen.find(NH) == seen.end() && "Loop detected");
72 seen.insert(NH);
73 NH = NH->ForwardNH.N;
74 }
75 }
76 );
Chris Lattner731b2d72003-02-13 19:09:00 +000077 // Handle node forwarding here!
78 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
79 Offset += N->ForwardNH.getOffset();
80
81 if (--N->NumReferrers == 0) {
82 // Removing the last referrer to the node, sever the forwarding link
83 N->stopForwarding();
84 }
85
86 N = Next;
87 N->NumReferrers++;
88 if (N->Size <= Offset) {
89 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
90 Offset = 0;
91 }
92 return N;
93}
94
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000095//===----------------------------------------------------------------------===//
Chris Lattner612f0b72005-03-22 00:09:45 +000096// DSScalarMap Implementation
97//===----------------------------------------------------------------------===//
98
99DSNodeHandle &DSScalarMap::AddGlobal(GlobalValue *GV) {
100 assert(ValueMap.count(GV) == 0 && "GV already exists!");
101
102 // If the node doesn't exist, check to see if it's a global that is
103 // equated to another global in the program.
104 EquivalenceClasses<GlobalValue*>::iterator ECI = GlobalECs.findValue(GV);
105 if (ECI != GlobalECs.end()) {
106 GlobalValue *Leader = *GlobalECs.findLeader(ECI);
107 if (Leader != GV) {
108 GV = Leader;
109 iterator I = ValueMap.find(GV);
110 if (I != ValueMap.end())
111 return I->second;
112 }
113 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000114
Chris Lattner612f0b72005-03-22 00:09:45 +0000115 // Okay, this is either not an equivalenced global or it is the leader, it
116 // will be inserted into the scalar map now.
117 GlobalSet.insert(GV);
118
119 return ValueMap.insert(std::make_pair(GV, DSNodeHandle())).first->second;
120}
121
122
123//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000124// DSNode Implementation
125//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000126
Chris Lattnerbd92b732003-06-19 21:15:11 +0000127DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +0000128 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000129 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +0000130 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +0000131 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000132 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000133}
134
Chris Lattner0d9bab82002-07-18 00:12:30 +0000135// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +0000136DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +0000137 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattneraf2e3e02005-04-12 03:59:27 +0000138 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattnerf590ced2004-03-04 17:06:53 +0000139 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +0000140 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +0000141 } else
Chris Lattner0b144872004-01-27 22:03:40 +0000142 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +0000143 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000144 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000145}
146
Chris Lattner15869aa2003-11-02 22:27:28 +0000147/// getTargetData - Get the target data object used to construct this node.
148///
149const TargetData &DSNode::getTargetData() const {
150 return ParentGraph->getTargetData();
151}
152
Chris Lattner72d29a42003-02-11 23:11:51 +0000153void DSNode::assertOK() const {
154 assert((Ty != Type::VoidTy ||
155 Ty == Type::VoidTy && (Size == 0 ||
156 (NodeType & DSNode::Array))) &&
157 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000158
159 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000160 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000161 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000162 assert(SM.global_count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000163 assert(SM.find(Globals[i])->second.getNode() == this);
164 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000165}
166
167/// forwardNode - Mark this node as being obsolete, and all references to it
168/// should be forwarded to the specified node and offset.
169///
170void DSNode::forwardNode(DSNode *To, unsigned Offset) {
171 assert(this != To && "Cannot forward a node to itself!");
172 assert(ForwardNH.isNull() && "Already forwarding from this node!");
173 if (To->Size <= 1) Offset = 0;
174 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
175 "Forwarded offset is wrong!");
Chris Lattnerefffdc92004-07-07 06:12:52 +0000176 ForwardNH.setTo(To, Offset);
Chris Lattner72d29a42003-02-11 23:11:51 +0000177 NodeType = DEAD;
178 Size = 0;
179 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000180
181 // Remove this node from the parent graph's Nodes list.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000182 ParentGraph->unlinkNode(this);
Chris Lattner4ff0b962004-02-08 01:27:18 +0000183 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000184}
185
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000186// addGlobal - Add an entry for a global value to the Globals list. This also
187// marks the node with the 'G' flag if it does not already have it.
188//
189void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000190 // First, check to make sure this is the leader if the global is in an
191 // equivalence class.
192 GV = getParentGraph()->getScalarMap().getLeaderForGlobal(GV);
193
Chris Lattner0d9bab82002-07-18 00:12:30 +0000194 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000195 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000196 std::lower_bound(Globals.begin(), Globals.end(), GV);
197
198 if (I == Globals.end() || *I != GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000199 Globals.insert(I, GV);
200 NodeType |= GlobalNode;
201 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000202}
203
Chris Lattner7cdf3212005-03-20 03:29:54 +0000204// removeGlobal - Remove the specified global that is explicitly in the globals
205// list.
206void DSNode::removeGlobal(GlobalValue *GV) {
207 std::vector<GlobalValue*>::iterator I =
208 std::lower_bound(Globals.begin(), Globals.end(), GV);
209 assert(I != Globals.end() && *I == GV && "Global not in node!");
210 Globals.erase(I);
211}
212
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000213/// foldNodeCompletely - If we determine that this node has some funny
214/// behavior happening to it that we cannot represent, we fold it down to a
215/// single, completely pessimistic, node. This node is represented as a
216/// single byte with a single TypeEntry of "void".
217///
218void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000219 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000220
Chris Lattner08db7192002-11-06 06:20:27 +0000221 ++NumFolds;
222
Chris Lattner0b144872004-01-27 22:03:40 +0000223 // If this node has a size that is <= 1, we don't need to create a forwarding
224 // node.
225 if (getSize() <= 1) {
226 NodeType |= DSNode::Array;
227 Ty = Type::VoidTy;
228 Size = 1;
229 assert(Links.size() <= 1 && "Size is 1, but has more links?");
230 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000231 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000232 // Create the node we are going to forward to. This is required because
233 // some referrers may have an offset that is > 0. By forcing them to
234 // forward, the forwarder has the opportunity to correct the offset.
235 DSNode *DestNode = new DSNode(0, ParentGraph);
236 DestNode->NodeType = NodeType|DSNode::Array;
237 DestNode->Ty = Type::VoidTy;
238 DestNode->Size = 1;
239 DestNode->Globals.swap(Globals);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000240
Chris Lattner0b144872004-01-27 22:03:40 +0000241 // Start forwarding to the destination node...
242 forwardNode(DestNode, 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000243
Chris Lattner0b144872004-01-27 22:03:40 +0000244 if (!Links.empty()) {
245 DestNode->Links.reserve(1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000246
Chris Lattner0b144872004-01-27 22:03:40 +0000247 DSNodeHandle NH(DestNode);
248 DestNode->Links.push_back(Links[0]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000249
Chris Lattner0b144872004-01-27 22:03:40 +0000250 // If we have links, merge all of our outgoing links together...
251 for (unsigned i = Links.size()-1; i != 0; --i)
252 NH.getNode()->Links[0].mergeWith(Links[i]);
253 Links.clear();
254 } else {
255 DestNode->Links.resize(1);
256 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000257 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000258}
Chris Lattner076c1f92002-11-07 06:31:54 +0000259
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000260/// isNodeCompletelyFolded - Return true if this node has been completely
261/// folded down to something that can never be expanded, effectively losing
262/// all of the field sensitivity that may be present in the node.
263///
264bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000265 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000266}
267
Chris Lattner82c6c722005-03-20 02:41:38 +0000268/// addFullGlobalsList - Compute the full set of global values that are
269/// represented by this node. Unlike getGlobalsList(), this requires fair
270/// amount of work to compute, so don't treat this method call as free.
271void DSNode::addFullGlobalsList(std::vector<GlobalValue*> &List) const {
272 if (globals_begin() == globals_end()) return;
273
274 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
275
276 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
277 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
278 if (ECI == EC.end())
279 List.push_back(*I);
280 else
281 List.insert(List.end(), EC.member_begin(ECI), EC.member_end());
282 }
283}
284
285/// addFullFunctionList - Identical to addFullGlobalsList, but only return the
286/// functions in the full list.
287void DSNode::addFullFunctionList(std::vector<Function*> &List) const {
288 if (globals_begin() == globals_end()) return;
289
290 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
291
292 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
293 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
294 if (ECI == EC.end()) {
295 if (Function *F = dyn_cast<Function>(*I))
296 List.push_back(F);
297 } else {
298 for (EquivalenceClasses<GlobalValue*>::member_iterator MI =
299 EC.member_begin(ECI), E = EC.member_end(); MI != E; ++MI)
300 if (Function *F = dyn_cast<Function>(*MI))
301 List.push_back(F);
302 }
303 }
304}
305
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000306namespace {
307 /// TypeElementWalker Class - Used for implementation of physical subtyping...
308 ///
309 class TypeElementWalker {
310 struct StackState {
311 const Type *Ty;
312 unsigned Offset;
313 unsigned Idx;
314 StackState(const Type *T, unsigned Off = 0)
315 : Ty(T), Offset(Off), Idx(0) {}
316 };
317
318 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000319 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000320 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000321 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000322 Stack.push_back(T);
323 StepToLeaf();
324 }
325
326 bool isDone() const { return Stack.empty(); }
327 const Type *getCurrentType() const { return Stack.back().Ty; }
328 unsigned getCurrentOffset() const { return Stack.back().Offset; }
329
330 void StepToNextType() {
331 PopStackAndAdvance();
332 StepToLeaf();
333 }
334
335 private:
336 /// PopStackAndAdvance - Pop the current element off of the stack and
337 /// advance the underlying element to the next contained member.
338 void PopStackAndAdvance() {
339 assert(!Stack.empty() && "Cannot pop an empty stack!");
340 Stack.pop_back();
341 while (!Stack.empty()) {
342 StackState &SS = Stack.back();
343 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
344 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000345 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000346 const StructLayout *SL = TD.getStructLayout(ST);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000347 SS.Offset +=
Chris Lattner507bdf92005-01-12 04:51:37 +0000348 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000349 return;
350 }
351 Stack.pop_back(); // At the end of the structure
352 } else {
353 const ArrayType *AT = cast<ArrayType>(SS.Ty);
354 ++SS.Idx;
355 if (SS.Idx != AT->getNumElements()) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000356 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000357 return;
358 }
359 Stack.pop_back(); // At the end of the array
360 }
361 }
362 }
363
364 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
365 /// on the type stack.
366 void StepToLeaf() {
367 if (Stack.empty()) return;
368 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
369 StackState &SS = Stack.back();
370 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000371 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000372 assert(SS.Idx == 0);
373 PopStackAndAdvance();
374 } else {
375 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000376 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000377 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000378 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner507bdf92005-01-12 04:51:37 +0000379 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000380 }
381 } else {
382 const ArrayType *AT = cast<ArrayType>(SS.Ty);
383 if (AT->getNumElements() == 0) {
384 assert(SS.Idx == 0);
385 PopStackAndAdvance();
386 } else {
387 // Step into the array...
388 assert(SS.Idx < AT->getNumElements());
389 Stack.push_back(StackState(AT->getElementType(),
390 SS.Offset+SS.Idx*
Chris Lattner507bdf92005-01-12 04:51:37 +0000391 unsigned(TD.getTypeSize(AT->getElementType()))));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000392 }
393 }
394 }
395 }
396 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000397} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000398
399/// ElementTypesAreCompatible - Check to see if the specified types are
400/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000401/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
402/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000403///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000404static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000405 bool AllowLargerT1, const TargetData &TD){
406 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000407
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000408 while (!T1W.isDone() && !T2W.isDone()) {
409 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
410 return false;
411
412 const Type *T1 = T1W.getCurrentType();
413 const Type *T2 = T2W.getCurrentType();
Reid Spencer3da59db2006-11-27 01:05:10 +0000414 if (T1 != T2 && !T1->canLosslesslyBitCastTo(T2))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000415 return false;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000416
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000417 T1W.StepToNextType();
418 T2W.StepToNextType();
419 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000420
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000421 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000422}
423
424
Chris Lattner08db7192002-11-06 06:20:27 +0000425/// mergeTypeInfo - This method merges the specified type into the current node
426/// at the specified offset. This may update the current node's type record if
427/// this gives more information to the node, it may do nothing to the node if
428/// this information is already known, or it may merge the node completely (and
429/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000430///
Chris Lattner08db7192002-11-06 06:20:27 +0000431/// This method returns true if the node is completely folded, otherwise false.
432///
Chris Lattner088b6392003-03-03 17:13:31 +0000433bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
434 bool FoldIfIncompatible) {
Bill Wendling5294fb02006-11-17 07:33:59 +0000435 DOUT << "merging " << *NewTy << " at " << Offset << " with " << *Ty << "\n";
Chris Lattner15869aa2003-11-02 22:27:28 +0000436 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000437 // Check to make sure the Size member is up-to-date. Size can be one of the
438 // following:
439 // Size = 0, Ty = Void: Nothing is known about this node.
440 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
441 // Size = 1, Ty = Void, Array = 1: The node is collapsed
442 // Otherwise, sizeof(Ty) = Size
443 //
Chris Lattner18552922002-11-18 21:44:46 +0000444 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
445 (Size == 0 && !Ty->isSized() && !isArray()) ||
446 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
447 (Size == 0 && !Ty->isSized() && !isArray()) ||
448 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000449 "Size member of DSNode doesn't match the type structure!");
450 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000451
Chris Lattner18552922002-11-18 21:44:46 +0000452 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000453 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000454
Chris Lattner08db7192002-11-06 06:20:27 +0000455 // Return true immediately if the node is completely folded.
456 if (isNodeCompletelyFolded()) return true;
457
Chris Lattner23f83dc2002-11-08 22:49:57 +0000458 // If this is an array type, eliminate the outside arrays because they won't
459 // be used anyway. This greatly reduces the size of large static arrays used
460 // as global variables, for example.
461 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000462 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000463 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
464 // FIXME: we might want to keep small arrays, but must be careful about
465 // things like: [2 x [10000 x int*]]
466 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000467 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000468 }
469
Chris Lattner08db7192002-11-06 06:20:27 +0000470 // Figure out how big the new type we're merging in is...
Chris Lattner507bdf92005-01-12 04:51:37 +0000471 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000472
473 // Otherwise check to see if we can fold this type into the current node. If
474 // we can't, we fold the node completely, if we can, we potentially update our
475 // internal state.
476 //
Chris Lattner18552922002-11-18 21:44:46 +0000477 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000478 // If this is the first type that this node has seen, just accept it without
479 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000480 assert(Offset == 0 && !isArray() &&
481 "Cannot have an offset into a void node!");
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000482
483 // If this node would have to have an unreasonable number of fields, just
484 // collapse it. This can occur for fortran common blocks, which have stupid
485 // things like { [100000000 x double], [1000000 x double] }.
486 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
Andrew Lenharth0c3a0b62006-03-15 05:43:41 +0000487 if (NumFields > DSAFieldLimit) {
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000488 foldNodeCompletely();
489 return true;
490 }
491
Chris Lattner18552922002-11-18 21:44:46 +0000492 Ty = NewTy;
493 NodeType &= ~Array;
494 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000495 Size = NewTySize;
496
497 // Calculate the number of outgoing links from this node.
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000498 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000499 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000500 }
Chris Lattner08db7192002-11-06 06:20:27 +0000501
502 // Handle node expansion case here...
503 if (Offset+NewTySize > Size) {
504 // It is illegal to grow this node if we have treated it as an array of
505 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000506 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000507 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000508 return true;
509 }
510
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000511 // If this node would have to have an unreasonable number of fields, just
512 // collapse it. This can occur for fortran common blocks, which have stupid
513 // things like { [100000000 x double], [1000000 x double] }.
514 unsigned NumFields = (NewTySize+Offset+DS::PointerSize-1) >> DS::PointerShift;
Andrew Lenharth0c3a0b62006-03-15 05:43:41 +0000515 if (NumFields > DSAFieldLimit) {
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000516 foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000517 return true;
518 }
519
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000520 if (Offset) {
521 //handle some common cases:
522 // Ty: struct { t1, t2, t3, t4, ..., tn}
523 // NewTy: struct { offset, stuff...}
Bill Wendling5294fb02006-11-17 07:33:59 +0000524 // try merge with NewTy: struct {t1, t2, stuff...} if offset lands exactly
525 // on a field in Ty
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000526 if (isa<StructType>(NewTy) && isa<StructType>(Ty)) {
Bill Wendling5294fb02006-11-17 07:33:59 +0000527 DOUT << "Ty: " << *Ty << "\nNewTy: " << *NewTy << "@" << Offset << "\n";
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000528 const StructType *STy = cast<StructType>(Ty);
529 const StructLayout &SL = *TD.getStructLayout(STy);
530 unsigned i = SL.getElementContainingOffset(Offset);
531 //Either we hit it exactly or give up
532 if (SL.MemberOffsets[i] != Offset) {
533 if (FoldIfIncompatible) foldNodeCompletely();
534 return true;
535 }
536 std::vector<const Type*> nt;
537 for (unsigned x = 0; x < i; ++x)
538 nt.push_back(STy->getElementType(x));
539 STy = cast<StructType>(NewTy);
540 nt.insert(nt.end(), STy->element_begin(), STy->element_end());
541 //and merge
542 STy = StructType::get(nt);
Bill Wendling5294fb02006-11-17 07:33:59 +0000543 DOUT << "Trying with: " << *STy << "\n";
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000544 return mergeTypeInfo(STy, 0);
545 }
546
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000547 //Ty: struct { t1, t2, t3 ... tn}
548 //NewTy T offset x
Bill Wendling5294fb02006-11-17 07:33:59 +0000549 //try merge with NewTy: struct : {t1, t2, T} if offset lands on a field
550 //in Ty
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000551 if (isa<StructType>(Ty)) {
Bill Wendling5294fb02006-11-17 07:33:59 +0000552 DOUT << "Ty: " << *Ty << "\nNewTy: " << *NewTy << "@" << Offset << "\n";
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000553 const StructType *STy = cast<StructType>(Ty);
554 const StructLayout &SL = *TD.getStructLayout(STy);
555 unsigned i = SL.getElementContainingOffset(Offset);
556 //Either we hit it exactly or give up
557 if (SL.MemberOffsets[i] != Offset) {
558 if (FoldIfIncompatible) foldNodeCompletely();
559 return true;
560 }
561 std::vector<const Type*> nt;
562 for (unsigned x = 0; x < i; ++x)
563 nt.push_back(STy->getElementType(x));
564 nt.push_back(NewTy);
565 //and merge
566 STy = StructType::get(nt);
Bill Wendling5294fb02006-11-17 07:33:59 +0000567 DOUT << "Trying with: " << *STy << "\n";
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000568 return mergeTypeInfo(STy, 0);
569 }
570
Bill Wendling5294fb02006-11-17 07:33:59 +0000571 assert(0 &&
572 "UNIMP: Trying to merge a growth type into "
573 "offset != 0: Collapsing!");
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000574 abort();
575 if (FoldIfIncompatible) foldNodeCompletely();
576 return true;
577
578 }
579
580
Chris Lattner08db7192002-11-06 06:20:27 +0000581 // Okay, the situation is nice and simple, we are trying to merge a type in
582 // at offset 0 that is bigger than our current type. Implement this by
583 // switching to the new type and then merge in the smaller one, which should
584 // hit the other code path here. If the other code path decides it's not
585 // ok, it will collapse the node as appropriate.
586 //
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000587
Chris Lattner94f84702005-03-17 19:56:56 +0000588 const Type *OldTy = Ty;
589 Ty = NewTy;
590 NodeType &= ~Array;
591 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000592 Size = NewTySize;
593
594 // Must grow links to be the appropriate size...
Chris Lattner94f84702005-03-17 19:56:56 +0000595 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000596
597 // Merge in the old type now... which is guaranteed to be smaller than the
598 // "current" type.
599 return mergeTypeInfo(OldTy, 0);
600 }
601
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000602 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000603 "Cannot merge something into a part of our type that doesn't exist!");
604
Chris Lattner18552922002-11-18 21:44:46 +0000605 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000606 // type that starts at offset Offset.
607 //
608 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000609 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000610 while (O < Offset) {
611 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
612
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000613 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000614 case Type::StructTyID: {
615 const StructType *STy = cast<StructType>(SubType);
616 const StructLayout &SL = *TD.getStructLayout(STy);
Chris Lattner2787e032005-03-13 19:05:05 +0000617 unsigned i = SL.getElementContainingOffset(Offset-O);
Chris Lattner08db7192002-11-06 06:20:27 +0000618
619 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000620 SubType = STy->getElementType(i);
Chris Lattner507bdf92005-01-12 04:51:37 +0000621 O += (unsigned)SL.MemberOffsets[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000622 break;
623 }
624 case Type::ArrayTyID: {
625 SubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000626 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000627 unsigned Remainder = (Offset-O) % ElSize;
628 O = Offset-Remainder;
629 break;
630 }
631 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000632 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000633 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000634 }
635 }
636
637 assert(O == Offset && "Could not achieve the correct offset!");
638
639 // If we found our type exactly, early exit
640 if (SubType == NewTy) return false;
641
Misha Brukman96a8bd72004-04-29 04:05:30 +0000642 // Differing function types don't require us to merge. They are not values
643 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000644 if (isa<FunctionType>(SubType) &&
645 isa<FunctionType>(NewTy)) return false;
646
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000647 unsigned SubTypeSize = SubType->isSized() ?
Chris Lattner507bdf92005-01-12 04:51:37 +0000648 (unsigned)TD.getTypeSize(SubType) : 0;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000649
650 // Ok, we are getting desperate now. Check for physical subtyping, where we
651 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000652 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000653 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000654 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000655 return false;
656
Chris Lattner08db7192002-11-06 06:20:27 +0000657 // Okay, so we found the leader type at the offset requested. Search the list
658 // of types that starts at this offset. If SubType is currently an array or
659 // structure, the type desired may actually be the first element of the
660 // composite type...
661 //
Chris Lattner18552922002-11-18 21:44:46 +0000662 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000663 while (SubType != NewTy) {
664 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000665 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000666 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000667 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000668 case Type::StructTyID: {
669 const StructType *STy = cast<StructType>(SubType);
670 const StructLayout &SL = *TD.getStructLayout(STy);
671 if (SL.MemberOffsets.size() > 1)
Chris Lattner507bdf92005-01-12 04:51:37 +0000672 NextPadSize = (unsigned)SL.MemberOffsets[1];
Chris Lattner18552922002-11-18 21:44:46 +0000673 else
674 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000675 NextSubType = STy->getElementType(0);
Chris Lattner507bdf92005-01-12 04:51:37 +0000676 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000677 break;
Chris Lattner18552922002-11-18 21:44:46 +0000678 }
Chris Lattner08db7192002-11-06 06:20:27 +0000679 case Type::ArrayTyID:
680 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000681 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner18552922002-11-18 21:44:46 +0000682 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000683 break;
684 default: ;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000685 // fall out
Chris Lattner08db7192002-11-06 06:20:27 +0000686 }
687
688 if (NextSubType == 0)
689 break; // In the default case, break out of the loop
690
Chris Lattner18552922002-11-18 21:44:46 +0000691 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000692 break; // Don't allow shrinking to a smaller type than NewTySize
693 SubType = NextSubType;
694 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000695 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000696 }
697
698 // If we found the type exactly, return it...
699 if (SubType == NewTy)
700 return false;
701
702 // Check to see if we have a compatible, but different type...
703 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000704 // Check to see if this type is obviously convertible... int -> uint f.e.
Reid Spencer3da59db2006-11-27 01:05:10 +0000705 if (NewTy->canLosslesslyBitCastTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000706 return false;
707
708 // Check to see if we have a pointer & integer mismatch going on here,
709 // loading a pointer as a long, for example.
710 //
711 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
712 NewTy->isInteger() && isa<PointerType>(SubType))
713 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000714 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
715 // We are accessing the field, plus some structure padding. Ignore the
716 // structure padding.
717 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000718 }
719
Chris Lattner58f98d02003-07-02 04:38:49 +0000720 Module *M = 0;
Chris Lattnera5f47ea2005-03-15 16:55:04 +0000721 if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
722 M = getParentGraph()->retnodes_begin()->first->getParent();
Bill Wendling5294fb02006-11-17 07:33:59 +0000723
724 DOUT << "MergeTypeInfo Folding OrigTy: ";
725 DEBUG(WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
Chris Lattner58f98d02003-07-02 04:38:49 +0000726 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
Bill Wendling5294fb02006-11-17 07:33:59 +0000727 << "SubType: ";
Chris Lattner58f98d02003-07-02 04:38:49 +0000728 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000729
Chris Lattner088b6392003-03-03 17:13:31 +0000730 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000731 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000732}
733
Chris Lattner08db7192002-11-06 06:20:27 +0000734
735
Misha Brukman96a8bd72004-04-29 04:05:30 +0000736/// addEdgeTo - Add an edge from the current node to the specified node. This
737/// can cause merging of nodes in the graph.
738///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000739void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000740 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000741
Andrew Lenharth79acb692006-03-27 23:39:58 +0000742 if (isNodeCompletelyFolded())
743 Offset = 0;
744
Chris Lattner08db7192002-11-06 06:20:27 +0000745 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000746 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000747 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000748 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000749 } else { // No merging to perform...
750 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000751 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000752}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000753
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000754
Misha Brukman96a8bd72004-04-29 04:05:30 +0000755/// MergeSortedVectors - Efficiently merge a vector into another vector where
756/// duplicates are not allowed and both are sorted. This assumes that 'T's are
757/// efficiently copyable and have sane comparison semantics.
758///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000759static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
760 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000761 // By far, the most common cases will be the simple ones. In these cases,
762 // avoid having to allocate a temporary vector...
763 //
764 if (Src.empty()) { // Nothing to merge in...
765 return;
766 } else if (Dest.empty()) { // Just copy the result in...
767 Dest = Src;
768 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000769 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000770 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000771 std::lower_bound(Dest.begin(), Dest.end(), V);
772 if (I == Dest.end() || *I != Src[0]) // If not already contained...
773 Dest.insert(I, Src[0]);
774 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000775 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000776 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000777 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000778 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
779 if (I == Dest.end() || *I != Tmp) // If not already contained...
780 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000781
782 } else {
783 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000784 std::vector<GlobalValue*> Old(Dest);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000785
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000786 // Make space for all of the type entries now...
787 Dest.resize(Dest.size()+Src.size());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000788
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000789 // Merge the two sorted ranges together... into Dest.
790 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000791
792 // Now erase any duplicate entries that may have accumulated into the
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000793 // vectors (because they were in both of the input sets)
794 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
795 }
796}
797
Chris Lattner0b144872004-01-27 22:03:40 +0000798void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
799 MergeSortedVectors(Globals, RHS);
800}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000801
Chris Lattner0b144872004-01-27 22:03:40 +0000802// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000803// This function does the hard work of merging two nodes, CurNodeH
804// and NH after filtering out trivial cases and making sure that
805// CurNodeH.offset >= NH.offset.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000806//
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000807// ***WARNING***
808// Since merging may cause either node to go away, we must always
809// use the node-handles to refer to the nodes. These node handles are
810// automatically updated during merging, so will always provide access
811// to the correct node after a merge.
812//
813void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
814 assert(CurNodeH.getOffset() >= NH.getOffset() &&
815 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000816 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
817 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000818
819 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
820 // respect to NH.Offset) is now zero. NOffset is the distance from the base
821 // of our object that N starts from.
822 //
823 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
824 unsigned NSize = NH.getNode()->getSize();
825
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000826 // If the two nodes are of different size, and the smaller node has the array
827 // bit set, collapse!
828 if (NSize != CurNodeH.getNode()->getSize()) {
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000829#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000830 if (NSize < CurNodeH.getNode()->getSize()) {
831 if (NH.getNode()->isArray())
832 NH.getNode()->foldNodeCompletely();
833 } else if (CurNodeH.getNode()->isArray()) {
834 NH.getNode()->foldNodeCompletely();
835 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000836#endif
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000837 }
838
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000839 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000840 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000841 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000842 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000843
844 // If we are merging a node with a completely folded node, then both nodes are
845 // now completely folded.
846 //
847 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
848 if (!NH.getNode()->isNodeCompletelyFolded()) {
849 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000850 assert(NH.getNode() && NH.getOffset() == 0 &&
851 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000852 NOffset = NH.getOffset();
853 NSize = NH.getNode()->getSize();
854 assert(NOffset == 0 && NSize == 1);
855 }
856 } else if (NH.getNode()->isNodeCompletelyFolded()) {
857 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000858 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
859 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000860 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000861 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000862 assert(NOffset == 0 && NSize == 1);
863 }
864
Chris Lattner72d29a42003-02-11 23:11:51 +0000865 DSNode *N = NH.getNode();
866 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000867 assert(!CurNodeH.getNode()->isDeadNode());
868
Chris Lattner0b144872004-01-27 22:03:40 +0000869 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000870 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000871
Chris Lattner72d29a42003-02-11 23:11:51 +0000872 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000873 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000874 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000875
Chris Lattner72d29a42003-02-11 23:11:51 +0000876 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
877 //
878 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
879 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000880 if (Link.getNode()) {
881 // Compute the offset into the current node at which to
882 // merge this link. In the common case, this is a linear
883 // relation to the offset in the original node (with
884 // wrapping), but if the current node gets collapsed due to
885 // recursive merging, we must make sure to merge in all remaining
886 // links at offset zero.
887 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000888 DSNode *CN = CurNodeH.getNode();
889 if (CN->Size != 1)
890 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
891 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000892 }
893 }
894
895 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000896 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000897
898 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000899 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000900 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000901
902 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000903 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000904 }
905}
906
907
Misha Brukman96a8bd72004-04-29 04:05:30 +0000908/// mergeWith - Merge this node and the specified node, moving all links to and
909/// from the argument node into the current node, deleting the node argument.
910/// Offset indicates what offset the specified node is to be merged into the
911/// current node.
912///
913/// The specified node may be a null pointer (in which case, we update it to
914/// point to this node).
915///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000916void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
917 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000918 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000919 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000920
Chris Lattner5254a8d2004-01-22 16:31:08 +0000921 // If the RHS is a null node, make it point to this node!
922 if (N == 0) {
923 NH.mergeWith(DSNodeHandle(this, Offset));
924 return;
925 }
926
Chris Lattnerbd92b732003-06-19 21:15:11 +0000927 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000928 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
929
Chris Lattner02606632002-11-04 06:48:26 +0000930 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000931 // We cannot merge two pieces of the same node together, collapse the node
932 // completely.
Bill Wendling5294fb02006-11-17 07:33:59 +0000933 DOUT << "Attempting to merge two chunks of the same node together!\n";
Chris Lattner08db7192002-11-06 06:20:27 +0000934 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000935 return;
936 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000937
Chris Lattner5190ce82002-11-12 07:20:45 +0000938 // If both nodes are not at offset 0, make sure that we are merging the node
939 // at an later offset into the node with the zero offset.
940 //
941 if (Offset < NH.getOffset()) {
942 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
943 return;
944 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
945 // If the offsets are the same, merge the smaller node into the bigger node
946 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
947 return;
948 }
949
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000950 // Ok, now we can merge the two nodes. Use a static helper that works with
951 // two node handles, since "this" may get merged away at intermediate steps.
952 DSNodeHandle CurNodeH(this, Offset);
953 DSNodeHandle NHCopy(NH);
Andrew Lenharth37705002006-06-19 15:42:47 +0000954 if (CurNodeH.getOffset() >= NHCopy.getOffset())
955 DSNode::MergeNodes(CurNodeH, NHCopy);
956 else
957 DSNode::MergeNodes(NHCopy, CurNodeH);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000958}
959
Chris Lattner0b144872004-01-27 22:03:40 +0000960
961//===----------------------------------------------------------------------===//
962// ReachabilityCloner Implementation
963//===----------------------------------------------------------------------===//
964
965DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
966 if (SrcNH.isNull()) return DSNodeHandle();
967 const DSNode *SN = SrcNH.getNode();
968
969 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000970 if (!NH.isNull()) { // Node already mapped?
971 DSNode *NHN = NH.getNode();
972 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
973 }
Chris Lattner0b144872004-01-27 22:03:40 +0000974
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000975 // If SrcNH has globals and the destination graph has one of the same globals,
976 // merge this node with the destination node, which is much more efficient.
Chris Lattner82c6c722005-03-20 02:41:38 +0000977 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000978 DSScalarMap &DestSM = Dest.getScalarMap();
Chris Lattner82c6c722005-03-20 02:41:38 +0000979 for (DSNode::globals_iterator I = SN->globals_begin(),E = SN->globals_end();
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000980 I != E; ++I) {
981 GlobalValue *GV = *I;
982 DSScalarMap::iterator GI = DestSM.find(GV);
983 if (GI != DestSM.end() && !GI->second.isNull()) {
984 // We found one, use merge instead!
985 merge(GI->second, Src.getNodeForValue(GV));
986 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000987 DSNode *NHN = NH.getNode();
988 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000989 }
990 }
991 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000992
Chris Lattner0b144872004-01-27 22:03:40 +0000993 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
994 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000995 NH = DN;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000996
Chris Lattner0b144872004-01-27 22:03:40 +0000997 // Next, recursively clone all outgoing links as necessary. Note that
998 // adding these links can cause the node to collapse itself at any time, and
999 // the current node may be merged with arbitrary other nodes. For this
1000 // reason, we must always go through NH.
1001 DN = 0;
1002 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1003 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1004 if (!SrcEdge.isNull()) {
1005 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
1006 // Compute the offset into the current node at which to
1007 // merge this link. In the common case, this is a linear
1008 // relation to the offset in the original node (with
1009 // wrapping), but if the current node gets collapsed due to
1010 // recursive merging, we must make sure to merge in all remaining
1011 // links at offset zero.
1012 unsigned MergeOffset = 0;
1013 DSNode *CN = NH.getNode();
1014 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +00001015 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +00001016 CN->addEdgeTo(MergeOffset, DestEdge);
1017 }
1018 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001019
Chris Lattner0b144872004-01-27 22:03:40 +00001020 // If this node contains any globals, make sure they end up in the scalar
1021 // map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +00001022 for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
Chris Lattner0b144872004-01-27 22:03:40 +00001023 I != E; ++I) {
1024 GlobalValue *GV = *I;
1025 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1026 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1027 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
1028 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +00001029 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001030 }
Chris Lattner82c6c722005-03-20 02:41:38 +00001031 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001032
1033 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
1034}
1035
1036void ReachabilityCloner::merge(const DSNodeHandle &NH,
1037 const DSNodeHandle &SrcNH) {
1038 if (SrcNH.isNull()) return; // Noop
1039 if (NH.isNull()) {
1040 // If there is no destination node, just clone the source and assign the
1041 // destination node to be it.
1042 NH.mergeWith(getClonedNH(SrcNH));
1043 return;
1044 }
1045
1046 // Okay, at this point, we know that we have both a destination and a source
1047 // node that need to be merged. Check to see if the source node has already
1048 // been cloned.
1049 const DSNode *SN = SrcNH.getNode();
1050 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +00001051 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +00001052 DSNode *SCNHN = SCNH.getNode();
1053 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +00001054 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001055 return; // Nothing to do!
1056 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001057
Chris Lattner0b144872004-01-27 22:03:40 +00001058 // Okay, so the source node has not already been cloned. Instead of creating
1059 // a new DSNode, only to merge it into the one we already have, try to perform
1060 // the merge in-place. The only case we cannot handle here is when the offset
1061 // into the existing node is less than the offset into the virtual node we are
1062 // merging in. In this case, we have to extend the existing node, which
1063 // requires an allocation anyway.
1064 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
1065 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +00001066 if (!DN->isNodeCompletelyFolded()) {
1067 // Make sure the destination node is folded if the source node is folded.
1068 if (SN->isNodeCompletelyFolded()) {
1069 DN->foldNodeCompletely();
1070 DN = NH.getNode();
1071 } else if (SN->getSize() != DN->getSize()) {
1072 // If the two nodes are of different size, and the smaller node has the
1073 // array bit set, collapse!
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001074#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner0b144872004-01-27 22:03:40 +00001075 if (SN->getSize() < DN->getSize()) {
1076 if (SN->isArray()) {
1077 DN->foldNodeCompletely();
1078 DN = NH.getNode();
1079 }
1080 } else if (DN->isArray()) {
1081 DN->foldNodeCompletely();
1082 DN = NH.getNode();
1083 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001084#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001085 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001086
1087 // Merge the type entries of the two nodes together...
Chris Lattner0b144872004-01-27 22:03:40 +00001088 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
1089 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
1090 DN = NH.getNode();
1091 }
1092 }
1093
1094 assert(!DN->isDeadNode());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001095
Chris Lattner0b144872004-01-27 22:03:40 +00001096 // Merge the NodeType information.
1097 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
1098
1099 // Before we start merging outgoing links and updating the scalar map, make
1100 // sure it is known that this is the representative node for the src node.
1101 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
1102
1103 // If the source node contains any globals, make sure they end up in the
1104 // scalar map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +00001105 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattner0b144872004-01-27 22:03:40 +00001106 // Update the globals in the destination node itself.
Chris Lattner82c6c722005-03-20 02:41:38 +00001107 DN->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001108
1109 // Update the scalar map for the graph we are merging the source node
1110 // into.
Chris Lattner82c6c722005-03-20 02:41:38 +00001111 for (DSNode::globals_iterator I = SN->globals_begin(),
1112 E = SN->globals_end(); I != E; ++I) {
Chris Lattner0b144872004-01-27 22:03:40 +00001113 GlobalValue *GV = *I;
1114 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1115 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1116 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1117 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +00001118 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001119 }
Chris Lattner82c6c722005-03-20 02:41:38 +00001120 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001121 }
1122 } else {
1123 // We cannot handle this case without allocating a temporary node. Fall
1124 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +00001125 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
1126 NewDN->maskNodeTypes(BitsToKeep);
1127
1128 unsigned NHOffset = NH.getOffset();
1129 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001130
Chris Lattner0b144872004-01-27 22:03:40 +00001131 assert(NH.getNode() &&
1132 (NH.getOffset() > NHOffset ||
1133 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
1134 "Merging did not adjust the offset!");
1135
1136 // Before we start merging outgoing links and updating the scalar map, make
1137 // sure it is known that this is the representative node for the src node.
1138 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +00001139
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001140 // If the source node contained any globals, make sure to create entries
Chris Lattneread9eb72004-01-29 08:36:22 +00001141 // in the scalar map for them!
Chris Lattner82c6c722005-03-20 02:41:38 +00001142 for (DSNode::globals_iterator I = SN->globals_begin(),
1143 E = SN->globals_end(); I != E; ++I) {
Chris Lattneread9eb72004-01-29 08:36:22 +00001144 GlobalValue *GV = *I;
1145 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1146 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1147 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1148 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
1149 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1150 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001151 }
Chris Lattner0b144872004-01-27 22:03:40 +00001152 }
1153
1154
1155 // Next, recursively merge all outgoing links as necessary. Note that
1156 // adding these links can cause the destination node to collapse itself at
1157 // any time, and the current node may be merged with arbitrary other nodes.
1158 // For this reason, we must always go through NH.
1159 DN = 0;
1160 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1161 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1162 if (!SrcEdge.isNull()) {
1163 // Compute the offset into the current node at which to
1164 // merge this link. In the common case, this is a linear
1165 // relation to the offset in the original node (with
1166 // wrapping), but if the current node gets collapsed due to
1167 // recursive merging, we must make sure to merge in all remaining
1168 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +00001169 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +00001170 unsigned MergeOffset =
1171 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001172
Chris Lattnerf590ced2004-03-04 17:06:53 +00001173 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1174 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001175 // Perform the recursive merging. Make sure to create a temporary NH,
1176 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001177 merge(Tmp, SrcEdge);
1178 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001179 Tmp.mergeWith(getClonedNH(SrcEdge));
1180 // Merging this could cause all kinds of recursive things to happen,
1181 // culminating in the current node being eliminated. Since this is
1182 // possible, make sure to reaquire the link from 'CN'.
1183
1184 unsigned MergeOffset = 0;
1185 CN = SCNH.getNode();
1186 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1187 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001188 }
Chris Lattner0b144872004-01-27 22:03:40 +00001189 }
1190 }
1191}
1192
1193/// mergeCallSite - Merge the nodes reachable from the specified src call
1194/// site into the nodes reachable from DestCS.
Chris Lattnerb3439372005-03-21 20:28:50 +00001195void ReachabilityCloner::mergeCallSite(DSCallSite &DestCS,
Chris Lattner0b144872004-01-27 22:03:40 +00001196 const DSCallSite &SrcCS) {
1197 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1198 unsigned MinArgs = DestCS.getNumPtrArgs();
1199 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001200
Chris Lattner0b144872004-01-27 22:03:40 +00001201 for (unsigned a = 0; a != MinArgs; ++a)
1202 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
Chris Lattner3f90a942005-03-21 09:39:51 +00001203
1204 for (unsigned a = MinArgs, e = SrcCS.getNumPtrArgs(); a != e; ++a)
Chris Lattnerb3439372005-03-21 20:28:50 +00001205 DestCS.addPtrArg(getClonedNH(SrcCS.getPtrArg(a)));
Chris Lattner0b144872004-01-27 22:03:40 +00001206}
1207
1208
Chris Lattner9de906c2002-10-20 22:11:44 +00001209//===----------------------------------------------------------------------===//
1210// DSCallSite Implementation
1211//===----------------------------------------------------------------------===//
1212
Vikram S. Adve26b98262002-10-20 21:41:02 +00001213// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001214Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001215 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001216}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001217
Chris Lattner0b144872004-01-27 22:03:40 +00001218void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1219 ReachabilityCloner &RC) {
1220 NH = RC.getClonedNH(Src);
1221}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001222
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001223//===----------------------------------------------------------------------===//
1224// DSGraph Implementation
1225//===----------------------------------------------------------------------===//
1226
Chris Lattnera9d65662003-06-30 05:57:30 +00001227/// getFunctionNames - Return a space separated list of the name of the
1228/// functions in this graph (if any)
1229std::string DSGraph::getFunctionNames() const {
1230 switch (getReturnNodes().size()) {
1231 case 0: return "Globals graph";
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001232 case 1: return retnodes_begin()->first->getName();
Chris Lattnera9d65662003-06-30 05:57:30 +00001233 default:
1234 std::string Return;
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001235 for (DSGraph::retnodes_iterator I = retnodes_begin();
1236 I != retnodes_end(); ++I)
Chris Lattnera9d65662003-06-30 05:57:30 +00001237 Return += I->first->getName() + " ";
1238 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1239 return Return;
1240 }
1241}
1242
1243
Chris Lattnerf09ecff2005-03-21 22:49:53 +00001244DSGraph::DSGraph(const DSGraph &G, EquivalenceClasses<GlobalValue*> &ECs,
1245 unsigned CloneFlags)
Chris Lattnerf4f62272005-03-19 22:23:45 +00001246 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001247 PrintAuxCalls = false;
Chris Lattnera2197132005-03-22 00:36:51 +00001248 cloneInto(G, CloneFlags);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001249}
1250
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001251DSGraph::~DSGraph() {
1252 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001253 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001254 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001255 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001256
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001257 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001258 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
Chris Lattner84b80a22005-03-16 22:42:19 +00001259 NI->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001260
Chris Lattner28897e12004-02-08 00:53:26 +00001261 // Free all of the nodes.
1262 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001263}
1264
Chris Lattner0d9bab82002-07-18 00:12:30 +00001265// dump - Allow inspection of graph in a debugger.
Bill Wendlinga5b31ca2006-11-28 23:33:06 +00001266void DSGraph::dump() const { print(llvm_cerr); }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001267
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001268
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001269/// remapLinks - Change all of the Links in the current node according to the
1270/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001271///
Chris Lattner8d327672003-06-30 03:36:09 +00001272void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001273 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1274 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001275 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001276 if (ONMI != OldNodeMap.end()) {
1277 DSNode *ONMIN = ONMI->second.getNode();
1278 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1279 }
Chris Lattner2f561382004-01-22 16:56:13 +00001280 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001281}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001282
Chris Lattnerd672ab92005-02-15 18:40:55 +00001283/// addObjectToGraph - This method can be used to add global, stack, and heap
1284/// objects to the graph. This can be used when updating DSGraphs due to the
1285/// introduction of new temporary objects. The new object is not pointed to
1286/// and does not point to any other objects in the graph.
1287DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1288 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1289 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1290 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
Chris Lattner7a0c7752005-02-15 18:48:48 +00001291 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
Chris Lattnerd672ab92005-02-15 18:40:55 +00001292 ScalarMap[Ptr] = N;
1293
1294 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1295 N->addGlobal(GV);
Reid Spencer3ed469c2006-11-02 20:25:50 +00001296 } else if (isa<MallocInst>(Ptr)) {
Chris Lattnerd672ab92005-02-15 18:40:55 +00001297 N->setHeapNodeMarker();
Reid Spencer3ed469c2006-11-02 20:25:50 +00001298 } else if (isa<AllocaInst>(Ptr)) {
Chris Lattnerd672ab92005-02-15 18:40:55 +00001299 N->setAllocaNodeMarker();
1300 } else {
1301 assert(0 && "Illegal memory object input!");
1302 }
1303 return N;
1304}
1305
1306
Chris Lattner5a540632003-06-30 03:15:25 +00001307/// cloneInto - Clone the specified DSGraph into the current graph. The
Chris Lattner3c920fa2005-03-22 00:21:05 +00001308/// translated ScalarMap for the old function is filled into the ScalarMap
1309/// for the graph, and the translated ReturnNodes map is returned into
1310/// ReturnNodes.
Chris Lattner5a540632003-06-30 03:15:25 +00001311///
1312/// The CloneFlags member controls various aspects of the cloning process.
1313///
Chris Lattnera2197132005-03-22 00:36:51 +00001314void DSGraph::cloneInto(const DSGraph &G, unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001315 TIME_REGION(X, "cloneInto");
Chris Lattner33312f72002-11-08 01:21:07 +00001316 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001317
Chris Lattnera2197132005-03-22 00:36:51 +00001318 NodeMapTy OldNodeMap;
1319
Chris Lattner1e883692003-02-03 20:08:51 +00001320 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001321 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1322 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1323 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001324 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001325
Chris Lattner84b80a22005-03-16 22:42:19 +00001326 for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1327 assert(!I->isForwarding() &&
Chris Lattnerd85645f2004-02-21 22:28:26 +00001328 "Forward nodes shouldn't be in node list!");
Chris Lattner84b80a22005-03-16 22:42:19 +00001329 DSNode *New = new DSNode(*I, this);
Chris Lattnerd85645f2004-02-21 22:28:26 +00001330 New->maskNodeTypes(~BitsToClear);
Chris Lattner84b80a22005-03-16 22:42:19 +00001331 OldNodeMap[I] = New;
Chris Lattnerd85645f2004-02-21 22:28:26 +00001332 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001333
Chris Lattner18552922002-11-18 21:44:46 +00001334#ifndef NDEBUG
1335 Timer::addPeakMemoryMeasurement();
1336#endif
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001337
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001338 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001339 // Note that we don't loop over the node's list to do this. The problem is
1340 // that remaping links can cause recursive merging to happen, which means
1341 // that node_iterator's can get easily invalidated! Because of this, we
1342 // loop over the OldNodeMap, which contains all of the new nodes as the
1343 // .second element of the map elements. Also note that if we remap a node
1344 // more than once, we won't break anything.
1345 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1346 I != E; ++I)
1347 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001348
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001349 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001350 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001351 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001352 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner3bc703b2005-03-22 01:42:59 +00001353 DSNodeHandle &H = ScalarMap.getRawEntryRef(I->first);
Chris Lattner6f967742004-10-30 04:05:01 +00001354 DSNode *MappedNodeN = MappedNode.getNode();
1355 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001356 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001357 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001358
Chris Lattner679e8e12002-11-08 21:27:12 +00001359 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001360 // Copy the function calls list.
1361 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1362 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001363 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001364
Chris Lattneracf491f2002-11-08 22:27:09 +00001365 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001366 // Copy the auxiliary function calls list.
1367 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1368 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattner679e8e12002-11-08 21:27:12 +00001369 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001370
Chris Lattner5a540632003-06-30 03:15:25 +00001371 // Map the return node pointers over...
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001372 for (retnodes_iterator I = G.retnodes_begin(),
1373 E = G.retnodes_end(); I != E; ++I) {
Chris Lattner5a540632003-06-30 03:15:25 +00001374 const DSNodeHandle &Ret = I->second;
1375 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001376 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattnerd65145b2005-03-22 00:29:44 +00001377 ReturnNodes.insert(std::make_pair(I->first,
1378 DSNodeHandle(MappedRetN,
1379 MappedRet.getOffset()+Ret.getOffset())));
Chris Lattner5a540632003-06-30 03:15:25 +00001380 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001381}
1382
Chris Lattner5734e432005-03-24 23:46:04 +00001383/// spliceFrom - Logically perform the operation of cloning the RHS graph into
1384/// this graph, then clearing the RHS graph. Instead of performing this as
1385/// two seperate operations, do it as a single, much faster, one.
1386///
1387void DSGraph::spliceFrom(DSGraph &RHS) {
1388 // Change all of the nodes in RHS to think we are their parent.
1389 for (NodeListTy::iterator I = RHS.Nodes.begin(), E = RHS.Nodes.end();
1390 I != E; ++I)
1391 I->setParentGraph(this);
1392 // Take all of the nodes.
1393 Nodes.splice(Nodes.end(), RHS.Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001394
Chris Lattner5734e432005-03-24 23:46:04 +00001395 // Take all of the calls.
1396 FunctionCalls.splice(FunctionCalls.end(), RHS.FunctionCalls);
1397 AuxFunctionCalls.splice(AuxFunctionCalls.end(), RHS.AuxFunctionCalls);
1398
1399 // Take all of the return nodes.
Chris Lattnerce7068d2005-03-25 00:02:41 +00001400 if (ReturnNodes.empty()) {
1401 ReturnNodes.swap(RHS.ReturnNodes);
1402 } else {
1403 ReturnNodes.insert(RHS.ReturnNodes.begin(), RHS.ReturnNodes.end());
1404 RHS.ReturnNodes.clear();
1405 }
Chris Lattner5734e432005-03-24 23:46:04 +00001406
1407 // Merge the scalar map in.
1408 ScalarMap.spliceFrom(RHS.ScalarMap);
1409}
1410
1411/// spliceFrom - Copy all entries from RHS, then clear RHS.
1412///
1413void DSScalarMap::spliceFrom(DSScalarMap &RHS) {
1414 // Special case if this is empty.
1415 if (ValueMap.empty()) {
1416 ValueMap.swap(RHS.ValueMap);
1417 GlobalSet.swap(RHS.GlobalSet);
1418 } else {
1419 GlobalSet.insert(RHS.GlobalSet.begin(), RHS.GlobalSet.end());
1420 for (ValueMapTy::iterator I = RHS.ValueMap.begin(), E = RHS.ValueMap.end();
1421 I != E; ++I)
1422 ValueMap[I->first].mergeWith(I->second);
1423 RHS.ValueMap.clear();
1424 }
1425}
1426
1427
Chris Lattnerbb753c42005-02-03 18:40:25 +00001428/// getFunctionArgumentsForCall - Given a function that is currently in this
1429/// graph, return the DSNodeHandles that correspond to the pointer-compatible
1430/// function arguments. The vector is filled in with the return value (or
1431/// null if it is not pointer compatible), followed by all of the
1432/// pointer-compatible arguments.
1433void DSGraph::getFunctionArgumentsForCall(Function *F,
1434 std::vector<DSNodeHandle> &Args) const {
1435 Args.push_back(getReturnNodeFor(*F));
Chris Lattnereb394922005-03-23 16:43:11 +00001436 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1437 AI != E; ++AI)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001438 if (isPointerType(AI->getType())) {
1439 Args.push_back(getNodeForValue(AI));
1440 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1441 }
1442}
1443
Chris Lattner4da120e2005-03-24 23:06:02 +00001444namespace {
1445 // HackedGraphSCCFinder - This is used to find nodes that have a path from the
1446 // node to a node cloned by the ReachabilityCloner object contained. To be
1447 // extra obnoxious it ignores edges from nodes that are globals, and truncates
1448 // search at RC marked nodes. This is designed as an object so that
1449 // intermediate results can be memoized across invocations of
1450 // PathExistsToClonedNode.
1451 struct HackedGraphSCCFinder {
1452 ReachabilityCloner &RC;
1453 unsigned CurNodeId;
1454 std::vector<const DSNode*> SCCStack;
1455 std::map<const DSNode*, std::pair<unsigned, bool> > NodeInfo;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001456
Chris Lattner4da120e2005-03-24 23:06:02 +00001457 HackedGraphSCCFinder(ReachabilityCloner &rc) : RC(rc), CurNodeId(1) {
1458 // Remove null pointer as a special case.
1459 NodeInfo[0] = std::make_pair(0, false);
Chris Lattnerd8642122005-03-24 21:07:47 +00001460 }
1461
Chris Lattner4da120e2005-03-24 23:06:02 +00001462 std::pair<unsigned, bool> &VisitForSCCs(const DSNode *N);
1463
1464 bool PathExistsToClonedNode(const DSNode *N) {
1465 return VisitForSCCs(N).second;
1466 }
1467
1468 bool PathExistsToClonedNode(const DSCallSite &CS) {
1469 if (PathExistsToClonedNode(CS.getRetVal().getNode()))
1470 return true;
1471 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1472 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode()))
1473 return true;
1474 return false;
1475 }
1476 };
1477}
1478
1479std::pair<unsigned, bool> &HackedGraphSCCFinder::
1480VisitForSCCs(const DSNode *N) {
1481 std::map<const DSNode*, std::pair<unsigned, bool> >::iterator
1482 NodeInfoIt = NodeInfo.lower_bound(N);
1483 if (NodeInfoIt != NodeInfo.end() && NodeInfoIt->first == N)
1484 return NodeInfoIt->second;
1485
1486 unsigned Min = CurNodeId++;
1487 unsigned MyId = Min;
1488 std::pair<unsigned, bool> &ThisNodeInfo =
1489 NodeInfo.insert(NodeInfoIt,
1490 std::make_pair(N, std::make_pair(MyId, false)))->second;
1491
1492 // Base case: if we find a global, this doesn't reach the cloned graph
1493 // portion.
1494 if (N->isGlobalNode()) {
1495 ThisNodeInfo.second = false;
1496 return ThisNodeInfo;
Chris Lattnerd8642122005-03-24 21:07:47 +00001497 }
1498
Chris Lattner4da120e2005-03-24 23:06:02 +00001499 // Base case: if this does reach the cloned graph portion... it does. :)
1500 if (RC.hasClonedNode(N)) {
1501 ThisNodeInfo.second = true;
1502 return ThisNodeInfo;
1503 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001504
Chris Lattner4da120e2005-03-24 23:06:02 +00001505 SCCStack.push_back(N);
Chris Lattnerd8642122005-03-24 21:07:47 +00001506
Chris Lattner4da120e2005-03-24 23:06:02 +00001507 // Otherwise, check all successors.
1508 bool AnyDirectSuccessorsReachClonedNodes = false;
1509 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
Chris Lattner63320cc2005-04-25 19:16:17 +00001510 EI != EE; ++EI)
1511 if (DSNode *Succ = EI->getNode()) {
1512 std::pair<unsigned, bool> &SuccInfo = VisitForSCCs(Succ);
1513 if (SuccInfo.first < Min) Min = SuccInfo.first;
1514 AnyDirectSuccessorsReachClonedNodes |= SuccInfo.second;
1515 }
Chris Lattner4da120e2005-03-24 23:06:02 +00001516
1517 if (Min != MyId)
1518 return ThisNodeInfo; // Part of a large SCC. Leave self on stack.
1519
1520 if (SCCStack.back() == N) { // Special case single node SCC.
1521 SCCStack.pop_back();
1522 ThisNodeInfo.second = AnyDirectSuccessorsReachClonedNodes;
1523 return ThisNodeInfo;
1524 }
1525
1526 // Find out if any direct successors of any node reach cloned nodes.
1527 if (!AnyDirectSuccessorsReachClonedNodes)
1528 for (unsigned i = SCCStack.size()-1; SCCStack[i] != N; --i)
1529 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1530 EI != EE; ++EI)
1531 if (DSNode *N = EI->getNode())
1532 if (NodeInfo[N].second) {
1533 AnyDirectSuccessorsReachClonedNodes = true;
1534 goto OutOfLoop;
1535 }
1536OutOfLoop:
1537 // If any successor reaches a cloned node, mark all nodes in this SCC as
1538 // reaching the cloned node.
1539 if (AnyDirectSuccessorsReachClonedNodes)
1540 while (SCCStack.back() != N) {
1541 NodeInfo[SCCStack.back()].second = true;
1542 SCCStack.pop_back();
1543 }
1544 SCCStack.pop_back();
1545 ThisNodeInfo.second = true;
1546 return ThisNodeInfo;
1547}
Chris Lattnerd8642122005-03-24 21:07:47 +00001548
Chris Lattnere8594442005-02-04 19:58:28 +00001549/// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1550/// nodes from G2 into 'this' graph, merging the bindings specified by the
1551/// call site (in this graph) with the bindings specified by the vector in G2.
1552/// The two DSGraphs must be different.
Chris Lattner076c1f92002-11-07 06:31:54 +00001553///
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001554void DSGraph::mergeInGraph(const DSCallSite &CS,
Chris Lattnere8594442005-02-04 19:58:28 +00001555 std::vector<DSNodeHandle> &Args,
Chris Lattner9f930552003-06-30 05:27:18 +00001556 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001557 TIME_REGION(X, "mergeInGraph");
1558
Chris Lattnerc14f59c2005-03-23 20:12:08 +00001559 assert((CloneFlags & DontCloneCallNodes) &&
1560 "Doesn't support copying of call nodes!");
1561
Chris Lattner076c1f92002-11-07 06:31:54 +00001562 // If this is not a recursive call, clone the graph into this graph...
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001563 if (&Graph == this) {
Chris Lattnerbb753c42005-02-03 18:40:25 +00001564 // Merge the return value with the return value of the context.
1565 Args[0].mergeWith(CS.getRetVal());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001566
Chris Lattnerbb753c42005-02-03 18:40:25 +00001567 // Resolve all of the function arguments.
1568 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001569 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001570 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001571
Chris Lattnerbb753c42005-02-03 18:40:25 +00001572 // Add the link from the argument scalar to the provided value.
1573 Args[i+1].mergeWith(CS.getPtrArg(i));
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001574 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001575 return;
Chris Lattner076c1f92002-11-07 06:31:54 +00001576 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001577
1578 // Clone the callee's graph into the current graph, keeping track of where
1579 // scalars in the old graph _used_ to point, and of the new nodes matching
1580 // nodes of the old graph.
1581 ReachabilityCloner RC(*this, Graph, CloneFlags);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001582
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001583 // Map the return node pointer over.
1584 if (!CS.getRetVal().isNull())
1585 RC.merge(CS.getRetVal(), Args[0]);
1586
1587 // Map over all of the arguments.
1588 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1589 if (i == Args.size()-1)
1590 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001591
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001592 // Add the link from the argument scalar to the provided value.
1593 RC.merge(CS.getPtrArg(i), Args[i+1]);
1594 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001595
Chris Lattnerd8642122005-03-24 21:07:47 +00001596 // We generally don't want to copy global nodes or aux calls from the callee
1597 // graph to the caller graph. However, we have to copy them if there is a
1598 // path from the node to a node we have already copied which does not go
1599 // through another global. Compute the set of node that can reach globals and
1600 // aux call nodes to copy over, then do it.
1601 std::vector<const DSCallSite*> AuxCallToCopy;
1602 std::vector<GlobalValue*> GlobalsToCopy;
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001603
Chris Lattnerd8642122005-03-24 21:07:47 +00001604 // NodesReachCopiedNodes - Memoize results for efficiency. Contains a
1605 // true/false value for every visited node that reaches a copied node without
1606 // going through a global.
Chris Lattner4da120e2005-03-24 23:06:02 +00001607 HackedGraphSCCFinder SCCFinder(RC);
Chris Lattnerd8642122005-03-24 21:07:47 +00001608
1609 if (!(CloneFlags & DontCloneAuxCallNodes))
1610 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
Chris Lattner4da120e2005-03-24 23:06:02 +00001611 if (SCCFinder.PathExistsToClonedNode(*I))
Chris Lattnerd8642122005-03-24 21:07:47 +00001612 AuxCallToCopy.push_back(&*I);
Andrew Lenharthdf983de2006-11-07 20:36:02 +00001613// else if (I->isIndirectCall()){
1614// //If the call node doesn't have any callees, clone it
1615// std::vector< Function *> List;
1616// I->getCalleeNode()->addFullFunctionList(List);
1617// if (!List.size())
1618// AuxCallToCopy.push_back(&*I);
1619// }
Chris Lattnerd8642122005-03-24 21:07:47 +00001620
Chris Lattner4da120e2005-03-24 23:06:02 +00001621 const DSScalarMap &GSM = Graph.getScalarMap();
Chris Lattnerd8642122005-03-24 21:07:47 +00001622 for (DSScalarMap::global_iterator GI = GSM.global_begin(),
Chris Lattner09adbbc92005-03-24 21:17:27 +00001623 E = GSM.global_end(); GI != E; ++GI) {
1624 DSNode *GlobalNode = Graph.getNodeForValue(*GI).getNode();
1625 for (DSNode::edge_iterator EI = GlobalNode->edge_begin(),
1626 EE = GlobalNode->edge_end(); EI != EE; ++EI)
Chris Lattner4da120e2005-03-24 23:06:02 +00001627 if (SCCFinder.PathExistsToClonedNode(EI->getNode())) {
Chris Lattner09adbbc92005-03-24 21:17:27 +00001628 GlobalsToCopy.push_back(*GI);
1629 break;
1630 }
1631 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001632
1633 // Copy aux calls that are needed.
1634 for (unsigned i = 0, e = AuxCallToCopy.size(); i != e; ++i)
1635 AuxFunctionCalls.push_back(DSCallSite(*AuxCallToCopy[i], RC));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001636
Chris Lattnerd8642122005-03-24 21:07:47 +00001637 // Copy globals that are needed.
1638 for (unsigned i = 0, e = GlobalsToCopy.size(); i != e; ++i)
1639 RC.getClonedNH(Graph.getNodeForValue(GlobalsToCopy[i]));
Chris Lattner076c1f92002-11-07 06:31:54 +00001640}
1641
Chris Lattnere8594442005-02-04 19:58:28 +00001642
1643
1644/// mergeInGraph - The method is used for merging graphs together. If the
1645/// argument graph is not *this, it makes a clone of the specified graph, then
1646/// merges the nodes specified in the call site with the formal arguments in the
1647/// graph.
1648///
1649void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1650 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattnere8594442005-02-04 19:58:28 +00001651 // Set up argument bindings.
1652 std::vector<DSNodeHandle> Args;
1653 Graph.getFunctionArgumentsForCall(&F, Args);
1654
1655 mergeInGraph(CS, Args, Graph, CloneFlags);
1656}
1657
Chris Lattner58f98d02003-07-02 04:38:49 +00001658/// getCallSiteForArguments - Get the arguments and return value bindings for
1659/// the specified function in the current graph.
1660///
1661DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1662 std::vector<DSNodeHandle> Args;
1663
Chris Lattnere4d5c442005-03-15 04:54:21 +00001664 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner58f98d02003-07-02 04:38:49 +00001665 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001666 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001667
Chris Lattner808a7ae2003-09-20 16:34:13 +00001668 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001669}
1670
Chris Lattner85fb1be2004-03-09 19:37:06 +00001671/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1672/// the context of this graph, return the DSCallSite for it.
1673DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1674 DSNodeHandle RetVal;
1675 Instruction *I = CS.getInstruction();
1676 if (isPointerType(I->getType()))
1677 RetVal = getNodeForValue(I);
1678
1679 std::vector<DSNodeHandle> Args;
1680 Args.reserve(CS.arg_end()-CS.arg_begin());
1681
1682 // Calculate the arguments vector...
1683 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1684 if (isPointerType((*I)->getType()))
Chris Lattner94f84702005-03-17 19:56:56 +00001685 if (isa<ConstantPointerNull>(*I))
1686 Args.push_back(DSNodeHandle());
1687 else
1688 Args.push_back(getNodeForValue(*I));
Chris Lattner85fb1be2004-03-09 19:37:06 +00001689
1690 // Add a new function call entry...
1691 if (Function *F = CS.getCalledFunction())
1692 return DSCallSite(CS, RetVal, F, Args);
1693 else
1694 return DSCallSite(CS, RetVal,
1695 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1696}
1697
Chris Lattner58f98d02003-07-02 04:38:49 +00001698
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001699
Chris Lattner0d9bab82002-07-18 00:12:30 +00001700// markIncompleteNodes - Mark the specified node as having contents that are not
1701// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001702// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001703// must recursively traverse the data structure graph, marking all reachable
1704// nodes as incomplete.
1705//
1706static void markIncompleteNode(DSNode *N) {
1707 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001708 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001709
1710 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001711 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001712
Misha Brukman2f2d0652003-09-11 18:14:24 +00001713 // Recursively process children...
Chris Lattner6be07942005-02-09 03:20:43 +00001714 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1715 if (DSNode *DSN = I->getNode())
Chris Lattner08db7192002-11-06 06:20:27 +00001716 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001717}
1718
Chris Lattnere71ffc22002-11-11 03:36:55 +00001719static void markIncomplete(DSCallSite &Call) {
1720 // Then the return value is certainly incomplete!
1721 markIncompleteNode(Call.getRetVal().getNode());
1722
1723 // All objects pointed to by function arguments are incomplete!
1724 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1725 markIncompleteNode(Call.getPtrArg(i).getNode());
1726}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001727
1728// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1729// modified by other functions that have not been resolved yet. This marks
1730// nodes that are reachable through three sources of "unknownness":
1731//
1732// Global Variables, Function Calls, and Incoming Arguments
1733//
1734// For any node that may have unknown components (because something outside the
1735// scope of current analysis may have modified it), the 'Incomplete' flag is
1736// added to the NodeType.
1737//
Chris Lattner394471f2003-01-23 22:05:33 +00001738void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001739 // Mark any incoming arguments as incomplete.
Chris Lattner5a540632003-06-30 03:15:25 +00001740 if (Flags & DSGraph::MarkFormalArgs)
1741 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1742 FI != E; ++FI) {
1743 Function &F = *FI->first;
Chris Lattner9342a932005-03-29 19:16:59 +00001744 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1745 I != E; ++I)
Chris Lattnerb5ecd2e2005-03-13 20:22:10 +00001746 if (isPointerType(I->getType()))
1747 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattnera4319e52005-03-12 14:58:28 +00001748 markIncompleteNode(FI->second.getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001749 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001750
Chris Lattnera9548d92005-01-30 23:51:02 +00001751 // Mark stuff passed into functions calls as being incomplete.
Chris Lattnere71ffc22002-11-11 03:36:55 +00001752 if (!shouldPrintAuxCalls())
Chris Lattnera9548d92005-01-30 23:51:02 +00001753 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1754 E = FunctionCalls.end(); I != E; ++I)
1755 markIncomplete(*I);
Chris Lattnere71ffc22002-11-11 03:36:55 +00001756 else
Chris Lattnera9548d92005-01-30 23:51:02 +00001757 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1758 E = AuxFunctionCalls.end(); I != E; ++I)
1759 markIncomplete(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001760
Chris Lattnere2bc7b22005-03-13 20:36:01 +00001761 // Mark all global nodes as incomplete.
1762 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1763 E = ScalarMap.global_end(); I != E; ++I)
1764 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1765 if (!GV->hasInitializer() || // Always mark external globals incomp.
1766 (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1767 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001768}
1769
Chris Lattneraa8146f2002-11-10 06:59:55 +00001770static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1771 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001772 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001773 // No interesting info?
1774 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001775 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001776 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001777}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001778
Chris Lattneraa8146f2002-11-10 06:59:55 +00001779static inline bool nodeContainsExternalFunction(const DSNode *N) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001780 std::vector<Function*> Funcs;
1781 N->addFullFunctionList(Funcs);
1782 for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
1783 if (Funcs[i]->isExternal()) return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001784 return false;
1785}
1786
Chris Lattnera9548d92005-01-30 23:51:02 +00001787static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001788 // Remove trivially identical function calls
Chris Lattnera9548d92005-01-30 23:51:02 +00001789 Calls.sort(); // Sort by callee as primary key!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001790
1791 // Scan the call list cleaning it up as necessary...
Chris Lattner1e9d1472005-03-22 23:54:52 +00001792 DSNodeHandle LastCalleeNode;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001793#if 0
Chris Lattner923fc052003-02-05 21:59:58 +00001794 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001795 unsigned NumDuplicateCalls = 0;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001796#endif
Chris Lattneraa8146f2002-11-10 06:59:55 +00001797 bool LastCalleeContainsExternalFunction = false;
Chris Lattner857eb062004-10-30 05:41:23 +00001798
Chris Lattnera9548d92005-01-30 23:51:02 +00001799 unsigned NumDeleted = 0;
1800 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1801 I != E;) {
1802 DSCallSite &CS = *I;
1803 std::list<DSCallSite>::iterator OldIt = I++;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001804
Chris Lattner1e9d1472005-03-22 23:54:52 +00001805 if (!CS.isIndirectCall()) {
1806 LastCalleeNode = 0;
1807 } else {
1808 DSNode *Callee = CS.getCalleeNode();
1809
1810 // If the Callee is a useless edge, this must be an unreachable call site,
1811 // eliminate it.
1812 if (Callee->getNumReferrers() == 1 && Callee->isComplete() &&
1813 Callee->getGlobalsList().empty()) { // No useful info?
Bill Wendling5294fb02006-11-17 07:33:59 +00001814 DOUT << "WARNING: Useless call site found.\n";
Chris Lattner1e9d1472005-03-22 23:54:52 +00001815 Calls.erase(OldIt);
1816 ++NumDeleted;
1817 continue;
1818 }
1819
1820 // If the last call site in the list has the same callee as this one, and
1821 // if the callee contains an external function, it will never be
1822 // resolvable, just merge the call sites.
1823 if (!LastCalleeNode.isNull() && LastCalleeNode.getNode() == Callee) {
1824 LastCalleeContainsExternalFunction =
1825 nodeContainsExternalFunction(Callee);
1826
1827 std::list<DSCallSite>::iterator PrevIt = OldIt;
1828 --PrevIt;
1829 PrevIt->mergeWith(CS);
1830
1831 // No need to keep this call anymore.
1832 Calls.erase(OldIt);
1833 ++NumDeleted;
1834 continue;
1835 } else {
1836 LastCalleeNode = Callee;
1837 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001838 }
1839
1840 // If the return value or any arguments point to a void node with no
1841 // information at all in it, and the call node is the only node to point
1842 // to it, remove the edge to the node (killing the node).
1843 //
1844 killIfUselessEdge(CS.getRetVal());
1845 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1846 killIfUselessEdge(CS.getPtrArg(a));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001847
Chris Lattner0b144872004-01-27 22:03:40 +00001848#if 0
Chris Lattnera9548d92005-01-30 23:51:02 +00001849 // If this call site calls the same function as the last call site, and if
1850 // the function pointer contains an external function, this node will
1851 // never be resolved. Merge the arguments of the call node because no
1852 // information will be lost.
1853 //
1854 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1855 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1856 ++NumDuplicateCalls;
1857 if (NumDuplicateCalls == 1) {
1858 if (LastCalleeNode)
1859 LastCalleeContainsExternalFunction =
1860 nodeContainsExternalFunction(LastCalleeNode);
1861 else
1862 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001863 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001864
Chris Lattnera9548d92005-01-30 23:51:02 +00001865 // It is not clear why, but enabling this code makes DSA really
1866 // sensitive to node forwarding. Basically, with this enabled, DSA
1867 // performs different number of inlinings based on which nodes are
1868 // forwarding or not. This is clearly a problem, so this code is
1869 // disabled until this can be resolved.
1870#if 1
1871 if (LastCalleeContainsExternalFunction
1872#if 0
1873 ||
1874 // This should be more than enough context sensitivity!
1875 // FIXME: Evaluate how many times this is tripped!
1876 NumDuplicateCalls > 20
1877#endif
1878 ) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001879
Chris Lattnera9548d92005-01-30 23:51:02 +00001880 std::list<DSCallSite>::iterator PrevIt = OldIt;
1881 --PrevIt;
1882 PrevIt->mergeWith(CS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001883
Chris Lattnera9548d92005-01-30 23:51:02 +00001884 // No need to keep this call anymore.
1885 Calls.erase(OldIt);
1886 ++NumDeleted;
1887 continue;
1888 }
1889#endif
1890 } else {
1891 if (CS.isDirectCall()) {
1892 LastCalleeFunc = CS.getCalleeFunc();
1893 LastCalleeNode = 0;
1894 } else {
1895 LastCalleeNode = CS.getCalleeNode();
1896 LastCalleeFunc = 0;
1897 }
1898 NumDuplicateCalls = 0;
1899 }
1900#endif
1901
1902 if (I != Calls.end() && CS == *I) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001903 LastCalleeNode = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00001904 Calls.erase(OldIt);
1905 ++NumDeleted;
1906 continue;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001907 }
1908 }
Chris Lattner857eb062004-10-30 05:41:23 +00001909
Chris Lattnera9548d92005-01-30 23:51:02 +00001910 // Resort now that we simplified things.
1911 Calls.sort();
Chris Lattner857eb062004-10-30 05:41:23 +00001912
Chris Lattnera9548d92005-01-30 23:51:02 +00001913 // Now that we are in sorted order, eliminate duplicates.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001914 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1915 if (CI != CE)
Chris Lattnera9548d92005-01-30 23:51:02 +00001916 while (1) {
Chris Lattnerf9aace22005-01-31 00:10:58 +00001917 std::list<DSCallSite>::iterator OldIt = CI++;
1918 if (CI == CE) break;
Chris Lattnera9548d92005-01-30 23:51:02 +00001919
1920 // If this call site is now the same as the previous one, we can delete it
1921 // as a duplicate.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001922 if (*OldIt == *CI) {
1923 Calls.erase(CI);
1924 CI = OldIt;
Chris Lattnera9548d92005-01-30 23:51:02 +00001925 ++NumDeleted;
1926 }
1927 }
1928
1929 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001930
Chris Lattner33312f72002-11-08 01:21:07 +00001931 // Track the number of call nodes merged away...
Chris Lattnera9548d92005-01-30 23:51:02 +00001932 NumCallNodesMerged += NumDeleted;
Chris Lattner33312f72002-11-08 01:21:07 +00001933
Bill Wendling5294fb02006-11-17 07:33:59 +00001934 if (NumDeleted)
1935 DOUT << "Merged " << NumDeleted << " call nodes.\n";
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001936}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001937
Chris Lattneraa8146f2002-11-10 06:59:55 +00001938
Chris Lattnere2219762002-07-18 18:22:40 +00001939// removeTriviallyDeadNodes - After the graph has been constructed, this method
1940// removes all unreachable nodes that are created because they got merged with
1941// other nodes in the graph. These nodes will all be trivially unreachable, so
1942// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001943//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001944void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001945 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001946
Chris Lattner5ace1e42004-07-08 07:25:51 +00001947#if 0
1948 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1949 /// substantially!
1950
Chris Lattnerbab8c282003-09-20 21:34:07 +00001951 // Loop over all of the nodes in the graph, calling getNode on each field.
1952 // This will cause all nodes to update their forwarding edges, causing
1953 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001954 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001955 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
Chris Lattner84b80a22005-03-16 22:42:19 +00001956 DSNode &N = *NI;
1957 for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1958 N.getLink(l*N.getPointerSize()).getNode();
Chris Lattnerbab8c282003-09-20 21:34:07 +00001959 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001960 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001961
Chris Lattner0b144872004-01-27 22:03:40 +00001962 // NOTE: This code is disabled. Though it should, in theory, allow us to
1963 // remove more nodes down below, the scan of the scalar map is incredibly
1964 // expensive for certain programs (with large SCCs). In the future, if we can
1965 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001966 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1967
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001968 // Likewise, forward any edges from the scalar nodes. While we are at it,
1969 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001970 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001971 I->second.getNode();
1972 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001973 }
Chris Lattner0b144872004-01-27 22:03:40 +00001974 }
1975#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001976 bool isGlobalsGraph = !GlobalsGraph;
1977
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001978 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001979 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001980
1981 // Do not remove *any* global nodes in the globals graph.
1982 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001983 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001984 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001985 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001986 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001987
Chris Lattner28897e12004-02-08 00:53:26 +00001988 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001989 // This is a useless node if it has no mod/ref info (checked above),
1990 // outgoing edges (which it cannot, as it is not modified in this
1991 // context), and it has no incoming edges. If it is a global node it may
1992 // have all of these properties and still have incoming edges, due to the
1993 // scalar map, so we check those now.
1994 //
Chris Lattner82c6c722005-03-20 02:41:38 +00001995 if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1996 const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
Chris Lattner72d29a42003-02-11 23:11:51 +00001997
Chris Lattner17a93e22004-01-29 03:32:15 +00001998 // Loop through and make sure all of the globals are referring directly
1999 // to the node...
2000 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
2001 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00002002 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00002003 }
2004
Chris Lattnerbd92b732003-06-19 21:15:11 +00002005 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00002006 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00002007 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
2008 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00002009 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002010 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00002011 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002012 }
2013 }
2014
Chris Lattner28897e12004-02-08 00:53:26 +00002015 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00002016 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00002017 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002018 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00002019 } else {
2020 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002021 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002022 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002023
2024 removeIdenticalCalls(FunctionCalls);
2025 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00002026}
2027
2028
Chris Lattner5c7380e2003-01-29 21:10:20 +00002029/// markReachableNodes - This method recursively traverses the specified
2030/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
2031/// to the set, which allows it to only traverse visited nodes once.
2032///
Chris Lattnera9548d92005-01-30 23:51:02 +00002033void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00002034 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00002035 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00002036 if (ReachableNodes.insert(this).second) // Is newly reachable?
Chris Lattner6be07942005-02-09 03:20:43 +00002037 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
2038 I != E; ++I)
2039 I->getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00002040}
2041
Chris Lattnera9548d92005-01-30 23:51:02 +00002042void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00002043 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00002044 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002045
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002046 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
2047 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00002048}
2049
Chris Lattnera1220af2003-02-01 06:17:02 +00002050// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
2051// looking for a node that is marked alive. If an alive node is found, return
2052// true, otherwise return false. If an alive node is reachable, this node is
2053// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00002054//
Chris Lattnera9548d92005-01-30 23:51:02 +00002055static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
2056 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00002057 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002058 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00002059 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002060
Chris Lattner85cfe012003-07-03 02:03:53 +00002061 // If this is a global node, it will end up in the globals graph anyway, so we
2062 // don't need to worry about it.
2063 if (IgnoreGlobals && N->isGlobalNode()) return false;
2064
Chris Lattneraa8146f2002-11-10 06:59:55 +00002065 // If we know that this node is alive, return so!
2066 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002067
Chris Lattneraa8146f2002-11-10 06:59:55 +00002068 // Otherwise, we don't think the node is alive yet, check for infinite
2069 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00002070 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00002071 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00002072
Chris Lattner6be07942005-02-09 03:20:43 +00002073 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
2074 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00002075 N->markReachableNodes(Alive);
2076 return true;
2077 }
2078 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002079}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002080
Chris Lattnera1220af2003-02-01 06:17:02 +00002081// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
2082// alive nodes.
2083//
Chris Lattnera9548d92005-01-30 23:51:02 +00002084static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
2085 hash_set<const DSNode*> &Alive,
2086 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00002087 bool IgnoreGlobals) {
2088 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
2089 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00002090 return true;
2091 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00002092 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002093 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002094 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00002095 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
2096 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002097 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002098 return false;
2099}
2100
Chris Lattnere2219762002-07-18 18:22:40 +00002101// removeDeadNodes - Use a more powerful reachability analysis to eliminate
2102// subgraphs that are unreachable. This often occurs because the data
2103// structure doesn't "escape" into it's caller, and thus should be eliminated
2104// from the caller's graph entirely. This is only appropriate to use when
2105// inlining graphs.
2106//
Chris Lattner394471f2003-01-23 22:05:33 +00002107void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00002108 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00002109
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002110 // Reduce the amount of work we have to do... remove dummy nodes left over by
2111 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00002112 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002113
Chris Lattner93ddd7e2004-01-22 16:36:28 +00002114 TIME_REGION(X, "removeDeadNodes");
2115
Misha Brukman2f2d0652003-09-11 18:14:24 +00002116 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00002117
2118 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattnera9548d92005-01-30 23:51:02 +00002119 hash_set<const DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002120 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00002121
Chris Lattner0b144872004-01-27 22:03:40 +00002122 // Copy and merge all information about globals to the GlobalsGraph if this is
2123 // not a final pass (where unreachable globals are removed).
2124 //
2125 // Strip all alloca bits since the current function is only for the BU pass.
2126 // Strip all incomplete bits since they are short-lived properties and they
2127 // will be correctly computed when rematerializing nodes into the functions.
2128 //
2129 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
2130 DSGraph::StripIncompleteBit);
2131
Chris Lattneraa8146f2002-11-10 06:59:55 +00002132 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattnerf4f62272005-03-19 22:23:45 +00002133{ TIME_REGION(Y, "removeDeadNodes:scalarscan");
2134 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
2135 I != E; ++I)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002136 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00002137 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002138 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002139 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00002140
2141 // Make sure that all globals are cloned over as roots.
Chris Lattner021decc2005-04-02 19:17:18 +00002142 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && GlobalsGraph) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002143 DSGraph::ScalarMapTy::iterator SMI =
Chris Lattner00948c02004-01-28 02:05:05 +00002144 GlobalsGraph->getScalarMap().find(I->first);
2145 if (SMI != GlobalsGraph->getScalarMap().end())
2146 GGCloner.merge(SMI->second, I->second);
2147 else
2148 GGCloner.getClonedNH(I->second);
2149 }
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002150 } else {
Chris Lattnerf4f62272005-03-19 22:23:45 +00002151 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002152 }
Chris Lattnerf4f62272005-03-19 22:23:45 +00002153}
Chris Lattnere2219762002-07-18 18:22:40 +00002154
Chris Lattner0b144872004-01-27 22:03:40 +00002155 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00002156 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
2157 I != E; ++I)
2158 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002159
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002160 // Mark any nodes reachable by primary calls as alive...
Chris Lattnera9548d92005-01-30 23:51:02 +00002161 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2162 I->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002163
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002164
2165 // Now find globals and aux call nodes that are already live or reach a live
2166 // value (which makes them live in turn), and continue till no more are found.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002167 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002168 bool Iterate;
Chris Lattnera9548d92005-01-30 23:51:02 +00002169 hash_set<const DSNode*> Visited;
2170 hash_set<const DSCallSite*> AuxFCallsAlive;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002171 do {
2172 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00002173 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00002174 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002175 // unreachable globals in the list.
2176 //
2177 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002178 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00002179 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002180 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
Chris Lattner0b144872004-01-27 22:03:40 +00002181 Flags & DSGraph::RemoveUnreachableGlobals)) {
2182 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
2183 GlobalNodes.pop_back(); // erase efficiently
2184 Iterate = true;
2185 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002186
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002187 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
2188 // call nodes that get resolved will be difficult to remove from that graph.
2189 // The final unresolved call nodes must be handled specially at the end of
2190 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattnera9548d92005-01-30 23:51:02 +00002191 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
Chris Lattnerd7642c42005-02-24 18:48:07 +00002192 if (!AuxFCallsAlive.count(&*CI) &&
Chris Lattnera9548d92005-01-30 23:51:02 +00002193 (CI->isIndirectCall()
2194 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002195 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattnera9548d92005-01-30 23:51:02 +00002196 CI->markReachableNodes(Alive);
Chris Lattnerd7642c42005-02-24 18:48:07 +00002197 AuxFCallsAlive.insert(&*CI);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002198 Iterate = true;
2199 }
2200 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00002201
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002202 // Move dead aux function calls to the end of the list
Chris Lattnera9548d92005-01-30 23:51:02 +00002203 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
2204 E = AuxFunctionCalls.end(); CI != E; )
2205 if (AuxFCallsAlive.count(&*CI))
2206 ++CI;
2207 else {
2208 // Copy and merge global nodes and dead aux call nodes into the
2209 // GlobalsGraph, and all nodes reachable from those nodes. Update their
2210 // target pointers using the GGCloner.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002211 //
Chris Lattnera9548d92005-01-30 23:51:02 +00002212 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2213 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002214
Chris Lattnera9548d92005-01-30 23:51:02 +00002215 AuxFunctionCalls.erase(CI++);
2216 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002217
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002218 // We are finally done with the GGCloner so we can destroy it.
2219 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002220
Vikram S. Adve40c600e2003-07-22 12:08:58 +00002221 // At this point, any nodes which are visited, but not alive, are nodes
2222 // which can be removed. Loop over all nodes, eliminating completely
2223 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002224 //
Chris Lattner72d29a42003-02-11 23:11:51 +00002225 std::vector<DSNode*> DeadNodes;
2226 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00002227 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2228 DSNode *N = NI++;
2229 assert(!N->isForwarding() && "Forwarded node in nodes list?");
2230
2231 if (!Alive.count(N)) {
2232 Nodes.remove(N);
2233 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002234 DeadNodes.push_back(N);
2235 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00002236 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00002237 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00002238 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002239
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002240 // Remove all unreachable globals from the ScalarMap.
2241 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2242 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00002243 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002244 if (!Alive.count(GlobalNodes[i].second))
2245 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00002246 else
2247 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002248
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002249 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00002250 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2251 delete DeadNodes[i];
2252
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002253 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00002254}
2255
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002256void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
Chris Lattner82c6c722005-03-20 02:41:38 +00002257 assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2258 N->globals_end() && "Global value not in node!");
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002259}
2260
Chris Lattner2c7725a2004-03-03 20:55:27 +00002261void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2262 if (CS.isIndirectCall()) {
2263 AssertNodeInGraph(CS.getCalleeNode());
2264#if 0
2265 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2266 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
Bill Wendling5294fb02006-11-17 07:33:59 +00002267 DOUT << "WARNING: WEIRD CALL SITE FOUND!\n";
Chris Lattner2c7725a2004-03-03 20:55:27 +00002268#endif
2269 }
2270 AssertNodeInGraph(CS.getRetVal().getNode());
2271 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2272 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2273}
2274
2275void DSGraph::AssertCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002276 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2277 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002278}
2279void DSGraph::AssertAuxCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002280 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2281 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002282}
2283
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002284void DSGraph::AssertGraphOK() const {
Chris Lattner84b80a22005-03-16 22:42:19 +00002285 for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2286 NI->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00002287
Chris Lattner8d327672003-06-30 03:36:09 +00002288 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002289 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00002290 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002291 AssertNodeInGraph(I->second.getNode());
2292 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00002293 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002294 "Global points to node, but node isn't global?");
2295 AssertNodeContainsGlobal(I->second.getNode(), GV);
2296 }
2297 }
2298 AssertCallNodesInGraph();
2299 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00002300
2301 // Check that all pointer arguments to any functions in this graph have
2302 // destinations.
2303 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2304 E = ReturnNodes.end();
2305 RI != E; ++RI) {
2306 Function &F = *RI->first;
Chris Lattnere4d5c442005-03-15 04:54:21 +00002307 for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
Chris Lattner7d8d4712004-10-31 17:45:40 +00002308 if (isPointerType(AI->getType()))
2309 assert(!getNodeForValue(AI).isNull() &&
2310 "Pointer argument must be in the scalar map!");
2311 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002312}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002313
Chris Lattner400433d2003-11-11 05:08:59 +00002314/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00002315/// nodes reachable from the two graphs, computing the mapping of nodes from the
2316/// first to the second graph. This mapping may be many-to-one (i.e. the first
2317/// graph may have multiple nodes representing one node in the second graph),
2318/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00002319///
2320void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00002321 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2322 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00002323 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2324 if (N1 == 0 || N2 == 0) return;
2325
2326 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002327 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002328 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002329 if (StrictChecking) {
2330 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2331 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2332 Entry.getNode()->isNodeCompletelyFolded()) &&
2333 "Inconsistent mapping detected!");
2334 }
Chris Lattner400433d2003-11-11 05:08:59 +00002335 return;
2336 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002337
Chris Lattnerefffdc92004-07-07 06:12:52 +00002338 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002339
2340 // Loop over all of the fields that N1 and N2 have in common, recursively
2341 // mapping the edges together now.
2342 int N2Idx = NH2.getOffset()-NH1.getOffset();
2343 unsigned N2Size = N2->getSize();
Chris Lattner841957e2005-03-15 04:40:24 +00002344 if (N2Size == 0) return; // No edges to map to.
2345
Chris Lattner4d5af8e2005-03-15 21:36:50 +00002346 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2347 const DSNodeHandle &N1NH = N1->getLink(i);
2348 // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2349 // aligned right).
2350 if (!N1NH.isNull()) {
2351 if (unsigned(N2Idx)+i < N2Size)
2352 computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2353 else
2354 computeNodeMapping(N1NH,
2355 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2356 }
2357 }
Chris Lattner400433d2003-11-11 05:08:59 +00002358}
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002359
2360
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002361/// computeGToGGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002362/// nodes in this graph.
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002363void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002364 DSGraph &GG = *getGlobalsGraph();
2365
2366 DSScalarMap &SM = getScalarMap();
2367 for (DSScalarMap::global_iterator I = SM.global_begin(),
2368 E = SM.global_end(); I != E; ++I)
2369 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2370}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002371
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002372/// computeGGToGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002373/// nodes in this graph. Note that any uses of this method are probably bugs,
2374/// unless it is known that the globals graph has been merged into this graph!
2375void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2376 NodeMapTy NodeMap;
2377 computeGToGGMapping(NodeMap);
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002378
Chris Lattner36a13cd2005-03-15 17:52:18 +00002379 while (!NodeMap.empty()) {
2380 InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2381 NodeMap.begin()->first));
2382 NodeMap.erase(NodeMap.begin());
2383 }
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002384}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002385
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002386
2387/// computeCalleeCallerMapping - Given a call from a function in the current
2388/// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2389/// mapping of nodes from the callee to nodes in the caller.
2390void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2391 DSGraph &CalleeGraph,
2392 NodeMapTy &NodeMap) {
2393
2394 DSCallSite CalleeArgs =
2395 CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002396
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002397 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2398
2399 unsigned NumArgs = CS.getNumPtrArgs();
2400 if (NumArgs > CalleeArgs.getNumPtrArgs())
2401 NumArgs = CalleeArgs.getNumPtrArgs();
2402
2403 for (unsigned i = 0; i != NumArgs; ++i)
2404 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002405
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002406 // Map the nodes that are pointed to by globals.
2407 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2408 DSScalarMap &CallerSM = getScalarMap();
2409
2410 if (CalleeSM.global_size() >= CallerSM.global_size()) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002411 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002412 E = CallerSM.global_end(); GI != E; ++GI)
2413 if (CalleeSM.global_count(*GI))
2414 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2415 } else {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002416 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002417 E = CalleeSM.global_end(); GI != E; ++GI)
2418 if (CallerSM.global_count(*GI))
2419 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2420 }
2421}
Andrew Lenharth37705002006-06-19 15:42:47 +00002422
2423/// updateFromGlobalGraph - This function rematerializes global nodes and
2424/// nodes reachable from them from the globals graph into the current graph.
2425///
2426void DSGraph::updateFromGlobalGraph() {
2427 TIME_REGION(X, "updateFromGlobalGraph");
2428 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
2429
2430 // Clone the non-up-to-date global nodes into this graph.
2431 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
2432 E = getScalarMap().global_end(); I != E; ++I) {
2433 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
2434 if (It != GlobalsGraph->ScalarMap.end())
2435 RC.merge(getNodeForValue(*I), It->second);
2436 }
2437}