blob: 666b615825b3dded90512db57515eb8838691630 [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 Lattner0d9bab82002-07-18 00:12:30 +000029#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Chris Lattnerb29dd0f2004-12-08 21:03:56 +000032#define COLLAPSE_ARRAYS_AGGRESSIVELY 0
33
Chris Lattner08db7192002-11-06 06:20:27 +000034namespace {
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000035 Statistic NumFolds ("dsa", "Number of nodes completely folded");
36 Statistic NumCallNodesMerged("dsa", "Number of call nodes merged");
37 Statistic NumNodeAllocated ("dsa", "Number of nodes allocated");
38 Statistic NumDNE ("dsa", "Number of nodes removed by reachability");
39 Statistic NumTrivialDNE ("dsa", "Number of nodes trivially removed");
40 Statistic NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Andrew Lenharth0c3a0b62006-03-15 05:43:41 +000041 static cl::opt<unsigned>
42 DSAFieldLimit("dsa-field-limit", cl::Hidden,
43 cl::desc("Number of fields to track before collapsing a node"),
44 cl::init(256));
Chris Lattnerd74ea2b2006-05-24 17:04:05 +000045}
Chris Lattner08db7192002-11-06 06:20:27 +000046
Chris Lattner1e9d1472005-03-22 23:54:52 +000047#if 0
Chris Lattner93ddd7e2004-01-22 16:36:28 +000048#define TIME_REGION(VARNAME, DESC) \
49 NamedRegionTimer VARNAME(DESC)
50#else
51#define TIME_REGION(VARNAME, DESC)
52#endif
53
Chris Lattnerb1060432002-11-07 05:20:53 +000054using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000055
Chris Lattner6f967742004-10-30 04:05:01 +000056/// isForwarding - Return true if this NodeHandle is forwarding to another
57/// one.
58bool DSNodeHandle::isForwarding() const {
59 return N && N->isForwarding();
60}
61
Chris Lattner731b2d72003-02-13 19:09:00 +000062DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000063 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Andrew Lenharthdf983de2006-11-07 20:36:02 +000064 DEBUG(
65 { //assert not looping
66 DSNode* NH = N;
67 std::set<DSNode*> seen;
68 while(NH && NH->isForwarding()) {
69 assert(seen.find(NH) == seen.end() && "Loop detected");
70 seen.insert(NH);
71 NH = NH->ForwardNH.N;
72 }
73 }
74 );
Chris Lattner731b2d72003-02-13 19:09:00 +000075 // Handle node forwarding here!
76 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
77 Offset += N->ForwardNH.getOffset();
78
79 if (--N->NumReferrers == 0) {
80 // Removing the last referrer to the node, sever the forwarding link
81 N->stopForwarding();
82 }
83
84 N = Next;
85 N->NumReferrers++;
86 if (N->Size <= Offset) {
87 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
88 Offset = 0;
89 }
90 return N;
91}
92
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000093//===----------------------------------------------------------------------===//
Chris Lattner612f0b72005-03-22 00:09:45 +000094// DSScalarMap Implementation
95//===----------------------------------------------------------------------===//
96
97DSNodeHandle &DSScalarMap::AddGlobal(GlobalValue *GV) {
98 assert(ValueMap.count(GV) == 0 && "GV already exists!");
99
100 // If the node doesn't exist, check to see if it's a global that is
101 // equated to another global in the program.
102 EquivalenceClasses<GlobalValue*>::iterator ECI = GlobalECs.findValue(GV);
103 if (ECI != GlobalECs.end()) {
104 GlobalValue *Leader = *GlobalECs.findLeader(ECI);
105 if (Leader != GV) {
106 GV = Leader;
107 iterator I = ValueMap.find(GV);
108 if (I != ValueMap.end())
109 return I->second;
110 }
111 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000112
Chris Lattner612f0b72005-03-22 00:09:45 +0000113 // Okay, this is either not an equivalenced global or it is the leader, it
114 // will be inserted into the scalar map now.
115 GlobalSet.insert(GV);
116
117 return ValueMap.insert(std::make_pair(GV, DSNodeHandle())).first->second;
118}
119
120
121//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000122// DSNode Implementation
123//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000124
Chris Lattnerbd92b732003-06-19 21:15:11 +0000125DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +0000126 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000127 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +0000128 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +0000129 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000130 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000131}
132
Chris Lattner0d9bab82002-07-18 00:12:30 +0000133// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +0000134DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +0000135 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattneraf2e3e02005-04-12 03:59:27 +0000136 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattnerf590ced2004-03-04 17:06:53 +0000137 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +0000138 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +0000139 } else
Chris Lattner0b144872004-01-27 22:03:40 +0000140 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +0000141 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000142 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000143}
144
Chris Lattner15869aa2003-11-02 22:27:28 +0000145/// getTargetData - Get the target data object used to construct this node.
146///
147const TargetData &DSNode::getTargetData() const {
148 return ParentGraph->getTargetData();
149}
150
Chris Lattner72d29a42003-02-11 23:11:51 +0000151void DSNode::assertOK() const {
152 assert((Ty != Type::VoidTy ||
153 Ty == Type::VoidTy && (Size == 0 ||
154 (NodeType & DSNode::Array))) &&
155 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000156
157 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000158 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000159 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000160 assert(SM.global_count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000161 assert(SM.find(Globals[i])->second.getNode() == this);
162 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000163}
164
165/// forwardNode - Mark this node as being obsolete, and all references to it
166/// should be forwarded to the specified node and offset.
167///
168void DSNode::forwardNode(DSNode *To, unsigned Offset) {
169 assert(this != To && "Cannot forward a node to itself!");
170 assert(ForwardNH.isNull() && "Already forwarding from this node!");
171 if (To->Size <= 1) Offset = 0;
172 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
173 "Forwarded offset is wrong!");
Chris Lattnerefffdc92004-07-07 06:12:52 +0000174 ForwardNH.setTo(To, Offset);
Chris Lattner72d29a42003-02-11 23:11:51 +0000175 NodeType = DEAD;
176 Size = 0;
177 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000178
179 // Remove this node from the parent graph's Nodes list.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000180 ParentGraph->unlinkNode(this);
Chris Lattner4ff0b962004-02-08 01:27:18 +0000181 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000182}
183
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000184// addGlobal - Add an entry for a global value to the Globals list. This also
185// marks the node with the 'G' flag if it does not already have it.
186//
187void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000188 // First, check to make sure this is the leader if the global is in an
189 // equivalence class.
190 GV = getParentGraph()->getScalarMap().getLeaderForGlobal(GV);
191
Chris Lattner0d9bab82002-07-18 00:12:30 +0000192 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000193 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000194 std::lower_bound(Globals.begin(), Globals.end(), GV);
195
196 if (I == Globals.end() || *I != GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000197 Globals.insert(I, GV);
198 NodeType |= GlobalNode;
199 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000200}
201
Chris Lattner7cdf3212005-03-20 03:29:54 +0000202// removeGlobal - Remove the specified global that is explicitly in the globals
203// list.
204void DSNode::removeGlobal(GlobalValue *GV) {
205 std::vector<GlobalValue*>::iterator I =
206 std::lower_bound(Globals.begin(), Globals.end(), GV);
207 assert(I != Globals.end() && *I == GV && "Global not in node!");
208 Globals.erase(I);
209}
210
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000211/// foldNodeCompletely - If we determine that this node has some funny
212/// behavior happening to it that we cannot represent, we fold it down to a
213/// single, completely pessimistic, node. This node is represented as a
214/// single byte with a single TypeEntry of "void".
215///
216void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000217 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000218
Chris Lattner08db7192002-11-06 06:20:27 +0000219 ++NumFolds;
220
Chris Lattner0b144872004-01-27 22:03:40 +0000221 // If this node has a size that is <= 1, we don't need to create a forwarding
222 // node.
223 if (getSize() <= 1) {
224 NodeType |= DSNode::Array;
225 Ty = Type::VoidTy;
226 Size = 1;
227 assert(Links.size() <= 1 && "Size is 1, but has more links?");
228 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000229 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000230 // Create the node we are going to forward to. This is required because
231 // some referrers may have an offset that is > 0. By forcing them to
232 // forward, the forwarder has the opportunity to correct the offset.
233 DSNode *DestNode = new DSNode(0, ParentGraph);
234 DestNode->NodeType = NodeType|DSNode::Array;
235 DestNode->Ty = Type::VoidTy;
236 DestNode->Size = 1;
237 DestNode->Globals.swap(Globals);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000238
Chris Lattner0b144872004-01-27 22:03:40 +0000239 // Start forwarding to the destination node...
240 forwardNode(DestNode, 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000241
Chris Lattner0b144872004-01-27 22:03:40 +0000242 if (!Links.empty()) {
243 DestNode->Links.reserve(1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000244
Chris Lattner0b144872004-01-27 22:03:40 +0000245 DSNodeHandle NH(DestNode);
246 DestNode->Links.push_back(Links[0]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000247
Chris Lattner0b144872004-01-27 22:03:40 +0000248 // If we have links, merge all of our outgoing links together...
249 for (unsigned i = Links.size()-1; i != 0; --i)
250 NH.getNode()->Links[0].mergeWith(Links[i]);
251 Links.clear();
252 } else {
253 DestNode->Links.resize(1);
254 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000255 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000256}
Chris Lattner076c1f92002-11-07 06:31:54 +0000257
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000258/// isNodeCompletelyFolded - Return true if this node has been completely
259/// folded down to something that can never be expanded, effectively losing
260/// all of the field sensitivity that may be present in the node.
261///
262bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000263 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000264}
265
Chris Lattner82c6c722005-03-20 02:41:38 +0000266/// addFullGlobalsList - Compute the full set of global values that are
267/// represented by this node. Unlike getGlobalsList(), this requires fair
268/// amount of work to compute, so don't treat this method call as free.
269void DSNode::addFullGlobalsList(std::vector<GlobalValue*> &List) const {
270 if (globals_begin() == globals_end()) return;
271
272 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
273
274 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
275 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
276 if (ECI == EC.end())
277 List.push_back(*I);
278 else
279 List.insert(List.end(), EC.member_begin(ECI), EC.member_end());
280 }
281}
282
283/// addFullFunctionList - Identical to addFullGlobalsList, but only return the
284/// functions in the full list.
285void DSNode::addFullFunctionList(std::vector<Function*> &List) const {
286 if (globals_begin() == globals_end()) return;
287
288 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
289
290 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
291 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
292 if (ECI == EC.end()) {
293 if (Function *F = dyn_cast<Function>(*I))
294 List.push_back(F);
295 } else {
296 for (EquivalenceClasses<GlobalValue*>::member_iterator MI =
297 EC.member_begin(ECI), E = EC.member_end(); MI != E; ++MI)
298 if (Function *F = dyn_cast<Function>(*MI))
299 List.push_back(F);
300 }
301 }
302}
303
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000304namespace {
305 /// TypeElementWalker Class - Used for implementation of physical subtyping...
306 ///
307 class TypeElementWalker {
308 struct StackState {
309 const Type *Ty;
310 unsigned Offset;
311 unsigned Idx;
312 StackState(const Type *T, unsigned Off = 0)
313 : Ty(T), Offset(Off), Idx(0) {}
314 };
315
316 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000317 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000318 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000319 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000320 Stack.push_back(T);
321 StepToLeaf();
322 }
323
324 bool isDone() const { return Stack.empty(); }
325 const Type *getCurrentType() const { return Stack.back().Ty; }
326 unsigned getCurrentOffset() const { return Stack.back().Offset; }
327
328 void StepToNextType() {
329 PopStackAndAdvance();
330 StepToLeaf();
331 }
332
333 private:
334 /// PopStackAndAdvance - Pop the current element off of the stack and
335 /// advance the underlying element to the next contained member.
336 void PopStackAndAdvance() {
337 assert(!Stack.empty() && "Cannot pop an empty stack!");
338 Stack.pop_back();
339 while (!Stack.empty()) {
340 StackState &SS = Stack.back();
341 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
342 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000343 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000344 const StructLayout *SL = TD.getStructLayout(ST);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000345 SS.Offset +=
Chris Lattner507bdf92005-01-12 04:51:37 +0000346 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000347 return;
348 }
349 Stack.pop_back(); // At the end of the structure
350 } else {
351 const ArrayType *AT = cast<ArrayType>(SS.Ty);
352 ++SS.Idx;
353 if (SS.Idx != AT->getNumElements()) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000354 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000355 return;
356 }
357 Stack.pop_back(); // At the end of the array
358 }
359 }
360 }
361
362 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
363 /// on the type stack.
364 void StepToLeaf() {
365 if (Stack.empty()) return;
366 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
367 StackState &SS = Stack.back();
368 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000369 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000370 assert(SS.Idx == 0);
371 PopStackAndAdvance();
372 } else {
373 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000374 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000375 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000376 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner507bdf92005-01-12 04:51:37 +0000377 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000378 }
379 } else {
380 const ArrayType *AT = cast<ArrayType>(SS.Ty);
381 if (AT->getNumElements() == 0) {
382 assert(SS.Idx == 0);
383 PopStackAndAdvance();
384 } else {
385 // Step into the array...
386 assert(SS.Idx < AT->getNumElements());
387 Stack.push_back(StackState(AT->getElementType(),
388 SS.Offset+SS.Idx*
Chris Lattner507bdf92005-01-12 04:51:37 +0000389 unsigned(TD.getTypeSize(AT->getElementType()))));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000390 }
391 }
392 }
393 }
394 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000395} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000396
397/// ElementTypesAreCompatible - Check to see if the specified types are
398/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000399/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
400/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000401///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000402static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000403 bool AllowLargerT1, const TargetData &TD){
404 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000405
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000406 while (!T1W.isDone() && !T2W.isDone()) {
407 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
408 return false;
409
410 const Type *T1 = T1W.getCurrentType();
411 const Type *T2 = T2W.getCurrentType();
Reid Spencer3da59db2006-11-27 01:05:10 +0000412 if (T1 != T2 && !T1->canLosslesslyBitCastTo(T2))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000413 return false;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000414
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000415 T1W.StepToNextType();
416 T2W.StepToNextType();
417 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000418
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000419 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000420}
421
422
Chris Lattner08db7192002-11-06 06:20:27 +0000423/// mergeTypeInfo - This method merges the specified type into the current node
424/// at the specified offset. This may update the current node's type record if
425/// this gives more information to the node, it may do nothing to the node if
426/// this information is already known, or it may merge the node completely (and
427/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000428///
Chris Lattner08db7192002-11-06 06:20:27 +0000429/// This method returns true if the node is completely folded, otherwise false.
430///
Chris Lattner088b6392003-03-03 17:13:31 +0000431bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
432 bool FoldIfIncompatible) {
Bill Wendling5294fb02006-11-17 07:33:59 +0000433 DOUT << "merging " << *NewTy << " at " << Offset << " with " << *Ty << "\n";
Chris Lattner15869aa2003-11-02 22:27:28 +0000434 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000435 // Check to make sure the Size member is up-to-date. Size can be one of the
436 // following:
437 // Size = 0, Ty = Void: Nothing is known about this node.
438 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
439 // Size = 1, Ty = Void, Array = 1: The node is collapsed
440 // Otherwise, sizeof(Ty) = Size
441 //
Chris Lattner18552922002-11-18 21:44:46 +0000442 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
443 (Size == 0 && !Ty->isSized() && !isArray()) ||
444 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
445 (Size == 0 && !Ty->isSized() && !isArray()) ||
446 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000447 "Size member of DSNode doesn't match the type structure!");
448 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000449
Chris Lattner18552922002-11-18 21:44:46 +0000450 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000451 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000452
Chris Lattner08db7192002-11-06 06:20:27 +0000453 // Return true immediately if the node is completely folded.
454 if (isNodeCompletelyFolded()) return true;
455
Chris Lattner23f83dc2002-11-08 22:49:57 +0000456 // If this is an array type, eliminate the outside arrays because they won't
457 // be used anyway. This greatly reduces the size of large static arrays used
458 // as global variables, for example.
459 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000460 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000461 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
462 // FIXME: we might want to keep small arrays, but must be careful about
463 // things like: [2 x [10000 x int*]]
464 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000465 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000466 }
467
Chris Lattner08db7192002-11-06 06:20:27 +0000468 // Figure out how big the new type we're merging in is...
Chris Lattner507bdf92005-01-12 04:51:37 +0000469 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000470
471 // Otherwise check to see if we can fold this type into the current node. If
472 // we can't, we fold the node completely, if we can, we potentially update our
473 // internal state.
474 //
Chris Lattner18552922002-11-18 21:44:46 +0000475 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000476 // If this is the first type that this node has seen, just accept it without
477 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000478 assert(Offset == 0 && !isArray() &&
479 "Cannot have an offset into a void node!");
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000480
481 // If this node would have to have an unreasonable number of fields, just
482 // collapse it. This can occur for fortran common blocks, which have stupid
483 // things like { [100000000 x double], [1000000 x double] }.
484 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
Andrew Lenharth0c3a0b62006-03-15 05:43:41 +0000485 if (NumFields > DSAFieldLimit) {
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000486 foldNodeCompletely();
487 return true;
488 }
489
Chris Lattner18552922002-11-18 21:44:46 +0000490 Ty = NewTy;
491 NodeType &= ~Array;
492 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000493 Size = NewTySize;
494
495 // Calculate the number of outgoing links from this node.
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000496 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000497 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000498 }
Chris Lattner08db7192002-11-06 06:20:27 +0000499
500 // Handle node expansion case here...
501 if (Offset+NewTySize > Size) {
502 // It is illegal to grow this node if we have treated it as an array of
503 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000504 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000505 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000506 return true;
507 }
508
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000509 // If this node would have to have an unreasonable number of fields, just
510 // collapse it. This can occur for fortran common blocks, which have stupid
511 // things like { [100000000 x double], [1000000 x double] }.
512 unsigned NumFields = (NewTySize+Offset+DS::PointerSize-1) >> DS::PointerShift;
Andrew Lenharth0c3a0b62006-03-15 05:43:41 +0000513 if (NumFields > DSAFieldLimit) {
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000514 foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000515 return true;
516 }
517
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000518 if (Offset) {
519 //handle some common cases:
520 // Ty: struct { t1, t2, t3, t4, ..., tn}
521 // NewTy: struct { offset, stuff...}
Bill Wendling5294fb02006-11-17 07:33:59 +0000522 // try merge with NewTy: struct {t1, t2, stuff...} if offset lands exactly
523 // on a field in Ty
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000524 if (isa<StructType>(NewTy) && isa<StructType>(Ty)) {
Bill Wendling5294fb02006-11-17 07:33:59 +0000525 DOUT << "Ty: " << *Ty << "\nNewTy: " << *NewTy << "@" << Offset << "\n";
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000526 const StructType *STy = cast<StructType>(Ty);
527 const StructLayout &SL = *TD.getStructLayout(STy);
528 unsigned i = SL.getElementContainingOffset(Offset);
529 //Either we hit it exactly or give up
530 if (SL.MemberOffsets[i] != Offset) {
531 if (FoldIfIncompatible) foldNodeCompletely();
532 return true;
533 }
534 std::vector<const Type*> nt;
535 for (unsigned x = 0; x < i; ++x)
536 nt.push_back(STy->getElementType(x));
537 STy = cast<StructType>(NewTy);
538 nt.insert(nt.end(), STy->element_begin(), STy->element_end());
539 //and merge
540 STy = StructType::get(nt);
Bill Wendling5294fb02006-11-17 07:33:59 +0000541 DOUT << "Trying with: " << *STy << "\n";
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000542 return mergeTypeInfo(STy, 0);
543 }
544
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000545 //Ty: struct { t1, t2, t3 ... tn}
546 //NewTy T offset x
Bill Wendling5294fb02006-11-17 07:33:59 +0000547 //try merge with NewTy: struct : {t1, t2, T} if offset lands on a field
548 //in Ty
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000549 if (isa<StructType>(Ty)) {
Bill Wendling5294fb02006-11-17 07:33:59 +0000550 DOUT << "Ty: " << *Ty << "\nNewTy: " << *NewTy << "@" << Offset << "\n";
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000551 const StructType *STy = cast<StructType>(Ty);
552 const StructLayout &SL = *TD.getStructLayout(STy);
553 unsigned i = SL.getElementContainingOffset(Offset);
554 //Either we hit it exactly or give up
555 if (SL.MemberOffsets[i] != Offset) {
556 if (FoldIfIncompatible) foldNodeCompletely();
557 return true;
558 }
559 std::vector<const Type*> nt;
560 for (unsigned x = 0; x < i; ++x)
561 nt.push_back(STy->getElementType(x));
562 nt.push_back(NewTy);
563 //and merge
564 STy = StructType::get(nt);
Bill Wendling5294fb02006-11-17 07:33:59 +0000565 DOUT << "Trying with: " << *STy << "\n";
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000566 return mergeTypeInfo(STy, 0);
567 }
568
Bill Wendling5294fb02006-11-17 07:33:59 +0000569 assert(0 &&
570 "UNIMP: Trying to merge a growth type into "
571 "offset != 0: Collapsing!");
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000572 abort();
573 if (FoldIfIncompatible) foldNodeCompletely();
574 return true;
575
576 }
577
578
Chris Lattner08db7192002-11-06 06:20:27 +0000579 // Okay, the situation is nice and simple, we are trying to merge a type in
580 // at offset 0 that is bigger than our current type. Implement this by
581 // switching to the new type and then merge in the smaller one, which should
582 // hit the other code path here. If the other code path decides it's not
583 // ok, it will collapse the node as appropriate.
584 //
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000585
Chris Lattner94f84702005-03-17 19:56:56 +0000586 const Type *OldTy = Ty;
587 Ty = NewTy;
588 NodeType &= ~Array;
589 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000590 Size = NewTySize;
591
592 // Must grow links to be the appropriate size...
Chris Lattner94f84702005-03-17 19:56:56 +0000593 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000594
595 // Merge in the old type now... which is guaranteed to be smaller than the
596 // "current" type.
597 return mergeTypeInfo(OldTy, 0);
598 }
599
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000600 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000601 "Cannot merge something into a part of our type that doesn't exist!");
602
Chris Lattner18552922002-11-18 21:44:46 +0000603 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000604 // type that starts at offset Offset.
605 //
606 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000607 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000608 while (O < Offset) {
609 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
610
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000611 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000612 case Type::StructTyID: {
613 const StructType *STy = cast<StructType>(SubType);
614 const StructLayout &SL = *TD.getStructLayout(STy);
Chris Lattner2787e032005-03-13 19:05:05 +0000615 unsigned i = SL.getElementContainingOffset(Offset-O);
Chris Lattner08db7192002-11-06 06:20:27 +0000616
617 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000618 SubType = STy->getElementType(i);
Chris Lattner507bdf92005-01-12 04:51:37 +0000619 O += (unsigned)SL.MemberOffsets[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000620 break;
621 }
622 case Type::ArrayTyID: {
623 SubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000624 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000625 unsigned Remainder = (Offset-O) % ElSize;
626 O = Offset-Remainder;
627 break;
628 }
629 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000630 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000631 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000632 }
633 }
634
635 assert(O == Offset && "Could not achieve the correct offset!");
636
637 // If we found our type exactly, early exit
638 if (SubType == NewTy) return false;
639
Misha Brukman96a8bd72004-04-29 04:05:30 +0000640 // Differing function types don't require us to merge. They are not values
641 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000642 if (isa<FunctionType>(SubType) &&
643 isa<FunctionType>(NewTy)) return false;
644
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000645 unsigned SubTypeSize = SubType->isSized() ?
Chris Lattner507bdf92005-01-12 04:51:37 +0000646 (unsigned)TD.getTypeSize(SubType) : 0;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000647
648 // Ok, we are getting desperate now. Check for physical subtyping, where we
649 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000650 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000651 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000652 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000653 return false;
654
Chris Lattner08db7192002-11-06 06:20:27 +0000655 // Okay, so we found the leader type at the offset requested. Search the list
656 // of types that starts at this offset. If SubType is currently an array or
657 // structure, the type desired may actually be the first element of the
658 // composite type...
659 //
Chris Lattner18552922002-11-18 21:44:46 +0000660 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000661 while (SubType != NewTy) {
662 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000663 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000664 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000665 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000666 case Type::StructTyID: {
667 const StructType *STy = cast<StructType>(SubType);
668 const StructLayout &SL = *TD.getStructLayout(STy);
669 if (SL.MemberOffsets.size() > 1)
Chris Lattner507bdf92005-01-12 04:51:37 +0000670 NextPadSize = (unsigned)SL.MemberOffsets[1];
Chris Lattner18552922002-11-18 21:44:46 +0000671 else
672 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000673 NextSubType = STy->getElementType(0);
Chris Lattner507bdf92005-01-12 04:51:37 +0000674 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000675 break;
Chris Lattner18552922002-11-18 21:44:46 +0000676 }
Chris Lattner08db7192002-11-06 06:20:27 +0000677 case Type::ArrayTyID:
678 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000679 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner18552922002-11-18 21:44:46 +0000680 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000681 break;
682 default: ;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000683 // fall out
Chris Lattner08db7192002-11-06 06:20:27 +0000684 }
685
686 if (NextSubType == 0)
687 break; // In the default case, break out of the loop
688
Chris Lattner18552922002-11-18 21:44:46 +0000689 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000690 break; // Don't allow shrinking to a smaller type than NewTySize
691 SubType = NextSubType;
692 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000693 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000694 }
695
696 // If we found the type exactly, return it...
697 if (SubType == NewTy)
698 return false;
699
700 // Check to see if we have a compatible, but different type...
701 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000702 // Check to see if this type is obviously convertible... int -> uint f.e.
Reid Spencer3da59db2006-11-27 01:05:10 +0000703 if (NewTy->canLosslesslyBitCastTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000704 return false;
705
706 // Check to see if we have a pointer & integer mismatch going on here,
707 // loading a pointer as a long, for example.
708 //
709 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
710 NewTy->isInteger() && isa<PointerType>(SubType))
711 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000712 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
713 // We are accessing the field, plus some structure padding. Ignore the
714 // structure padding.
715 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000716 }
717
Chris Lattner58f98d02003-07-02 04:38:49 +0000718 Module *M = 0;
Chris Lattnera5f47ea2005-03-15 16:55:04 +0000719 if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
720 M = getParentGraph()->retnodes_begin()->first->getParent();
Bill Wendling5294fb02006-11-17 07:33:59 +0000721
722 DOUT << "MergeTypeInfo Folding OrigTy: ";
Bill Wendlingbcd24982006-12-07 20:28:15 +0000723 DEBUG(WriteTypeSymbolic(*cerr.stream(), Ty, M) << "\n due to:";
724 WriteTypeSymbolic(*cerr.stream(), NewTy, M) << " @ " << Offset << "!\n"
725 << "SubType: ";
726 WriteTypeSymbolic(*cerr.stream(), SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000727
Chris Lattner088b6392003-03-03 17:13:31 +0000728 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000729 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000730}
731
Chris Lattner08db7192002-11-06 06:20:27 +0000732
733
Misha Brukman96a8bd72004-04-29 04:05:30 +0000734/// addEdgeTo - Add an edge from the current node to the specified node. This
735/// can cause merging of nodes in the graph.
736///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000737void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000738 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000739
Andrew Lenharth79acb692006-03-27 23:39:58 +0000740 if (isNodeCompletelyFolded())
741 Offset = 0;
742
Chris Lattner08db7192002-11-06 06:20:27 +0000743 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000744 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000745 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000746 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000747 } else { // No merging to perform...
748 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000749 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000750}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000751
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000752
Misha Brukman96a8bd72004-04-29 04:05:30 +0000753/// MergeSortedVectors - Efficiently merge a vector into another vector where
754/// duplicates are not allowed and both are sorted. This assumes that 'T's are
755/// efficiently copyable and have sane comparison semantics.
756///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000757static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
758 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000759 // By far, the most common cases will be the simple ones. In these cases,
760 // avoid having to allocate a temporary vector...
761 //
762 if (Src.empty()) { // Nothing to merge in...
763 return;
764 } else if (Dest.empty()) { // Just copy the result in...
765 Dest = Src;
766 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000767 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000768 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000769 std::lower_bound(Dest.begin(), Dest.end(), V);
770 if (I == Dest.end() || *I != Src[0]) // If not already contained...
771 Dest.insert(I, Src[0]);
772 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000773 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000774 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000775 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000776 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
777 if (I == Dest.end() || *I != Tmp) // If not already contained...
778 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000779
780 } else {
781 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000782 std::vector<GlobalValue*> Old(Dest);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000783
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000784 // Make space for all of the type entries now...
785 Dest.resize(Dest.size()+Src.size());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000786
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000787 // Merge the two sorted ranges together... into Dest.
788 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000789
790 // Now erase any duplicate entries that may have accumulated into the
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000791 // vectors (because they were in both of the input sets)
792 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
793 }
794}
795
Chris Lattner0b144872004-01-27 22:03:40 +0000796void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
797 MergeSortedVectors(Globals, RHS);
798}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000799
Chris Lattner0b144872004-01-27 22:03:40 +0000800// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000801// This function does the hard work of merging two nodes, CurNodeH
802// and NH after filtering out trivial cases and making sure that
803// CurNodeH.offset >= NH.offset.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000804//
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000805// ***WARNING***
806// Since merging may cause either node to go away, we must always
807// use the node-handles to refer to the nodes. These node handles are
808// automatically updated during merging, so will always provide access
809// to the correct node after a merge.
810//
811void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
812 assert(CurNodeH.getOffset() >= NH.getOffset() &&
813 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000814 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
815 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000816
817 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
818 // respect to NH.Offset) is now zero. NOffset is the distance from the base
819 // of our object that N starts from.
820 //
821 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
822 unsigned NSize = NH.getNode()->getSize();
823
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000824 // If the two nodes are of different size, and the smaller node has the array
825 // bit set, collapse!
826 if (NSize != CurNodeH.getNode()->getSize()) {
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000827#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000828 if (NSize < CurNodeH.getNode()->getSize()) {
829 if (NH.getNode()->isArray())
830 NH.getNode()->foldNodeCompletely();
831 } else if (CurNodeH.getNode()->isArray()) {
832 NH.getNode()->foldNodeCompletely();
833 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000834#endif
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000835 }
836
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000837 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000838 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000839 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000840 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000841
842 // If we are merging a node with a completely folded node, then both nodes are
843 // now completely folded.
844 //
845 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
846 if (!NH.getNode()->isNodeCompletelyFolded()) {
847 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000848 assert(NH.getNode() && NH.getOffset() == 0 &&
849 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000850 NOffset = NH.getOffset();
851 NSize = NH.getNode()->getSize();
852 assert(NOffset == 0 && NSize == 1);
853 }
854 } else if (NH.getNode()->isNodeCompletelyFolded()) {
855 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000856 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
857 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000858 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000859 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000860 assert(NOffset == 0 && NSize == 1);
861 }
862
Chris Lattner72d29a42003-02-11 23:11:51 +0000863 DSNode *N = NH.getNode();
864 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000865 assert(!CurNodeH.getNode()->isDeadNode());
866
Chris Lattner0b144872004-01-27 22:03:40 +0000867 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000868 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000869
Chris Lattner72d29a42003-02-11 23:11:51 +0000870 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000871 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000872 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000873
Chris Lattner72d29a42003-02-11 23:11:51 +0000874 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
875 //
876 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
877 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000878 if (Link.getNode()) {
879 // Compute the offset into the current node at which to
880 // merge this link. In the common case, this is a linear
881 // relation to the offset in the original node (with
882 // wrapping), but if the current node gets collapsed due to
883 // recursive merging, we must make sure to merge in all remaining
884 // links at offset zero.
885 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000886 DSNode *CN = CurNodeH.getNode();
887 if (CN->Size != 1)
888 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
889 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000890 }
891 }
892
893 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000894 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000895
896 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000897 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000898 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000899
900 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000901 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000902 }
903}
904
905
Misha Brukman96a8bd72004-04-29 04:05:30 +0000906/// mergeWith - Merge this node and the specified node, moving all links to and
907/// from the argument node into the current node, deleting the node argument.
908/// Offset indicates what offset the specified node is to be merged into the
909/// current node.
910///
911/// The specified node may be a null pointer (in which case, we update it to
912/// point to this node).
913///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000914void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
915 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000916 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000917 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000918
Chris Lattner5254a8d2004-01-22 16:31:08 +0000919 // If the RHS is a null node, make it point to this node!
920 if (N == 0) {
921 NH.mergeWith(DSNodeHandle(this, Offset));
922 return;
923 }
924
Chris Lattnerbd92b732003-06-19 21:15:11 +0000925 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000926 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
927
Chris Lattner02606632002-11-04 06:48:26 +0000928 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000929 // We cannot merge two pieces of the same node together, collapse the node
930 // completely.
Bill Wendling5294fb02006-11-17 07:33:59 +0000931 DOUT << "Attempting to merge two chunks of the same node together!\n";
Chris Lattner08db7192002-11-06 06:20:27 +0000932 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000933 return;
934 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000935
Chris Lattner5190ce82002-11-12 07:20:45 +0000936 // If both nodes are not at offset 0, make sure that we are merging the node
937 // at an later offset into the node with the zero offset.
938 //
939 if (Offset < NH.getOffset()) {
940 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
941 return;
942 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
943 // If the offsets are the same, merge the smaller node into the bigger node
944 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
945 return;
946 }
947
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000948 // Ok, now we can merge the two nodes. Use a static helper that works with
949 // two node handles, since "this" may get merged away at intermediate steps.
950 DSNodeHandle CurNodeH(this, Offset);
951 DSNodeHandle NHCopy(NH);
Andrew Lenharth37705002006-06-19 15:42:47 +0000952 if (CurNodeH.getOffset() >= NHCopy.getOffset())
953 DSNode::MergeNodes(CurNodeH, NHCopy);
954 else
955 DSNode::MergeNodes(NHCopy, CurNodeH);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000956}
957
Chris Lattner0b144872004-01-27 22:03:40 +0000958
959//===----------------------------------------------------------------------===//
960// ReachabilityCloner Implementation
961//===----------------------------------------------------------------------===//
962
963DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
964 if (SrcNH.isNull()) return DSNodeHandle();
965 const DSNode *SN = SrcNH.getNode();
966
967 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000968 if (!NH.isNull()) { // Node already mapped?
969 DSNode *NHN = NH.getNode();
970 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
971 }
Chris Lattner0b144872004-01-27 22:03:40 +0000972
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000973 // If SrcNH has globals and the destination graph has one of the same globals,
974 // merge this node with the destination node, which is much more efficient.
Chris Lattner82c6c722005-03-20 02:41:38 +0000975 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000976 DSScalarMap &DestSM = Dest.getScalarMap();
Chris Lattner82c6c722005-03-20 02:41:38 +0000977 for (DSNode::globals_iterator I = SN->globals_begin(),E = SN->globals_end();
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000978 I != E; ++I) {
979 GlobalValue *GV = *I;
980 DSScalarMap::iterator GI = DestSM.find(GV);
981 if (GI != DestSM.end() && !GI->second.isNull()) {
982 // We found one, use merge instead!
983 merge(GI->second, Src.getNodeForValue(GV));
984 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000985 DSNode *NHN = NH.getNode();
986 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000987 }
988 }
989 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000990
Chris Lattner0b144872004-01-27 22:03:40 +0000991 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
992 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000993 NH = DN;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000994
Chris Lattner0b144872004-01-27 22:03:40 +0000995 // Next, recursively clone all outgoing links as necessary. Note that
996 // adding these links can cause the node to collapse itself at any time, and
997 // the current node may be merged with arbitrary other nodes. For this
998 // reason, we must always go through NH.
999 DN = 0;
1000 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1001 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1002 if (!SrcEdge.isNull()) {
1003 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
1004 // Compute the offset into the current node at which to
1005 // merge this link. In the common case, this is a linear
1006 // relation to the offset in the original node (with
1007 // wrapping), but if the current node gets collapsed due to
1008 // recursive merging, we must make sure to merge in all remaining
1009 // links at offset zero.
1010 unsigned MergeOffset = 0;
1011 DSNode *CN = NH.getNode();
1012 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +00001013 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +00001014 CN->addEdgeTo(MergeOffset, DestEdge);
1015 }
1016 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001017
Chris Lattner0b144872004-01-27 22:03:40 +00001018 // If this node contains any globals, make sure they end up in the scalar
1019 // map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +00001020 for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
Chris Lattner0b144872004-01-27 22:03:40 +00001021 I != E; ++I) {
1022 GlobalValue *GV = *I;
1023 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1024 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1025 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
1026 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +00001027 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001028 }
Chris Lattner82c6c722005-03-20 02:41:38 +00001029 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001030
1031 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
1032}
1033
1034void ReachabilityCloner::merge(const DSNodeHandle &NH,
1035 const DSNodeHandle &SrcNH) {
1036 if (SrcNH.isNull()) return; // Noop
1037 if (NH.isNull()) {
1038 // If there is no destination node, just clone the source and assign the
1039 // destination node to be it.
1040 NH.mergeWith(getClonedNH(SrcNH));
1041 return;
1042 }
1043
1044 // Okay, at this point, we know that we have both a destination and a source
1045 // node that need to be merged. Check to see if the source node has already
1046 // been cloned.
1047 const DSNode *SN = SrcNH.getNode();
1048 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +00001049 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +00001050 DSNode *SCNHN = SCNH.getNode();
1051 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +00001052 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001053 return; // Nothing to do!
1054 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001055
Chris Lattner0b144872004-01-27 22:03:40 +00001056 // Okay, so the source node has not already been cloned. Instead of creating
1057 // a new DSNode, only to merge it into the one we already have, try to perform
1058 // the merge in-place. The only case we cannot handle here is when the offset
1059 // into the existing node is less than the offset into the virtual node we are
1060 // merging in. In this case, we have to extend the existing node, which
1061 // requires an allocation anyway.
1062 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
1063 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +00001064 if (!DN->isNodeCompletelyFolded()) {
1065 // Make sure the destination node is folded if the source node is folded.
1066 if (SN->isNodeCompletelyFolded()) {
1067 DN->foldNodeCompletely();
1068 DN = NH.getNode();
1069 } else if (SN->getSize() != DN->getSize()) {
1070 // If the two nodes are of different size, and the smaller node has the
1071 // array bit set, collapse!
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001072#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner0b144872004-01-27 22:03:40 +00001073 if (SN->getSize() < DN->getSize()) {
1074 if (SN->isArray()) {
1075 DN->foldNodeCompletely();
1076 DN = NH.getNode();
1077 }
1078 } else if (DN->isArray()) {
1079 DN->foldNodeCompletely();
1080 DN = NH.getNode();
1081 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001082#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001083 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001084
1085 // Merge the type entries of the two nodes together...
Chris Lattner0b144872004-01-27 22:03:40 +00001086 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
1087 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
1088 DN = NH.getNode();
1089 }
1090 }
1091
1092 assert(!DN->isDeadNode());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001093
Chris Lattner0b144872004-01-27 22:03:40 +00001094 // Merge the NodeType information.
1095 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
1096
1097 // Before we start merging outgoing links and updating the scalar map, make
1098 // sure it is known that this is the representative node for the src node.
1099 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
1100
1101 // If the source node contains any globals, make sure they end up in the
1102 // scalar map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +00001103 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattner0b144872004-01-27 22:03:40 +00001104 // Update the globals in the destination node itself.
Chris Lattner82c6c722005-03-20 02:41:38 +00001105 DN->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001106
1107 // Update the scalar map for the graph we are merging the source node
1108 // into.
Chris Lattner82c6c722005-03-20 02:41:38 +00001109 for (DSNode::globals_iterator I = SN->globals_begin(),
1110 E = SN->globals_end(); I != E; ++I) {
Chris Lattner0b144872004-01-27 22:03:40 +00001111 GlobalValue *GV = *I;
1112 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1113 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1114 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1115 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +00001116 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001117 }
Chris Lattner82c6c722005-03-20 02:41:38 +00001118 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001119 }
1120 } else {
1121 // We cannot handle this case without allocating a temporary node. Fall
1122 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +00001123 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
1124 NewDN->maskNodeTypes(BitsToKeep);
1125
1126 unsigned NHOffset = NH.getOffset();
1127 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001128
Chris Lattner0b144872004-01-27 22:03:40 +00001129 assert(NH.getNode() &&
1130 (NH.getOffset() > NHOffset ||
1131 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
1132 "Merging did not adjust the offset!");
1133
1134 // Before we start merging outgoing links and updating the scalar map, make
1135 // sure it is known that this is the representative node for the src node.
1136 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +00001137
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001138 // If the source node contained any globals, make sure to create entries
Chris Lattneread9eb72004-01-29 08:36:22 +00001139 // in the scalar map for them!
Chris Lattner82c6c722005-03-20 02:41:38 +00001140 for (DSNode::globals_iterator I = SN->globals_begin(),
1141 E = SN->globals_end(); I != E; ++I) {
Chris Lattneread9eb72004-01-29 08:36:22 +00001142 GlobalValue *GV = *I;
1143 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1144 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1145 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1146 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
1147 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1148 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001149 }
Chris Lattner0b144872004-01-27 22:03:40 +00001150 }
1151
1152
1153 // Next, recursively merge all outgoing links as necessary. Note that
1154 // adding these links can cause the destination node to collapse itself at
1155 // any time, and the current node may be merged with arbitrary other nodes.
1156 // For this reason, we must always go through NH.
1157 DN = 0;
1158 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1159 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1160 if (!SrcEdge.isNull()) {
1161 // Compute the offset into the current node at which to
1162 // merge this link. In the common case, this is a linear
1163 // relation to the offset in the original node (with
1164 // wrapping), but if the current node gets collapsed due to
1165 // recursive merging, we must make sure to merge in all remaining
1166 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +00001167 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +00001168 unsigned MergeOffset =
1169 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001170
Chris Lattnerf590ced2004-03-04 17:06:53 +00001171 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1172 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001173 // Perform the recursive merging. Make sure to create a temporary NH,
1174 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001175 merge(Tmp, SrcEdge);
1176 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001177 Tmp.mergeWith(getClonedNH(SrcEdge));
1178 // Merging this could cause all kinds of recursive things to happen,
1179 // culminating in the current node being eliminated. Since this is
1180 // possible, make sure to reaquire the link from 'CN'.
1181
1182 unsigned MergeOffset = 0;
1183 CN = SCNH.getNode();
1184 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1185 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001186 }
Chris Lattner0b144872004-01-27 22:03:40 +00001187 }
1188 }
1189}
1190
1191/// mergeCallSite - Merge the nodes reachable from the specified src call
1192/// site into the nodes reachable from DestCS.
Chris Lattnerb3439372005-03-21 20:28:50 +00001193void ReachabilityCloner::mergeCallSite(DSCallSite &DestCS,
Chris Lattner0b144872004-01-27 22:03:40 +00001194 const DSCallSite &SrcCS) {
1195 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1196 unsigned MinArgs = DestCS.getNumPtrArgs();
1197 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001198
Chris Lattner0b144872004-01-27 22:03:40 +00001199 for (unsigned a = 0; a != MinArgs; ++a)
1200 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
Chris Lattner3f90a942005-03-21 09:39:51 +00001201
1202 for (unsigned a = MinArgs, e = SrcCS.getNumPtrArgs(); a != e; ++a)
Chris Lattnerb3439372005-03-21 20:28:50 +00001203 DestCS.addPtrArg(getClonedNH(SrcCS.getPtrArg(a)));
Chris Lattner0b144872004-01-27 22:03:40 +00001204}
1205
1206
Chris Lattner9de906c2002-10-20 22:11:44 +00001207//===----------------------------------------------------------------------===//
1208// DSCallSite Implementation
1209//===----------------------------------------------------------------------===//
1210
Vikram S. Adve26b98262002-10-20 21:41:02 +00001211// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001212Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001213 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001214}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001215
Chris Lattner0b144872004-01-27 22:03:40 +00001216void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1217 ReachabilityCloner &RC) {
1218 NH = RC.getClonedNH(Src);
1219}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001220
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001221//===----------------------------------------------------------------------===//
1222// DSGraph Implementation
1223//===----------------------------------------------------------------------===//
1224
Chris Lattnera9d65662003-06-30 05:57:30 +00001225/// getFunctionNames - Return a space separated list of the name of the
1226/// functions in this graph (if any)
1227std::string DSGraph::getFunctionNames() const {
1228 switch (getReturnNodes().size()) {
1229 case 0: return "Globals graph";
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001230 case 1: return retnodes_begin()->first->getName();
Chris Lattnera9d65662003-06-30 05:57:30 +00001231 default:
1232 std::string Return;
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001233 for (DSGraph::retnodes_iterator I = retnodes_begin();
1234 I != retnodes_end(); ++I)
Chris Lattnera9d65662003-06-30 05:57:30 +00001235 Return += I->first->getName() + " ";
1236 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1237 return Return;
1238 }
1239}
1240
1241
Chris Lattnerf09ecff2005-03-21 22:49:53 +00001242DSGraph::DSGraph(const DSGraph &G, EquivalenceClasses<GlobalValue*> &ECs,
1243 unsigned CloneFlags)
Chris Lattnerf4f62272005-03-19 22:23:45 +00001244 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001245 PrintAuxCalls = false;
Chris Lattnera2197132005-03-22 00:36:51 +00001246 cloneInto(G, CloneFlags);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001247}
1248
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001249DSGraph::~DSGraph() {
1250 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001251 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001252 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001253 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001254
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001255 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001256 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
Chris Lattner84b80a22005-03-16 22:42:19 +00001257 NI->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001258
Chris Lattner28897e12004-02-08 00:53:26 +00001259 // Free all of the nodes.
1260 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001261}
1262
Chris Lattner0d9bab82002-07-18 00:12:30 +00001263// dump - Allow inspection of graph in a debugger.
Bill Wendlinge8156192006-12-07 01:30:32 +00001264void DSGraph::dump() const { print(cerr); }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001265
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001266
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001267/// remapLinks - Change all of the Links in the current node according to the
1268/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001269///
Chris Lattner8d327672003-06-30 03:36:09 +00001270void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001271 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1272 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001273 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001274 if (ONMI != OldNodeMap.end()) {
1275 DSNode *ONMIN = ONMI->second.getNode();
1276 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1277 }
Chris Lattner2f561382004-01-22 16:56:13 +00001278 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001279}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001280
Chris Lattnerd672ab92005-02-15 18:40:55 +00001281/// addObjectToGraph - This method can be used to add global, stack, and heap
1282/// objects to the graph. This can be used when updating DSGraphs due to the
1283/// introduction of new temporary objects. The new object is not pointed to
1284/// and does not point to any other objects in the graph.
1285DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1286 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1287 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1288 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
Chris Lattner7a0c7752005-02-15 18:48:48 +00001289 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
Chris Lattnerd672ab92005-02-15 18:40:55 +00001290 ScalarMap[Ptr] = N;
1291
1292 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1293 N->addGlobal(GV);
Reid Spencer3ed469c2006-11-02 20:25:50 +00001294 } else if (isa<MallocInst>(Ptr)) {
Chris Lattnerd672ab92005-02-15 18:40:55 +00001295 N->setHeapNodeMarker();
Reid Spencer3ed469c2006-11-02 20:25:50 +00001296 } else if (isa<AllocaInst>(Ptr)) {
Chris Lattnerd672ab92005-02-15 18:40:55 +00001297 N->setAllocaNodeMarker();
1298 } else {
1299 assert(0 && "Illegal memory object input!");
1300 }
1301 return N;
1302}
1303
1304
Chris Lattner5a540632003-06-30 03:15:25 +00001305/// cloneInto - Clone the specified DSGraph into the current graph. The
Chris Lattner3c920fa2005-03-22 00:21:05 +00001306/// translated ScalarMap for the old function is filled into the ScalarMap
1307/// for the graph, and the translated ReturnNodes map is returned into
1308/// ReturnNodes.
Chris Lattner5a540632003-06-30 03:15:25 +00001309///
1310/// The CloneFlags member controls various aspects of the cloning process.
1311///
Chris Lattnera2197132005-03-22 00:36:51 +00001312void DSGraph::cloneInto(const DSGraph &G, unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001313 TIME_REGION(X, "cloneInto");
Chris Lattner33312f72002-11-08 01:21:07 +00001314 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001315
Chris Lattnera2197132005-03-22 00:36:51 +00001316 NodeMapTy OldNodeMap;
1317
Chris Lattner1e883692003-02-03 20:08:51 +00001318 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001319 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1320 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1321 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001322 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001323
Chris Lattner84b80a22005-03-16 22:42:19 +00001324 for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1325 assert(!I->isForwarding() &&
Chris Lattnerd85645f2004-02-21 22:28:26 +00001326 "Forward nodes shouldn't be in node list!");
Chris Lattner84b80a22005-03-16 22:42:19 +00001327 DSNode *New = new DSNode(*I, this);
Chris Lattnerd85645f2004-02-21 22:28:26 +00001328 New->maskNodeTypes(~BitsToClear);
Chris Lattner84b80a22005-03-16 22:42:19 +00001329 OldNodeMap[I] = New;
Chris Lattnerd85645f2004-02-21 22:28:26 +00001330 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001331
Chris Lattner18552922002-11-18 21:44:46 +00001332#ifndef NDEBUG
1333 Timer::addPeakMemoryMeasurement();
1334#endif
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001335
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001336 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001337 // Note that we don't loop over the node's list to do this. The problem is
1338 // that remaping links can cause recursive merging to happen, which means
1339 // that node_iterator's can get easily invalidated! Because of this, we
1340 // loop over the OldNodeMap, which contains all of the new nodes as the
1341 // .second element of the map elements. Also note that if we remap a node
1342 // more than once, we won't break anything.
1343 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1344 I != E; ++I)
1345 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001346
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001347 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001348 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001349 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001350 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner3bc703b2005-03-22 01:42:59 +00001351 DSNodeHandle &H = ScalarMap.getRawEntryRef(I->first);
Chris Lattner6f967742004-10-30 04:05:01 +00001352 DSNode *MappedNodeN = MappedNode.getNode();
1353 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001354 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001355 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001356
Chris Lattner679e8e12002-11-08 21:27:12 +00001357 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001358 // Copy the function calls list.
1359 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1360 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001361 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001362
Chris Lattneracf491f2002-11-08 22:27:09 +00001363 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001364 // Copy the auxiliary function calls list.
1365 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1366 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattner679e8e12002-11-08 21:27:12 +00001367 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001368
Chris Lattner5a540632003-06-30 03:15:25 +00001369 // Map the return node pointers over...
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001370 for (retnodes_iterator I = G.retnodes_begin(),
1371 E = G.retnodes_end(); I != E; ++I) {
Chris Lattner5a540632003-06-30 03:15:25 +00001372 const DSNodeHandle &Ret = I->second;
1373 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001374 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattnerd65145b2005-03-22 00:29:44 +00001375 ReturnNodes.insert(std::make_pair(I->first,
1376 DSNodeHandle(MappedRetN,
1377 MappedRet.getOffset()+Ret.getOffset())));
Chris Lattner5a540632003-06-30 03:15:25 +00001378 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001379}
1380
Chris Lattner5734e432005-03-24 23:46:04 +00001381/// spliceFrom - Logically perform the operation of cloning the RHS graph into
1382/// this graph, then clearing the RHS graph. Instead of performing this as
1383/// two seperate operations, do it as a single, much faster, one.
1384///
1385void DSGraph::spliceFrom(DSGraph &RHS) {
1386 // Change all of the nodes in RHS to think we are their parent.
1387 for (NodeListTy::iterator I = RHS.Nodes.begin(), E = RHS.Nodes.end();
1388 I != E; ++I)
1389 I->setParentGraph(this);
1390 // Take all of the nodes.
1391 Nodes.splice(Nodes.end(), RHS.Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001392
Chris Lattner5734e432005-03-24 23:46:04 +00001393 // Take all of the calls.
1394 FunctionCalls.splice(FunctionCalls.end(), RHS.FunctionCalls);
1395 AuxFunctionCalls.splice(AuxFunctionCalls.end(), RHS.AuxFunctionCalls);
1396
1397 // Take all of the return nodes.
Chris Lattnerce7068d2005-03-25 00:02:41 +00001398 if (ReturnNodes.empty()) {
1399 ReturnNodes.swap(RHS.ReturnNodes);
1400 } else {
1401 ReturnNodes.insert(RHS.ReturnNodes.begin(), RHS.ReturnNodes.end());
1402 RHS.ReturnNodes.clear();
1403 }
Chris Lattner5734e432005-03-24 23:46:04 +00001404
1405 // Merge the scalar map in.
1406 ScalarMap.spliceFrom(RHS.ScalarMap);
1407}
1408
1409/// spliceFrom - Copy all entries from RHS, then clear RHS.
1410///
1411void DSScalarMap::spliceFrom(DSScalarMap &RHS) {
1412 // Special case if this is empty.
1413 if (ValueMap.empty()) {
1414 ValueMap.swap(RHS.ValueMap);
1415 GlobalSet.swap(RHS.GlobalSet);
1416 } else {
1417 GlobalSet.insert(RHS.GlobalSet.begin(), RHS.GlobalSet.end());
1418 for (ValueMapTy::iterator I = RHS.ValueMap.begin(), E = RHS.ValueMap.end();
1419 I != E; ++I)
1420 ValueMap[I->first].mergeWith(I->second);
1421 RHS.ValueMap.clear();
1422 }
1423}
1424
1425
Chris Lattnerbb753c42005-02-03 18:40:25 +00001426/// getFunctionArgumentsForCall - Given a function that is currently in this
1427/// graph, return the DSNodeHandles that correspond to the pointer-compatible
1428/// function arguments. The vector is filled in with the return value (or
1429/// null if it is not pointer compatible), followed by all of the
1430/// pointer-compatible arguments.
1431void DSGraph::getFunctionArgumentsForCall(Function *F,
1432 std::vector<DSNodeHandle> &Args) const {
1433 Args.push_back(getReturnNodeFor(*F));
Chris Lattnereb394922005-03-23 16:43:11 +00001434 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1435 AI != E; ++AI)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001436 if (isPointerType(AI->getType())) {
1437 Args.push_back(getNodeForValue(AI));
1438 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1439 }
1440}
1441
Chris Lattner4da120e2005-03-24 23:06:02 +00001442namespace {
1443 // HackedGraphSCCFinder - This is used to find nodes that have a path from the
1444 // node to a node cloned by the ReachabilityCloner object contained. To be
1445 // extra obnoxious it ignores edges from nodes that are globals, and truncates
1446 // search at RC marked nodes. This is designed as an object so that
1447 // intermediate results can be memoized across invocations of
1448 // PathExistsToClonedNode.
1449 struct HackedGraphSCCFinder {
1450 ReachabilityCloner &RC;
1451 unsigned CurNodeId;
1452 std::vector<const DSNode*> SCCStack;
1453 std::map<const DSNode*, std::pair<unsigned, bool> > NodeInfo;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001454
Chris Lattner4da120e2005-03-24 23:06:02 +00001455 HackedGraphSCCFinder(ReachabilityCloner &rc) : RC(rc), CurNodeId(1) {
1456 // Remove null pointer as a special case.
1457 NodeInfo[0] = std::make_pair(0, false);
Chris Lattnerd8642122005-03-24 21:07:47 +00001458 }
1459
Chris Lattner4da120e2005-03-24 23:06:02 +00001460 std::pair<unsigned, bool> &VisitForSCCs(const DSNode *N);
1461
1462 bool PathExistsToClonedNode(const DSNode *N) {
1463 return VisitForSCCs(N).second;
1464 }
1465
1466 bool PathExistsToClonedNode(const DSCallSite &CS) {
1467 if (PathExistsToClonedNode(CS.getRetVal().getNode()))
1468 return true;
1469 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1470 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode()))
1471 return true;
1472 return false;
1473 }
1474 };
1475}
1476
1477std::pair<unsigned, bool> &HackedGraphSCCFinder::
1478VisitForSCCs(const DSNode *N) {
1479 std::map<const DSNode*, std::pair<unsigned, bool> >::iterator
1480 NodeInfoIt = NodeInfo.lower_bound(N);
1481 if (NodeInfoIt != NodeInfo.end() && NodeInfoIt->first == N)
1482 return NodeInfoIt->second;
1483
1484 unsigned Min = CurNodeId++;
1485 unsigned MyId = Min;
1486 std::pair<unsigned, bool> &ThisNodeInfo =
1487 NodeInfo.insert(NodeInfoIt,
1488 std::make_pair(N, std::make_pair(MyId, false)))->second;
1489
1490 // Base case: if we find a global, this doesn't reach the cloned graph
1491 // portion.
1492 if (N->isGlobalNode()) {
1493 ThisNodeInfo.second = false;
1494 return ThisNodeInfo;
Chris Lattnerd8642122005-03-24 21:07:47 +00001495 }
1496
Chris Lattner4da120e2005-03-24 23:06:02 +00001497 // Base case: if this does reach the cloned graph portion... it does. :)
1498 if (RC.hasClonedNode(N)) {
1499 ThisNodeInfo.second = true;
1500 return ThisNodeInfo;
1501 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001502
Chris Lattner4da120e2005-03-24 23:06:02 +00001503 SCCStack.push_back(N);
Chris Lattnerd8642122005-03-24 21:07:47 +00001504
Chris Lattner4da120e2005-03-24 23:06:02 +00001505 // Otherwise, check all successors.
1506 bool AnyDirectSuccessorsReachClonedNodes = false;
1507 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
Chris Lattner63320cc2005-04-25 19:16:17 +00001508 EI != EE; ++EI)
1509 if (DSNode *Succ = EI->getNode()) {
1510 std::pair<unsigned, bool> &SuccInfo = VisitForSCCs(Succ);
1511 if (SuccInfo.first < Min) Min = SuccInfo.first;
1512 AnyDirectSuccessorsReachClonedNodes |= SuccInfo.second;
1513 }
Chris Lattner4da120e2005-03-24 23:06:02 +00001514
1515 if (Min != MyId)
1516 return ThisNodeInfo; // Part of a large SCC. Leave self on stack.
1517
1518 if (SCCStack.back() == N) { // Special case single node SCC.
1519 SCCStack.pop_back();
1520 ThisNodeInfo.second = AnyDirectSuccessorsReachClonedNodes;
1521 return ThisNodeInfo;
1522 }
1523
1524 // Find out if any direct successors of any node reach cloned nodes.
1525 if (!AnyDirectSuccessorsReachClonedNodes)
1526 for (unsigned i = SCCStack.size()-1; SCCStack[i] != N; --i)
1527 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1528 EI != EE; ++EI)
1529 if (DSNode *N = EI->getNode())
1530 if (NodeInfo[N].second) {
1531 AnyDirectSuccessorsReachClonedNodes = true;
1532 goto OutOfLoop;
1533 }
1534OutOfLoop:
1535 // If any successor reaches a cloned node, mark all nodes in this SCC as
1536 // reaching the cloned node.
1537 if (AnyDirectSuccessorsReachClonedNodes)
1538 while (SCCStack.back() != N) {
1539 NodeInfo[SCCStack.back()].second = true;
1540 SCCStack.pop_back();
1541 }
1542 SCCStack.pop_back();
1543 ThisNodeInfo.second = true;
1544 return ThisNodeInfo;
1545}
Chris Lattnerd8642122005-03-24 21:07:47 +00001546
Chris Lattnere8594442005-02-04 19:58:28 +00001547/// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1548/// nodes from G2 into 'this' graph, merging the bindings specified by the
1549/// call site (in this graph) with the bindings specified by the vector in G2.
1550/// The two DSGraphs must be different.
Chris Lattner076c1f92002-11-07 06:31:54 +00001551///
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001552void DSGraph::mergeInGraph(const DSCallSite &CS,
Chris Lattnere8594442005-02-04 19:58:28 +00001553 std::vector<DSNodeHandle> &Args,
Chris Lattner9f930552003-06-30 05:27:18 +00001554 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001555 TIME_REGION(X, "mergeInGraph");
1556
Chris Lattnerc14f59c2005-03-23 20:12:08 +00001557 assert((CloneFlags & DontCloneCallNodes) &&
1558 "Doesn't support copying of call nodes!");
1559
Chris Lattner076c1f92002-11-07 06:31:54 +00001560 // If this is not a recursive call, clone the graph into this graph...
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001561 if (&Graph == this) {
Chris Lattnerbb753c42005-02-03 18:40:25 +00001562 // Merge the return value with the return value of the context.
1563 Args[0].mergeWith(CS.getRetVal());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001564
Chris Lattnerbb753c42005-02-03 18:40:25 +00001565 // Resolve all of the function arguments.
1566 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001567 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001568 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001569
Chris Lattnerbb753c42005-02-03 18:40:25 +00001570 // Add the link from the argument scalar to the provided value.
1571 Args[i+1].mergeWith(CS.getPtrArg(i));
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001572 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001573 return;
Chris Lattner076c1f92002-11-07 06:31:54 +00001574 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001575
1576 // Clone the callee's graph into the current graph, keeping track of where
1577 // scalars in the old graph _used_ to point, and of the new nodes matching
1578 // nodes of the old graph.
1579 ReachabilityCloner RC(*this, Graph, CloneFlags);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001580
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001581 // Map the return node pointer over.
1582 if (!CS.getRetVal().isNull())
1583 RC.merge(CS.getRetVal(), Args[0]);
1584
1585 // Map over all of the arguments.
1586 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1587 if (i == Args.size()-1)
1588 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001589
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001590 // Add the link from the argument scalar to the provided value.
1591 RC.merge(CS.getPtrArg(i), Args[i+1]);
1592 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001593
Chris Lattnerd8642122005-03-24 21:07:47 +00001594 // We generally don't want to copy global nodes or aux calls from the callee
1595 // graph to the caller graph. However, we have to copy them if there is a
1596 // path from the node to a node we have already copied which does not go
1597 // through another global. Compute the set of node that can reach globals and
1598 // aux call nodes to copy over, then do it.
1599 std::vector<const DSCallSite*> AuxCallToCopy;
1600 std::vector<GlobalValue*> GlobalsToCopy;
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001601
Chris Lattnerd8642122005-03-24 21:07:47 +00001602 // NodesReachCopiedNodes - Memoize results for efficiency. Contains a
1603 // true/false value for every visited node that reaches a copied node without
1604 // going through a global.
Chris Lattner4da120e2005-03-24 23:06:02 +00001605 HackedGraphSCCFinder SCCFinder(RC);
Chris Lattnerd8642122005-03-24 21:07:47 +00001606
1607 if (!(CloneFlags & DontCloneAuxCallNodes))
1608 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
Chris Lattner4da120e2005-03-24 23:06:02 +00001609 if (SCCFinder.PathExistsToClonedNode(*I))
Chris Lattnerd8642122005-03-24 21:07:47 +00001610 AuxCallToCopy.push_back(&*I);
Andrew Lenharthdf983de2006-11-07 20:36:02 +00001611// else if (I->isIndirectCall()){
1612// //If the call node doesn't have any callees, clone it
1613// std::vector< Function *> List;
1614// I->getCalleeNode()->addFullFunctionList(List);
1615// if (!List.size())
1616// AuxCallToCopy.push_back(&*I);
1617// }
Chris Lattnerd8642122005-03-24 21:07:47 +00001618
Chris Lattner4da120e2005-03-24 23:06:02 +00001619 const DSScalarMap &GSM = Graph.getScalarMap();
Chris Lattnerd8642122005-03-24 21:07:47 +00001620 for (DSScalarMap::global_iterator GI = GSM.global_begin(),
Chris Lattner09adbbc92005-03-24 21:17:27 +00001621 E = GSM.global_end(); GI != E; ++GI) {
1622 DSNode *GlobalNode = Graph.getNodeForValue(*GI).getNode();
1623 for (DSNode::edge_iterator EI = GlobalNode->edge_begin(),
1624 EE = GlobalNode->edge_end(); EI != EE; ++EI)
Chris Lattner4da120e2005-03-24 23:06:02 +00001625 if (SCCFinder.PathExistsToClonedNode(EI->getNode())) {
Chris Lattner09adbbc92005-03-24 21:17:27 +00001626 GlobalsToCopy.push_back(*GI);
1627 break;
1628 }
1629 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001630
1631 // Copy aux calls that are needed.
1632 for (unsigned i = 0, e = AuxCallToCopy.size(); i != e; ++i)
1633 AuxFunctionCalls.push_back(DSCallSite(*AuxCallToCopy[i], RC));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001634
Chris Lattnerd8642122005-03-24 21:07:47 +00001635 // Copy globals that are needed.
1636 for (unsigned i = 0, e = GlobalsToCopy.size(); i != e; ++i)
1637 RC.getClonedNH(Graph.getNodeForValue(GlobalsToCopy[i]));
Chris Lattner076c1f92002-11-07 06:31:54 +00001638}
1639
Chris Lattnere8594442005-02-04 19:58:28 +00001640
1641
1642/// mergeInGraph - The method is used for merging graphs together. If the
1643/// argument graph is not *this, it makes a clone of the specified graph, then
1644/// merges the nodes specified in the call site with the formal arguments in the
1645/// graph.
1646///
1647void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1648 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattnere8594442005-02-04 19:58:28 +00001649 // Set up argument bindings.
1650 std::vector<DSNodeHandle> Args;
1651 Graph.getFunctionArgumentsForCall(&F, Args);
1652
1653 mergeInGraph(CS, Args, Graph, CloneFlags);
1654}
1655
Chris Lattner58f98d02003-07-02 04:38:49 +00001656/// getCallSiteForArguments - Get the arguments and return value bindings for
1657/// the specified function in the current graph.
1658///
1659DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1660 std::vector<DSNodeHandle> Args;
1661
Chris Lattnere4d5c442005-03-15 04:54:21 +00001662 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner58f98d02003-07-02 04:38:49 +00001663 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001664 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001665
Chris Lattner808a7ae2003-09-20 16:34:13 +00001666 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001667}
1668
Chris Lattner85fb1be2004-03-09 19:37:06 +00001669/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1670/// the context of this graph, return the DSCallSite for it.
1671DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1672 DSNodeHandle RetVal;
1673 Instruction *I = CS.getInstruction();
1674 if (isPointerType(I->getType()))
1675 RetVal = getNodeForValue(I);
1676
1677 std::vector<DSNodeHandle> Args;
1678 Args.reserve(CS.arg_end()-CS.arg_begin());
1679
1680 // Calculate the arguments vector...
1681 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1682 if (isPointerType((*I)->getType()))
Chris Lattner94f84702005-03-17 19:56:56 +00001683 if (isa<ConstantPointerNull>(*I))
1684 Args.push_back(DSNodeHandle());
1685 else
1686 Args.push_back(getNodeForValue(*I));
Chris Lattner85fb1be2004-03-09 19:37:06 +00001687
1688 // Add a new function call entry...
1689 if (Function *F = CS.getCalledFunction())
1690 return DSCallSite(CS, RetVal, F, Args);
1691 else
1692 return DSCallSite(CS, RetVal,
1693 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1694}
1695
Chris Lattner58f98d02003-07-02 04:38:49 +00001696
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001697
Chris Lattner0d9bab82002-07-18 00:12:30 +00001698// markIncompleteNodes - Mark the specified node as having contents that are not
1699// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001700// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001701// must recursively traverse the data structure graph, marking all reachable
1702// nodes as incomplete.
1703//
1704static void markIncompleteNode(DSNode *N) {
1705 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001706 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001707
1708 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001709 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001710
Misha Brukman2f2d0652003-09-11 18:14:24 +00001711 // Recursively process children...
Chris Lattner6be07942005-02-09 03:20:43 +00001712 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1713 if (DSNode *DSN = I->getNode())
Chris Lattner08db7192002-11-06 06:20:27 +00001714 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001715}
1716
Chris Lattnere71ffc22002-11-11 03:36:55 +00001717static void markIncomplete(DSCallSite &Call) {
1718 // Then the return value is certainly incomplete!
1719 markIncompleteNode(Call.getRetVal().getNode());
1720
1721 // All objects pointed to by function arguments are incomplete!
1722 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1723 markIncompleteNode(Call.getPtrArg(i).getNode());
1724}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001725
1726// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1727// modified by other functions that have not been resolved yet. This marks
1728// nodes that are reachable through three sources of "unknownness":
1729//
1730// Global Variables, Function Calls, and Incoming Arguments
1731//
1732// For any node that may have unknown components (because something outside the
1733// scope of current analysis may have modified it), the 'Incomplete' flag is
1734// added to the NodeType.
1735//
Chris Lattner394471f2003-01-23 22:05:33 +00001736void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001737 // Mark any incoming arguments as incomplete.
Chris Lattner5a540632003-06-30 03:15:25 +00001738 if (Flags & DSGraph::MarkFormalArgs)
1739 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1740 FI != E; ++FI) {
1741 Function &F = *FI->first;
Chris Lattner9342a932005-03-29 19:16:59 +00001742 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1743 I != E; ++I)
Chris Lattnerb5ecd2e2005-03-13 20:22:10 +00001744 if (isPointerType(I->getType()))
1745 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattnera4319e52005-03-12 14:58:28 +00001746 markIncompleteNode(FI->second.getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001747 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001748
Chris Lattnera9548d92005-01-30 23:51:02 +00001749 // Mark stuff passed into functions calls as being incomplete.
Chris Lattnere71ffc22002-11-11 03:36:55 +00001750 if (!shouldPrintAuxCalls())
Chris Lattnera9548d92005-01-30 23:51:02 +00001751 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1752 E = FunctionCalls.end(); I != E; ++I)
1753 markIncomplete(*I);
Chris Lattnere71ffc22002-11-11 03:36:55 +00001754 else
Chris Lattnera9548d92005-01-30 23:51:02 +00001755 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1756 E = AuxFunctionCalls.end(); I != E; ++I)
1757 markIncomplete(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001758
Chris Lattnere2bc7b22005-03-13 20:36:01 +00001759 // Mark all global nodes as incomplete.
1760 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1761 E = ScalarMap.global_end(); I != E; ++I)
1762 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1763 if (!GV->hasInitializer() || // Always mark external globals incomp.
1764 (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1765 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001766}
1767
Chris Lattneraa8146f2002-11-10 06:59:55 +00001768static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1769 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001770 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001771 // No interesting info?
1772 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001773 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001774 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001775}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001776
Chris Lattneraa8146f2002-11-10 06:59:55 +00001777static inline bool nodeContainsExternalFunction(const DSNode *N) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001778 std::vector<Function*> Funcs;
1779 N->addFullFunctionList(Funcs);
1780 for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
1781 if (Funcs[i]->isExternal()) return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001782 return false;
1783}
1784
Chris Lattnera9548d92005-01-30 23:51:02 +00001785static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001786 // Remove trivially identical function calls
Chris Lattnera9548d92005-01-30 23:51:02 +00001787 Calls.sort(); // Sort by callee as primary key!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001788
1789 // Scan the call list cleaning it up as necessary...
Chris Lattner1e9d1472005-03-22 23:54:52 +00001790 DSNodeHandle LastCalleeNode;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001791#if 0
Chris Lattner923fc052003-02-05 21:59:58 +00001792 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001793 unsigned NumDuplicateCalls = 0;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001794#endif
Chris Lattneraa8146f2002-11-10 06:59:55 +00001795 bool LastCalleeContainsExternalFunction = false;
Chris Lattner857eb062004-10-30 05:41:23 +00001796
Chris Lattnera9548d92005-01-30 23:51:02 +00001797 unsigned NumDeleted = 0;
1798 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1799 I != E;) {
1800 DSCallSite &CS = *I;
1801 std::list<DSCallSite>::iterator OldIt = I++;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001802
Chris Lattner1e9d1472005-03-22 23:54:52 +00001803 if (!CS.isIndirectCall()) {
1804 LastCalleeNode = 0;
1805 } else {
1806 DSNode *Callee = CS.getCalleeNode();
1807
1808 // If the Callee is a useless edge, this must be an unreachable call site,
1809 // eliminate it.
1810 if (Callee->getNumReferrers() == 1 && Callee->isComplete() &&
1811 Callee->getGlobalsList().empty()) { // No useful info?
Bill Wendling5294fb02006-11-17 07:33:59 +00001812 DOUT << "WARNING: Useless call site found.\n";
Chris Lattner1e9d1472005-03-22 23:54:52 +00001813 Calls.erase(OldIt);
1814 ++NumDeleted;
1815 continue;
1816 }
1817
1818 // If the last call site in the list has the same callee as this one, and
1819 // if the callee contains an external function, it will never be
1820 // resolvable, just merge the call sites.
1821 if (!LastCalleeNode.isNull() && LastCalleeNode.getNode() == Callee) {
1822 LastCalleeContainsExternalFunction =
1823 nodeContainsExternalFunction(Callee);
1824
1825 std::list<DSCallSite>::iterator PrevIt = OldIt;
1826 --PrevIt;
1827 PrevIt->mergeWith(CS);
1828
1829 // No need to keep this call anymore.
1830 Calls.erase(OldIt);
1831 ++NumDeleted;
1832 continue;
1833 } else {
1834 LastCalleeNode = Callee;
1835 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001836 }
1837
1838 // If the return value or any arguments point to a void node with no
1839 // information at all in it, and the call node is the only node to point
1840 // to it, remove the edge to the node (killing the node).
1841 //
1842 killIfUselessEdge(CS.getRetVal());
1843 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1844 killIfUselessEdge(CS.getPtrArg(a));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001845
Chris Lattner0b144872004-01-27 22:03:40 +00001846#if 0
Chris Lattnera9548d92005-01-30 23:51:02 +00001847 // If this call site calls the same function as the last call site, and if
1848 // the function pointer contains an external function, this node will
1849 // never be resolved. Merge the arguments of the call node because no
1850 // information will be lost.
1851 //
1852 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1853 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1854 ++NumDuplicateCalls;
1855 if (NumDuplicateCalls == 1) {
1856 if (LastCalleeNode)
1857 LastCalleeContainsExternalFunction =
1858 nodeContainsExternalFunction(LastCalleeNode);
1859 else
1860 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001861 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001862
Chris Lattnera9548d92005-01-30 23:51:02 +00001863 // It is not clear why, but enabling this code makes DSA really
1864 // sensitive to node forwarding. Basically, with this enabled, DSA
1865 // performs different number of inlinings based on which nodes are
1866 // forwarding or not. This is clearly a problem, so this code is
1867 // disabled until this can be resolved.
1868#if 1
1869 if (LastCalleeContainsExternalFunction
1870#if 0
1871 ||
1872 // This should be more than enough context sensitivity!
1873 // FIXME: Evaluate how many times this is tripped!
1874 NumDuplicateCalls > 20
1875#endif
1876 ) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001877
Chris Lattnera9548d92005-01-30 23:51:02 +00001878 std::list<DSCallSite>::iterator PrevIt = OldIt;
1879 --PrevIt;
1880 PrevIt->mergeWith(CS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001881
Chris Lattnera9548d92005-01-30 23:51:02 +00001882 // No need to keep this call anymore.
1883 Calls.erase(OldIt);
1884 ++NumDeleted;
1885 continue;
1886 }
1887#endif
1888 } else {
1889 if (CS.isDirectCall()) {
1890 LastCalleeFunc = CS.getCalleeFunc();
1891 LastCalleeNode = 0;
1892 } else {
1893 LastCalleeNode = CS.getCalleeNode();
1894 LastCalleeFunc = 0;
1895 }
1896 NumDuplicateCalls = 0;
1897 }
1898#endif
1899
1900 if (I != Calls.end() && CS == *I) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001901 LastCalleeNode = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00001902 Calls.erase(OldIt);
1903 ++NumDeleted;
1904 continue;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001905 }
1906 }
Chris Lattner857eb062004-10-30 05:41:23 +00001907
Chris Lattnera9548d92005-01-30 23:51:02 +00001908 // Resort now that we simplified things.
1909 Calls.sort();
Chris Lattner857eb062004-10-30 05:41:23 +00001910
Chris Lattnera9548d92005-01-30 23:51:02 +00001911 // Now that we are in sorted order, eliminate duplicates.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001912 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1913 if (CI != CE)
Chris Lattnera9548d92005-01-30 23:51:02 +00001914 while (1) {
Chris Lattnerf9aace22005-01-31 00:10:58 +00001915 std::list<DSCallSite>::iterator OldIt = CI++;
1916 if (CI == CE) break;
Chris Lattnera9548d92005-01-30 23:51:02 +00001917
1918 // If this call site is now the same as the previous one, we can delete it
1919 // as a duplicate.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001920 if (*OldIt == *CI) {
1921 Calls.erase(CI);
1922 CI = OldIt;
Chris Lattnera9548d92005-01-30 23:51:02 +00001923 ++NumDeleted;
1924 }
1925 }
1926
1927 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001928
Chris Lattner33312f72002-11-08 01:21:07 +00001929 // Track the number of call nodes merged away...
Chris Lattnera9548d92005-01-30 23:51:02 +00001930 NumCallNodesMerged += NumDeleted;
Chris Lattner33312f72002-11-08 01:21:07 +00001931
Bill Wendling5294fb02006-11-17 07:33:59 +00001932 if (NumDeleted)
1933 DOUT << "Merged " << NumDeleted << " call nodes.\n";
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001934}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001935
Chris Lattneraa8146f2002-11-10 06:59:55 +00001936
Chris Lattnere2219762002-07-18 18:22:40 +00001937// removeTriviallyDeadNodes - After the graph has been constructed, this method
1938// removes all unreachable nodes that are created because they got merged with
1939// other nodes in the graph. These nodes will all be trivially unreachable, so
1940// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001941//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001942void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001943 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001944
Chris Lattner5ace1e42004-07-08 07:25:51 +00001945#if 0
1946 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1947 /// substantially!
1948
Chris Lattnerbab8c282003-09-20 21:34:07 +00001949 // Loop over all of the nodes in the graph, calling getNode on each field.
1950 // This will cause all nodes to update their forwarding edges, causing
1951 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001952 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001953 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
Chris Lattner84b80a22005-03-16 22:42:19 +00001954 DSNode &N = *NI;
1955 for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1956 N.getLink(l*N.getPointerSize()).getNode();
Chris Lattnerbab8c282003-09-20 21:34:07 +00001957 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001958 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001959
Chris Lattner0b144872004-01-27 22:03:40 +00001960 // NOTE: This code is disabled. Though it should, in theory, allow us to
1961 // remove more nodes down below, the scan of the scalar map is incredibly
1962 // expensive for certain programs (with large SCCs). In the future, if we can
1963 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001964 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1965
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001966 // Likewise, forward any edges from the scalar nodes. While we are at it,
1967 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001968 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001969 I->second.getNode();
1970 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001971 }
Chris Lattner0b144872004-01-27 22:03:40 +00001972 }
1973#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001974 bool isGlobalsGraph = !GlobalsGraph;
1975
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001976 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001977 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001978
1979 // Do not remove *any* global nodes in the globals graph.
1980 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001981 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001982 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001983 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001984 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001985
Chris Lattner28897e12004-02-08 00:53:26 +00001986 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001987 // This is a useless node if it has no mod/ref info (checked above),
1988 // outgoing edges (which it cannot, as it is not modified in this
1989 // context), and it has no incoming edges. If it is a global node it may
1990 // have all of these properties and still have incoming edges, due to the
1991 // scalar map, so we check those now.
1992 //
Chris Lattner82c6c722005-03-20 02:41:38 +00001993 if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1994 const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
Chris Lattner72d29a42003-02-11 23:11:51 +00001995
Chris Lattner17a93e22004-01-29 03:32:15 +00001996 // Loop through and make sure all of the globals are referring directly
1997 // to the node...
1998 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1999 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00002000 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00002001 }
2002
Chris Lattnerbd92b732003-06-19 21:15:11 +00002003 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00002004 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00002005 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
2006 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00002007 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002008 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00002009 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002010 }
2011 }
2012
Chris Lattner28897e12004-02-08 00:53:26 +00002013 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00002014 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00002015 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002016 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00002017 } else {
2018 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002019 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002020 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002021
2022 removeIdenticalCalls(FunctionCalls);
2023 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00002024}
2025
2026
Chris Lattner5c7380e2003-01-29 21:10:20 +00002027/// markReachableNodes - This method recursively traverses the specified
2028/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
2029/// to the set, which allows it to only traverse visited nodes once.
2030///
Chris Lattnera9548d92005-01-30 23:51:02 +00002031void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00002032 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00002033 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00002034 if (ReachableNodes.insert(this).second) // Is newly reachable?
Chris Lattner6be07942005-02-09 03:20:43 +00002035 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
2036 I != E; ++I)
2037 I->getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00002038}
2039
Chris Lattnera9548d92005-01-30 23:51:02 +00002040void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00002041 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00002042 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002043
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002044 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
2045 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00002046}
2047
Chris Lattnera1220af2003-02-01 06:17:02 +00002048// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
2049// looking for a node that is marked alive. If an alive node is found, return
2050// true, otherwise return false. If an alive node is reachable, this node is
2051// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00002052//
Chris Lattnera9548d92005-01-30 23:51:02 +00002053static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
2054 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00002055 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002056 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00002057 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002058
Chris Lattner85cfe012003-07-03 02:03:53 +00002059 // If this is a global node, it will end up in the globals graph anyway, so we
2060 // don't need to worry about it.
2061 if (IgnoreGlobals && N->isGlobalNode()) return false;
2062
Chris Lattneraa8146f2002-11-10 06:59:55 +00002063 // If we know that this node is alive, return so!
2064 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002065
Chris Lattneraa8146f2002-11-10 06:59:55 +00002066 // Otherwise, we don't think the node is alive yet, check for infinite
2067 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00002068 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00002069 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00002070
Chris Lattner6be07942005-02-09 03:20:43 +00002071 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
2072 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00002073 N->markReachableNodes(Alive);
2074 return true;
2075 }
2076 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002077}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002078
Chris Lattnera1220af2003-02-01 06:17:02 +00002079// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
2080// alive nodes.
2081//
Chris Lattnera9548d92005-01-30 23:51:02 +00002082static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
2083 hash_set<const DSNode*> &Alive,
2084 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00002085 bool IgnoreGlobals) {
2086 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
2087 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00002088 return true;
2089 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00002090 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002091 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002092 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00002093 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
2094 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002095 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002096 return false;
2097}
2098
Chris Lattnere2219762002-07-18 18:22:40 +00002099// removeDeadNodes - Use a more powerful reachability analysis to eliminate
2100// subgraphs that are unreachable. This often occurs because the data
2101// structure doesn't "escape" into it's caller, and thus should be eliminated
2102// from the caller's graph entirely. This is only appropriate to use when
2103// inlining graphs.
2104//
Chris Lattner394471f2003-01-23 22:05:33 +00002105void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00002106 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00002107
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002108 // Reduce the amount of work we have to do... remove dummy nodes left over by
2109 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00002110 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002111
Chris Lattner93ddd7e2004-01-22 16:36:28 +00002112 TIME_REGION(X, "removeDeadNodes");
2113
Misha Brukman2f2d0652003-09-11 18:14:24 +00002114 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00002115
2116 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattnera9548d92005-01-30 23:51:02 +00002117 hash_set<const DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002118 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00002119
Chris Lattner0b144872004-01-27 22:03:40 +00002120 // Copy and merge all information about globals to the GlobalsGraph if this is
2121 // not a final pass (where unreachable globals are removed).
2122 //
2123 // Strip all alloca bits since the current function is only for the BU pass.
2124 // Strip all incomplete bits since they are short-lived properties and they
2125 // will be correctly computed when rematerializing nodes into the functions.
2126 //
2127 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
2128 DSGraph::StripIncompleteBit);
2129
Chris Lattneraa8146f2002-11-10 06:59:55 +00002130 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattnerf4f62272005-03-19 22:23:45 +00002131{ TIME_REGION(Y, "removeDeadNodes:scalarscan");
2132 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
2133 I != E; ++I)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002134 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00002135 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002136 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002137 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00002138
2139 // Make sure that all globals are cloned over as roots.
Chris Lattner021decc2005-04-02 19:17:18 +00002140 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && GlobalsGraph) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002141 DSGraph::ScalarMapTy::iterator SMI =
Chris Lattner00948c02004-01-28 02:05:05 +00002142 GlobalsGraph->getScalarMap().find(I->first);
2143 if (SMI != GlobalsGraph->getScalarMap().end())
2144 GGCloner.merge(SMI->second, I->second);
2145 else
2146 GGCloner.getClonedNH(I->second);
2147 }
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002148 } else {
Chris Lattnerf4f62272005-03-19 22:23:45 +00002149 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002150 }
Chris Lattnerf4f62272005-03-19 22:23:45 +00002151}
Chris Lattnere2219762002-07-18 18:22:40 +00002152
Chris Lattner0b144872004-01-27 22:03:40 +00002153 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00002154 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
2155 I != E; ++I)
2156 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002157
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002158 // Mark any nodes reachable by primary calls as alive...
Chris Lattnera9548d92005-01-30 23:51:02 +00002159 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2160 I->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002161
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002162
2163 // Now find globals and aux call nodes that are already live or reach a live
2164 // value (which makes them live in turn), and continue till no more are found.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002165 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002166 bool Iterate;
Chris Lattnera9548d92005-01-30 23:51:02 +00002167 hash_set<const DSNode*> Visited;
2168 hash_set<const DSCallSite*> AuxFCallsAlive;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002169 do {
2170 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00002171 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00002172 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002173 // unreachable globals in the list.
2174 //
2175 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002176 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00002177 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002178 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
Chris Lattner0b144872004-01-27 22:03:40 +00002179 Flags & DSGraph::RemoveUnreachableGlobals)) {
2180 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
2181 GlobalNodes.pop_back(); // erase efficiently
2182 Iterate = true;
2183 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002184
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002185 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
2186 // call nodes that get resolved will be difficult to remove from that graph.
2187 // The final unresolved call nodes must be handled specially at the end of
2188 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattnera9548d92005-01-30 23:51:02 +00002189 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
Chris Lattnerd7642c42005-02-24 18:48:07 +00002190 if (!AuxFCallsAlive.count(&*CI) &&
Chris Lattnera9548d92005-01-30 23:51:02 +00002191 (CI->isIndirectCall()
2192 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002193 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattnera9548d92005-01-30 23:51:02 +00002194 CI->markReachableNodes(Alive);
Chris Lattnerd7642c42005-02-24 18:48:07 +00002195 AuxFCallsAlive.insert(&*CI);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002196 Iterate = true;
2197 }
2198 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00002199
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002200 // Move dead aux function calls to the end of the list
Chris Lattnera9548d92005-01-30 23:51:02 +00002201 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
2202 E = AuxFunctionCalls.end(); CI != E; )
2203 if (AuxFCallsAlive.count(&*CI))
2204 ++CI;
2205 else {
2206 // Copy and merge global nodes and dead aux call nodes into the
2207 // GlobalsGraph, and all nodes reachable from those nodes. Update their
2208 // target pointers using the GGCloner.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002209 //
Chris Lattnera9548d92005-01-30 23:51:02 +00002210 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2211 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002212
Chris Lattnera9548d92005-01-30 23:51:02 +00002213 AuxFunctionCalls.erase(CI++);
2214 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002215
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002216 // We are finally done with the GGCloner so we can destroy it.
2217 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002218
Vikram S. Adve40c600e2003-07-22 12:08:58 +00002219 // At this point, any nodes which are visited, but not alive, are nodes
2220 // which can be removed. Loop over all nodes, eliminating completely
2221 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002222 //
Chris Lattner72d29a42003-02-11 23:11:51 +00002223 std::vector<DSNode*> DeadNodes;
2224 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00002225 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2226 DSNode *N = NI++;
2227 assert(!N->isForwarding() && "Forwarded node in nodes list?");
2228
2229 if (!Alive.count(N)) {
2230 Nodes.remove(N);
2231 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002232 DeadNodes.push_back(N);
2233 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00002234 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00002235 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00002236 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002237
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002238 // Remove all unreachable globals from the ScalarMap.
2239 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2240 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00002241 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002242 if (!Alive.count(GlobalNodes[i].second))
2243 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00002244 else
2245 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002246
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002247 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00002248 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2249 delete DeadNodes[i];
2250
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002251 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00002252}
2253
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002254void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
Chris Lattner82c6c722005-03-20 02:41:38 +00002255 assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2256 N->globals_end() && "Global value not in node!");
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002257}
2258
Chris Lattner2c7725a2004-03-03 20:55:27 +00002259void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2260 if (CS.isIndirectCall()) {
2261 AssertNodeInGraph(CS.getCalleeNode());
2262#if 0
2263 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2264 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
Bill Wendling5294fb02006-11-17 07:33:59 +00002265 DOUT << "WARNING: WEIRD CALL SITE FOUND!\n";
Chris Lattner2c7725a2004-03-03 20:55:27 +00002266#endif
2267 }
2268 AssertNodeInGraph(CS.getRetVal().getNode());
2269 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2270 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2271}
2272
2273void DSGraph::AssertCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002274 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2275 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002276}
2277void DSGraph::AssertAuxCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002278 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2279 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002280}
2281
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002282void DSGraph::AssertGraphOK() const {
Chris Lattner84b80a22005-03-16 22:42:19 +00002283 for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2284 NI->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00002285
Chris Lattner8d327672003-06-30 03:36:09 +00002286 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002287 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00002288 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002289 AssertNodeInGraph(I->second.getNode());
2290 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00002291 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002292 "Global points to node, but node isn't global?");
2293 AssertNodeContainsGlobal(I->second.getNode(), GV);
2294 }
2295 }
2296 AssertCallNodesInGraph();
2297 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00002298
2299 // Check that all pointer arguments to any functions in this graph have
2300 // destinations.
2301 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2302 E = ReturnNodes.end();
2303 RI != E; ++RI) {
2304 Function &F = *RI->first;
Chris Lattnere4d5c442005-03-15 04:54:21 +00002305 for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
Chris Lattner7d8d4712004-10-31 17:45:40 +00002306 if (isPointerType(AI->getType()))
2307 assert(!getNodeForValue(AI).isNull() &&
2308 "Pointer argument must be in the scalar map!");
2309 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002310}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002311
Chris Lattner400433d2003-11-11 05:08:59 +00002312/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00002313/// nodes reachable from the two graphs, computing the mapping of nodes from the
2314/// first to the second graph. This mapping may be many-to-one (i.e. the first
2315/// graph may have multiple nodes representing one node in the second graph),
2316/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00002317///
2318void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00002319 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2320 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00002321 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2322 if (N1 == 0 || N2 == 0) return;
2323
2324 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002325 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002326 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002327 if (StrictChecking) {
2328 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2329 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2330 Entry.getNode()->isNodeCompletelyFolded()) &&
2331 "Inconsistent mapping detected!");
2332 }
Chris Lattner400433d2003-11-11 05:08:59 +00002333 return;
2334 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002335
Chris Lattnerefffdc92004-07-07 06:12:52 +00002336 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002337
2338 // Loop over all of the fields that N1 and N2 have in common, recursively
2339 // mapping the edges together now.
2340 int N2Idx = NH2.getOffset()-NH1.getOffset();
2341 unsigned N2Size = N2->getSize();
Chris Lattner841957e2005-03-15 04:40:24 +00002342 if (N2Size == 0) return; // No edges to map to.
2343
Chris Lattner4d5af8e2005-03-15 21:36:50 +00002344 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2345 const DSNodeHandle &N1NH = N1->getLink(i);
2346 // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2347 // aligned right).
2348 if (!N1NH.isNull()) {
2349 if (unsigned(N2Idx)+i < N2Size)
2350 computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2351 else
2352 computeNodeMapping(N1NH,
2353 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2354 }
2355 }
Chris Lattner400433d2003-11-11 05:08:59 +00002356}
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002357
2358
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002359/// computeGToGGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002360/// nodes in this graph.
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002361void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002362 DSGraph &GG = *getGlobalsGraph();
2363
2364 DSScalarMap &SM = getScalarMap();
2365 for (DSScalarMap::global_iterator I = SM.global_begin(),
2366 E = SM.global_end(); I != E; ++I)
2367 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2368}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002369
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002370/// computeGGToGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002371/// nodes in this graph. Note that any uses of this method are probably bugs,
2372/// unless it is known that the globals graph has been merged into this graph!
2373void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2374 NodeMapTy NodeMap;
2375 computeGToGGMapping(NodeMap);
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002376
Chris Lattner36a13cd2005-03-15 17:52:18 +00002377 while (!NodeMap.empty()) {
2378 InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2379 NodeMap.begin()->first));
2380 NodeMap.erase(NodeMap.begin());
2381 }
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002382}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002383
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002384
2385/// computeCalleeCallerMapping - Given a call from a function in the current
2386/// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2387/// mapping of nodes from the callee to nodes in the caller.
2388void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2389 DSGraph &CalleeGraph,
2390 NodeMapTy &NodeMap) {
2391
2392 DSCallSite CalleeArgs =
2393 CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002394
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002395 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2396
2397 unsigned NumArgs = CS.getNumPtrArgs();
2398 if (NumArgs > CalleeArgs.getNumPtrArgs())
2399 NumArgs = CalleeArgs.getNumPtrArgs();
2400
2401 for (unsigned i = 0; i != NumArgs; ++i)
2402 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002403
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002404 // Map the nodes that are pointed to by globals.
2405 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2406 DSScalarMap &CallerSM = getScalarMap();
2407
2408 if (CalleeSM.global_size() >= CallerSM.global_size()) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002409 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002410 E = CallerSM.global_end(); GI != E; ++GI)
2411 if (CalleeSM.global_count(*GI))
2412 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2413 } else {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002414 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002415 E = CalleeSM.global_end(); GI != E; ++GI)
2416 if (CallerSM.global_count(*GI))
2417 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2418 }
2419}
Andrew Lenharth37705002006-06-19 15:42:47 +00002420
2421/// updateFromGlobalGraph - This function rematerializes global nodes and
2422/// nodes reachable from them from the globals graph into the current graph.
2423///
2424void DSGraph::updateFromGlobalGraph() {
2425 TIME_REGION(X, "updateFromGlobalGraph");
2426 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
2427
2428 // Clone the non-up-to-date global nodes into this graph.
2429 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
2430 E = getScalarMap().global_end(); I != E; ++I) {
2431 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
2432 if (It != GlobalsGraph->ScalarMap.end())
2433 RC.merge(getNodeForValue(*I), It->second);
2434 }
2435}