blob: c81fd6ad34118e9dba2bc8fb7dbeba8f269e14c4 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00009//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner4dabb2c2004-07-07 06:32:21 +000014#include "llvm/Analysis/DataStructure/DSGraphTraits.h"
Chris Lattner94f84702005-03-17 19:56:56 +000015#include "llvm/Constants.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000016#include "llvm/Function.h"
Chris Lattnercf14e712004-02-25 23:36:08 +000017#include "llvm/GlobalVariable.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000019#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000020#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000021#include "llvm/Assembly/Writer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000022#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/ADT/DepthFirstIterator.h"
25#include "llvm/ADT/STLExtras.h"
Chris Lattnerd8642122005-03-24 21:07:47 +000026#include "llvm/ADT/SCCIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000027#include "llvm/ADT/Statistic.h"
28#include "llvm/Support/Timer.h"
Chris Lattner72382102006-01-22 23:19:18 +000029#include <iostream>
Chris Lattner0d9bab82002-07-18 00:12:30 +000030#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Chris Lattnerb29dd0f2004-12-08 21:03:56 +000033#define COLLAPSE_ARRAYS_AGGRESSIVELY 0
34
Chris Lattner08db7192002-11-06 06:20:27 +000035namespace {
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000036 Statistic NumFolds ("dsa", "Number of nodes completely folded");
37 Statistic NumCallNodesMerged("dsa", "Number of call nodes merged");
38 Statistic NumNodeAllocated ("dsa", "Number of nodes allocated");
39 Statistic NumDNE ("dsa", "Number of nodes removed by reachability");
40 Statistic NumTrivialDNE ("dsa", "Number of nodes trivially removed");
41 Statistic NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Andrew Lenharth0c3a0b62006-03-15 05:43:41 +000042 static cl::opt<unsigned>
43 DSAFieldLimit("dsa-field-limit", cl::Hidden,
44 cl::desc("Number of fields to track before collapsing a node"),
45 cl::init(256));
Chris Lattnerd74ea2b2006-05-24 17:04:05 +000046}
Chris Lattner08db7192002-11-06 06:20:27 +000047
Chris Lattner1e9d1472005-03-22 23:54:52 +000048#if 0
Chris Lattner93ddd7e2004-01-22 16:36:28 +000049#define TIME_REGION(VARNAME, DESC) \
50 NamedRegionTimer VARNAME(DESC)
51#else
52#define TIME_REGION(VARNAME, DESC)
53#endif
54
Chris Lattnerb1060432002-11-07 05:20:53 +000055using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000056
Chris Lattner6f967742004-10-30 04:05:01 +000057/// isForwarding - Return true if this NodeHandle is forwarding to another
58/// one.
59bool DSNodeHandle::isForwarding() const {
60 return N && N->isForwarding();
61}
62
Chris Lattner731b2d72003-02-13 19:09:00 +000063DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000064 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Andrew Lenharthdf983de2006-11-07 20:36:02 +000065 DEBUG(
66 { //assert not looping
67 DSNode* NH = N;
68 std::set<DSNode*> seen;
69 while(NH && NH->isForwarding()) {
70 assert(seen.find(NH) == seen.end() && "Loop detected");
71 seen.insert(NH);
72 NH = NH->ForwardNH.N;
73 }
74 }
75 );
Chris Lattner731b2d72003-02-13 19:09:00 +000076 // Handle node forwarding here!
77 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
78 Offset += N->ForwardNH.getOffset();
79
80 if (--N->NumReferrers == 0) {
81 // Removing the last referrer to the node, sever the forwarding link
82 N->stopForwarding();
83 }
84
85 N = Next;
86 N->NumReferrers++;
87 if (N->Size <= Offset) {
88 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
89 Offset = 0;
90 }
91 return N;
92}
93
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000094//===----------------------------------------------------------------------===//
Chris Lattner612f0b72005-03-22 00:09:45 +000095// DSScalarMap Implementation
96//===----------------------------------------------------------------------===//
97
98DSNodeHandle &DSScalarMap::AddGlobal(GlobalValue *GV) {
99 assert(ValueMap.count(GV) == 0 && "GV already exists!");
100
101 // If the node doesn't exist, check to see if it's a global that is
102 // equated to another global in the program.
103 EquivalenceClasses<GlobalValue*>::iterator ECI = GlobalECs.findValue(GV);
104 if (ECI != GlobalECs.end()) {
105 GlobalValue *Leader = *GlobalECs.findLeader(ECI);
106 if (Leader != GV) {
107 GV = Leader;
108 iterator I = ValueMap.find(GV);
109 if (I != ValueMap.end())
110 return I->second;
111 }
112 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000113
Chris Lattner612f0b72005-03-22 00:09:45 +0000114 // Okay, this is either not an equivalenced global or it is the leader, it
115 // will be inserted into the scalar map now.
116 GlobalSet.insert(GV);
117
118 return ValueMap.insert(std::make_pair(GV, DSNodeHandle())).first->second;
119}
120
121
122//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000123// DSNode Implementation
124//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000125
Chris Lattnerbd92b732003-06-19 21:15:11 +0000126DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +0000127 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000128 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +0000129 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +0000130 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000131 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000132}
133
Chris Lattner0d9bab82002-07-18 00:12:30 +0000134// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +0000135DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +0000136 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattneraf2e3e02005-04-12 03:59:27 +0000137 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattnerf590ced2004-03-04 17:06:53 +0000138 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +0000139 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +0000140 } else
Chris Lattner0b144872004-01-27 22:03:40 +0000141 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +0000142 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000143 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000144}
145
Chris Lattner15869aa2003-11-02 22:27:28 +0000146/// getTargetData - Get the target data object used to construct this node.
147///
148const TargetData &DSNode::getTargetData() const {
149 return ParentGraph->getTargetData();
150}
151
Chris Lattner72d29a42003-02-11 23:11:51 +0000152void DSNode::assertOK() const {
153 assert((Ty != Type::VoidTy ||
154 Ty == Type::VoidTy && (Size == 0 ||
155 (NodeType & DSNode::Array))) &&
156 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000157
158 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000159 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000160 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000161 assert(SM.global_count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000162 assert(SM.find(Globals[i])->second.getNode() == this);
163 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000164}
165
166/// forwardNode - Mark this node as being obsolete, and all references to it
167/// should be forwarded to the specified node and offset.
168///
169void DSNode::forwardNode(DSNode *To, unsigned Offset) {
170 assert(this != To && "Cannot forward a node to itself!");
171 assert(ForwardNH.isNull() && "Already forwarding from this node!");
172 if (To->Size <= 1) Offset = 0;
173 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
174 "Forwarded offset is wrong!");
Chris Lattnerefffdc92004-07-07 06:12:52 +0000175 ForwardNH.setTo(To, Offset);
Chris Lattner72d29a42003-02-11 23:11:51 +0000176 NodeType = DEAD;
177 Size = 0;
178 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000179
180 // Remove this node from the parent graph's Nodes list.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000181 ParentGraph->unlinkNode(this);
Chris Lattner4ff0b962004-02-08 01:27:18 +0000182 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000183}
184
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000185// addGlobal - Add an entry for a global value to the Globals list. This also
186// marks the node with the 'G' flag if it does not already have it.
187//
188void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000189 // First, check to make sure this is the leader if the global is in an
190 // equivalence class.
191 GV = getParentGraph()->getScalarMap().getLeaderForGlobal(GV);
192
Chris Lattner0d9bab82002-07-18 00:12:30 +0000193 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000194 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000195 std::lower_bound(Globals.begin(), Globals.end(), GV);
196
197 if (I == Globals.end() || *I != GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000198 Globals.insert(I, GV);
199 NodeType |= GlobalNode;
200 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000201}
202
Chris Lattner7cdf3212005-03-20 03:29:54 +0000203// removeGlobal - Remove the specified global that is explicitly in the globals
204// list.
205void DSNode::removeGlobal(GlobalValue *GV) {
206 std::vector<GlobalValue*>::iterator I =
207 std::lower_bound(Globals.begin(), Globals.end(), GV);
208 assert(I != Globals.end() && *I == GV && "Global not in node!");
209 Globals.erase(I);
210}
211
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000212/// foldNodeCompletely - If we determine that this node has some funny
213/// behavior happening to it that we cannot represent, we fold it down to a
214/// single, completely pessimistic, node. This node is represented as a
215/// single byte with a single TypeEntry of "void".
216///
217void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000218 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000219
Chris Lattner08db7192002-11-06 06:20:27 +0000220 ++NumFolds;
221
Chris Lattner0b144872004-01-27 22:03:40 +0000222 // If this node has a size that is <= 1, we don't need to create a forwarding
223 // node.
224 if (getSize() <= 1) {
225 NodeType |= DSNode::Array;
226 Ty = Type::VoidTy;
227 Size = 1;
228 assert(Links.size() <= 1 && "Size is 1, but has more links?");
229 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000230 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000231 // Create the node we are going to forward to. This is required because
232 // some referrers may have an offset that is > 0. By forcing them to
233 // forward, the forwarder has the opportunity to correct the offset.
234 DSNode *DestNode = new DSNode(0, ParentGraph);
235 DestNode->NodeType = NodeType|DSNode::Array;
236 DestNode->Ty = Type::VoidTy;
237 DestNode->Size = 1;
238 DestNode->Globals.swap(Globals);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000239
Chris Lattner0b144872004-01-27 22:03:40 +0000240 // Start forwarding to the destination node...
241 forwardNode(DestNode, 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000242
Chris Lattner0b144872004-01-27 22:03:40 +0000243 if (!Links.empty()) {
244 DestNode->Links.reserve(1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000245
Chris Lattner0b144872004-01-27 22:03:40 +0000246 DSNodeHandle NH(DestNode);
247 DestNode->Links.push_back(Links[0]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000248
Chris Lattner0b144872004-01-27 22:03:40 +0000249 // If we have links, merge all of our outgoing links together...
250 for (unsigned i = Links.size()-1; i != 0; --i)
251 NH.getNode()->Links[0].mergeWith(Links[i]);
252 Links.clear();
253 } else {
254 DestNode->Links.resize(1);
255 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000256 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000257}
Chris Lattner076c1f92002-11-07 06:31:54 +0000258
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000259/// isNodeCompletelyFolded - Return true if this node has been completely
260/// folded down to something that can never be expanded, effectively losing
261/// all of the field sensitivity that may be present in the node.
262///
263bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000264 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000265}
266
Chris Lattner82c6c722005-03-20 02:41:38 +0000267/// addFullGlobalsList - Compute the full set of global values that are
268/// represented by this node. Unlike getGlobalsList(), this requires fair
269/// amount of work to compute, so don't treat this method call as free.
270void DSNode::addFullGlobalsList(std::vector<GlobalValue*> &List) const {
271 if (globals_begin() == globals_end()) return;
272
273 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
274
275 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
276 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
277 if (ECI == EC.end())
278 List.push_back(*I);
279 else
280 List.insert(List.end(), EC.member_begin(ECI), EC.member_end());
281 }
282}
283
284/// addFullFunctionList - Identical to addFullGlobalsList, but only return the
285/// functions in the full list.
286void DSNode::addFullFunctionList(std::vector<Function*> &List) const {
287 if (globals_begin() == globals_end()) return;
288
289 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
290
291 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
292 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
293 if (ECI == EC.end()) {
294 if (Function *F = dyn_cast<Function>(*I))
295 List.push_back(F);
296 } else {
297 for (EquivalenceClasses<GlobalValue*>::member_iterator MI =
298 EC.member_begin(ECI), E = EC.member_end(); MI != E; ++MI)
299 if (Function *F = dyn_cast<Function>(*MI))
300 List.push_back(F);
301 }
302 }
303}
304
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000305namespace {
306 /// TypeElementWalker Class - Used for implementation of physical subtyping...
307 ///
308 class TypeElementWalker {
309 struct StackState {
310 const Type *Ty;
311 unsigned Offset;
312 unsigned Idx;
313 StackState(const Type *T, unsigned Off = 0)
314 : Ty(T), Offset(Off), Idx(0) {}
315 };
316
317 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000318 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000319 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000320 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000321 Stack.push_back(T);
322 StepToLeaf();
323 }
324
325 bool isDone() const { return Stack.empty(); }
326 const Type *getCurrentType() const { return Stack.back().Ty; }
327 unsigned getCurrentOffset() const { return Stack.back().Offset; }
328
329 void StepToNextType() {
330 PopStackAndAdvance();
331 StepToLeaf();
332 }
333
334 private:
335 /// PopStackAndAdvance - Pop the current element off of the stack and
336 /// advance the underlying element to the next contained member.
337 void PopStackAndAdvance() {
338 assert(!Stack.empty() && "Cannot pop an empty stack!");
339 Stack.pop_back();
340 while (!Stack.empty()) {
341 StackState &SS = Stack.back();
342 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
343 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000344 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000345 const StructLayout *SL = TD.getStructLayout(ST);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000346 SS.Offset +=
Chris Lattner507bdf92005-01-12 04:51:37 +0000347 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000348 return;
349 }
350 Stack.pop_back(); // At the end of the structure
351 } else {
352 const ArrayType *AT = cast<ArrayType>(SS.Ty);
353 ++SS.Idx;
354 if (SS.Idx != AT->getNumElements()) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000355 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000356 return;
357 }
358 Stack.pop_back(); // At the end of the array
359 }
360 }
361 }
362
363 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
364 /// on the type stack.
365 void StepToLeaf() {
366 if (Stack.empty()) return;
367 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
368 StackState &SS = Stack.back();
369 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000370 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000371 assert(SS.Idx == 0);
372 PopStackAndAdvance();
373 } else {
374 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000375 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000376 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000377 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner507bdf92005-01-12 04:51:37 +0000378 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000379 }
380 } else {
381 const ArrayType *AT = cast<ArrayType>(SS.Ty);
382 if (AT->getNumElements() == 0) {
383 assert(SS.Idx == 0);
384 PopStackAndAdvance();
385 } else {
386 // Step into the array...
387 assert(SS.Idx < AT->getNumElements());
388 Stack.push_back(StackState(AT->getElementType(),
389 SS.Offset+SS.Idx*
Chris Lattner507bdf92005-01-12 04:51:37 +0000390 unsigned(TD.getTypeSize(AT->getElementType()))));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000391 }
392 }
393 }
394 }
395 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000396} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000397
398/// ElementTypesAreCompatible - Check to see if the specified types are
399/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000400/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
401/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000402///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000403static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000404 bool AllowLargerT1, const TargetData &TD){
405 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000406
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000407 while (!T1W.isDone() && !T2W.isDone()) {
408 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
409 return false;
410
411 const Type *T1 = T1W.getCurrentType();
412 const Type *T2 = T2W.getCurrentType();
Reid Spencer3da59db2006-11-27 01:05:10 +0000413 if (T1 != T2 && !T1->canLosslesslyBitCastTo(T2))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000414 return false;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000415
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000416 T1W.StepToNextType();
417 T2W.StepToNextType();
418 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000419
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000420 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000421}
422
423
Chris Lattner08db7192002-11-06 06:20:27 +0000424/// mergeTypeInfo - This method merges the specified type into the current node
425/// at the specified offset. This may update the current node's type record if
426/// this gives more information to the node, it may do nothing to the node if
427/// this information is already known, or it may merge the node completely (and
428/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000429///
Chris Lattner08db7192002-11-06 06:20:27 +0000430/// This method returns true if the node is completely folded, otherwise false.
431///
Chris Lattner088b6392003-03-03 17:13:31 +0000432bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
433 bool FoldIfIncompatible) {
Bill Wendling5294fb02006-11-17 07:33:59 +0000434 DOUT << "merging " << *NewTy << " at " << Offset << " with " << *Ty << "\n";
Chris Lattner15869aa2003-11-02 22:27:28 +0000435 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000436 // Check to make sure the Size member is up-to-date. Size can be one of the
437 // following:
438 // Size = 0, Ty = Void: Nothing is known about this node.
439 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
440 // Size = 1, Ty = Void, Array = 1: The node is collapsed
441 // Otherwise, sizeof(Ty) = Size
442 //
Chris Lattner18552922002-11-18 21:44:46 +0000443 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
444 (Size == 0 && !Ty->isSized() && !isArray()) ||
445 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
446 (Size == 0 && !Ty->isSized() && !isArray()) ||
447 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000448 "Size member of DSNode doesn't match the type structure!");
449 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000450
Chris Lattner18552922002-11-18 21:44:46 +0000451 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000452 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000453
Chris Lattner08db7192002-11-06 06:20:27 +0000454 // Return true immediately if the node is completely folded.
455 if (isNodeCompletelyFolded()) return true;
456
Chris Lattner23f83dc2002-11-08 22:49:57 +0000457 // If this is an array type, eliminate the outside arrays because they won't
458 // be used anyway. This greatly reduces the size of large static arrays used
459 // as global variables, for example.
460 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000461 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000462 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
463 // FIXME: we might want to keep small arrays, but must be careful about
464 // things like: [2 x [10000 x int*]]
465 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000466 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000467 }
468
Chris Lattner08db7192002-11-06 06:20:27 +0000469 // Figure out how big the new type we're merging in is...
Chris Lattner507bdf92005-01-12 04:51:37 +0000470 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000471
472 // Otherwise check to see if we can fold this type into the current node. If
473 // we can't, we fold the node completely, if we can, we potentially update our
474 // internal state.
475 //
Chris Lattner18552922002-11-18 21:44:46 +0000476 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000477 // If this is the first type that this node has seen, just accept it without
478 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000479 assert(Offset == 0 && !isArray() &&
480 "Cannot have an offset into a void node!");
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000481
482 // If this node would have to have an unreasonable number of fields, just
483 // collapse it. This can occur for fortran common blocks, which have stupid
484 // things like { [100000000 x double], [1000000 x double] }.
485 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
Andrew Lenharth0c3a0b62006-03-15 05:43:41 +0000486 if (NumFields > DSAFieldLimit) {
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000487 foldNodeCompletely();
488 return true;
489 }
490
Chris Lattner18552922002-11-18 21:44:46 +0000491 Ty = NewTy;
492 NodeType &= ~Array;
493 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000494 Size = NewTySize;
495
496 // Calculate the number of outgoing links from this node.
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000497 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000498 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000499 }
Chris Lattner08db7192002-11-06 06:20:27 +0000500
501 // Handle node expansion case here...
502 if (Offset+NewTySize > Size) {
503 // It is illegal to grow this node if we have treated it as an array of
504 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000505 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000506 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000507 return true;
508 }
509
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000510 // If this node would have to have an unreasonable number of fields, just
511 // collapse it. This can occur for fortran common blocks, which have stupid
512 // things like { [100000000 x double], [1000000 x double] }.
513 unsigned NumFields = (NewTySize+Offset+DS::PointerSize-1) >> DS::PointerShift;
Andrew Lenharth0c3a0b62006-03-15 05:43:41 +0000514 if (NumFields > DSAFieldLimit) {
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000515 foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000516 return true;
517 }
518
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000519 if (Offset) {
520 //handle some common cases:
521 // Ty: struct { t1, t2, t3, t4, ..., tn}
522 // NewTy: struct { offset, stuff...}
Bill Wendling5294fb02006-11-17 07:33:59 +0000523 // try merge with NewTy: struct {t1, t2, stuff...} if offset lands exactly
524 // on a field in Ty
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000525 if (isa<StructType>(NewTy) && isa<StructType>(Ty)) {
Bill Wendling5294fb02006-11-17 07:33:59 +0000526 DOUT << "Ty: " << *Ty << "\nNewTy: " << *NewTy << "@" << Offset << "\n";
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000527 const StructType *STy = cast<StructType>(Ty);
528 const StructLayout &SL = *TD.getStructLayout(STy);
529 unsigned i = SL.getElementContainingOffset(Offset);
530 //Either we hit it exactly or give up
531 if (SL.MemberOffsets[i] != Offset) {
532 if (FoldIfIncompatible) foldNodeCompletely();
533 return true;
534 }
535 std::vector<const Type*> nt;
536 for (unsigned x = 0; x < i; ++x)
537 nt.push_back(STy->getElementType(x));
538 STy = cast<StructType>(NewTy);
539 nt.insert(nt.end(), STy->element_begin(), STy->element_end());
540 //and merge
541 STy = StructType::get(nt);
Bill Wendling5294fb02006-11-17 07:33:59 +0000542 DOUT << "Trying with: " << *STy << "\n";
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000543 return mergeTypeInfo(STy, 0);
544 }
545
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000546 //Ty: struct { t1, t2, t3 ... tn}
547 //NewTy T offset x
Bill Wendling5294fb02006-11-17 07:33:59 +0000548 //try merge with NewTy: struct : {t1, t2, T} if offset lands on a field
549 //in Ty
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000550 if (isa<StructType>(Ty)) {
Bill Wendling5294fb02006-11-17 07:33:59 +0000551 DOUT << "Ty: " << *Ty << "\nNewTy: " << *NewTy << "@" << Offset << "\n";
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000552 const StructType *STy = cast<StructType>(Ty);
553 const StructLayout &SL = *TD.getStructLayout(STy);
554 unsigned i = SL.getElementContainingOffset(Offset);
555 //Either we hit it exactly or give up
556 if (SL.MemberOffsets[i] != Offset) {
557 if (FoldIfIncompatible) foldNodeCompletely();
558 return true;
559 }
560 std::vector<const Type*> nt;
561 for (unsigned x = 0; x < i; ++x)
562 nt.push_back(STy->getElementType(x));
563 nt.push_back(NewTy);
564 //and merge
565 STy = StructType::get(nt);
Bill Wendling5294fb02006-11-17 07:33:59 +0000566 DOUT << "Trying with: " << *STy << "\n";
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000567 return mergeTypeInfo(STy, 0);
568 }
569
Bill Wendling5294fb02006-11-17 07:33:59 +0000570 assert(0 &&
571 "UNIMP: Trying to merge a growth type into "
572 "offset != 0: Collapsing!");
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000573 abort();
574 if (FoldIfIncompatible) foldNodeCompletely();
575 return true;
576
577 }
578
579
Chris Lattner08db7192002-11-06 06:20:27 +0000580 // Okay, the situation is nice and simple, we are trying to merge a type in
581 // at offset 0 that is bigger than our current type. Implement this by
582 // switching to the new type and then merge in the smaller one, which should
583 // hit the other code path here. If the other code path decides it's not
584 // ok, it will collapse the node as appropriate.
585 //
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000586
Chris Lattner94f84702005-03-17 19:56:56 +0000587 const Type *OldTy = Ty;
588 Ty = NewTy;
589 NodeType &= ~Array;
590 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000591 Size = NewTySize;
592
593 // Must grow links to be the appropriate size...
Chris Lattner94f84702005-03-17 19:56:56 +0000594 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000595
596 // Merge in the old type now... which is guaranteed to be smaller than the
597 // "current" type.
598 return mergeTypeInfo(OldTy, 0);
599 }
600
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000601 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000602 "Cannot merge something into a part of our type that doesn't exist!");
603
Chris Lattner18552922002-11-18 21:44:46 +0000604 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000605 // type that starts at offset Offset.
606 //
607 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000608 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000609 while (O < Offset) {
610 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
611
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000612 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000613 case Type::StructTyID: {
614 const StructType *STy = cast<StructType>(SubType);
615 const StructLayout &SL = *TD.getStructLayout(STy);
Chris Lattner2787e032005-03-13 19:05:05 +0000616 unsigned i = SL.getElementContainingOffset(Offset-O);
Chris Lattner08db7192002-11-06 06:20:27 +0000617
618 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000619 SubType = STy->getElementType(i);
Chris Lattner507bdf92005-01-12 04:51:37 +0000620 O += (unsigned)SL.MemberOffsets[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000621 break;
622 }
623 case Type::ArrayTyID: {
624 SubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000625 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000626 unsigned Remainder = (Offset-O) % ElSize;
627 O = Offset-Remainder;
628 break;
629 }
630 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000631 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000632 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000633 }
634 }
635
636 assert(O == Offset && "Could not achieve the correct offset!");
637
638 // If we found our type exactly, early exit
639 if (SubType == NewTy) return false;
640
Misha Brukman96a8bd72004-04-29 04:05:30 +0000641 // Differing function types don't require us to merge. They are not values
642 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000643 if (isa<FunctionType>(SubType) &&
644 isa<FunctionType>(NewTy)) return false;
645
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000646 unsigned SubTypeSize = SubType->isSized() ?
Chris Lattner507bdf92005-01-12 04:51:37 +0000647 (unsigned)TD.getTypeSize(SubType) : 0;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000648
649 // Ok, we are getting desperate now. Check for physical subtyping, where we
650 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000651 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000652 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000653 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000654 return false;
655
Chris Lattner08db7192002-11-06 06:20:27 +0000656 // Okay, so we found the leader type at the offset requested. Search the list
657 // of types that starts at this offset. If SubType is currently an array or
658 // structure, the type desired may actually be the first element of the
659 // composite type...
660 //
Chris Lattner18552922002-11-18 21:44:46 +0000661 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000662 while (SubType != NewTy) {
663 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000664 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000665 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000666 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000667 case Type::StructTyID: {
668 const StructType *STy = cast<StructType>(SubType);
669 const StructLayout &SL = *TD.getStructLayout(STy);
670 if (SL.MemberOffsets.size() > 1)
Chris Lattner507bdf92005-01-12 04:51:37 +0000671 NextPadSize = (unsigned)SL.MemberOffsets[1];
Chris Lattner18552922002-11-18 21:44:46 +0000672 else
673 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000674 NextSubType = STy->getElementType(0);
Chris Lattner507bdf92005-01-12 04:51:37 +0000675 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000676 break;
Chris Lattner18552922002-11-18 21:44:46 +0000677 }
Chris Lattner08db7192002-11-06 06:20:27 +0000678 case Type::ArrayTyID:
679 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000680 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner18552922002-11-18 21:44:46 +0000681 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000682 break;
683 default: ;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000684 // fall out
Chris Lattner08db7192002-11-06 06:20:27 +0000685 }
686
687 if (NextSubType == 0)
688 break; // In the default case, break out of the loop
689
Chris Lattner18552922002-11-18 21:44:46 +0000690 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000691 break; // Don't allow shrinking to a smaller type than NewTySize
692 SubType = NextSubType;
693 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000694 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000695 }
696
697 // If we found the type exactly, return it...
698 if (SubType == NewTy)
699 return false;
700
701 // Check to see if we have a compatible, but different type...
702 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000703 // Check to see if this type is obviously convertible... int -> uint f.e.
Reid Spencer3da59db2006-11-27 01:05:10 +0000704 if (NewTy->canLosslesslyBitCastTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000705 return false;
706
707 // Check to see if we have a pointer & integer mismatch going on here,
708 // loading a pointer as a long, for example.
709 //
710 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
711 NewTy->isInteger() && isa<PointerType>(SubType))
712 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000713 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
714 // We are accessing the field, plus some structure padding. Ignore the
715 // structure padding.
716 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000717 }
718
Chris Lattner58f98d02003-07-02 04:38:49 +0000719 Module *M = 0;
Chris Lattnera5f47ea2005-03-15 16:55:04 +0000720 if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
721 M = getParentGraph()->retnodes_begin()->first->getParent();
Bill Wendling5294fb02006-11-17 07:33:59 +0000722
723 DOUT << "MergeTypeInfo Folding OrigTy: ";
724 DEBUG(WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
Chris Lattner58f98d02003-07-02 04:38:49 +0000725 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
Bill Wendling5294fb02006-11-17 07:33:59 +0000726 << "SubType: ";
Chris Lattner58f98d02003-07-02 04:38:49 +0000727 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000728
Chris Lattner088b6392003-03-03 17:13:31 +0000729 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000730 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000731}
732
Chris Lattner08db7192002-11-06 06:20:27 +0000733
734
Misha Brukman96a8bd72004-04-29 04:05:30 +0000735/// addEdgeTo - Add an edge from the current node to the specified node. This
736/// can cause merging of nodes in the graph.
737///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000738void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000739 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000740
Andrew Lenharth79acb692006-03-27 23:39:58 +0000741 if (isNodeCompletelyFolded())
742 Offset = 0;
743
Chris Lattner08db7192002-11-06 06:20:27 +0000744 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000745 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000746 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000747 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000748 } else { // No merging to perform...
749 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000750 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000751}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000752
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000753
Misha Brukman96a8bd72004-04-29 04:05:30 +0000754/// MergeSortedVectors - Efficiently merge a vector into another vector where
755/// duplicates are not allowed and both are sorted. This assumes that 'T's are
756/// efficiently copyable and have sane comparison semantics.
757///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000758static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
759 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000760 // By far, the most common cases will be the simple ones. In these cases,
761 // avoid having to allocate a temporary vector...
762 //
763 if (Src.empty()) { // Nothing to merge in...
764 return;
765 } else if (Dest.empty()) { // Just copy the result in...
766 Dest = Src;
767 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000768 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000769 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000770 std::lower_bound(Dest.begin(), Dest.end(), V);
771 if (I == Dest.end() || *I != Src[0]) // If not already contained...
772 Dest.insert(I, Src[0]);
773 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000774 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000775 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000776 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000777 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
778 if (I == Dest.end() || *I != Tmp) // If not already contained...
779 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000780
781 } else {
782 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000783 std::vector<GlobalValue*> Old(Dest);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000784
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000785 // Make space for all of the type entries now...
786 Dest.resize(Dest.size()+Src.size());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000787
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000788 // Merge the two sorted ranges together... into Dest.
789 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000790
791 // Now erase any duplicate entries that may have accumulated into the
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000792 // vectors (because they were in both of the input sets)
793 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
794 }
795}
796
Chris Lattner0b144872004-01-27 22:03:40 +0000797void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
798 MergeSortedVectors(Globals, RHS);
799}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000800
Chris Lattner0b144872004-01-27 22:03:40 +0000801// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000802// This function does the hard work of merging two nodes, CurNodeH
803// and NH after filtering out trivial cases and making sure that
804// CurNodeH.offset >= NH.offset.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000805//
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000806// ***WARNING***
807// Since merging may cause either node to go away, we must always
808// use the node-handles to refer to the nodes. These node handles are
809// automatically updated during merging, so will always provide access
810// to the correct node after a merge.
811//
812void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
813 assert(CurNodeH.getOffset() >= NH.getOffset() &&
814 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000815 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
816 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000817
818 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
819 // respect to NH.Offset) is now zero. NOffset is the distance from the base
820 // of our object that N starts from.
821 //
822 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
823 unsigned NSize = NH.getNode()->getSize();
824
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000825 // If the two nodes are of different size, and the smaller node has the array
826 // bit set, collapse!
827 if (NSize != CurNodeH.getNode()->getSize()) {
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000828#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000829 if (NSize < CurNodeH.getNode()->getSize()) {
830 if (NH.getNode()->isArray())
831 NH.getNode()->foldNodeCompletely();
832 } else if (CurNodeH.getNode()->isArray()) {
833 NH.getNode()->foldNodeCompletely();
834 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000835#endif
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000836 }
837
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000838 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000839 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000840 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000841 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000842
843 // If we are merging a node with a completely folded node, then both nodes are
844 // now completely folded.
845 //
846 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
847 if (!NH.getNode()->isNodeCompletelyFolded()) {
848 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000849 assert(NH.getNode() && NH.getOffset() == 0 &&
850 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000851 NOffset = NH.getOffset();
852 NSize = NH.getNode()->getSize();
853 assert(NOffset == 0 && NSize == 1);
854 }
855 } else if (NH.getNode()->isNodeCompletelyFolded()) {
856 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000857 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
858 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000859 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000860 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000861 assert(NOffset == 0 && NSize == 1);
862 }
863
Chris Lattner72d29a42003-02-11 23:11:51 +0000864 DSNode *N = NH.getNode();
865 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000866 assert(!CurNodeH.getNode()->isDeadNode());
867
Chris Lattner0b144872004-01-27 22:03:40 +0000868 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000869 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000870
Chris Lattner72d29a42003-02-11 23:11:51 +0000871 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000872 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000873 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000874
Chris Lattner72d29a42003-02-11 23:11:51 +0000875 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
876 //
877 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
878 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000879 if (Link.getNode()) {
880 // Compute the offset into the current node at which to
881 // merge this link. In the common case, this is a linear
882 // relation to the offset in the original node (with
883 // wrapping), but if the current node gets collapsed due to
884 // recursive merging, we must make sure to merge in all remaining
885 // links at offset zero.
886 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000887 DSNode *CN = CurNodeH.getNode();
888 if (CN->Size != 1)
889 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
890 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000891 }
892 }
893
894 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000895 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000896
897 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000898 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000899 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000900
901 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000902 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000903 }
904}
905
906
Misha Brukman96a8bd72004-04-29 04:05:30 +0000907/// mergeWith - Merge this node and the specified node, moving all links to and
908/// from the argument node into the current node, deleting the node argument.
909/// Offset indicates what offset the specified node is to be merged into the
910/// current node.
911///
912/// The specified node may be a null pointer (in which case, we update it to
913/// point to this node).
914///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000915void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
916 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000917 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000918 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000919
Chris Lattner5254a8d2004-01-22 16:31:08 +0000920 // If the RHS is a null node, make it point to this node!
921 if (N == 0) {
922 NH.mergeWith(DSNodeHandle(this, Offset));
923 return;
924 }
925
Chris Lattnerbd92b732003-06-19 21:15:11 +0000926 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000927 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
928
Chris Lattner02606632002-11-04 06:48:26 +0000929 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000930 // We cannot merge two pieces of the same node together, collapse the node
931 // completely.
Bill Wendling5294fb02006-11-17 07:33:59 +0000932 DOUT << "Attempting to merge two chunks of the same node together!\n";
Chris Lattner08db7192002-11-06 06:20:27 +0000933 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000934 return;
935 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000936
Chris Lattner5190ce82002-11-12 07:20:45 +0000937 // If both nodes are not at offset 0, make sure that we are merging the node
938 // at an later offset into the node with the zero offset.
939 //
940 if (Offset < NH.getOffset()) {
941 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
942 return;
943 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
944 // If the offsets are the same, merge the smaller node into the bigger node
945 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
946 return;
947 }
948
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000949 // Ok, now we can merge the two nodes. Use a static helper that works with
950 // two node handles, since "this" may get merged away at intermediate steps.
951 DSNodeHandle CurNodeH(this, Offset);
952 DSNodeHandle NHCopy(NH);
Andrew Lenharth37705002006-06-19 15:42:47 +0000953 if (CurNodeH.getOffset() >= NHCopy.getOffset())
954 DSNode::MergeNodes(CurNodeH, NHCopy);
955 else
956 DSNode::MergeNodes(NHCopy, CurNodeH);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000957}
958
Chris Lattner0b144872004-01-27 22:03:40 +0000959
960//===----------------------------------------------------------------------===//
961// ReachabilityCloner Implementation
962//===----------------------------------------------------------------------===//
963
964DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
965 if (SrcNH.isNull()) return DSNodeHandle();
966 const DSNode *SN = SrcNH.getNode();
967
968 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000969 if (!NH.isNull()) { // Node already mapped?
970 DSNode *NHN = NH.getNode();
971 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
972 }
Chris Lattner0b144872004-01-27 22:03:40 +0000973
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000974 // If SrcNH has globals and the destination graph has one of the same globals,
975 // merge this node with the destination node, which is much more efficient.
Chris Lattner82c6c722005-03-20 02:41:38 +0000976 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000977 DSScalarMap &DestSM = Dest.getScalarMap();
Chris Lattner82c6c722005-03-20 02:41:38 +0000978 for (DSNode::globals_iterator I = SN->globals_begin(),E = SN->globals_end();
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000979 I != E; ++I) {
980 GlobalValue *GV = *I;
981 DSScalarMap::iterator GI = DestSM.find(GV);
982 if (GI != DestSM.end() && !GI->second.isNull()) {
983 // We found one, use merge instead!
984 merge(GI->second, Src.getNodeForValue(GV));
985 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000986 DSNode *NHN = NH.getNode();
987 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000988 }
989 }
990 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000991
Chris Lattner0b144872004-01-27 22:03:40 +0000992 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
993 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000994 NH = DN;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000995
Chris Lattner0b144872004-01-27 22:03:40 +0000996 // Next, recursively clone all outgoing links as necessary. Note that
997 // adding these links can cause the node to collapse itself at any time, and
998 // the current node may be merged with arbitrary other nodes. For this
999 // reason, we must always go through NH.
1000 DN = 0;
1001 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1002 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1003 if (!SrcEdge.isNull()) {
1004 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
1005 // Compute the offset into the current node at which to
1006 // merge this link. In the common case, this is a linear
1007 // relation to the offset in the original node (with
1008 // wrapping), but if the current node gets collapsed due to
1009 // recursive merging, we must make sure to merge in all remaining
1010 // links at offset zero.
1011 unsigned MergeOffset = 0;
1012 DSNode *CN = NH.getNode();
1013 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +00001014 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +00001015 CN->addEdgeTo(MergeOffset, DestEdge);
1016 }
1017 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001018
Chris Lattner0b144872004-01-27 22:03:40 +00001019 // If this node contains any globals, make sure they end up in the scalar
1020 // map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +00001021 for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
Chris Lattner0b144872004-01-27 22:03:40 +00001022 I != E; ++I) {
1023 GlobalValue *GV = *I;
1024 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1025 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1026 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
1027 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +00001028 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001029 }
Chris Lattner82c6c722005-03-20 02:41:38 +00001030 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001031
1032 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
1033}
1034
1035void ReachabilityCloner::merge(const DSNodeHandle &NH,
1036 const DSNodeHandle &SrcNH) {
1037 if (SrcNH.isNull()) return; // Noop
1038 if (NH.isNull()) {
1039 // If there is no destination node, just clone the source and assign the
1040 // destination node to be it.
1041 NH.mergeWith(getClonedNH(SrcNH));
1042 return;
1043 }
1044
1045 // Okay, at this point, we know that we have both a destination and a source
1046 // node that need to be merged. Check to see if the source node has already
1047 // been cloned.
1048 const DSNode *SN = SrcNH.getNode();
1049 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +00001050 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +00001051 DSNode *SCNHN = SCNH.getNode();
1052 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +00001053 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001054 return; // Nothing to do!
1055 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001056
Chris Lattner0b144872004-01-27 22:03:40 +00001057 // Okay, so the source node has not already been cloned. Instead of creating
1058 // a new DSNode, only to merge it into the one we already have, try to perform
1059 // the merge in-place. The only case we cannot handle here is when the offset
1060 // into the existing node is less than the offset into the virtual node we are
1061 // merging in. In this case, we have to extend the existing node, which
1062 // requires an allocation anyway.
1063 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
1064 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +00001065 if (!DN->isNodeCompletelyFolded()) {
1066 // Make sure the destination node is folded if the source node is folded.
1067 if (SN->isNodeCompletelyFolded()) {
1068 DN->foldNodeCompletely();
1069 DN = NH.getNode();
1070 } else if (SN->getSize() != DN->getSize()) {
1071 // If the two nodes are of different size, and the smaller node has the
1072 // array bit set, collapse!
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001073#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner0b144872004-01-27 22:03:40 +00001074 if (SN->getSize() < DN->getSize()) {
1075 if (SN->isArray()) {
1076 DN->foldNodeCompletely();
1077 DN = NH.getNode();
1078 }
1079 } else if (DN->isArray()) {
1080 DN->foldNodeCompletely();
1081 DN = NH.getNode();
1082 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001083#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001084 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001085
1086 // Merge the type entries of the two nodes together...
Chris Lattner0b144872004-01-27 22:03:40 +00001087 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
1088 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
1089 DN = NH.getNode();
1090 }
1091 }
1092
1093 assert(!DN->isDeadNode());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001094
Chris Lattner0b144872004-01-27 22:03:40 +00001095 // Merge the NodeType information.
1096 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
1097
1098 // Before we start merging outgoing links and updating the scalar map, make
1099 // sure it is known that this is the representative node for the src node.
1100 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
1101
1102 // If the source node contains any globals, make sure they end up in the
1103 // scalar map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +00001104 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattner0b144872004-01-27 22:03:40 +00001105 // Update the globals in the destination node itself.
Chris Lattner82c6c722005-03-20 02:41:38 +00001106 DN->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001107
1108 // Update the scalar map for the graph we are merging the source node
1109 // into.
Chris Lattner82c6c722005-03-20 02:41:38 +00001110 for (DSNode::globals_iterator I = SN->globals_begin(),
1111 E = SN->globals_end(); I != E; ++I) {
Chris Lattner0b144872004-01-27 22:03:40 +00001112 GlobalValue *GV = *I;
1113 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1114 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1115 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1116 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +00001117 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001118 }
Chris Lattner82c6c722005-03-20 02:41:38 +00001119 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001120 }
1121 } else {
1122 // We cannot handle this case without allocating a temporary node. Fall
1123 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +00001124 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
1125 NewDN->maskNodeTypes(BitsToKeep);
1126
1127 unsigned NHOffset = NH.getOffset();
1128 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001129
Chris Lattner0b144872004-01-27 22:03:40 +00001130 assert(NH.getNode() &&
1131 (NH.getOffset() > NHOffset ||
1132 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
1133 "Merging did not adjust the offset!");
1134
1135 // Before we start merging outgoing links and updating the scalar map, make
1136 // sure it is known that this is the representative node for the src node.
1137 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +00001138
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001139 // If the source node contained any globals, make sure to create entries
Chris Lattneread9eb72004-01-29 08:36:22 +00001140 // in the scalar map for them!
Chris Lattner82c6c722005-03-20 02:41:38 +00001141 for (DSNode::globals_iterator I = SN->globals_begin(),
1142 E = SN->globals_end(); I != E; ++I) {
Chris Lattneread9eb72004-01-29 08:36:22 +00001143 GlobalValue *GV = *I;
1144 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1145 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1146 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1147 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
1148 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1149 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001150 }
Chris Lattner0b144872004-01-27 22:03:40 +00001151 }
1152
1153
1154 // Next, recursively merge all outgoing links as necessary. Note that
1155 // adding these links can cause the destination node to collapse itself at
1156 // any time, and the current node may be merged with arbitrary other nodes.
1157 // For this reason, we must always go through NH.
1158 DN = 0;
1159 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1160 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1161 if (!SrcEdge.isNull()) {
1162 // Compute the offset into the current node at which to
1163 // merge this link. In the common case, this is a linear
1164 // relation to the offset in the original node (with
1165 // wrapping), but if the current node gets collapsed due to
1166 // recursive merging, we must make sure to merge in all remaining
1167 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +00001168 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +00001169 unsigned MergeOffset =
1170 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001171
Chris Lattnerf590ced2004-03-04 17:06:53 +00001172 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1173 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001174 // Perform the recursive merging. Make sure to create a temporary NH,
1175 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001176 merge(Tmp, SrcEdge);
1177 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001178 Tmp.mergeWith(getClonedNH(SrcEdge));
1179 // Merging this could cause all kinds of recursive things to happen,
1180 // culminating in the current node being eliminated. Since this is
1181 // possible, make sure to reaquire the link from 'CN'.
1182
1183 unsigned MergeOffset = 0;
1184 CN = SCNH.getNode();
1185 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1186 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001187 }
Chris Lattner0b144872004-01-27 22:03:40 +00001188 }
1189 }
1190}
1191
1192/// mergeCallSite - Merge the nodes reachable from the specified src call
1193/// site into the nodes reachable from DestCS.
Chris Lattnerb3439372005-03-21 20:28:50 +00001194void ReachabilityCloner::mergeCallSite(DSCallSite &DestCS,
Chris Lattner0b144872004-01-27 22:03:40 +00001195 const DSCallSite &SrcCS) {
1196 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1197 unsigned MinArgs = DestCS.getNumPtrArgs();
1198 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001199
Chris Lattner0b144872004-01-27 22:03:40 +00001200 for (unsigned a = 0; a != MinArgs; ++a)
1201 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
Chris Lattner3f90a942005-03-21 09:39:51 +00001202
1203 for (unsigned a = MinArgs, e = SrcCS.getNumPtrArgs(); a != e; ++a)
Chris Lattnerb3439372005-03-21 20:28:50 +00001204 DestCS.addPtrArg(getClonedNH(SrcCS.getPtrArg(a)));
Chris Lattner0b144872004-01-27 22:03:40 +00001205}
1206
1207
Chris Lattner9de906c2002-10-20 22:11:44 +00001208//===----------------------------------------------------------------------===//
1209// DSCallSite Implementation
1210//===----------------------------------------------------------------------===//
1211
Vikram S. Adve26b98262002-10-20 21:41:02 +00001212// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001213Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001214 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001215}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001216
Chris Lattner0b144872004-01-27 22:03:40 +00001217void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1218 ReachabilityCloner &RC) {
1219 NH = RC.getClonedNH(Src);
1220}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001221
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001222//===----------------------------------------------------------------------===//
1223// DSGraph Implementation
1224//===----------------------------------------------------------------------===//
1225
Chris Lattnera9d65662003-06-30 05:57:30 +00001226/// getFunctionNames - Return a space separated list of the name of the
1227/// functions in this graph (if any)
1228std::string DSGraph::getFunctionNames() const {
1229 switch (getReturnNodes().size()) {
1230 case 0: return "Globals graph";
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001231 case 1: return retnodes_begin()->first->getName();
Chris Lattnera9d65662003-06-30 05:57:30 +00001232 default:
1233 std::string Return;
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001234 for (DSGraph::retnodes_iterator I = retnodes_begin();
1235 I != retnodes_end(); ++I)
Chris Lattnera9d65662003-06-30 05:57:30 +00001236 Return += I->first->getName() + " ";
1237 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1238 return Return;
1239 }
1240}
1241
1242
Chris Lattnerf09ecff2005-03-21 22:49:53 +00001243DSGraph::DSGraph(const DSGraph &G, EquivalenceClasses<GlobalValue*> &ECs,
1244 unsigned CloneFlags)
Chris Lattnerf4f62272005-03-19 22:23:45 +00001245 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001246 PrintAuxCalls = false;
Chris Lattnera2197132005-03-22 00:36:51 +00001247 cloneInto(G, CloneFlags);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001248}
1249
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001250DSGraph::~DSGraph() {
1251 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001252 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001253 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001254 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001255
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001256 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001257 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
Chris Lattner84b80a22005-03-16 22:42:19 +00001258 NI->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001259
Chris Lattner28897e12004-02-08 00:53:26 +00001260 // Free all of the nodes.
1261 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001262}
1263
Chris Lattner0d9bab82002-07-18 00:12:30 +00001264// dump - Allow inspection of graph in a debugger.
Bill Wendlinge8156192006-12-07 01:30:32 +00001265void DSGraph::dump() const { print(cerr); }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001266
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001267
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001268/// remapLinks - Change all of the Links in the current node according to the
1269/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001270///
Chris Lattner8d327672003-06-30 03:36:09 +00001271void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001272 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1273 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001274 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001275 if (ONMI != OldNodeMap.end()) {
1276 DSNode *ONMIN = ONMI->second.getNode();
1277 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1278 }
Chris Lattner2f561382004-01-22 16:56:13 +00001279 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001280}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001281
Chris Lattnerd672ab92005-02-15 18:40:55 +00001282/// addObjectToGraph - This method can be used to add global, stack, and heap
1283/// objects to the graph. This can be used when updating DSGraphs due to the
1284/// introduction of new temporary objects. The new object is not pointed to
1285/// and does not point to any other objects in the graph.
1286DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1287 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1288 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1289 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
Chris Lattner7a0c7752005-02-15 18:48:48 +00001290 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
Chris Lattnerd672ab92005-02-15 18:40:55 +00001291 ScalarMap[Ptr] = N;
1292
1293 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1294 N->addGlobal(GV);
Reid Spencer3ed469c2006-11-02 20:25:50 +00001295 } else if (isa<MallocInst>(Ptr)) {
Chris Lattnerd672ab92005-02-15 18:40:55 +00001296 N->setHeapNodeMarker();
Reid Spencer3ed469c2006-11-02 20:25:50 +00001297 } else if (isa<AllocaInst>(Ptr)) {
Chris Lattnerd672ab92005-02-15 18:40:55 +00001298 N->setAllocaNodeMarker();
1299 } else {
1300 assert(0 && "Illegal memory object input!");
1301 }
1302 return N;
1303}
1304
1305
Chris Lattner5a540632003-06-30 03:15:25 +00001306/// cloneInto - Clone the specified DSGraph into the current graph. The
Chris Lattner3c920fa2005-03-22 00:21:05 +00001307/// translated ScalarMap for the old function is filled into the ScalarMap
1308/// for the graph, and the translated ReturnNodes map is returned into
1309/// ReturnNodes.
Chris Lattner5a540632003-06-30 03:15:25 +00001310///
1311/// The CloneFlags member controls various aspects of the cloning process.
1312///
Chris Lattnera2197132005-03-22 00:36:51 +00001313void DSGraph::cloneInto(const DSGraph &G, unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001314 TIME_REGION(X, "cloneInto");
Chris Lattner33312f72002-11-08 01:21:07 +00001315 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001316
Chris Lattnera2197132005-03-22 00:36:51 +00001317 NodeMapTy OldNodeMap;
1318
Chris Lattner1e883692003-02-03 20:08:51 +00001319 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001320 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1321 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1322 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001323 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001324
Chris Lattner84b80a22005-03-16 22:42:19 +00001325 for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1326 assert(!I->isForwarding() &&
Chris Lattnerd85645f2004-02-21 22:28:26 +00001327 "Forward nodes shouldn't be in node list!");
Chris Lattner84b80a22005-03-16 22:42:19 +00001328 DSNode *New = new DSNode(*I, this);
Chris Lattnerd85645f2004-02-21 22:28:26 +00001329 New->maskNodeTypes(~BitsToClear);
Chris Lattner84b80a22005-03-16 22:42:19 +00001330 OldNodeMap[I] = New;
Chris Lattnerd85645f2004-02-21 22:28:26 +00001331 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001332
Chris Lattner18552922002-11-18 21:44:46 +00001333#ifndef NDEBUG
1334 Timer::addPeakMemoryMeasurement();
1335#endif
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001336
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001337 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001338 // Note that we don't loop over the node's list to do this. The problem is
1339 // that remaping links can cause recursive merging to happen, which means
1340 // that node_iterator's can get easily invalidated! Because of this, we
1341 // loop over the OldNodeMap, which contains all of the new nodes as the
1342 // .second element of the map elements. Also note that if we remap a node
1343 // more than once, we won't break anything.
1344 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1345 I != E; ++I)
1346 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001347
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001348 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001349 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001350 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001351 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner3bc703b2005-03-22 01:42:59 +00001352 DSNodeHandle &H = ScalarMap.getRawEntryRef(I->first);
Chris Lattner6f967742004-10-30 04:05:01 +00001353 DSNode *MappedNodeN = MappedNode.getNode();
1354 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001355 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001356 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001357
Chris Lattner679e8e12002-11-08 21:27:12 +00001358 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001359 // Copy the function calls list.
1360 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1361 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001362 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001363
Chris Lattneracf491f2002-11-08 22:27:09 +00001364 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001365 // Copy the auxiliary function calls list.
1366 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1367 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattner679e8e12002-11-08 21:27:12 +00001368 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001369
Chris Lattner5a540632003-06-30 03:15:25 +00001370 // Map the return node pointers over...
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001371 for (retnodes_iterator I = G.retnodes_begin(),
1372 E = G.retnodes_end(); I != E; ++I) {
Chris Lattner5a540632003-06-30 03:15:25 +00001373 const DSNodeHandle &Ret = I->second;
1374 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001375 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattnerd65145b2005-03-22 00:29:44 +00001376 ReturnNodes.insert(std::make_pair(I->first,
1377 DSNodeHandle(MappedRetN,
1378 MappedRet.getOffset()+Ret.getOffset())));
Chris Lattner5a540632003-06-30 03:15:25 +00001379 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001380}
1381
Chris Lattner5734e432005-03-24 23:46:04 +00001382/// spliceFrom - Logically perform the operation of cloning the RHS graph into
1383/// this graph, then clearing the RHS graph. Instead of performing this as
1384/// two seperate operations, do it as a single, much faster, one.
1385///
1386void DSGraph::spliceFrom(DSGraph &RHS) {
1387 // Change all of the nodes in RHS to think we are their parent.
1388 for (NodeListTy::iterator I = RHS.Nodes.begin(), E = RHS.Nodes.end();
1389 I != E; ++I)
1390 I->setParentGraph(this);
1391 // Take all of the nodes.
1392 Nodes.splice(Nodes.end(), RHS.Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001393
Chris Lattner5734e432005-03-24 23:46:04 +00001394 // Take all of the calls.
1395 FunctionCalls.splice(FunctionCalls.end(), RHS.FunctionCalls);
1396 AuxFunctionCalls.splice(AuxFunctionCalls.end(), RHS.AuxFunctionCalls);
1397
1398 // Take all of the return nodes.
Chris Lattnerce7068d2005-03-25 00:02:41 +00001399 if (ReturnNodes.empty()) {
1400 ReturnNodes.swap(RHS.ReturnNodes);
1401 } else {
1402 ReturnNodes.insert(RHS.ReturnNodes.begin(), RHS.ReturnNodes.end());
1403 RHS.ReturnNodes.clear();
1404 }
Chris Lattner5734e432005-03-24 23:46:04 +00001405
1406 // Merge the scalar map in.
1407 ScalarMap.spliceFrom(RHS.ScalarMap);
1408}
1409
1410/// spliceFrom - Copy all entries from RHS, then clear RHS.
1411///
1412void DSScalarMap::spliceFrom(DSScalarMap &RHS) {
1413 // Special case if this is empty.
1414 if (ValueMap.empty()) {
1415 ValueMap.swap(RHS.ValueMap);
1416 GlobalSet.swap(RHS.GlobalSet);
1417 } else {
1418 GlobalSet.insert(RHS.GlobalSet.begin(), RHS.GlobalSet.end());
1419 for (ValueMapTy::iterator I = RHS.ValueMap.begin(), E = RHS.ValueMap.end();
1420 I != E; ++I)
1421 ValueMap[I->first].mergeWith(I->second);
1422 RHS.ValueMap.clear();
1423 }
1424}
1425
1426
Chris Lattnerbb753c42005-02-03 18:40:25 +00001427/// getFunctionArgumentsForCall - Given a function that is currently in this
1428/// graph, return the DSNodeHandles that correspond to the pointer-compatible
1429/// function arguments. The vector is filled in with the return value (or
1430/// null if it is not pointer compatible), followed by all of the
1431/// pointer-compatible arguments.
1432void DSGraph::getFunctionArgumentsForCall(Function *F,
1433 std::vector<DSNodeHandle> &Args) const {
1434 Args.push_back(getReturnNodeFor(*F));
Chris Lattnereb394922005-03-23 16:43:11 +00001435 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1436 AI != E; ++AI)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001437 if (isPointerType(AI->getType())) {
1438 Args.push_back(getNodeForValue(AI));
1439 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1440 }
1441}
1442
Chris Lattner4da120e2005-03-24 23:06:02 +00001443namespace {
1444 // HackedGraphSCCFinder - This is used to find nodes that have a path from the
1445 // node to a node cloned by the ReachabilityCloner object contained. To be
1446 // extra obnoxious it ignores edges from nodes that are globals, and truncates
1447 // search at RC marked nodes. This is designed as an object so that
1448 // intermediate results can be memoized across invocations of
1449 // PathExistsToClonedNode.
1450 struct HackedGraphSCCFinder {
1451 ReachabilityCloner &RC;
1452 unsigned CurNodeId;
1453 std::vector<const DSNode*> SCCStack;
1454 std::map<const DSNode*, std::pair<unsigned, bool> > NodeInfo;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001455
Chris Lattner4da120e2005-03-24 23:06:02 +00001456 HackedGraphSCCFinder(ReachabilityCloner &rc) : RC(rc), CurNodeId(1) {
1457 // Remove null pointer as a special case.
1458 NodeInfo[0] = std::make_pair(0, false);
Chris Lattnerd8642122005-03-24 21:07:47 +00001459 }
1460
Chris Lattner4da120e2005-03-24 23:06:02 +00001461 std::pair<unsigned, bool> &VisitForSCCs(const DSNode *N);
1462
1463 bool PathExistsToClonedNode(const DSNode *N) {
1464 return VisitForSCCs(N).second;
1465 }
1466
1467 bool PathExistsToClonedNode(const DSCallSite &CS) {
1468 if (PathExistsToClonedNode(CS.getRetVal().getNode()))
1469 return true;
1470 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1471 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode()))
1472 return true;
1473 return false;
1474 }
1475 };
1476}
1477
1478std::pair<unsigned, bool> &HackedGraphSCCFinder::
1479VisitForSCCs(const DSNode *N) {
1480 std::map<const DSNode*, std::pair<unsigned, bool> >::iterator
1481 NodeInfoIt = NodeInfo.lower_bound(N);
1482 if (NodeInfoIt != NodeInfo.end() && NodeInfoIt->first == N)
1483 return NodeInfoIt->second;
1484
1485 unsigned Min = CurNodeId++;
1486 unsigned MyId = Min;
1487 std::pair<unsigned, bool> &ThisNodeInfo =
1488 NodeInfo.insert(NodeInfoIt,
1489 std::make_pair(N, std::make_pair(MyId, false)))->second;
1490
1491 // Base case: if we find a global, this doesn't reach the cloned graph
1492 // portion.
1493 if (N->isGlobalNode()) {
1494 ThisNodeInfo.second = false;
1495 return ThisNodeInfo;
Chris Lattnerd8642122005-03-24 21:07:47 +00001496 }
1497
Chris Lattner4da120e2005-03-24 23:06:02 +00001498 // Base case: if this does reach the cloned graph portion... it does. :)
1499 if (RC.hasClonedNode(N)) {
1500 ThisNodeInfo.second = true;
1501 return ThisNodeInfo;
1502 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001503
Chris Lattner4da120e2005-03-24 23:06:02 +00001504 SCCStack.push_back(N);
Chris Lattnerd8642122005-03-24 21:07:47 +00001505
Chris Lattner4da120e2005-03-24 23:06:02 +00001506 // Otherwise, check all successors.
1507 bool AnyDirectSuccessorsReachClonedNodes = false;
1508 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
Chris Lattner63320cc2005-04-25 19:16:17 +00001509 EI != EE; ++EI)
1510 if (DSNode *Succ = EI->getNode()) {
1511 std::pair<unsigned, bool> &SuccInfo = VisitForSCCs(Succ);
1512 if (SuccInfo.first < Min) Min = SuccInfo.first;
1513 AnyDirectSuccessorsReachClonedNodes |= SuccInfo.second;
1514 }
Chris Lattner4da120e2005-03-24 23:06:02 +00001515
1516 if (Min != MyId)
1517 return ThisNodeInfo; // Part of a large SCC. Leave self on stack.
1518
1519 if (SCCStack.back() == N) { // Special case single node SCC.
1520 SCCStack.pop_back();
1521 ThisNodeInfo.second = AnyDirectSuccessorsReachClonedNodes;
1522 return ThisNodeInfo;
1523 }
1524
1525 // Find out if any direct successors of any node reach cloned nodes.
1526 if (!AnyDirectSuccessorsReachClonedNodes)
1527 for (unsigned i = SCCStack.size()-1; SCCStack[i] != N; --i)
1528 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1529 EI != EE; ++EI)
1530 if (DSNode *N = EI->getNode())
1531 if (NodeInfo[N].second) {
1532 AnyDirectSuccessorsReachClonedNodes = true;
1533 goto OutOfLoop;
1534 }
1535OutOfLoop:
1536 // If any successor reaches a cloned node, mark all nodes in this SCC as
1537 // reaching the cloned node.
1538 if (AnyDirectSuccessorsReachClonedNodes)
1539 while (SCCStack.back() != N) {
1540 NodeInfo[SCCStack.back()].second = true;
1541 SCCStack.pop_back();
1542 }
1543 SCCStack.pop_back();
1544 ThisNodeInfo.second = true;
1545 return ThisNodeInfo;
1546}
Chris Lattnerd8642122005-03-24 21:07:47 +00001547
Chris Lattnere8594442005-02-04 19:58:28 +00001548/// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1549/// nodes from G2 into 'this' graph, merging the bindings specified by the
1550/// call site (in this graph) with the bindings specified by the vector in G2.
1551/// The two DSGraphs must be different.
Chris Lattner076c1f92002-11-07 06:31:54 +00001552///
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001553void DSGraph::mergeInGraph(const DSCallSite &CS,
Chris Lattnere8594442005-02-04 19:58:28 +00001554 std::vector<DSNodeHandle> &Args,
Chris Lattner9f930552003-06-30 05:27:18 +00001555 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001556 TIME_REGION(X, "mergeInGraph");
1557
Chris Lattnerc14f59c2005-03-23 20:12:08 +00001558 assert((CloneFlags & DontCloneCallNodes) &&
1559 "Doesn't support copying of call nodes!");
1560
Chris Lattner076c1f92002-11-07 06:31:54 +00001561 // If this is not a recursive call, clone the graph into this graph...
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001562 if (&Graph == this) {
Chris Lattnerbb753c42005-02-03 18:40:25 +00001563 // Merge the return value with the return value of the context.
1564 Args[0].mergeWith(CS.getRetVal());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001565
Chris Lattnerbb753c42005-02-03 18:40:25 +00001566 // Resolve all of the function arguments.
1567 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001568 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001569 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001570
Chris Lattnerbb753c42005-02-03 18:40:25 +00001571 // Add the link from the argument scalar to the provided value.
1572 Args[i+1].mergeWith(CS.getPtrArg(i));
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001573 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001574 return;
Chris Lattner076c1f92002-11-07 06:31:54 +00001575 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001576
1577 // Clone the callee's graph into the current graph, keeping track of where
1578 // scalars in the old graph _used_ to point, and of the new nodes matching
1579 // nodes of the old graph.
1580 ReachabilityCloner RC(*this, Graph, CloneFlags);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001581
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001582 // Map the return node pointer over.
1583 if (!CS.getRetVal().isNull())
1584 RC.merge(CS.getRetVal(), Args[0]);
1585
1586 // Map over all of the arguments.
1587 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1588 if (i == Args.size()-1)
1589 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001590
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001591 // Add the link from the argument scalar to the provided value.
1592 RC.merge(CS.getPtrArg(i), Args[i+1]);
1593 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001594
Chris Lattnerd8642122005-03-24 21:07:47 +00001595 // We generally don't want to copy global nodes or aux calls from the callee
1596 // graph to the caller graph. However, we have to copy them if there is a
1597 // path from the node to a node we have already copied which does not go
1598 // through another global. Compute the set of node that can reach globals and
1599 // aux call nodes to copy over, then do it.
1600 std::vector<const DSCallSite*> AuxCallToCopy;
1601 std::vector<GlobalValue*> GlobalsToCopy;
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001602
Chris Lattnerd8642122005-03-24 21:07:47 +00001603 // NodesReachCopiedNodes - Memoize results for efficiency. Contains a
1604 // true/false value for every visited node that reaches a copied node without
1605 // going through a global.
Chris Lattner4da120e2005-03-24 23:06:02 +00001606 HackedGraphSCCFinder SCCFinder(RC);
Chris Lattnerd8642122005-03-24 21:07:47 +00001607
1608 if (!(CloneFlags & DontCloneAuxCallNodes))
1609 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
Chris Lattner4da120e2005-03-24 23:06:02 +00001610 if (SCCFinder.PathExistsToClonedNode(*I))
Chris Lattnerd8642122005-03-24 21:07:47 +00001611 AuxCallToCopy.push_back(&*I);
Andrew Lenharthdf983de2006-11-07 20:36:02 +00001612// else if (I->isIndirectCall()){
1613// //If the call node doesn't have any callees, clone it
1614// std::vector< Function *> List;
1615// I->getCalleeNode()->addFullFunctionList(List);
1616// if (!List.size())
1617// AuxCallToCopy.push_back(&*I);
1618// }
Chris Lattnerd8642122005-03-24 21:07:47 +00001619
Chris Lattner4da120e2005-03-24 23:06:02 +00001620 const DSScalarMap &GSM = Graph.getScalarMap();
Chris Lattnerd8642122005-03-24 21:07:47 +00001621 for (DSScalarMap::global_iterator GI = GSM.global_begin(),
Chris Lattner09adbbc92005-03-24 21:17:27 +00001622 E = GSM.global_end(); GI != E; ++GI) {
1623 DSNode *GlobalNode = Graph.getNodeForValue(*GI).getNode();
1624 for (DSNode::edge_iterator EI = GlobalNode->edge_begin(),
1625 EE = GlobalNode->edge_end(); EI != EE; ++EI)
Chris Lattner4da120e2005-03-24 23:06:02 +00001626 if (SCCFinder.PathExistsToClonedNode(EI->getNode())) {
Chris Lattner09adbbc92005-03-24 21:17:27 +00001627 GlobalsToCopy.push_back(*GI);
1628 break;
1629 }
1630 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001631
1632 // Copy aux calls that are needed.
1633 for (unsigned i = 0, e = AuxCallToCopy.size(); i != e; ++i)
1634 AuxFunctionCalls.push_back(DSCallSite(*AuxCallToCopy[i], RC));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001635
Chris Lattnerd8642122005-03-24 21:07:47 +00001636 // Copy globals that are needed.
1637 for (unsigned i = 0, e = GlobalsToCopy.size(); i != e; ++i)
1638 RC.getClonedNH(Graph.getNodeForValue(GlobalsToCopy[i]));
Chris Lattner076c1f92002-11-07 06:31:54 +00001639}
1640
Chris Lattnere8594442005-02-04 19:58:28 +00001641
1642
1643/// mergeInGraph - The method is used for merging graphs together. If the
1644/// argument graph is not *this, it makes a clone of the specified graph, then
1645/// merges the nodes specified in the call site with the formal arguments in the
1646/// graph.
1647///
1648void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1649 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattnere8594442005-02-04 19:58:28 +00001650 // Set up argument bindings.
1651 std::vector<DSNodeHandle> Args;
1652 Graph.getFunctionArgumentsForCall(&F, Args);
1653
1654 mergeInGraph(CS, Args, Graph, CloneFlags);
1655}
1656
Chris Lattner58f98d02003-07-02 04:38:49 +00001657/// getCallSiteForArguments - Get the arguments and return value bindings for
1658/// the specified function in the current graph.
1659///
1660DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1661 std::vector<DSNodeHandle> Args;
1662
Chris Lattnere4d5c442005-03-15 04:54:21 +00001663 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner58f98d02003-07-02 04:38:49 +00001664 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001665 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001666
Chris Lattner808a7ae2003-09-20 16:34:13 +00001667 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001668}
1669
Chris Lattner85fb1be2004-03-09 19:37:06 +00001670/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1671/// the context of this graph, return the DSCallSite for it.
1672DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1673 DSNodeHandle RetVal;
1674 Instruction *I = CS.getInstruction();
1675 if (isPointerType(I->getType()))
1676 RetVal = getNodeForValue(I);
1677
1678 std::vector<DSNodeHandle> Args;
1679 Args.reserve(CS.arg_end()-CS.arg_begin());
1680
1681 // Calculate the arguments vector...
1682 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1683 if (isPointerType((*I)->getType()))
Chris Lattner94f84702005-03-17 19:56:56 +00001684 if (isa<ConstantPointerNull>(*I))
1685 Args.push_back(DSNodeHandle());
1686 else
1687 Args.push_back(getNodeForValue(*I));
Chris Lattner85fb1be2004-03-09 19:37:06 +00001688
1689 // Add a new function call entry...
1690 if (Function *F = CS.getCalledFunction())
1691 return DSCallSite(CS, RetVal, F, Args);
1692 else
1693 return DSCallSite(CS, RetVal,
1694 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1695}
1696
Chris Lattner58f98d02003-07-02 04:38:49 +00001697
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001698
Chris Lattner0d9bab82002-07-18 00:12:30 +00001699// markIncompleteNodes - Mark the specified node as having contents that are not
1700// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001701// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001702// must recursively traverse the data structure graph, marking all reachable
1703// nodes as incomplete.
1704//
1705static void markIncompleteNode(DSNode *N) {
1706 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001707 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001708
1709 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001710 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001711
Misha Brukman2f2d0652003-09-11 18:14:24 +00001712 // Recursively process children...
Chris Lattner6be07942005-02-09 03:20:43 +00001713 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1714 if (DSNode *DSN = I->getNode())
Chris Lattner08db7192002-11-06 06:20:27 +00001715 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001716}
1717
Chris Lattnere71ffc22002-11-11 03:36:55 +00001718static void markIncomplete(DSCallSite &Call) {
1719 // Then the return value is certainly incomplete!
1720 markIncompleteNode(Call.getRetVal().getNode());
1721
1722 // All objects pointed to by function arguments are incomplete!
1723 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1724 markIncompleteNode(Call.getPtrArg(i).getNode());
1725}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001726
1727// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1728// modified by other functions that have not been resolved yet. This marks
1729// nodes that are reachable through three sources of "unknownness":
1730//
1731// Global Variables, Function Calls, and Incoming Arguments
1732//
1733// For any node that may have unknown components (because something outside the
1734// scope of current analysis may have modified it), the 'Incomplete' flag is
1735// added to the NodeType.
1736//
Chris Lattner394471f2003-01-23 22:05:33 +00001737void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001738 // Mark any incoming arguments as incomplete.
Chris Lattner5a540632003-06-30 03:15:25 +00001739 if (Flags & DSGraph::MarkFormalArgs)
1740 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1741 FI != E; ++FI) {
1742 Function &F = *FI->first;
Chris Lattner9342a932005-03-29 19:16:59 +00001743 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1744 I != E; ++I)
Chris Lattnerb5ecd2e2005-03-13 20:22:10 +00001745 if (isPointerType(I->getType()))
1746 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattnera4319e52005-03-12 14:58:28 +00001747 markIncompleteNode(FI->second.getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001748 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001749
Chris Lattnera9548d92005-01-30 23:51:02 +00001750 // Mark stuff passed into functions calls as being incomplete.
Chris Lattnere71ffc22002-11-11 03:36:55 +00001751 if (!shouldPrintAuxCalls())
Chris Lattnera9548d92005-01-30 23:51:02 +00001752 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1753 E = FunctionCalls.end(); I != E; ++I)
1754 markIncomplete(*I);
Chris Lattnere71ffc22002-11-11 03:36:55 +00001755 else
Chris Lattnera9548d92005-01-30 23:51:02 +00001756 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1757 E = AuxFunctionCalls.end(); I != E; ++I)
1758 markIncomplete(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001759
Chris Lattnere2bc7b22005-03-13 20:36:01 +00001760 // Mark all global nodes as incomplete.
1761 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1762 E = ScalarMap.global_end(); I != E; ++I)
1763 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1764 if (!GV->hasInitializer() || // Always mark external globals incomp.
1765 (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1766 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001767}
1768
Chris Lattneraa8146f2002-11-10 06:59:55 +00001769static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1770 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001771 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001772 // No interesting info?
1773 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001774 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001775 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001776}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001777
Chris Lattneraa8146f2002-11-10 06:59:55 +00001778static inline bool nodeContainsExternalFunction(const DSNode *N) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001779 std::vector<Function*> Funcs;
1780 N->addFullFunctionList(Funcs);
1781 for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
1782 if (Funcs[i]->isExternal()) return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001783 return false;
1784}
1785
Chris Lattnera9548d92005-01-30 23:51:02 +00001786static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001787 // Remove trivially identical function calls
Chris Lattnera9548d92005-01-30 23:51:02 +00001788 Calls.sort(); // Sort by callee as primary key!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001789
1790 // Scan the call list cleaning it up as necessary...
Chris Lattner1e9d1472005-03-22 23:54:52 +00001791 DSNodeHandle LastCalleeNode;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001792#if 0
Chris Lattner923fc052003-02-05 21:59:58 +00001793 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001794 unsigned NumDuplicateCalls = 0;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001795#endif
Chris Lattneraa8146f2002-11-10 06:59:55 +00001796 bool LastCalleeContainsExternalFunction = false;
Chris Lattner857eb062004-10-30 05:41:23 +00001797
Chris Lattnera9548d92005-01-30 23:51:02 +00001798 unsigned NumDeleted = 0;
1799 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1800 I != E;) {
1801 DSCallSite &CS = *I;
1802 std::list<DSCallSite>::iterator OldIt = I++;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001803
Chris Lattner1e9d1472005-03-22 23:54:52 +00001804 if (!CS.isIndirectCall()) {
1805 LastCalleeNode = 0;
1806 } else {
1807 DSNode *Callee = CS.getCalleeNode();
1808
1809 // If the Callee is a useless edge, this must be an unreachable call site,
1810 // eliminate it.
1811 if (Callee->getNumReferrers() == 1 && Callee->isComplete() &&
1812 Callee->getGlobalsList().empty()) { // No useful info?
Bill Wendling5294fb02006-11-17 07:33:59 +00001813 DOUT << "WARNING: Useless call site found.\n";
Chris Lattner1e9d1472005-03-22 23:54:52 +00001814 Calls.erase(OldIt);
1815 ++NumDeleted;
1816 continue;
1817 }
1818
1819 // If the last call site in the list has the same callee as this one, and
1820 // if the callee contains an external function, it will never be
1821 // resolvable, just merge the call sites.
1822 if (!LastCalleeNode.isNull() && LastCalleeNode.getNode() == Callee) {
1823 LastCalleeContainsExternalFunction =
1824 nodeContainsExternalFunction(Callee);
1825
1826 std::list<DSCallSite>::iterator PrevIt = OldIt;
1827 --PrevIt;
1828 PrevIt->mergeWith(CS);
1829
1830 // No need to keep this call anymore.
1831 Calls.erase(OldIt);
1832 ++NumDeleted;
1833 continue;
1834 } else {
1835 LastCalleeNode = Callee;
1836 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001837 }
1838
1839 // If the return value or any arguments point to a void node with no
1840 // information at all in it, and the call node is the only node to point
1841 // to it, remove the edge to the node (killing the node).
1842 //
1843 killIfUselessEdge(CS.getRetVal());
1844 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1845 killIfUselessEdge(CS.getPtrArg(a));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001846
Chris Lattner0b144872004-01-27 22:03:40 +00001847#if 0
Chris Lattnera9548d92005-01-30 23:51:02 +00001848 // If this call site calls the same function as the last call site, and if
1849 // the function pointer contains an external function, this node will
1850 // never be resolved. Merge the arguments of the call node because no
1851 // information will be lost.
1852 //
1853 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1854 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1855 ++NumDuplicateCalls;
1856 if (NumDuplicateCalls == 1) {
1857 if (LastCalleeNode)
1858 LastCalleeContainsExternalFunction =
1859 nodeContainsExternalFunction(LastCalleeNode);
1860 else
1861 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001862 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001863
Chris Lattnera9548d92005-01-30 23:51:02 +00001864 // It is not clear why, but enabling this code makes DSA really
1865 // sensitive to node forwarding. Basically, with this enabled, DSA
1866 // performs different number of inlinings based on which nodes are
1867 // forwarding or not. This is clearly a problem, so this code is
1868 // disabled until this can be resolved.
1869#if 1
1870 if (LastCalleeContainsExternalFunction
1871#if 0
1872 ||
1873 // This should be more than enough context sensitivity!
1874 // FIXME: Evaluate how many times this is tripped!
1875 NumDuplicateCalls > 20
1876#endif
1877 ) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001878
Chris Lattnera9548d92005-01-30 23:51:02 +00001879 std::list<DSCallSite>::iterator PrevIt = OldIt;
1880 --PrevIt;
1881 PrevIt->mergeWith(CS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001882
Chris Lattnera9548d92005-01-30 23:51:02 +00001883 // No need to keep this call anymore.
1884 Calls.erase(OldIt);
1885 ++NumDeleted;
1886 continue;
1887 }
1888#endif
1889 } else {
1890 if (CS.isDirectCall()) {
1891 LastCalleeFunc = CS.getCalleeFunc();
1892 LastCalleeNode = 0;
1893 } else {
1894 LastCalleeNode = CS.getCalleeNode();
1895 LastCalleeFunc = 0;
1896 }
1897 NumDuplicateCalls = 0;
1898 }
1899#endif
1900
1901 if (I != Calls.end() && CS == *I) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001902 LastCalleeNode = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00001903 Calls.erase(OldIt);
1904 ++NumDeleted;
1905 continue;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001906 }
1907 }
Chris Lattner857eb062004-10-30 05:41:23 +00001908
Chris Lattnera9548d92005-01-30 23:51:02 +00001909 // Resort now that we simplified things.
1910 Calls.sort();
Chris Lattner857eb062004-10-30 05:41:23 +00001911
Chris Lattnera9548d92005-01-30 23:51:02 +00001912 // Now that we are in sorted order, eliminate duplicates.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001913 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1914 if (CI != CE)
Chris Lattnera9548d92005-01-30 23:51:02 +00001915 while (1) {
Chris Lattnerf9aace22005-01-31 00:10:58 +00001916 std::list<DSCallSite>::iterator OldIt = CI++;
1917 if (CI == CE) break;
Chris Lattnera9548d92005-01-30 23:51:02 +00001918
1919 // If this call site is now the same as the previous one, we can delete it
1920 // as a duplicate.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001921 if (*OldIt == *CI) {
1922 Calls.erase(CI);
1923 CI = OldIt;
Chris Lattnera9548d92005-01-30 23:51:02 +00001924 ++NumDeleted;
1925 }
1926 }
1927
1928 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001929
Chris Lattner33312f72002-11-08 01:21:07 +00001930 // Track the number of call nodes merged away...
Chris Lattnera9548d92005-01-30 23:51:02 +00001931 NumCallNodesMerged += NumDeleted;
Chris Lattner33312f72002-11-08 01:21:07 +00001932
Bill Wendling5294fb02006-11-17 07:33:59 +00001933 if (NumDeleted)
1934 DOUT << "Merged " << NumDeleted << " call nodes.\n";
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001935}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001936
Chris Lattneraa8146f2002-11-10 06:59:55 +00001937
Chris Lattnere2219762002-07-18 18:22:40 +00001938// removeTriviallyDeadNodes - After the graph has been constructed, this method
1939// removes all unreachable nodes that are created because they got merged with
1940// other nodes in the graph. These nodes will all be trivially unreachable, so
1941// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001942//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001943void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001944 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001945
Chris Lattner5ace1e42004-07-08 07:25:51 +00001946#if 0
1947 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1948 /// substantially!
1949
Chris Lattnerbab8c282003-09-20 21:34:07 +00001950 // Loop over all of the nodes in the graph, calling getNode on each field.
1951 // This will cause all nodes to update their forwarding edges, causing
1952 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001953 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001954 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
Chris Lattner84b80a22005-03-16 22:42:19 +00001955 DSNode &N = *NI;
1956 for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1957 N.getLink(l*N.getPointerSize()).getNode();
Chris Lattnerbab8c282003-09-20 21:34:07 +00001958 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001959 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001960
Chris Lattner0b144872004-01-27 22:03:40 +00001961 // NOTE: This code is disabled. Though it should, in theory, allow us to
1962 // remove more nodes down below, the scan of the scalar map is incredibly
1963 // expensive for certain programs (with large SCCs). In the future, if we can
1964 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001965 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1966
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001967 // Likewise, forward any edges from the scalar nodes. While we are at it,
1968 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001969 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001970 I->second.getNode();
1971 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001972 }
Chris Lattner0b144872004-01-27 22:03:40 +00001973 }
1974#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001975 bool isGlobalsGraph = !GlobalsGraph;
1976
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001977 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001978 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001979
1980 // Do not remove *any* global nodes in the globals graph.
1981 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001982 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001983 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001984 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001985 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001986
Chris Lattner28897e12004-02-08 00:53:26 +00001987 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001988 // This is a useless node if it has no mod/ref info (checked above),
1989 // outgoing edges (which it cannot, as it is not modified in this
1990 // context), and it has no incoming edges. If it is a global node it may
1991 // have all of these properties and still have incoming edges, due to the
1992 // scalar map, so we check those now.
1993 //
Chris Lattner82c6c722005-03-20 02:41:38 +00001994 if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1995 const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
Chris Lattner72d29a42003-02-11 23:11:51 +00001996
Chris Lattner17a93e22004-01-29 03:32:15 +00001997 // Loop through and make sure all of the globals are referring directly
1998 // to the node...
1999 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
2000 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00002001 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00002002 }
2003
Chris Lattnerbd92b732003-06-19 21:15:11 +00002004 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00002005 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00002006 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
2007 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00002008 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002009 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00002010 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002011 }
2012 }
2013
Chris Lattner28897e12004-02-08 00:53:26 +00002014 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00002015 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00002016 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002017 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00002018 } else {
2019 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002020 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002021 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002022
2023 removeIdenticalCalls(FunctionCalls);
2024 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00002025}
2026
2027
Chris Lattner5c7380e2003-01-29 21:10:20 +00002028/// markReachableNodes - This method recursively traverses the specified
2029/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
2030/// to the set, which allows it to only traverse visited nodes once.
2031///
Chris Lattnera9548d92005-01-30 23:51:02 +00002032void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00002033 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00002034 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00002035 if (ReachableNodes.insert(this).second) // Is newly reachable?
Chris Lattner6be07942005-02-09 03:20:43 +00002036 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
2037 I != E; ++I)
2038 I->getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00002039}
2040
Chris Lattnera9548d92005-01-30 23:51:02 +00002041void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00002042 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00002043 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002044
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002045 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
2046 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00002047}
2048
Chris Lattnera1220af2003-02-01 06:17:02 +00002049// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
2050// looking for a node that is marked alive. If an alive node is found, return
2051// true, otherwise return false. If an alive node is reachable, this node is
2052// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00002053//
Chris Lattnera9548d92005-01-30 23:51:02 +00002054static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
2055 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00002056 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002057 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00002058 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002059
Chris Lattner85cfe012003-07-03 02:03:53 +00002060 // If this is a global node, it will end up in the globals graph anyway, so we
2061 // don't need to worry about it.
2062 if (IgnoreGlobals && N->isGlobalNode()) return false;
2063
Chris Lattneraa8146f2002-11-10 06:59:55 +00002064 // If we know that this node is alive, return so!
2065 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002066
Chris Lattneraa8146f2002-11-10 06:59:55 +00002067 // Otherwise, we don't think the node is alive yet, check for infinite
2068 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00002069 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00002070 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00002071
Chris Lattner6be07942005-02-09 03:20:43 +00002072 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
2073 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00002074 N->markReachableNodes(Alive);
2075 return true;
2076 }
2077 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002078}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002079
Chris Lattnera1220af2003-02-01 06:17:02 +00002080// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
2081// alive nodes.
2082//
Chris Lattnera9548d92005-01-30 23:51:02 +00002083static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
2084 hash_set<const DSNode*> &Alive,
2085 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00002086 bool IgnoreGlobals) {
2087 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
2088 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00002089 return true;
2090 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00002091 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002092 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002093 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00002094 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
2095 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002096 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002097 return false;
2098}
2099
Chris Lattnere2219762002-07-18 18:22:40 +00002100// removeDeadNodes - Use a more powerful reachability analysis to eliminate
2101// subgraphs that are unreachable. This often occurs because the data
2102// structure doesn't "escape" into it's caller, and thus should be eliminated
2103// from the caller's graph entirely. This is only appropriate to use when
2104// inlining graphs.
2105//
Chris Lattner394471f2003-01-23 22:05:33 +00002106void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00002107 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00002108
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002109 // Reduce the amount of work we have to do... remove dummy nodes left over by
2110 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00002111 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002112
Chris Lattner93ddd7e2004-01-22 16:36:28 +00002113 TIME_REGION(X, "removeDeadNodes");
2114
Misha Brukman2f2d0652003-09-11 18:14:24 +00002115 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00002116
2117 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattnera9548d92005-01-30 23:51:02 +00002118 hash_set<const DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002119 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00002120
Chris Lattner0b144872004-01-27 22:03:40 +00002121 // Copy and merge all information about globals to the GlobalsGraph if this is
2122 // not a final pass (where unreachable globals are removed).
2123 //
2124 // Strip all alloca bits since the current function is only for the BU pass.
2125 // Strip all incomplete bits since they are short-lived properties and they
2126 // will be correctly computed when rematerializing nodes into the functions.
2127 //
2128 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
2129 DSGraph::StripIncompleteBit);
2130
Chris Lattneraa8146f2002-11-10 06:59:55 +00002131 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattnerf4f62272005-03-19 22:23:45 +00002132{ TIME_REGION(Y, "removeDeadNodes:scalarscan");
2133 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
2134 I != E; ++I)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002135 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00002136 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002137 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002138 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00002139
2140 // Make sure that all globals are cloned over as roots.
Chris Lattner021decc2005-04-02 19:17:18 +00002141 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && GlobalsGraph) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002142 DSGraph::ScalarMapTy::iterator SMI =
Chris Lattner00948c02004-01-28 02:05:05 +00002143 GlobalsGraph->getScalarMap().find(I->first);
2144 if (SMI != GlobalsGraph->getScalarMap().end())
2145 GGCloner.merge(SMI->second, I->second);
2146 else
2147 GGCloner.getClonedNH(I->second);
2148 }
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002149 } else {
Chris Lattnerf4f62272005-03-19 22:23:45 +00002150 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002151 }
Chris Lattnerf4f62272005-03-19 22:23:45 +00002152}
Chris Lattnere2219762002-07-18 18:22:40 +00002153
Chris Lattner0b144872004-01-27 22:03:40 +00002154 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00002155 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
2156 I != E; ++I)
2157 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002158
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002159 // Mark any nodes reachable by primary calls as alive...
Chris Lattnera9548d92005-01-30 23:51:02 +00002160 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2161 I->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002162
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002163
2164 // Now find globals and aux call nodes that are already live or reach a live
2165 // value (which makes them live in turn), and continue till no more are found.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002166 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002167 bool Iterate;
Chris Lattnera9548d92005-01-30 23:51:02 +00002168 hash_set<const DSNode*> Visited;
2169 hash_set<const DSCallSite*> AuxFCallsAlive;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002170 do {
2171 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00002172 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00002173 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002174 // unreachable globals in the list.
2175 //
2176 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002177 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00002178 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002179 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
Chris Lattner0b144872004-01-27 22:03:40 +00002180 Flags & DSGraph::RemoveUnreachableGlobals)) {
2181 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
2182 GlobalNodes.pop_back(); // erase efficiently
2183 Iterate = true;
2184 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002185
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002186 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
2187 // call nodes that get resolved will be difficult to remove from that graph.
2188 // The final unresolved call nodes must be handled specially at the end of
2189 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattnera9548d92005-01-30 23:51:02 +00002190 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
Chris Lattnerd7642c42005-02-24 18:48:07 +00002191 if (!AuxFCallsAlive.count(&*CI) &&
Chris Lattnera9548d92005-01-30 23:51:02 +00002192 (CI->isIndirectCall()
2193 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002194 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattnera9548d92005-01-30 23:51:02 +00002195 CI->markReachableNodes(Alive);
Chris Lattnerd7642c42005-02-24 18:48:07 +00002196 AuxFCallsAlive.insert(&*CI);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002197 Iterate = true;
2198 }
2199 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00002200
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002201 // Move dead aux function calls to the end of the list
Chris Lattnera9548d92005-01-30 23:51:02 +00002202 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
2203 E = AuxFunctionCalls.end(); CI != E; )
2204 if (AuxFCallsAlive.count(&*CI))
2205 ++CI;
2206 else {
2207 // Copy and merge global nodes and dead aux call nodes into the
2208 // GlobalsGraph, and all nodes reachable from those nodes. Update their
2209 // target pointers using the GGCloner.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002210 //
Chris Lattnera9548d92005-01-30 23:51:02 +00002211 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2212 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002213
Chris Lattnera9548d92005-01-30 23:51:02 +00002214 AuxFunctionCalls.erase(CI++);
2215 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002216
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002217 // We are finally done with the GGCloner so we can destroy it.
2218 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002219
Vikram S. Adve40c600e2003-07-22 12:08:58 +00002220 // At this point, any nodes which are visited, but not alive, are nodes
2221 // which can be removed. Loop over all nodes, eliminating completely
2222 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002223 //
Chris Lattner72d29a42003-02-11 23:11:51 +00002224 std::vector<DSNode*> DeadNodes;
2225 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00002226 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2227 DSNode *N = NI++;
2228 assert(!N->isForwarding() && "Forwarded node in nodes list?");
2229
2230 if (!Alive.count(N)) {
2231 Nodes.remove(N);
2232 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002233 DeadNodes.push_back(N);
2234 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00002235 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00002236 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00002237 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002238
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002239 // Remove all unreachable globals from the ScalarMap.
2240 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2241 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00002242 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002243 if (!Alive.count(GlobalNodes[i].second))
2244 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00002245 else
2246 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002247
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002248 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00002249 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2250 delete DeadNodes[i];
2251
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002252 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00002253}
2254
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002255void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
Chris Lattner82c6c722005-03-20 02:41:38 +00002256 assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2257 N->globals_end() && "Global value not in node!");
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002258}
2259
Chris Lattner2c7725a2004-03-03 20:55:27 +00002260void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2261 if (CS.isIndirectCall()) {
2262 AssertNodeInGraph(CS.getCalleeNode());
2263#if 0
2264 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2265 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
Bill Wendling5294fb02006-11-17 07:33:59 +00002266 DOUT << "WARNING: WEIRD CALL SITE FOUND!\n";
Chris Lattner2c7725a2004-03-03 20:55:27 +00002267#endif
2268 }
2269 AssertNodeInGraph(CS.getRetVal().getNode());
2270 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2271 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2272}
2273
2274void DSGraph::AssertCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002275 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2276 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002277}
2278void DSGraph::AssertAuxCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002279 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2280 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002281}
2282
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002283void DSGraph::AssertGraphOK() const {
Chris Lattner84b80a22005-03-16 22:42:19 +00002284 for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2285 NI->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00002286
Chris Lattner8d327672003-06-30 03:36:09 +00002287 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002288 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00002289 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002290 AssertNodeInGraph(I->second.getNode());
2291 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00002292 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002293 "Global points to node, but node isn't global?");
2294 AssertNodeContainsGlobal(I->second.getNode(), GV);
2295 }
2296 }
2297 AssertCallNodesInGraph();
2298 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00002299
2300 // Check that all pointer arguments to any functions in this graph have
2301 // destinations.
2302 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2303 E = ReturnNodes.end();
2304 RI != E; ++RI) {
2305 Function &F = *RI->first;
Chris Lattnere4d5c442005-03-15 04:54:21 +00002306 for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
Chris Lattner7d8d4712004-10-31 17:45:40 +00002307 if (isPointerType(AI->getType()))
2308 assert(!getNodeForValue(AI).isNull() &&
2309 "Pointer argument must be in the scalar map!");
2310 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002311}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002312
Chris Lattner400433d2003-11-11 05:08:59 +00002313/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00002314/// nodes reachable from the two graphs, computing the mapping of nodes from the
2315/// first to the second graph. This mapping may be many-to-one (i.e. the first
2316/// graph may have multiple nodes representing one node in the second graph),
2317/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00002318///
2319void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00002320 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2321 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00002322 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2323 if (N1 == 0 || N2 == 0) return;
2324
2325 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002326 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002327 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002328 if (StrictChecking) {
2329 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2330 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2331 Entry.getNode()->isNodeCompletelyFolded()) &&
2332 "Inconsistent mapping detected!");
2333 }
Chris Lattner400433d2003-11-11 05:08:59 +00002334 return;
2335 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002336
Chris Lattnerefffdc92004-07-07 06:12:52 +00002337 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002338
2339 // Loop over all of the fields that N1 and N2 have in common, recursively
2340 // mapping the edges together now.
2341 int N2Idx = NH2.getOffset()-NH1.getOffset();
2342 unsigned N2Size = N2->getSize();
Chris Lattner841957e2005-03-15 04:40:24 +00002343 if (N2Size == 0) return; // No edges to map to.
2344
Chris Lattner4d5af8e2005-03-15 21:36:50 +00002345 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2346 const DSNodeHandle &N1NH = N1->getLink(i);
2347 // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2348 // aligned right).
2349 if (!N1NH.isNull()) {
2350 if (unsigned(N2Idx)+i < N2Size)
2351 computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2352 else
2353 computeNodeMapping(N1NH,
2354 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2355 }
2356 }
Chris Lattner400433d2003-11-11 05:08:59 +00002357}
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002358
2359
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002360/// computeGToGGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002361/// nodes in this graph.
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002362void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002363 DSGraph &GG = *getGlobalsGraph();
2364
2365 DSScalarMap &SM = getScalarMap();
2366 for (DSScalarMap::global_iterator I = SM.global_begin(),
2367 E = SM.global_end(); I != E; ++I)
2368 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2369}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002370
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002371/// computeGGToGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002372/// nodes in this graph. Note that any uses of this method are probably bugs,
2373/// unless it is known that the globals graph has been merged into this graph!
2374void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2375 NodeMapTy NodeMap;
2376 computeGToGGMapping(NodeMap);
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002377
Chris Lattner36a13cd2005-03-15 17:52:18 +00002378 while (!NodeMap.empty()) {
2379 InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2380 NodeMap.begin()->first));
2381 NodeMap.erase(NodeMap.begin());
2382 }
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002383}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002384
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002385
2386/// computeCalleeCallerMapping - Given a call from a function in the current
2387/// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2388/// mapping of nodes from the callee to nodes in the caller.
2389void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2390 DSGraph &CalleeGraph,
2391 NodeMapTy &NodeMap) {
2392
2393 DSCallSite CalleeArgs =
2394 CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002395
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002396 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2397
2398 unsigned NumArgs = CS.getNumPtrArgs();
2399 if (NumArgs > CalleeArgs.getNumPtrArgs())
2400 NumArgs = CalleeArgs.getNumPtrArgs();
2401
2402 for (unsigned i = 0; i != NumArgs; ++i)
2403 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002404
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002405 // Map the nodes that are pointed to by globals.
2406 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2407 DSScalarMap &CallerSM = getScalarMap();
2408
2409 if (CalleeSM.global_size() >= CallerSM.global_size()) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002410 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002411 E = CallerSM.global_end(); GI != E; ++GI)
2412 if (CalleeSM.global_count(*GI))
2413 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2414 } else {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002415 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002416 E = CalleeSM.global_end(); GI != E; ++GI)
2417 if (CallerSM.global_count(*GI))
2418 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2419 }
2420}
Andrew Lenharth37705002006-06-19 15:42:47 +00002421
2422/// updateFromGlobalGraph - This function rematerializes global nodes and
2423/// nodes reachable from them from the globals graph into the current graph.
2424///
2425void DSGraph::updateFromGlobalGraph() {
2426 TIME_REGION(X, "updateFromGlobalGraph");
2427 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
2428
2429 // Clone the non-up-to-date global nodes into this graph.
2430 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
2431 E = getScalarMap().global_end(); I != E; ++I) {
2432 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
2433 if (It != GlobalsGraph->ScalarMap.end())
2434 RC.merge(getNodeForValue(*I), It->second);
2435 }
2436}