blob: 169cd659e5dc9c98768398d2699254bdda58733a [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00009//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner4dabb2c2004-07-07 06:32:21 +000014#include "llvm/Analysis/DataStructure/DSGraphTraits.h"
Chris Lattner94f84702005-03-17 19:56:56 +000015#include "llvm/Constants.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000016#include "llvm/Function.h"
Chris Lattnercf14e712004-02-25 23:36:08 +000017#include "llvm/GlobalVariable.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000019#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000020#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000021#include "llvm/Assembly/Writer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000022#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/ADT/DepthFirstIterator.h"
25#include "llvm/ADT/STLExtras.h"
Chris Lattnerd8642122005-03-24 21:07:47 +000026#include "llvm/ADT/SCCIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000027#include "llvm/ADT/Statistic.h"
28#include "llvm/Support/Timer.h"
Chris Lattner72382102006-01-22 23:19:18 +000029#include <iostream>
Chris Lattner0d9bab82002-07-18 00:12:30 +000030#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Chris Lattnerb29dd0f2004-12-08 21:03:56 +000033#define COLLAPSE_ARRAYS_AGGRESSIVELY 0
34
Chris Lattner08db7192002-11-06 06:20:27 +000035namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000036 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
37 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
38 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
39 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000040 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
41 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Andrew Lenharth0c3a0b62006-03-15 05:43:41 +000042 static cl::opt<unsigned>
43 DSAFieldLimit("dsa-field-limit", cl::Hidden,
44 cl::desc("Number of fields to track before collapsing a node"),
45 cl::init(256));
Chris Lattnerd74ea2b2006-05-24 17:04:05 +000046}
Chris Lattner08db7192002-11-06 06:20:27 +000047
Chris Lattner1e9d1472005-03-22 23:54:52 +000048#if 0
Chris Lattner93ddd7e2004-01-22 16:36:28 +000049#define TIME_REGION(VARNAME, DESC) \
50 NamedRegionTimer VARNAME(DESC)
51#else
52#define TIME_REGION(VARNAME, DESC)
53#endif
54
Chris Lattnerb1060432002-11-07 05:20:53 +000055using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000056
Chris Lattner6f967742004-10-30 04:05:01 +000057/// isForwarding - Return true if this NodeHandle is forwarding to another
58/// one.
59bool DSNodeHandle::isForwarding() const {
60 return N && N->isForwarding();
61}
62
Chris Lattner731b2d72003-02-13 19:09:00 +000063DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000064 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000065
66 // Handle node forwarding here!
67 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
68 Offset += N->ForwardNH.getOffset();
69
70 if (--N->NumReferrers == 0) {
71 // Removing the last referrer to the node, sever the forwarding link
72 N->stopForwarding();
73 }
74
75 N = Next;
76 N->NumReferrers++;
77 if (N->Size <= Offset) {
78 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
79 Offset = 0;
80 }
81 return N;
82}
83
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000084//===----------------------------------------------------------------------===//
Chris Lattner612f0b72005-03-22 00:09:45 +000085// DSScalarMap Implementation
86//===----------------------------------------------------------------------===//
87
88DSNodeHandle &DSScalarMap::AddGlobal(GlobalValue *GV) {
89 assert(ValueMap.count(GV) == 0 && "GV already exists!");
90
91 // If the node doesn't exist, check to see if it's a global that is
92 // equated to another global in the program.
93 EquivalenceClasses<GlobalValue*>::iterator ECI = GlobalECs.findValue(GV);
94 if (ECI != GlobalECs.end()) {
95 GlobalValue *Leader = *GlobalECs.findLeader(ECI);
96 if (Leader != GV) {
97 GV = Leader;
98 iterator I = ValueMap.find(GV);
99 if (I != ValueMap.end())
100 return I->second;
101 }
102 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000103
Chris Lattner612f0b72005-03-22 00:09:45 +0000104 // Okay, this is either not an equivalenced global or it is the leader, it
105 // will be inserted into the scalar map now.
106 GlobalSet.insert(GV);
107
108 return ValueMap.insert(std::make_pair(GV, DSNodeHandle())).first->second;
109}
110
111
112//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000113// DSNode Implementation
114//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000115
Chris Lattnerbd92b732003-06-19 21:15:11 +0000116DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +0000117 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000118 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +0000119 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +0000120 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000121 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000122}
123
Chris Lattner0d9bab82002-07-18 00:12:30 +0000124// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +0000125DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +0000126 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattneraf2e3e02005-04-12 03:59:27 +0000127 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattnerf590ced2004-03-04 17:06:53 +0000128 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +0000129 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +0000130 } else
Chris Lattner0b144872004-01-27 22:03:40 +0000131 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +0000132 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000133 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000134}
135
Chris Lattner15869aa2003-11-02 22:27:28 +0000136/// getTargetData - Get the target data object used to construct this node.
137///
138const TargetData &DSNode::getTargetData() const {
139 return ParentGraph->getTargetData();
140}
141
Chris Lattner72d29a42003-02-11 23:11:51 +0000142void DSNode::assertOK() const {
143 assert((Ty != Type::VoidTy ||
144 Ty == Type::VoidTy && (Size == 0 ||
145 (NodeType & DSNode::Array))) &&
146 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000147
148 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000149 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000150 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000151 assert(SM.global_count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000152 assert(SM.find(Globals[i])->second.getNode() == this);
153 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000154}
155
156/// forwardNode - Mark this node as being obsolete, and all references to it
157/// should be forwarded to the specified node and offset.
158///
159void DSNode::forwardNode(DSNode *To, unsigned Offset) {
160 assert(this != To && "Cannot forward a node to itself!");
161 assert(ForwardNH.isNull() && "Already forwarding from this node!");
162 if (To->Size <= 1) Offset = 0;
163 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
164 "Forwarded offset is wrong!");
Chris Lattnerefffdc92004-07-07 06:12:52 +0000165 ForwardNH.setTo(To, Offset);
Chris Lattner72d29a42003-02-11 23:11:51 +0000166 NodeType = DEAD;
167 Size = 0;
168 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000169
170 // Remove this node from the parent graph's Nodes list.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000171 ParentGraph->unlinkNode(this);
Chris Lattner4ff0b962004-02-08 01:27:18 +0000172 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000173}
174
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000175// addGlobal - Add an entry for a global value to the Globals list. This also
176// marks the node with the 'G' flag if it does not already have it.
177//
178void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000179 // First, check to make sure this is the leader if the global is in an
180 // equivalence class.
181 GV = getParentGraph()->getScalarMap().getLeaderForGlobal(GV);
182
Chris Lattner0d9bab82002-07-18 00:12:30 +0000183 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000184 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000185 std::lower_bound(Globals.begin(), Globals.end(), GV);
186
187 if (I == Globals.end() || *I != GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000188 Globals.insert(I, GV);
189 NodeType |= GlobalNode;
190 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000191}
192
Chris Lattner7cdf3212005-03-20 03:29:54 +0000193// removeGlobal - Remove the specified global that is explicitly in the globals
194// list.
195void DSNode::removeGlobal(GlobalValue *GV) {
196 std::vector<GlobalValue*>::iterator I =
197 std::lower_bound(Globals.begin(), Globals.end(), GV);
198 assert(I != Globals.end() && *I == GV && "Global not in node!");
199 Globals.erase(I);
200}
201
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000202/// foldNodeCompletely - If we determine that this node has some funny
203/// behavior happening to it that we cannot represent, we fold it down to a
204/// single, completely pessimistic, node. This node is represented as a
205/// single byte with a single TypeEntry of "void".
206///
207void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000208 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000209
Chris Lattner08db7192002-11-06 06:20:27 +0000210 ++NumFolds;
211
Chris Lattner0b144872004-01-27 22:03:40 +0000212 // If this node has a size that is <= 1, we don't need to create a forwarding
213 // node.
214 if (getSize() <= 1) {
215 NodeType |= DSNode::Array;
216 Ty = Type::VoidTy;
217 Size = 1;
218 assert(Links.size() <= 1 && "Size is 1, but has more links?");
219 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000220 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000221 // Create the node we are going to forward to. This is required because
222 // some referrers may have an offset that is > 0. By forcing them to
223 // forward, the forwarder has the opportunity to correct the offset.
224 DSNode *DestNode = new DSNode(0, ParentGraph);
225 DestNode->NodeType = NodeType|DSNode::Array;
226 DestNode->Ty = Type::VoidTy;
227 DestNode->Size = 1;
228 DestNode->Globals.swap(Globals);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000229
Chris Lattner0b144872004-01-27 22:03:40 +0000230 // Start forwarding to the destination node...
231 forwardNode(DestNode, 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000232
Chris Lattner0b144872004-01-27 22:03:40 +0000233 if (!Links.empty()) {
234 DestNode->Links.reserve(1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000235
Chris Lattner0b144872004-01-27 22:03:40 +0000236 DSNodeHandle NH(DestNode);
237 DestNode->Links.push_back(Links[0]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000238
Chris Lattner0b144872004-01-27 22:03:40 +0000239 // If we have links, merge all of our outgoing links together...
240 for (unsigned i = Links.size()-1; i != 0; --i)
241 NH.getNode()->Links[0].mergeWith(Links[i]);
242 Links.clear();
243 } else {
244 DestNode->Links.resize(1);
245 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000246 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000247}
Chris Lattner076c1f92002-11-07 06:31:54 +0000248
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000249/// isNodeCompletelyFolded - Return true if this node has been completely
250/// folded down to something that can never be expanded, effectively losing
251/// all of the field sensitivity that may be present in the node.
252///
253bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000254 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000255}
256
Chris Lattner82c6c722005-03-20 02:41:38 +0000257/// addFullGlobalsList - Compute the full set of global values that are
258/// represented by this node. Unlike getGlobalsList(), this requires fair
259/// amount of work to compute, so don't treat this method call as free.
260void DSNode::addFullGlobalsList(std::vector<GlobalValue*> &List) const {
261 if (globals_begin() == globals_end()) return;
262
263 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
264
265 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
266 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
267 if (ECI == EC.end())
268 List.push_back(*I);
269 else
270 List.insert(List.end(), EC.member_begin(ECI), EC.member_end());
271 }
272}
273
274/// addFullFunctionList - Identical to addFullGlobalsList, but only return the
275/// functions in the full list.
276void DSNode::addFullFunctionList(std::vector<Function*> &List) const {
277 if (globals_begin() == globals_end()) return;
278
279 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
280
281 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
282 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
283 if (ECI == EC.end()) {
284 if (Function *F = dyn_cast<Function>(*I))
285 List.push_back(F);
286 } else {
287 for (EquivalenceClasses<GlobalValue*>::member_iterator MI =
288 EC.member_begin(ECI), E = EC.member_end(); MI != E; ++MI)
289 if (Function *F = dyn_cast<Function>(*MI))
290 List.push_back(F);
291 }
292 }
293}
294
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000295namespace {
296 /// TypeElementWalker Class - Used for implementation of physical subtyping...
297 ///
298 class TypeElementWalker {
299 struct StackState {
300 const Type *Ty;
301 unsigned Offset;
302 unsigned Idx;
303 StackState(const Type *T, unsigned Off = 0)
304 : Ty(T), Offset(Off), Idx(0) {}
305 };
306
307 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000308 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000309 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000310 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000311 Stack.push_back(T);
312 StepToLeaf();
313 }
314
315 bool isDone() const { return Stack.empty(); }
316 const Type *getCurrentType() const { return Stack.back().Ty; }
317 unsigned getCurrentOffset() const { return Stack.back().Offset; }
318
319 void StepToNextType() {
320 PopStackAndAdvance();
321 StepToLeaf();
322 }
323
324 private:
325 /// PopStackAndAdvance - Pop the current element off of the stack and
326 /// advance the underlying element to the next contained member.
327 void PopStackAndAdvance() {
328 assert(!Stack.empty() && "Cannot pop an empty stack!");
329 Stack.pop_back();
330 while (!Stack.empty()) {
331 StackState &SS = Stack.back();
332 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
333 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000334 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000335 const StructLayout *SL = TD.getStructLayout(ST);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000336 SS.Offset +=
Chris Lattner507bdf92005-01-12 04:51:37 +0000337 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000338 return;
339 }
340 Stack.pop_back(); // At the end of the structure
341 } else {
342 const ArrayType *AT = cast<ArrayType>(SS.Ty);
343 ++SS.Idx;
344 if (SS.Idx != AT->getNumElements()) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000345 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000346 return;
347 }
348 Stack.pop_back(); // At the end of the array
349 }
350 }
351 }
352
353 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
354 /// on the type stack.
355 void StepToLeaf() {
356 if (Stack.empty()) return;
357 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
358 StackState &SS = Stack.back();
359 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000360 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000361 assert(SS.Idx == 0);
362 PopStackAndAdvance();
363 } else {
364 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000365 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000366 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000367 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner507bdf92005-01-12 04:51:37 +0000368 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000369 }
370 } else {
371 const ArrayType *AT = cast<ArrayType>(SS.Ty);
372 if (AT->getNumElements() == 0) {
373 assert(SS.Idx == 0);
374 PopStackAndAdvance();
375 } else {
376 // Step into the array...
377 assert(SS.Idx < AT->getNumElements());
378 Stack.push_back(StackState(AT->getElementType(),
379 SS.Offset+SS.Idx*
Chris Lattner507bdf92005-01-12 04:51:37 +0000380 unsigned(TD.getTypeSize(AT->getElementType()))));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000381 }
382 }
383 }
384 }
385 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000386} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000387
388/// ElementTypesAreCompatible - Check to see if the specified types are
389/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000390/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
391/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000392///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000393static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000394 bool AllowLargerT1, const TargetData &TD){
395 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000396
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000397 while (!T1W.isDone() && !T2W.isDone()) {
398 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
399 return false;
400
401 const Type *T1 = T1W.getCurrentType();
402 const Type *T2 = T2W.getCurrentType();
403 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
404 return false;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000405
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000406 T1W.StepToNextType();
407 T2W.StepToNextType();
408 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000409
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000410 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000411}
412
413
Chris Lattner08db7192002-11-06 06:20:27 +0000414/// mergeTypeInfo - This method merges the specified type into the current node
415/// at the specified offset. This may update the current node's type record if
416/// this gives more information to the node, it may do nothing to the node if
417/// this information is already known, or it may merge the node completely (and
418/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000419///
Chris Lattner08db7192002-11-06 06:20:27 +0000420/// This method returns true if the node is completely folded, otherwise false.
421///
Chris Lattner088b6392003-03-03 17:13:31 +0000422bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
423 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000424 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000425 // Check to make sure the Size member is up-to-date. Size can be one of the
426 // following:
427 // Size = 0, Ty = Void: Nothing is known about this node.
428 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
429 // Size = 1, Ty = Void, Array = 1: The node is collapsed
430 // Otherwise, sizeof(Ty) = Size
431 //
Chris Lattner18552922002-11-18 21:44:46 +0000432 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
433 (Size == 0 && !Ty->isSized() && !isArray()) ||
434 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
435 (Size == 0 && !Ty->isSized() && !isArray()) ||
436 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000437 "Size member of DSNode doesn't match the type structure!");
438 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000439
Chris Lattner18552922002-11-18 21:44:46 +0000440 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000441 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000442
Chris Lattner08db7192002-11-06 06:20:27 +0000443 // Return true immediately if the node is completely folded.
444 if (isNodeCompletelyFolded()) return true;
445
Chris Lattner23f83dc2002-11-08 22:49:57 +0000446 // If this is an array type, eliminate the outside arrays because they won't
447 // be used anyway. This greatly reduces the size of large static arrays used
448 // as global variables, for example.
449 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000450 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000451 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
452 // FIXME: we might want to keep small arrays, but must be careful about
453 // things like: [2 x [10000 x int*]]
454 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000455 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000456 }
457
Chris Lattner08db7192002-11-06 06:20:27 +0000458 // Figure out how big the new type we're merging in is...
Chris Lattner507bdf92005-01-12 04:51:37 +0000459 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000460
461 // Otherwise check to see if we can fold this type into the current node. If
462 // we can't, we fold the node completely, if we can, we potentially update our
463 // internal state.
464 //
Chris Lattner18552922002-11-18 21:44:46 +0000465 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000466 // If this is the first type that this node has seen, just accept it without
467 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000468 assert(Offset == 0 && !isArray() &&
469 "Cannot have an offset into a void node!");
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000470
471 // If this node would have to have an unreasonable number of fields, just
472 // collapse it. This can occur for fortran common blocks, which have stupid
473 // things like { [100000000 x double], [1000000 x double] }.
474 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
Andrew Lenharth0c3a0b62006-03-15 05:43:41 +0000475 if (NumFields > DSAFieldLimit) {
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000476 foldNodeCompletely();
477 return true;
478 }
479
Chris Lattner18552922002-11-18 21:44:46 +0000480 Ty = NewTy;
481 NodeType &= ~Array;
482 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000483 Size = NewTySize;
484
485 // Calculate the number of outgoing links from this node.
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000486 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000487 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000488 }
Chris Lattner08db7192002-11-06 06:20:27 +0000489
490 // Handle node expansion case here...
491 if (Offset+NewTySize > Size) {
492 // It is illegal to grow this node if we have treated it as an array of
493 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000494 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000495 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000496 return true;
497 }
498
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000499 // If this node would have to have an unreasonable number of fields, just
500 // collapse it. This can occur for fortran common blocks, which have stupid
501 // things like { [100000000 x double], [1000000 x double] }.
502 unsigned NumFields = (NewTySize+Offset+DS::PointerSize-1) >> DS::PointerShift;
Andrew Lenharth0c3a0b62006-03-15 05:43:41 +0000503 if (NumFields > DSAFieldLimit) {
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000504 foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000505 return true;
506 }
507
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000508 if (Offset) {
509 //handle some common cases:
510 // Ty: struct { t1, t2, t3, t4, ..., tn}
511 // NewTy: struct { offset, stuff...}
512 // try merge with NewTy: struct {t1, t2, stuff...} if offset lands exactly on a field in Ty
513 if (isa<StructType>(NewTy) && isa<StructType>(Ty)) {
514 DEBUG(std::cerr << "Ty: " << *Ty << "\nNewTy: " << *NewTy << "@" << Offset << "\n");
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000515 const StructType *STy = cast<StructType>(Ty);
516 const StructLayout &SL = *TD.getStructLayout(STy);
517 unsigned i = SL.getElementContainingOffset(Offset);
518 //Either we hit it exactly or give up
519 if (SL.MemberOffsets[i] != Offset) {
520 if (FoldIfIncompatible) foldNodeCompletely();
521 return true;
522 }
523 std::vector<const Type*> nt;
524 for (unsigned x = 0; x < i; ++x)
525 nt.push_back(STy->getElementType(x));
526 STy = cast<StructType>(NewTy);
527 nt.insert(nt.end(), STy->element_begin(), STy->element_end());
528 //and merge
529 STy = StructType::get(nt);
530 DEBUG(std::cerr << "Trying with: " << *STy << "\n");
531 return mergeTypeInfo(STy, 0);
532 }
533
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000534 //Ty: struct { t1, t2, t3 ... tn}
535 //NewTy T offset x
536 //try merge with NewTy: struct : {t1, t2, T} if offset lands on a field in Ty
537 if (isa<StructType>(Ty)) {
538 DEBUG(std::cerr << "Ty: " << *Ty << "\nNewTy: " << *NewTy << "@" << Offset << "\n");
Andrew Lenharth9df47b52006-04-19 15:34:34 +0000539 const StructType *STy = cast<StructType>(Ty);
540 const StructLayout &SL = *TD.getStructLayout(STy);
541 unsigned i = SL.getElementContainingOffset(Offset);
542 //Either we hit it exactly or give up
543 if (SL.MemberOffsets[i] != Offset) {
544 if (FoldIfIncompatible) foldNodeCompletely();
545 return true;
546 }
547 std::vector<const Type*> nt;
548 for (unsigned x = 0; x < i; ++x)
549 nt.push_back(STy->getElementType(x));
550 nt.push_back(NewTy);
551 //and merge
552 STy = StructType::get(nt);
553 DEBUG(std::cerr << "Trying with: " << *STy << "\n");
554 return mergeTypeInfo(STy, 0);
555 }
556
Andrew Lenharth4bebcdb2006-03-15 04:04:21 +0000557 std::cerr << "UNIMP: Trying to merge a growth type into "
558 << "offset != 0: Collapsing!\n";
559 abort();
560 if (FoldIfIncompatible) foldNodeCompletely();
561 return true;
562
563 }
564
565
Chris Lattner08db7192002-11-06 06:20:27 +0000566 // Okay, the situation is nice and simple, we are trying to merge a type in
567 // at offset 0 that is bigger than our current type. Implement this by
568 // switching to the new type and then merge in the smaller one, which should
569 // hit the other code path here. If the other code path decides it's not
570 // ok, it will collapse the node as appropriate.
571 //
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000572
Chris Lattner94f84702005-03-17 19:56:56 +0000573 const Type *OldTy = Ty;
574 Ty = NewTy;
575 NodeType &= ~Array;
576 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000577 Size = NewTySize;
578
579 // Must grow links to be the appropriate size...
Chris Lattner94f84702005-03-17 19:56:56 +0000580 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000581
582 // Merge in the old type now... which is guaranteed to be smaller than the
583 // "current" type.
584 return mergeTypeInfo(OldTy, 0);
585 }
586
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000587 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000588 "Cannot merge something into a part of our type that doesn't exist!");
589
Chris Lattner18552922002-11-18 21:44:46 +0000590 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000591 // type that starts at offset Offset.
592 //
593 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000594 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000595 while (O < Offset) {
596 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
597
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000598 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000599 case Type::StructTyID: {
600 const StructType *STy = cast<StructType>(SubType);
601 const StructLayout &SL = *TD.getStructLayout(STy);
Chris Lattner2787e032005-03-13 19:05:05 +0000602 unsigned i = SL.getElementContainingOffset(Offset-O);
Chris Lattner08db7192002-11-06 06:20:27 +0000603
604 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000605 SubType = STy->getElementType(i);
Chris Lattner507bdf92005-01-12 04:51:37 +0000606 O += (unsigned)SL.MemberOffsets[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000607 break;
608 }
609 case Type::ArrayTyID: {
610 SubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000611 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000612 unsigned Remainder = (Offset-O) % ElSize;
613 O = Offset-Remainder;
614 break;
615 }
616 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000617 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000618 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000619 }
620 }
621
622 assert(O == Offset && "Could not achieve the correct offset!");
623
624 // If we found our type exactly, early exit
625 if (SubType == NewTy) return false;
626
Misha Brukman96a8bd72004-04-29 04:05:30 +0000627 // Differing function types don't require us to merge. They are not values
628 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000629 if (isa<FunctionType>(SubType) &&
630 isa<FunctionType>(NewTy)) return false;
631
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000632 unsigned SubTypeSize = SubType->isSized() ?
Chris Lattner507bdf92005-01-12 04:51:37 +0000633 (unsigned)TD.getTypeSize(SubType) : 0;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000634
635 // Ok, we are getting desperate now. Check for physical subtyping, where we
636 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000637 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000638 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000639 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000640 return false;
641
Chris Lattner08db7192002-11-06 06:20:27 +0000642 // Okay, so we found the leader type at the offset requested. Search the list
643 // of types that starts at this offset. If SubType is currently an array or
644 // structure, the type desired may actually be the first element of the
645 // composite type...
646 //
Chris Lattner18552922002-11-18 21:44:46 +0000647 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000648 while (SubType != NewTy) {
649 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000650 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000651 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000652 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000653 case Type::StructTyID: {
654 const StructType *STy = cast<StructType>(SubType);
655 const StructLayout &SL = *TD.getStructLayout(STy);
656 if (SL.MemberOffsets.size() > 1)
Chris Lattner507bdf92005-01-12 04:51:37 +0000657 NextPadSize = (unsigned)SL.MemberOffsets[1];
Chris Lattner18552922002-11-18 21:44:46 +0000658 else
659 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000660 NextSubType = STy->getElementType(0);
Chris Lattner507bdf92005-01-12 04:51:37 +0000661 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000662 break;
Chris Lattner18552922002-11-18 21:44:46 +0000663 }
Chris Lattner08db7192002-11-06 06:20:27 +0000664 case Type::ArrayTyID:
665 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000666 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner18552922002-11-18 21:44:46 +0000667 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000668 break;
669 default: ;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000670 // fall out
Chris Lattner08db7192002-11-06 06:20:27 +0000671 }
672
673 if (NextSubType == 0)
674 break; // In the default case, break out of the loop
675
Chris Lattner18552922002-11-18 21:44:46 +0000676 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000677 break; // Don't allow shrinking to a smaller type than NewTySize
678 SubType = NextSubType;
679 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000680 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000681 }
682
683 // If we found the type exactly, return it...
684 if (SubType == NewTy)
685 return false;
686
687 // Check to see if we have a compatible, but different type...
688 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000689 // Check to see if this type is obviously convertible... int -> uint f.e.
690 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000691 return false;
692
693 // Check to see if we have a pointer & integer mismatch going on here,
694 // loading a pointer as a long, for example.
695 //
696 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
697 NewTy->isInteger() && isa<PointerType>(SubType))
698 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000699 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
700 // We are accessing the field, plus some structure padding. Ignore the
701 // structure padding.
702 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000703 }
704
Chris Lattner58f98d02003-07-02 04:38:49 +0000705 Module *M = 0;
Chris Lattnera5f47ea2005-03-15 16:55:04 +0000706 if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
707 M = getParentGraph()->retnodes_begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000708 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
709 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
710 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
711 << "SubType: ";
712 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000713
Chris Lattner088b6392003-03-03 17:13:31 +0000714 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000715 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000716}
717
Chris Lattner08db7192002-11-06 06:20:27 +0000718
719
Misha Brukman96a8bd72004-04-29 04:05:30 +0000720/// addEdgeTo - Add an edge from the current node to the specified node. This
721/// can cause merging of nodes in the graph.
722///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000723void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000724 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000725
Andrew Lenharth79acb692006-03-27 23:39:58 +0000726 if (isNodeCompletelyFolded())
727 Offset = 0;
728
Chris Lattner08db7192002-11-06 06:20:27 +0000729 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000730 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000731 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000732 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000733 } else { // No merging to perform...
734 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000735 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000736}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000737
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000738
Misha Brukman96a8bd72004-04-29 04:05:30 +0000739/// MergeSortedVectors - Efficiently merge a vector into another vector where
740/// duplicates are not allowed and both are sorted. This assumes that 'T's are
741/// efficiently copyable and have sane comparison semantics.
742///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000743static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
744 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000745 // By far, the most common cases will be the simple ones. In these cases,
746 // avoid having to allocate a temporary vector...
747 //
748 if (Src.empty()) { // Nothing to merge in...
749 return;
750 } else if (Dest.empty()) { // Just copy the result in...
751 Dest = Src;
752 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000753 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000754 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000755 std::lower_bound(Dest.begin(), Dest.end(), V);
756 if (I == Dest.end() || *I != Src[0]) // If not already contained...
757 Dest.insert(I, Src[0]);
758 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000759 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000760 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000761 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000762 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
763 if (I == Dest.end() || *I != Tmp) // If not already contained...
764 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000765
766 } else {
767 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000768 std::vector<GlobalValue*> Old(Dest);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000769
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000770 // Make space for all of the type entries now...
771 Dest.resize(Dest.size()+Src.size());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000772
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000773 // Merge the two sorted ranges together... into Dest.
774 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000775
776 // Now erase any duplicate entries that may have accumulated into the
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000777 // vectors (because they were in both of the input sets)
778 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
779 }
780}
781
Chris Lattner0b144872004-01-27 22:03:40 +0000782void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
783 MergeSortedVectors(Globals, RHS);
784}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000785
Chris Lattner0b144872004-01-27 22:03:40 +0000786// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000787// This function does the hard work of merging two nodes, CurNodeH
788// and NH after filtering out trivial cases and making sure that
789// CurNodeH.offset >= NH.offset.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000790//
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000791// ***WARNING***
792// Since merging may cause either node to go away, we must always
793// use the node-handles to refer to the nodes. These node handles are
794// automatically updated during merging, so will always provide access
795// to the correct node after a merge.
796//
797void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
798 assert(CurNodeH.getOffset() >= NH.getOffset() &&
799 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000800 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
801 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000802
803 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
804 // respect to NH.Offset) is now zero. NOffset is the distance from the base
805 // of our object that N starts from.
806 //
807 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
808 unsigned NSize = NH.getNode()->getSize();
809
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000810 // If the two nodes are of different size, and the smaller node has the array
811 // bit set, collapse!
812 if (NSize != CurNodeH.getNode()->getSize()) {
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000813#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000814 if (NSize < CurNodeH.getNode()->getSize()) {
815 if (NH.getNode()->isArray())
816 NH.getNode()->foldNodeCompletely();
817 } else if (CurNodeH.getNode()->isArray()) {
818 NH.getNode()->foldNodeCompletely();
819 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000820#endif
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000821 }
822
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000823 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000824 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000825 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000826 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000827
828 // If we are merging a node with a completely folded node, then both nodes are
829 // now completely folded.
830 //
831 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
832 if (!NH.getNode()->isNodeCompletelyFolded()) {
833 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000834 assert(NH.getNode() && NH.getOffset() == 0 &&
835 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000836 NOffset = NH.getOffset();
837 NSize = NH.getNode()->getSize();
838 assert(NOffset == 0 && NSize == 1);
839 }
840 } else if (NH.getNode()->isNodeCompletelyFolded()) {
841 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000842 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
843 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000844 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000845 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000846 assert(NOffset == 0 && NSize == 1);
847 }
848
Chris Lattner72d29a42003-02-11 23:11:51 +0000849 DSNode *N = NH.getNode();
850 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000851 assert(!CurNodeH.getNode()->isDeadNode());
852
Chris Lattner0b144872004-01-27 22:03:40 +0000853 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000854 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000855
Chris Lattner72d29a42003-02-11 23:11:51 +0000856 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000857 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000858 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000859
Chris Lattner72d29a42003-02-11 23:11:51 +0000860 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
861 //
862 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
863 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000864 if (Link.getNode()) {
865 // Compute the offset into the current node at which to
866 // merge this link. In the common case, this is a linear
867 // relation to the offset in the original node (with
868 // wrapping), but if the current node gets collapsed due to
869 // recursive merging, we must make sure to merge in all remaining
870 // links at offset zero.
871 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000872 DSNode *CN = CurNodeH.getNode();
873 if (CN->Size != 1)
874 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
875 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000876 }
877 }
878
879 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000880 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000881
882 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000883 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000884 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000885
886 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000887 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000888 }
889}
890
891
Misha Brukman96a8bd72004-04-29 04:05:30 +0000892/// mergeWith - Merge this node and the specified node, moving all links to and
893/// from the argument node into the current node, deleting the node argument.
894/// Offset indicates what offset the specified node is to be merged into the
895/// current node.
896///
897/// The specified node may be a null pointer (in which case, we update it to
898/// point to this node).
899///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000900void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
901 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000902 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000903 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000904
Chris Lattner5254a8d2004-01-22 16:31:08 +0000905 // If the RHS is a null node, make it point to this node!
906 if (N == 0) {
907 NH.mergeWith(DSNodeHandle(this, Offset));
908 return;
909 }
910
Chris Lattnerbd92b732003-06-19 21:15:11 +0000911 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000912 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
913
Chris Lattner02606632002-11-04 06:48:26 +0000914 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000915 // We cannot merge two pieces of the same node together, collapse the node
916 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000917 DEBUG(std::cerr << "Attempting to merge two chunks of"
918 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000919 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000920 return;
921 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000922
Chris Lattner5190ce82002-11-12 07:20:45 +0000923 // If both nodes are not at offset 0, make sure that we are merging the node
924 // at an later offset into the node with the zero offset.
925 //
926 if (Offset < NH.getOffset()) {
927 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
928 return;
929 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
930 // If the offsets are the same, merge the smaller node into the bigger node
931 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
932 return;
933 }
934
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000935 // Ok, now we can merge the two nodes. Use a static helper that works with
936 // two node handles, since "this" may get merged away at intermediate steps.
937 DSNodeHandle CurNodeH(this, Offset);
938 DSNodeHandle NHCopy(NH);
Andrew Lenharth37705002006-06-19 15:42:47 +0000939 if (CurNodeH.getOffset() >= NHCopy.getOffset())
940 DSNode::MergeNodes(CurNodeH, NHCopy);
941 else
942 DSNode::MergeNodes(NHCopy, CurNodeH);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000943}
944
Chris Lattner0b144872004-01-27 22:03:40 +0000945
946//===----------------------------------------------------------------------===//
947// ReachabilityCloner Implementation
948//===----------------------------------------------------------------------===//
949
950DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
951 if (SrcNH.isNull()) return DSNodeHandle();
952 const DSNode *SN = SrcNH.getNode();
953
954 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000955 if (!NH.isNull()) { // Node already mapped?
956 DSNode *NHN = NH.getNode();
957 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
958 }
Chris Lattner0b144872004-01-27 22:03:40 +0000959
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000960 // If SrcNH has globals and the destination graph has one of the same globals,
961 // merge this node with the destination node, which is much more efficient.
Chris Lattner82c6c722005-03-20 02:41:38 +0000962 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000963 DSScalarMap &DestSM = Dest.getScalarMap();
Chris Lattner82c6c722005-03-20 02:41:38 +0000964 for (DSNode::globals_iterator I = SN->globals_begin(),E = SN->globals_end();
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000965 I != E; ++I) {
966 GlobalValue *GV = *I;
967 DSScalarMap::iterator GI = DestSM.find(GV);
968 if (GI != DestSM.end() && !GI->second.isNull()) {
969 // We found one, use merge instead!
970 merge(GI->second, Src.getNodeForValue(GV));
971 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000972 DSNode *NHN = NH.getNode();
973 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000974 }
975 }
976 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000977
Chris Lattner0b144872004-01-27 22:03:40 +0000978 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
979 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000980 NH = DN;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000981
Chris Lattner0b144872004-01-27 22:03:40 +0000982 // Next, recursively clone all outgoing links as necessary. Note that
983 // adding these links can cause the node to collapse itself at any time, and
984 // the current node may be merged with arbitrary other nodes. For this
985 // reason, we must always go through NH.
986 DN = 0;
987 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
988 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
989 if (!SrcEdge.isNull()) {
990 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
991 // Compute the offset into the current node at which to
992 // merge this link. In the common case, this is a linear
993 // relation to the offset in the original node (with
994 // wrapping), but if the current node gets collapsed due to
995 // recursive merging, we must make sure to merge in all remaining
996 // links at offset zero.
997 unsigned MergeOffset = 0;
998 DSNode *CN = NH.getNode();
999 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +00001000 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +00001001 CN->addEdgeTo(MergeOffset, DestEdge);
1002 }
1003 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001004
Chris Lattner0b144872004-01-27 22:03:40 +00001005 // If this node contains any globals, make sure they end up in the scalar
1006 // map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +00001007 for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
Chris Lattner0b144872004-01-27 22:03:40 +00001008 I != E; ++I) {
1009 GlobalValue *GV = *I;
1010 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1011 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1012 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
1013 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +00001014 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001015 }
Chris Lattner82c6c722005-03-20 02:41:38 +00001016 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001017
1018 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
1019}
1020
1021void ReachabilityCloner::merge(const DSNodeHandle &NH,
1022 const DSNodeHandle &SrcNH) {
1023 if (SrcNH.isNull()) return; // Noop
1024 if (NH.isNull()) {
1025 // If there is no destination node, just clone the source and assign the
1026 // destination node to be it.
1027 NH.mergeWith(getClonedNH(SrcNH));
1028 return;
1029 }
1030
1031 // Okay, at this point, we know that we have both a destination and a source
1032 // node that need to be merged. Check to see if the source node has already
1033 // been cloned.
1034 const DSNode *SN = SrcNH.getNode();
1035 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +00001036 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +00001037 DSNode *SCNHN = SCNH.getNode();
1038 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +00001039 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001040 return; // Nothing to do!
1041 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001042
Chris Lattner0b144872004-01-27 22:03:40 +00001043 // Okay, so the source node has not already been cloned. Instead of creating
1044 // a new DSNode, only to merge it into the one we already have, try to perform
1045 // the merge in-place. The only case we cannot handle here is when the offset
1046 // into the existing node is less than the offset into the virtual node we are
1047 // merging in. In this case, we have to extend the existing node, which
1048 // requires an allocation anyway.
1049 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
1050 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +00001051 if (!DN->isNodeCompletelyFolded()) {
1052 // Make sure the destination node is folded if the source node is folded.
1053 if (SN->isNodeCompletelyFolded()) {
1054 DN->foldNodeCompletely();
1055 DN = NH.getNode();
1056 } else if (SN->getSize() != DN->getSize()) {
1057 // If the two nodes are of different size, and the smaller node has the
1058 // array bit set, collapse!
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001059#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner0b144872004-01-27 22:03:40 +00001060 if (SN->getSize() < DN->getSize()) {
1061 if (SN->isArray()) {
1062 DN->foldNodeCompletely();
1063 DN = NH.getNode();
1064 }
1065 } else if (DN->isArray()) {
1066 DN->foldNodeCompletely();
1067 DN = NH.getNode();
1068 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001069#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001070 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001071
1072 // Merge the type entries of the two nodes together...
Chris Lattner0b144872004-01-27 22:03:40 +00001073 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
1074 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
1075 DN = NH.getNode();
1076 }
1077 }
1078
1079 assert(!DN->isDeadNode());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001080
Chris Lattner0b144872004-01-27 22:03:40 +00001081 // Merge the NodeType information.
1082 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
1083
1084 // Before we start merging outgoing links and updating the scalar map, make
1085 // sure it is known that this is the representative node for the src node.
1086 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
1087
1088 // If the source node contains any globals, make sure they end up in the
1089 // scalar map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +00001090 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattner0b144872004-01-27 22:03:40 +00001091 // Update the globals in the destination node itself.
Chris Lattner82c6c722005-03-20 02:41:38 +00001092 DN->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001093
1094 // Update the scalar map for the graph we are merging the source node
1095 // into.
Chris Lattner82c6c722005-03-20 02:41:38 +00001096 for (DSNode::globals_iterator I = SN->globals_begin(),
1097 E = SN->globals_end(); I != E; ++I) {
Chris Lattner0b144872004-01-27 22:03:40 +00001098 GlobalValue *GV = *I;
1099 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1100 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1101 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1102 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +00001103 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001104 }
Chris Lattner82c6c722005-03-20 02:41:38 +00001105 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001106 }
1107 } else {
1108 // We cannot handle this case without allocating a temporary node. Fall
1109 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +00001110 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
1111 NewDN->maskNodeTypes(BitsToKeep);
1112
1113 unsigned NHOffset = NH.getOffset();
1114 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001115
Chris Lattner0b144872004-01-27 22:03:40 +00001116 assert(NH.getNode() &&
1117 (NH.getOffset() > NHOffset ||
1118 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
1119 "Merging did not adjust the offset!");
1120
1121 // Before we start merging outgoing links and updating the scalar map, make
1122 // sure it is known that this is the representative node for the src node.
1123 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +00001124
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001125 // If the source node contained any globals, make sure to create entries
Chris Lattneread9eb72004-01-29 08:36:22 +00001126 // in the scalar map for them!
Chris Lattner82c6c722005-03-20 02:41:38 +00001127 for (DSNode::globals_iterator I = SN->globals_begin(),
1128 E = SN->globals_end(); I != E; ++I) {
Chris Lattneread9eb72004-01-29 08:36:22 +00001129 GlobalValue *GV = *I;
1130 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1131 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1132 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1133 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
1134 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1135 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001136 }
Chris Lattner0b144872004-01-27 22:03:40 +00001137 }
1138
1139
1140 // Next, recursively merge all outgoing links as necessary. Note that
1141 // adding these links can cause the destination node to collapse itself at
1142 // any time, and the current node may be merged with arbitrary other nodes.
1143 // For this reason, we must always go through NH.
1144 DN = 0;
1145 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1146 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1147 if (!SrcEdge.isNull()) {
1148 // Compute the offset into the current node at which to
1149 // merge this link. In the common case, this is a linear
1150 // relation to the offset in the original node (with
1151 // wrapping), but if the current node gets collapsed due to
1152 // recursive merging, we must make sure to merge in all remaining
1153 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +00001154 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +00001155 unsigned MergeOffset =
1156 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001157
Chris Lattnerf590ced2004-03-04 17:06:53 +00001158 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1159 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001160 // Perform the recursive merging. Make sure to create a temporary NH,
1161 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001162 merge(Tmp, SrcEdge);
1163 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001164 Tmp.mergeWith(getClonedNH(SrcEdge));
1165 // Merging this could cause all kinds of recursive things to happen,
1166 // culminating in the current node being eliminated. Since this is
1167 // possible, make sure to reaquire the link from 'CN'.
1168
1169 unsigned MergeOffset = 0;
1170 CN = SCNH.getNode();
1171 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1172 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001173 }
Chris Lattner0b144872004-01-27 22:03:40 +00001174 }
1175 }
1176}
1177
1178/// mergeCallSite - Merge the nodes reachable from the specified src call
1179/// site into the nodes reachable from DestCS.
Chris Lattnerb3439372005-03-21 20:28:50 +00001180void ReachabilityCloner::mergeCallSite(DSCallSite &DestCS,
Chris Lattner0b144872004-01-27 22:03:40 +00001181 const DSCallSite &SrcCS) {
1182 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1183 unsigned MinArgs = DestCS.getNumPtrArgs();
1184 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001185
Chris Lattner0b144872004-01-27 22:03:40 +00001186 for (unsigned a = 0; a != MinArgs; ++a)
1187 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
Chris Lattner3f90a942005-03-21 09:39:51 +00001188
1189 for (unsigned a = MinArgs, e = SrcCS.getNumPtrArgs(); a != e; ++a)
Chris Lattnerb3439372005-03-21 20:28:50 +00001190 DestCS.addPtrArg(getClonedNH(SrcCS.getPtrArg(a)));
Chris Lattner0b144872004-01-27 22:03:40 +00001191}
1192
1193
Chris Lattner9de906c2002-10-20 22:11:44 +00001194//===----------------------------------------------------------------------===//
1195// DSCallSite Implementation
1196//===----------------------------------------------------------------------===//
1197
Vikram S. Adve26b98262002-10-20 21:41:02 +00001198// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001199Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001200 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001201}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001202
Chris Lattner0b144872004-01-27 22:03:40 +00001203void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1204 ReachabilityCloner &RC) {
1205 NH = RC.getClonedNH(Src);
1206}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001207
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001208//===----------------------------------------------------------------------===//
1209// DSGraph Implementation
1210//===----------------------------------------------------------------------===//
1211
Chris Lattnera9d65662003-06-30 05:57:30 +00001212/// getFunctionNames - Return a space separated list of the name of the
1213/// functions in this graph (if any)
1214std::string DSGraph::getFunctionNames() const {
1215 switch (getReturnNodes().size()) {
1216 case 0: return "Globals graph";
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001217 case 1: return retnodes_begin()->first->getName();
Chris Lattnera9d65662003-06-30 05:57:30 +00001218 default:
1219 std::string Return;
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001220 for (DSGraph::retnodes_iterator I = retnodes_begin();
1221 I != retnodes_end(); ++I)
Chris Lattnera9d65662003-06-30 05:57:30 +00001222 Return += I->first->getName() + " ";
1223 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1224 return Return;
1225 }
1226}
1227
1228
Chris Lattnerf09ecff2005-03-21 22:49:53 +00001229DSGraph::DSGraph(const DSGraph &G, EquivalenceClasses<GlobalValue*> &ECs,
1230 unsigned CloneFlags)
Chris Lattnerf4f62272005-03-19 22:23:45 +00001231 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001232 PrintAuxCalls = false;
Chris Lattnera2197132005-03-22 00:36:51 +00001233 cloneInto(G, CloneFlags);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001234}
1235
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001236DSGraph::~DSGraph() {
1237 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001238 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001239 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001240 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001241
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001242 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001243 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
Chris Lattner84b80a22005-03-16 22:42:19 +00001244 NI->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001245
Chris Lattner28897e12004-02-08 00:53:26 +00001246 // Free all of the nodes.
1247 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001248}
1249
Chris Lattner0d9bab82002-07-18 00:12:30 +00001250// dump - Allow inspection of graph in a debugger.
1251void DSGraph::dump() const { print(std::cerr); }
1252
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001253
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001254/// remapLinks - Change all of the Links in the current node according to the
1255/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001256///
Chris Lattner8d327672003-06-30 03:36:09 +00001257void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001258 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1259 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001260 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001261 if (ONMI != OldNodeMap.end()) {
1262 DSNode *ONMIN = ONMI->second.getNode();
1263 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1264 }
Chris Lattner2f561382004-01-22 16:56:13 +00001265 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001266}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001267
Chris Lattnerd672ab92005-02-15 18:40:55 +00001268/// addObjectToGraph - This method can be used to add global, stack, and heap
1269/// objects to the graph. This can be used when updating DSGraphs due to the
1270/// introduction of new temporary objects. The new object is not pointed to
1271/// and does not point to any other objects in the graph.
1272DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1273 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1274 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1275 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
Chris Lattner7a0c7752005-02-15 18:48:48 +00001276 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
Chris Lattnerd672ab92005-02-15 18:40:55 +00001277 ScalarMap[Ptr] = N;
1278
1279 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1280 N->addGlobal(GV);
Reid Spencer3ed469c2006-11-02 20:25:50 +00001281 } else if (isa<MallocInst>(Ptr)) {
Chris Lattnerd672ab92005-02-15 18:40:55 +00001282 N->setHeapNodeMarker();
Reid Spencer3ed469c2006-11-02 20:25:50 +00001283 } else if (isa<AllocaInst>(Ptr)) {
Chris Lattnerd672ab92005-02-15 18:40:55 +00001284 N->setAllocaNodeMarker();
1285 } else {
1286 assert(0 && "Illegal memory object input!");
1287 }
1288 return N;
1289}
1290
1291
Chris Lattner5a540632003-06-30 03:15:25 +00001292/// cloneInto - Clone the specified DSGraph into the current graph. The
Chris Lattner3c920fa2005-03-22 00:21:05 +00001293/// translated ScalarMap for the old function is filled into the ScalarMap
1294/// for the graph, and the translated ReturnNodes map is returned into
1295/// ReturnNodes.
Chris Lattner5a540632003-06-30 03:15:25 +00001296///
1297/// The CloneFlags member controls various aspects of the cloning process.
1298///
Chris Lattnera2197132005-03-22 00:36:51 +00001299void DSGraph::cloneInto(const DSGraph &G, unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001300 TIME_REGION(X, "cloneInto");
Chris Lattner33312f72002-11-08 01:21:07 +00001301 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001302
Chris Lattnera2197132005-03-22 00:36:51 +00001303 NodeMapTy OldNodeMap;
1304
Chris Lattner1e883692003-02-03 20:08:51 +00001305 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001306 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1307 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1308 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001309 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001310
Chris Lattner84b80a22005-03-16 22:42:19 +00001311 for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1312 assert(!I->isForwarding() &&
Chris Lattnerd85645f2004-02-21 22:28:26 +00001313 "Forward nodes shouldn't be in node list!");
Chris Lattner84b80a22005-03-16 22:42:19 +00001314 DSNode *New = new DSNode(*I, this);
Chris Lattnerd85645f2004-02-21 22:28:26 +00001315 New->maskNodeTypes(~BitsToClear);
Chris Lattner84b80a22005-03-16 22:42:19 +00001316 OldNodeMap[I] = New;
Chris Lattnerd85645f2004-02-21 22:28:26 +00001317 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001318
Chris Lattner18552922002-11-18 21:44:46 +00001319#ifndef NDEBUG
1320 Timer::addPeakMemoryMeasurement();
1321#endif
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001322
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001323 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001324 // Note that we don't loop over the node's list to do this. The problem is
1325 // that remaping links can cause recursive merging to happen, which means
1326 // that node_iterator's can get easily invalidated! Because of this, we
1327 // loop over the OldNodeMap, which contains all of the new nodes as the
1328 // .second element of the map elements. Also note that if we remap a node
1329 // more than once, we won't break anything.
1330 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1331 I != E; ++I)
1332 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001333
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001334 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001335 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001336 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001337 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner3bc703b2005-03-22 01:42:59 +00001338 DSNodeHandle &H = ScalarMap.getRawEntryRef(I->first);
Chris Lattner6f967742004-10-30 04:05:01 +00001339 DSNode *MappedNodeN = MappedNode.getNode();
1340 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001341 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001342 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001343
Chris Lattner679e8e12002-11-08 21:27:12 +00001344 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001345 // Copy the function calls list.
1346 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1347 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001348 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001349
Chris Lattneracf491f2002-11-08 22:27:09 +00001350 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001351 // Copy the auxiliary function calls list.
1352 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1353 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattner679e8e12002-11-08 21:27:12 +00001354 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001355
Chris Lattner5a540632003-06-30 03:15:25 +00001356 // Map the return node pointers over...
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001357 for (retnodes_iterator I = G.retnodes_begin(),
1358 E = G.retnodes_end(); I != E; ++I) {
Chris Lattner5a540632003-06-30 03:15:25 +00001359 const DSNodeHandle &Ret = I->second;
1360 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001361 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattnerd65145b2005-03-22 00:29:44 +00001362 ReturnNodes.insert(std::make_pair(I->first,
1363 DSNodeHandle(MappedRetN,
1364 MappedRet.getOffset()+Ret.getOffset())));
Chris Lattner5a540632003-06-30 03:15:25 +00001365 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001366}
1367
Chris Lattner5734e432005-03-24 23:46:04 +00001368/// spliceFrom - Logically perform the operation of cloning the RHS graph into
1369/// this graph, then clearing the RHS graph. Instead of performing this as
1370/// two seperate operations, do it as a single, much faster, one.
1371///
1372void DSGraph::spliceFrom(DSGraph &RHS) {
1373 // Change all of the nodes in RHS to think we are their parent.
1374 for (NodeListTy::iterator I = RHS.Nodes.begin(), E = RHS.Nodes.end();
1375 I != E; ++I)
1376 I->setParentGraph(this);
1377 // Take all of the nodes.
1378 Nodes.splice(Nodes.end(), RHS.Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001379
Chris Lattner5734e432005-03-24 23:46:04 +00001380 // Take all of the calls.
1381 FunctionCalls.splice(FunctionCalls.end(), RHS.FunctionCalls);
1382 AuxFunctionCalls.splice(AuxFunctionCalls.end(), RHS.AuxFunctionCalls);
1383
1384 // Take all of the return nodes.
Chris Lattnerce7068d2005-03-25 00:02:41 +00001385 if (ReturnNodes.empty()) {
1386 ReturnNodes.swap(RHS.ReturnNodes);
1387 } else {
1388 ReturnNodes.insert(RHS.ReturnNodes.begin(), RHS.ReturnNodes.end());
1389 RHS.ReturnNodes.clear();
1390 }
Chris Lattner5734e432005-03-24 23:46:04 +00001391
1392 // Merge the scalar map in.
1393 ScalarMap.spliceFrom(RHS.ScalarMap);
1394}
1395
1396/// spliceFrom - Copy all entries from RHS, then clear RHS.
1397///
1398void DSScalarMap::spliceFrom(DSScalarMap &RHS) {
1399 // Special case if this is empty.
1400 if (ValueMap.empty()) {
1401 ValueMap.swap(RHS.ValueMap);
1402 GlobalSet.swap(RHS.GlobalSet);
1403 } else {
1404 GlobalSet.insert(RHS.GlobalSet.begin(), RHS.GlobalSet.end());
1405 for (ValueMapTy::iterator I = RHS.ValueMap.begin(), E = RHS.ValueMap.end();
1406 I != E; ++I)
1407 ValueMap[I->first].mergeWith(I->second);
1408 RHS.ValueMap.clear();
1409 }
1410}
1411
1412
Chris Lattnerbb753c42005-02-03 18:40:25 +00001413/// getFunctionArgumentsForCall - Given a function that is currently in this
1414/// graph, return the DSNodeHandles that correspond to the pointer-compatible
1415/// function arguments. The vector is filled in with the return value (or
1416/// null if it is not pointer compatible), followed by all of the
1417/// pointer-compatible arguments.
1418void DSGraph::getFunctionArgumentsForCall(Function *F,
1419 std::vector<DSNodeHandle> &Args) const {
1420 Args.push_back(getReturnNodeFor(*F));
Chris Lattnereb394922005-03-23 16:43:11 +00001421 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1422 AI != E; ++AI)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001423 if (isPointerType(AI->getType())) {
1424 Args.push_back(getNodeForValue(AI));
1425 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1426 }
1427}
1428
Chris Lattner4da120e2005-03-24 23:06:02 +00001429namespace {
1430 // HackedGraphSCCFinder - This is used to find nodes that have a path from the
1431 // node to a node cloned by the ReachabilityCloner object contained. To be
1432 // extra obnoxious it ignores edges from nodes that are globals, and truncates
1433 // search at RC marked nodes. This is designed as an object so that
1434 // intermediate results can be memoized across invocations of
1435 // PathExistsToClonedNode.
1436 struct HackedGraphSCCFinder {
1437 ReachabilityCloner &RC;
1438 unsigned CurNodeId;
1439 std::vector<const DSNode*> SCCStack;
1440 std::map<const DSNode*, std::pair<unsigned, bool> > NodeInfo;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001441
Chris Lattner4da120e2005-03-24 23:06:02 +00001442 HackedGraphSCCFinder(ReachabilityCloner &rc) : RC(rc), CurNodeId(1) {
1443 // Remove null pointer as a special case.
1444 NodeInfo[0] = std::make_pair(0, false);
Chris Lattnerd8642122005-03-24 21:07:47 +00001445 }
1446
Chris Lattner4da120e2005-03-24 23:06:02 +00001447 std::pair<unsigned, bool> &VisitForSCCs(const DSNode *N);
1448
1449 bool PathExistsToClonedNode(const DSNode *N) {
1450 return VisitForSCCs(N).second;
1451 }
1452
1453 bool PathExistsToClonedNode(const DSCallSite &CS) {
1454 if (PathExistsToClonedNode(CS.getRetVal().getNode()))
1455 return true;
1456 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1457 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode()))
1458 return true;
1459 return false;
1460 }
1461 };
1462}
1463
1464std::pair<unsigned, bool> &HackedGraphSCCFinder::
1465VisitForSCCs(const DSNode *N) {
1466 std::map<const DSNode*, std::pair<unsigned, bool> >::iterator
1467 NodeInfoIt = NodeInfo.lower_bound(N);
1468 if (NodeInfoIt != NodeInfo.end() && NodeInfoIt->first == N)
1469 return NodeInfoIt->second;
1470
1471 unsigned Min = CurNodeId++;
1472 unsigned MyId = Min;
1473 std::pair<unsigned, bool> &ThisNodeInfo =
1474 NodeInfo.insert(NodeInfoIt,
1475 std::make_pair(N, std::make_pair(MyId, false)))->second;
1476
1477 // Base case: if we find a global, this doesn't reach the cloned graph
1478 // portion.
1479 if (N->isGlobalNode()) {
1480 ThisNodeInfo.second = false;
1481 return ThisNodeInfo;
Chris Lattnerd8642122005-03-24 21:07:47 +00001482 }
1483
Chris Lattner4da120e2005-03-24 23:06:02 +00001484 // Base case: if this does reach the cloned graph portion... it does. :)
1485 if (RC.hasClonedNode(N)) {
1486 ThisNodeInfo.second = true;
1487 return ThisNodeInfo;
1488 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001489
Chris Lattner4da120e2005-03-24 23:06:02 +00001490 SCCStack.push_back(N);
Chris Lattnerd8642122005-03-24 21:07:47 +00001491
Chris Lattner4da120e2005-03-24 23:06:02 +00001492 // Otherwise, check all successors.
1493 bool AnyDirectSuccessorsReachClonedNodes = false;
1494 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
Chris Lattner63320cc2005-04-25 19:16:17 +00001495 EI != EE; ++EI)
1496 if (DSNode *Succ = EI->getNode()) {
1497 std::pair<unsigned, bool> &SuccInfo = VisitForSCCs(Succ);
1498 if (SuccInfo.first < Min) Min = SuccInfo.first;
1499 AnyDirectSuccessorsReachClonedNodes |= SuccInfo.second;
1500 }
Chris Lattner4da120e2005-03-24 23:06:02 +00001501
1502 if (Min != MyId)
1503 return ThisNodeInfo; // Part of a large SCC. Leave self on stack.
1504
1505 if (SCCStack.back() == N) { // Special case single node SCC.
1506 SCCStack.pop_back();
1507 ThisNodeInfo.second = AnyDirectSuccessorsReachClonedNodes;
1508 return ThisNodeInfo;
1509 }
1510
1511 // Find out if any direct successors of any node reach cloned nodes.
1512 if (!AnyDirectSuccessorsReachClonedNodes)
1513 for (unsigned i = SCCStack.size()-1; SCCStack[i] != N; --i)
1514 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1515 EI != EE; ++EI)
1516 if (DSNode *N = EI->getNode())
1517 if (NodeInfo[N].second) {
1518 AnyDirectSuccessorsReachClonedNodes = true;
1519 goto OutOfLoop;
1520 }
1521OutOfLoop:
1522 // If any successor reaches a cloned node, mark all nodes in this SCC as
1523 // reaching the cloned node.
1524 if (AnyDirectSuccessorsReachClonedNodes)
1525 while (SCCStack.back() != N) {
1526 NodeInfo[SCCStack.back()].second = true;
1527 SCCStack.pop_back();
1528 }
1529 SCCStack.pop_back();
1530 ThisNodeInfo.second = true;
1531 return ThisNodeInfo;
1532}
Chris Lattnerd8642122005-03-24 21:07:47 +00001533
Chris Lattnere8594442005-02-04 19:58:28 +00001534/// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1535/// nodes from G2 into 'this' graph, merging the bindings specified by the
1536/// call site (in this graph) with the bindings specified by the vector in G2.
1537/// The two DSGraphs must be different.
Chris Lattner076c1f92002-11-07 06:31:54 +00001538///
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001539void DSGraph::mergeInGraph(const DSCallSite &CS,
Chris Lattnere8594442005-02-04 19:58:28 +00001540 std::vector<DSNodeHandle> &Args,
Chris Lattner9f930552003-06-30 05:27:18 +00001541 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001542 TIME_REGION(X, "mergeInGraph");
1543
Chris Lattnerc14f59c2005-03-23 20:12:08 +00001544 assert((CloneFlags & DontCloneCallNodes) &&
1545 "Doesn't support copying of call nodes!");
1546
Chris Lattner076c1f92002-11-07 06:31:54 +00001547 // If this is not a recursive call, clone the graph into this graph...
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001548 if (&Graph == this) {
Chris Lattnerbb753c42005-02-03 18:40:25 +00001549 // Merge the return value with the return value of the context.
1550 Args[0].mergeWith(CS.getRetVal());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001551
Chris Lattnerbb753c42005-02-03 18:40:25 +00001552 // Resolve all of the function arguments.
1553 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001554 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001555 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001556
Chris Lattnerbb753c42005-02-03 18:40:25 +00001557 // Add the link from the argument scalar to the provided value.
1558 Args[i+1].mergeWith(CS.getPtrArg(i));
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001559 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001560 return;
Chris Lattner076c1f92002-11-07 06:31:54 +00001561 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001562
1563 // Clone the callee's graph into the current graph, keeping track of where
1564 // scalars in the old graph _used_ to point, and of the new nodes matching
1565 // nodes of the old graph.
1566 ReachabilityCloner RC(*this, Graph, CloneFlags);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001567
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001568 // Map the return node pointer over.
1569 if (!CS.getRetVal().isNull())
1570 RC.merge(CS.getRetVal(), Args[0]);
1571
1572 // Map over all of the arguments.
1573 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1574 if (i == Args.size()-1)
1575 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001576
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001577 // Add the link from the argument scalar to the provided value.
1578 RC.merge(CS.getPtrArg(i), Args[i+1]);
1579 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001580
Chris Lattnerd8642122005-03-24 21:07:47 +00001581 // We generally don't want to copy global nodes or aux calls from the callee
1582 // graph to the caller graph. However, we have to copy them if there is a
1583 // path from the node to a node we have already copied which does not go
1584 // through another global. Compute the set of node that can reach globals and
1585 // aux call nodes to copy over, then do it.
1586 std::vector<const DSCallSite*> AuxCallToCopy;
1587 std::vector<GlobalValue*> GlobalsToCopy;
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001588
Chris Lattnerd8642122005-03-24 21:07:47 +00001589 // NodesReachCopiedNodes - Memoize results for efficiency. Contains a
1590 // true/false value for every visited node that reaches a copied node without
1591 // going through a global.
Chris Lattner4da120e2005-03-24 23:06:02 +00001592 HackedGraphSCCFinder SCCFinder(RC);
Chris Lattnerd8642122005-03-24 21:07:47 +00001593
1594 if (!(CloneFlags & DontCloneAuxCallNodes))
1595 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
Chris Lattner4da120e2005-03-24 23:06:02 +00001596 if (SCCFinder.PathExistsToClonedNode(*I))
Chris Lattnerd8642122005-03-24 21:07:47 +00001597 AuxCallToCopy.push_back(&*I);
Andrew Lenharth37705002006-06-19 15:42:47 +00001598 else if (I->isIndirectCall()){
1599 //If the call node doesn't have any callees, clone it
1600 std::vector< Function *> List;
1601 I->getCalleeNode()->addFullFunctionList(List);
1602 if (!List.size())
1603 AuxCallToCopy.push_back(&*I);
1604 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001605
Chris Lattner4da120e2005-03-24 23:06:02 +00001606 const DSScalarMap &GSM = Graph.getScalarMap();
Chris Lattnerd8642122005-03-24 21:07:47 +00001607 for (DSScalarMap::global_iterator GI = GSM.global_begin(),
Chris Lattner09adbbc92005-03-24 21:17:27 +00001608 E = GSM.global_end(); GI != E; ++GI) {
1609 DSNode *GlobalNode = Graph.getNodeForValue(*GI).getNode();
1610 for (DSNode::edge_iterator EI = GlobalNode->edge_begin(),
1611 EE = GlobalNode->edge_end(); EI != EE; ++EI)
Chris Lattner4da120e2005-03-24 23:06:02 +00001612 if (SCCFinder.PathExistsToClonedNode(EI->getNode())) {
Chris Lattner09adbbc92005-03-24 21:17:27 +00001613 GlobalsToCopy.push_back(*GI);
1614 break;
1615 }
1616 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001617
1618 // Copy aux calls that are needed.
1619 for (unsigned i = 0, e = AuxCallToCopy.size(); i != e; ++i)
1620 AuxFunctionCalls.push_back(DSCallSite(*AuxCallToCopy[i], RC));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001621
Chris Lattnerd8642122005-03-24 21:07:47 +00001622 // Copy globals that are needed.
1623 for (unsigned i = 0, e = GlobalsToCopy.size(); i != e; ++i)
1624 RC.getClonedNH(Graph.getNodeForValue(GlobalsToCopy[i]));
Chris Lattner076c1f92002-11-07 06:31:54 +00001625}
1626
Chris Lattnere8594442005-02-04 19:58:28 +00001627
1628
1629/// mergeInGraph - The method is used for merging graphs together. If the
1630/// argument graph is not *this, it makes a clone of the specified graph, then
1631/// merges the nodes specified in the call site with the formal arguments in the
1632/// graph.
1633///
1634void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1635 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattnere8594442005-02-04 19:58:28 +00001636 // Set up argument bindings.
1637 std::vector<DSNodeHandle> Args;
1638 Graph.getFunctionArgumentsForCall(&F, Args);
1639
1640 mergeInGraph(CS, Args, Graph, CloneFlags);
1641}
1642
Chris Lattner58f98d02003-07-02 04:38:49 +00001643/// getCallSiteForArguments - Get the arguments and return value bindings for
1644/// the specified function in the current graph.
1645///
1646DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1647 std::vector<DSNodeHandle> Args;
1648
Chris Lattnere4d5c442005-03-15 04:54:21 +00001649 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner58f98d02003-07-02 04:38:49 +00001650 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001651 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001652
Chris Lattner808a7ae2003-09-20 16:34:13 +00001653 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001654}
1655
Chris Lattner85fb1be2004-03-09 19:37:06 +00001656/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1657/// the context of this graph, return the DSCallSite for it.
1658DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1659 DSNodeHandle RetVal;
1660 Instruction *I = CS.getInstruction();
1661 if (isPointerType(I->getType()))
1662 RetVal = getNodeForValue(I);
1663
1664 std::vector<DSNodeHandle> Args;
1665 Args.reserve(CS.arg_end()-CS.arg_begin());
1666
1667 // Calculate the arguments vector...
1668 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1669 if (isPointerType((*I)->getType()))
Chris Lattner94f84702005-03-17 19:56:56 +00001670 if (isa<ConstantPointerNull>(*I))
1671 Args.push_back(DSNodeHandle());
1672 else
1673 Args.push_back(getNodeForValue(*I));
Chris Lattner85fb1be2004-03-09 19:37:06 +00001674
1675 // Add a new function call entry...
1676 if (Function *F = CS.getCalledFunction())
1677 return DSCallSite(CS, RetVal, F, Args);
1678 else
1679 return DSCallSite(CS, RetVal,
1680 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1681}
1682
Chris Lattner58f98d02003-07-02 04:38:49 +00001683
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001684
Chris Lattner0d9bab82002-07-18 00:12:30 +00001685// markIncompleteNodes - Mark the specified node as having contents that are not
1686// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001687// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001688// must recursively traverse the data structure graph, marking all reachable
1689// nodes as incomplete.
1690//
1691static void markIncompleteNode(DSNode *N) {
1692 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001693 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001694
1695 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001696 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001697
Misha Brukman2f2d0652003-09-11 18:14:24 +00001698 // Recursively process children...
Chris Lattner6be07942005-02-09 03:20:43 +00001699 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1700 if (DSNode *DSN = I->getNode())
Chris Lattner08db7192002-11-06 06:20:27 +00001701 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001702}
1703
Chris Lattnere71ffc22002-11-11 03:36:55 +00001704static void markIncomplete(DSCallSite &Call) {
1705 // Then the return value is certainly incomplete!
1706 markIncompleteNode(Call.getRetVal().getNode());
1707
1708 // All objects pointed to by function arguments are incomplete!
1709 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1710 markIncompleteNode(Call.getPtrArg(i).getNode());
1711}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001712
1713// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1714// modified by other functions that have not been resolved yet. This marks
1715// nodes that are reachable through three sources of "unknownness":
1716//
1717// Global Variables, Function Calls, and Incoming Arguments
1718//
1719// For any node that may have unknown components (because something outside the
1720// scope of current analysis may have modified it), the 'Incomplete' flag is
1721// added to the NodeType.
1722//
Chris Lattner394471f2003-01-23 22:05:33 +00001723void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001724 // Mark any incoming arguments as incomplete.
Chris Lattner5a540632003-06-30 03:15:25 +00001725 if (Flags & DSGraph::MarkFormalArgs)
1726 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1727 FI != E; ++FI) {
1728 Function &F = *FI->first;
Chris Lattner9342a932005-03-29 19:16:59 +00001729 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1730 I != E; ++I)
Chris Lattnerb5ecd2e2005-03-13 20:22:10 +00001731 if (isPointerType(I->getType()))
1732 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattnera4319e52005-03-12 14:58:28 +00001733 markIncompleteNode(FI->second.getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001734 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001735
Chris Lattnera9548d92005-01-30 23:51:02 +00001736 // Mark stuff passed into functions calls as being incomplete.
Chris Lattnere71ffc22002-11-11 03:36:55 +00001737 if (!shouldPrintAuxCalls())
Chris Lattnera9548d92005-01-30 23:51:02 +00001738 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1739 E = FunctionCalls.end(); I != E; ++I)
1740 markIncomplete(*I);
Chris Lattnere71ffc22002-11-11 03:36:55 +00001741 else
Chris Lattnera9548d92005-01-30 23:51:02 +00001742 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1743 E = AuxFunctionCalls.end(); I != E; ++I)
1744 markIncomplete(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001745
Chris Lattnere2bc7b22005-03-13 20:36:01 +00001746 // Mark all global nodes as incomplete.
1747 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1748 E = ScalarMap.global_end(); I != E; ++I)
1749 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1750 if (!GV->hasInitializer() || // Always mark external globals incomp.
1751 (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1752 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001753}
1754
Chris Lattneraa8146f2002-11-10 06:59:55 +00001755static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1756 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001757 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001758 // No interesting info?
1759 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001760 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001761 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001762}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001763
Chris Lattneraa8146f2002-11-10 06:59:55 +00001764static inline bool nodeContainsExternalFunction(const DSNode *N) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001765 std::vector<Function*> Funcs;
1766 N->addFullFunctionList(Funcs);
1767 for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
1768 if (Funcs[i]->isExternal()) return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001769 return false;
1770}
1771
Chris Lattnera9548d92005-01-30 23:51:02 +00001772static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001773 // Remove trivially identical function calls
Chris Lattnera9548d92005-01-30 23:51:02 +00001774 Calls.sort(); // Sort by callee as primary key!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001775
1776 // Scan the call list cleaning it up as necessary...
Chris Lattner1e9d1472005-03-22 23:54:52 +00001777 DSNodeHandle LastCalleeNode;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001778#if 0
Chris Lattner923fc052003-02-05 21:59:58 +00001779 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001780 unsigned NumDuplicateCalls = 0;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001781#endif
Chris Lattneraa8146f2002-11-10 06:59:55 +00001782 bool LastCalleeContainsExternalFunction = false;
Chris Lattner857eb062004-10-30 05:41:23 +00001783
Chris Lattnera9548d92005-01-30 23:51:02 +00001784 unsigned NumDeleted = 0;
1785 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1786 I != E;) {
1787 DSCallSite &CS = *I;
1788 std::list<DSCallSite>::iterator OldIt = I++;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001789
Chris Lattner1e9d1472005-03-22 23:54:52 +00001790 if (!CS.isIndirectCall()) {
1791 LastCalleeNode = 0;
1792 } else {
1793 DSNode *Callee = CS.getCalleeNode();
1794
1795 // If the Callee is a useless edge, this must be an unreachable call site,
1796 // eliminate it.
1797 if (Callee->getNumReferrers() == 1 && Callee->isComplete() &&
1798 Callee->getGlobalsList().empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001799#ifndef NDEBUG
Chris Lattner1e9d1472005-03-22 23:54:52 +00001800 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001801#endif
Chris Lattner1e9d1472005-03-22 23:54:52 +00001802 Calls.erase(OldIt);
1803 ++NumDeleted;
1804 continue;
1805 }
1806
1807 // If the last call site in the list has the same callee as this one, and
1808 // if the callee contains an external function, it will never be
1809 // resolvable, just merge the call sites.
1810 if (!LastCalleeNode.isNull() && LastCalleeNode.getNode() == Callee) {
1811 LastCalleeContainsExternalFunction =
1812 nodeContainsExternalFunction(Callee);
1813
1814 std::list<DSCallSite>::iterator PrevIt = OldIt;
1815 --PrevIt;
1816 PrevIt->mergeWith(CS);
1817
1818 // No need to keep this call anymore.
1819 Calls.erase(OldIt);
1820 ++NumDeleted;
1821 continue;
1822 } else {
1823 LastCalleeNode = Callee;
1824 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001825 }
1826
1827 // If the return value or any arguments point to a void node with no
1828 // information at all in it, and the call node is the only node to point
1829 // to it, remove the edge to the node (killing the node).
1830 //
1831 killIfUselessEdge(CS.getRetVal());
1832 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1833 killIfUselessEdge(CS.getPtrArg(a));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001834
Chris Lattner0b144872004-01-27 22:03:40 +00001835#if 0
Chris Lattnera9548d92005-01-30 23:51:02 +00001836 // If this call site calls the same function as the last call site, and if
1837 // the function pointer contains an external function, this node will
1838 // never be resolved. Merge the arguments of the call node because no
1839 // information will be lost.
1840 //
1841 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1842 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1843 ++NumDuplicateCalls;
1844 if (NumDuplicateCalls == 1) {
1845 if (LastCalleeNode)
1846 LastCalleeContainsExternalFunction =
1847 nodeContainsExternalFunction(LastCalleeNode);
1848 else
1849 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001850 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001851
Chris Lattnera9548d92005-01-30 23:51:02 +00001852 // It is not clear why, but enabling this code makes DSA really
1853 // sensitive to node forwarding. Basically, with this enabled, DSA
1854 // performs different number of inlinings based on which nodes are
1855 // forwarding or not. This is clearly a problem, so this code is
1856 // disabled until this can be resolved.
1857#if 1
1858 if (LastCalleeContainsExternalFunction
1859#if 0
1860 ||
1861 // This should be more than enough context sensitivity!
1862 // FIXME: Evaluate how many times this is tripped!
1863 NumDuplicateCalls > 20
1864#endif
1865 ) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001866
Chris Lattnera9548d92005-01-30 23:51:02 +00001867 std::list<DSCallSite>::iterator PrevIt = OldIt;
1868 --PrevIt;
1869 PrevIt->mergeWith(CS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001870
Chris Lattnera9548d92005-01-30 23:51:02 +00001871 // No need to keep this call anymore.
1872 Calls.erase(OldIt);
1873 ++NumDeleted;
1874 continue;
1875 }
1876#endif
1877 } else {
1878 if (CS.isDirectCall()) {
1879 LastCalleeFunc = CS.getCalleeFunc();
1880 LastCalleeNode = 0;
1881 } else {
1882 LastCalleeNode = CS.getCalleeNode();
1883 LastCalleeFunc = 0;
1884 }
1885 NumDuplicateCalls = 0;
1886 }
1887#endif
1888
1889 if (I != Calls.end() && CS == *I) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001890 LastCalleeNode = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00001891 Calls.erase(OldIt);
1892 ++NumDeleted;
1893 continue;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001894 }
1895 }
Chris Lattner857eb062004-10-30 05:41:23 +00001896
Chris Lattnera9548d92005-01-30 23:51:02 +00001897 // Resort now that we simplified things.
1898 Calls.sort();
Chris Lattner857eb062004-10-30 05:41:23 +00001899
Chris Lattnera9548d92005-01-30 23:51:02 +00001900 // Now that we are in sorted order, eliminate duplicates.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001901 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1902 if (CI != CE)
Chris Lattnera9548d92005-01-30 23:51:02 +00001903 while (1) {
Chris Lattnerf9aace22005-01-31 00:10:58 +00001904 std::list<DSCallSite>::iterator OldIt = CI++;
1905 if (CI == CE) break;
Chris Lattnera9548d92005-01-30 23:51:02 +00001906
1907 // If this call site is now the same as the previous one, we can delete it
1908 // as a duplicate.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001909 if (*OldIt == *CI) {
1910 Calls.erase(CI);
1911 CI = OldIt;
Chris Lattnera9548d92005-01-30 23:51:02 +00001912 ++NumDeleted;
1913 }
1914 }
1915
1916 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001917
Chris Lattner33312f72002-11-08 01:21:07 +00001918 // Track the number of call nodes merged away...
Chris Lattnera9548d92005-01-30 23:51:02 +00001919 NumCallNodesMerged += NumDeleted;
Chris Lattner33312f72002-11-08 01:21:07 +00001920
Chris Lattnera9548d92005-01-30 23:51:02 +00001921 DEBUG(if (NumDeleted)
1922 std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001923}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001924
Chris Lattneraa8146f2002-11-10 06:59:55 +00001925
Chris Lattnere2219762002-07-18 18:22:40 +00001926// removeTriviallyDeadNodes - After the graph has been constructed, this method
1927// removes all unreachable nodes that are created because they got merged with
1928// other nodes in the graph. These nodes will all be trivially unreachable, so
1929// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001930//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001931void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001932 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001933
Chris Lattner5ace1e42004-07-08 07:25:51 +00001934#if 0
1935 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1936 /// substantially!
1937
Chris Lattnerbab8c282003-09-20 21:34:07 +00001938 // Loop over all of the nodes in the graph, calling getNode on each field.
1939 // This will cause all nodes to update their forwarding edges, causing
1940 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001941 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001942 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
Chris Lattner84b80a22005-03-16 22:42:19 +00001943 DSNode &N = *NI;
1944 for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1945 N.getLink(l*N.getPointerSize()).getNode();
Chris Lattnerbab8c282003-09-20 21:34:07 +00001946 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001947 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001948
Chris Lattner0b144872004-01-27 22:03:40 +00001949 // NOTE: This code is disabled. Though it should, in theory, allow us to
1950 // remove more nodes down below, the scan of the scalar map is incredibly
1951 // expensive for certain programs (with large SCCs). In the future, if we can
1952 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001953 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1954
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001955 // Likewise, forward any edges from the scalar nodes. While we are at it,
1956 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001957 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001958 I->second.getNode();
1959 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001960 }
Chris Lattner0b144872004-01-27 22:03:40 +00001961 }
1962#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001963 bool isGlobalsGraph = !GlobalsGraph;
1964
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001965 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001966 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001967
1968 // Do not remove *any* global nodes in the globals graph.
1969 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001970 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001971 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001972 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001973 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001974
Chris Lattner28897e12004-02-08 00:53:26 +00001975 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001976 // This is a useless node if it has no mod/ref info (checked above),
1977 // outgoing edges (which it cannot, as it is not modified in this
1978 // context), and it has no incoming edges. If it is a global node it may
1979 // have all of these properties and still have incoming edges, due to the
1980 // scalar map, so we check those now.
1981 //
Chris Lattner82c6c722005-03-20 02:41:38 +00001982 if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1983 const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
Chris Lattner72d29a42003-02-11 23:11:51 +00001984
Chris Lattner17a93e22004-01-29 03:32:15 +00001985 // Loop through and make sure all of the globals are referring directly
1986 // to the node...
1987 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1988 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001989 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001990 }
1991
Chris Lattnerbd92b732003-06-19 21:15:11 +00001992 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001993 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001994 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1995 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001996 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001997 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001998 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001999 }
2000 }
2001
Chris Lattner28897e12004-02-08 00:53:26 +00002002 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00002003 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00002004 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002005 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00002006 } else {
2007 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002008 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002009 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002010
2011 removeIdenticalCalls(FunctionCalls);
2012 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00002013}
2014
2015
Chris Lattner5c7380e2003-01-29 21:10:20 +00002016/// markReachableNodes - This method recursively traverses the specified
2017/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
2018/// to the set, which allows it to only traverse visited nodes once.
2019///
Chris Lattnera9548d92005-01-30 23:51:02 +00002020void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00002021 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00002022 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00002023 if (ReachableNodes.insert(this).second) // Is newly reachable?
Chris Lattner6be07942005-02-09 03:20:43 +00002024 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
2025 I != E; ++I)
2026 I->getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00002027}
2028
Chris Lattnera9548d92005-01-30 23:51:02 +00002029void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00002030 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00002031 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002032
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002033 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
2034 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00002035}
2036
Chris Lattnera1220af2003-02-01 06:17:02 +00002037// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
2038// looking for a node that is marked alive. If an alive node is found, return
2039// true, otherwise return false. If an alive node is reachable, this node is
2040// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00002041//
Chris Lattnera9548d92005-01-30 23:51:02 +00002042static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
2043 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00002044 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002045 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00002046 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002047
Chris Lattner85cfe012003-07-03 02:03:53 +00002048 // If this is a global node, it will end up in the globals graph anyway, so we
2049 // don't need to worry about it.
2050 if (IgnoreGlobals && N->isGlobalNode()) return false;
2051
Chris Lattneraa8146f2002-11-10 06:59:55 +00002052 // If we know that this node is alive, return so!
2053 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002054
Chris Lattneraa8146f2002-11-10 06:59:55 +00002055 // Otherwise, we don't think the node is alive yet, check for infinite
2056 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00002057 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00002058 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00002059
Chris Lattner6be07942005-02-09 03:20:43 +00002060 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
2061 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00002062 N->markReachableNodes(Alive);
2063 return true;
2064 }
2065 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002066}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002067
Chris Lattnera1220af2003-02-01 06:17:02 +00002068// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
2069// alive nodes.
2070//
Chris Lattnera9548d92005-01-30 23:51:02 +00002071static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
2072 hash_set<const DSNode*> &Alive,
2073 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00002074 bool IgnoreGlobals) {
2075 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
2076 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00002077 return true;
2078 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00002079 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002080 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002081 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00002082 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
2083 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002084 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002085 return false;
2086}
2087
Chris Lattnere2219762002-07-18 18:22:40 +00002088// removeDeadNodes - Use a more powerful reachability analysis to eliminate
2089// subgraphs that are unreachable. This often occurs because the data
2090// structure doesn't "escape" into it's caller, and thus should be eliminated
2091// from the caller's graph entirely. This is only appropriate to use when
2092// inlining graphs.
2093//
Chris Lattner394471f2003-01-23 22:05:33 +00002094void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00002095 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00002096
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002097 // Reduce the amount of work we have to do... remove dummy nodes left over by
2098 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00002099 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002100
Chris Lattner93ddd7e2004-01-22 16:36:28 +00002101 TIME_REGION(X, "removeDeadNodes");
2102
Misha Brukman2f2d0652003-09-11 18:14:24 +00002103 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00002104
2105 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattnera9548d92005-01-30 23:51:02 +00002106 hash_set<const DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002107 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00002108
Chris Lattner0b144872004-01-27 22:03:40 +00002109 // Copy and merge all information about globals to the GlobalsGraph if this is
2110 // not a final pass (where unreachable globals are removed).
2111 //
2112 // Strip all alloca bits since the current function is only for the BU pass.
2113 // Strip all incomplete bits since they are short-lived properties and they
2114 // will be correctly computed when rematerializing nodes into the functions.
2115 //
2116 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
2117 DSGraph::StripIncompleteBit);
2118
Chris Lattneraa8146f2002-11-10 06:59:55 +00002119 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattnerf4f62272005-03-19 22:23:45 +00002120{ TIME_REGION(Y, "removeDeadNodes:scalarscan");
2121 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
2122 I != E; ++I)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002123 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00002124 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002125 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002126 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00002127
2128 // Make sure that all globals are cloned over as roots.
Chris Lattner021decc2005-04-02 19:17:18 +00002129 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && GlobalsGraph) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002130 DSGraph::ScalarMapTy::iterator SMI =
Chris Lattner00948c02004-01-28 02:05:05 +00002131 GlobalsGraph->getScalarMap().find(I->first);
2132 if (SMI != GlobalsGraph->getScalarMap().end())
2133 GGCloner.merge(SMI->second, I->second);
2134 else
2135 GGCloner.getClonedNH(I->second);
2136 }
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002137 } else {
Chris Lattnerf4f62272005-03-19 22:23:45 +00002138 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002139 }
Chris Lattnerf4f62272005-03-19 22:23:45 +00002140}
Chris Lattnere2219762002-07-18 18:22:40 +00002141
Chris Lattner0b144872004-01-27 22:03:40 +00002142 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00002143 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
2144 I != E; ++I)
2145 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002146
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002147 // Mark any nodes reachable by primary calls as alive...
Chris Lattnera9548d92005-01-30 23:51:02 +00002148 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2149 I->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002150
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002151
2152 // Now find globals and aux call nodes that are already live or reach a live
2153 // value (which makes them live in turn), and continue till no more are found.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002154 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002155 bool Iterate;
Chris Lattnera9548d92005-01-30 23:51:02 +00002156 hash_set<const DSNode*> Visited;
2157 hash_set<const DSCallSite*> AuxFCallsAlive;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002158 do {
2159 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00002160 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00002161 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002162 // unreachable globals in the list.
2163 //
2164 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002165 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00002166 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002167 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
Chris Lattner0b144872004-01-27 22:03:40 +00002168 Flags & DSGraph::RemoveUnreachableGlobals)) {
2169 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
2170 GlobalNodes.pop_back(); // erase efficiently
2171 Iterate = true;
2172 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002173
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002174 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
2175 // call nodes that get resolved will be difficult to remove from that graph.
2176 // The final unresolved call nodes must be handled specially at the end of
2177 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattnera9548d92005-01-30 23:51:02 +00002178 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
Chris Lattnerd7642c42005-02-24 18:48:07 +00002179 if (!AuxFCallsAlive.count(&*CI) &&
Chris Lattnera9548d92005-01-30 23:51:02 +00002180 (CI->isIndirectCall()
2181 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002182 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattnera9548d92005-01-30 23:51:02 +00002183 CI->markReachableNodes(Alive);
Chris Lattnerd7642c42005-02-24 18:48:07 +00002184 AuxFCallsAlive.insert(&*CI);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002185 Iterate = true;
2186 }
2187 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00002188
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002189 // Move dead aux function calls to the end of the list
Chris Lattnera9548d92005-01-30 23:51:02 +00002190 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
2191 E = AuxFunctionCalls.end(); CI != E; )
2192 if (AuxFCallsAlive.count(&*CI))
2193 ++CI;
2194 else {
2195 // Copy and merge global nodes and dead aux call nodes into the
2196 // GlobalsGraph, and all nodes reachable from those nodes. Update their
2197 // target pointers using the GGCloner.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002198 //
Chris Lattnera9548d92005-01-30 23:51:02 +00002199 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2200 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002201
Chris Lattnera9548d92005-01-30 23:51:02 +00002202 AuxFunctionCalls.erase(CI++);
2203 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002204
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002205 // We are finally done with the GGCloner so we can destroy it.
2206 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002207
Vikram S. Adve40c600e2003-07-22 12:08:58 +00002208 // At this point, any nodes which are visited, but not alive, are nodes
2209 // which can be removed. Loop over all nodes, eliminating completely
2210 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002211 //
Chris Lattner72d29a42003-02-11 23:11:51 +00002212 std::vector<DSNode*> DeadNodes;
2213 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00002214 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2215 DSNode *N = NI++;
2216 assert(!N->isForwarding() && "Forwarded node in nodes list?");
2217
2218 if (!Alive.count(N)) {
2219 Nodes.remove(N);
2220 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002221 DeadNodes.push_back(N);
2222 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00002223 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00002224 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00002225 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002226
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002227 // Remove all unreachable globals from the ScalarMap.
2228 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2229 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00002230 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002231 if (!Alive.count(GlobalNodes[i].second))
2232 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00002233 else
2234 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002235
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002236 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00002237 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2238 delete DeadNodes[i];
2239
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002240 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00002241}
2242
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002243void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
Chris Lattner82c6c722005-03-20 02:41:38 +00002244 assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2245 N->globals_end() && "Global value not in node!");
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002246}
2247
Chris Lattner2c7725a2004-03-03 20:55:27 +00002248void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2249 if (CS.isIndirectCall()) {
2250 AssertNodeInGraph(CS.getCalleeNode());
2251#if 0
2252 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2253 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002254 std::cerr << "WARNING: WEIRD CALL SITE FOUND!\n";
Chris Lattner2c7725a2004-03-03 20:55:27 +00002255#endif
2256 }
2257 AssertNodeInGraph(CS.getRetVal().getNode());
2258 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2259 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2260}
2261
2262void DSGraph::AssertCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002263 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2264 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002265}
2266void DSGraph::AssertAuxCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002267 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2268 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002269}
2270
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002271void DSGraph::AssertGraphOK() const {
Chris Lattner84b80a22005-03-16 22:42:19 +00002272 for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2273 NI->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00002274
Chris Lattner8d327672003-06-30 03:36:09 +00002275 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002276 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00002277 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002278 AssertNodeInGraph(I->second.getNode());
2279 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00002280 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002281 "Global points to node, but node isn't global?");
2282 AssertNodeContainsGlobal(I->second.getNode(), GV);
2283 }
2284 }
2285 AssertCallNodesInGraph();
2286 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00002287
2288 // Check that all pointer arguments to any functions in this graph have
2289 // destinations.
2290 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2291 E = ReturnNodes.end();
2292 RI != E; ++RI) {
2293 Function &F = *RI->first;
Chris Lattnere4d5c442005-03-15 04:54:21 +00002294 for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
Chris Lattner7d8d4712004-10-31 17:45:40 +00002295 if (isPointerType(AI->getType()))
2296 assert(!getNodeForValue(AI).isNull() &&
2297 "Pointer argument must be in the scalar map!");
2298 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002299}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002300
Chris Lattner400433d2003-11-11 05:08:59 +00002301/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00002302/// nodes reachable from the two graphs, computing the mapping of nodes from the
2303/// first to the second graph. This mapping may be many-to-one (i.e. the first
2304/// graph may have multiple nodes representing one node in the second graph),
2305/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00002306///
2307void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00002308 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2309 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00002310 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2311 if (N1 == 0 || N2 == 0) return;
2312
2313 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002314 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002315 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002316 if (StrictChecking) {
2317 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2318 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2319 Entry.getNode()->isNodeCompletelyFolded()) &&
2320 "Inconsistent mapping detected!");
2321 }
Chris Lattner400433d2003-11-11 05:08:59 +00002322 return;
2323 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002324
Chris Lattnerefffdc92004-07-07 06:12:52 +00002325 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002326
2327 // Loop over all of the fields that N1 and N2 have in common, recursively
2328 // mapping the edges together now.
2329 int N2Idx = NH2.getOffset()-NH1.getOffset();
2330 unsigned N2Size = N2->getSize();
Chris Lattner841957e2005-03-15 04:40:24 +00002331 if (N2Size == 0) return; // No edges to map to.
2332
Chris Lattner4d5af8e2005-03-15 21:36:50 +00002333 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2334 const DSNodeHandle &N1NH = N1->getLink(i);
2335 // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2336 // aligned right).
2337 if (!N1NH.isNull()) {
2338 if (unsigned(N2Idx)+i < N2Size)
2339 computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2340 else
2341 computeNodeMapping(N1NH,
2342 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2343 }
2344 }
Chris Lattner400433d2003-11-11 05:08:59 +00002345}
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002346
2347
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002348/// computeGToGGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002349/// nodes in this graph.
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002350void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002351 DSGraph &GG = *getGlobalsGraph();
2352
2353 DSScalarMap &SM = getScalarMap();
2354 for (DSScalarMap::global_iterator I = SM.global_begin(),
2355 E = SM.global_end(); I != E; ++I)
2356 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2357}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002358
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002359/// computeGGToGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002360/// nodes in this graph. Note that any uses of this method are probably bugs,
2361/// unless it is known that the globals graph has been merged into this graph!
2362void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2363 NodeMapTy NodeMap;
2364 computeGToGGMapping(NodeMap);
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002365
Chris Lattner36a13cd2005-03-15 17:52:18 +00002366 while (!NodeMap.empty()) {
2367 InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2368 NodeMap.begin()->first));
2369 NodeMap.erase(NodeMap.begin());
2370 }
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002371}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002372
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002373
2374/// computeCalleeCallerMapping - Given a call from a function in the current
2375/// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2376/// mapping of nodes from the callee to nodes in the caller.
2377void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2378 DSGraph &CalleeGraph,
2379 NodeMapTy &NodeMap) {
2380
2381 DSCallSite CalleeArgs =
2382 CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002383
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002384 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2385
2386 unsigned NumArgs = CS.getNumPtrArgs();
2387 if (NumArgs > CalleeArgs.getNumPtrArgs())
2388 NumArgs = CalleeArgs.getNumPtrArgs();
2389
2390 for (unsigned i = 0; i != NumArgs; ++i)
2391 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002392
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002393 // Map the nodes that are pointed to by globals.
2394 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2395 DSScalarMap &CallerSM = getScalarMap();
2396
2397 if (CalleeSM.global_size() >= CallerSM.global_size()) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002398 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002399 E = CallerSM.global_end(); GI != E; ++GI)
2400 if (CalleeSM.global_count(*GI))
2401 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2402 } else {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002403 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002404 E = CalleeSM.global_end(); GI != E; ++GI)
2405 if (CallerSM.global_count(*GI))
2406 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2407 }
2408}
Andrew Lenharth37705002006-06-19 15:42:47 +00002409
2410/// updateFromGlobalGraph - This function rematerializes global nodes and
2411/// nodes reachable from them from the globals graph into the current graph.
2412///
2413void DSGraph::updateFromGlobalGraph() {
2414 TIME_REGION(X, "updateFromGlobalGraph");
2415 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
2416
2417 // Clone the non-up-to-date global nodes into this graph.
2418 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
2419 E = getScalarMap().global_end(); I != E; ++I) {
2420 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
2421 if (It != GlobalsGraph->ScalarMap.end())
2422 RC.merge(getNodeForValue(*I), It->second);
2423 }
2424}