1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
3 // This file implements the core data structure functionality.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Module.h"
8 #include "llvm/DerivedTypes.h"
9 #include "Support/STLExtras.h"
10 #include "Support/StatisticReporter.h"
11 #include "Support/STLExtras.h"
13 #include "llvm/Analysis/DataStructure.h"
17 //===----------------------------------------------------------------------===//
18 // DSNode Implementation
19 //===----------------------------------------------------------------------===//
21 DSNode::DSNode(enum NodeTy NT, const Type *T) : Ty(T), NodeType(NT) {
22 // If this node has any fields, allocate them now, but leave them null.
23 switch (T->getPrimitiveID()) {
24 case Type::PointerTyID: Links.resize(1); break;
25 case Type::ArrayTyID: Links.resize(1); break;
26 case Type::StructTyID:
27 Links.resize(cast<StructType>(T)->getNumContainedTypes());
33 // DSNode copy constructor... do not copy over the referrers list!
34 DSNode::DSNode(const DSNode &N)
35 : Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
38 void DSNode::removeReferrer(DSNodeHandle *H) {
39 // Search backwards, because we depopulate the list from the back for
40 // efficiency (because it's a vector).
41 vector<DSNodeHandle*>::reverse_iterator I =
42 std::find(Referrers.rbegin(), Referrers.rend(), H);
43 assert(I != Referrers.rend() && "Referrer not pointing to node!");
44 Referrers.erase(I.base()-1);
47 // addGlobal - Add an entry for a global value to the Globals list. This also
48 // marks the node with the 'G' flag if it does not already have it.
50 void DSNode::addGlobal(GlobalValue *GV) {
51 // Keep the list sorted.
52 vector<GlobalValue*>::iterator I =
53 std::lower_bound(Globals.begin(), Globals.end(), GV);
55 if (I == Globals.end() || *I != GV) {
56 assert(GV->getType()->getElementType() == Ty);
57 Globals.insert(I, GV);
58 NodeType |= GlobalNode;
63 // addEdgeTo - Add an edge from the current node to the specified node. This
64 // can cause merging of nodes in the graph.
66 void DSNode::addEdgeTo(unsigned LinkNo, DSNode *N) {
67 assert(LinkNo < Links.size() && "LinkNo out of range!");
68 if (N == 0 || Links[LinkNo] == N) return; // Nothing to do
69 if (Links[LinkNo] == 0) { // No merging to perform
74 // Merge the two nodes...
75 Links[LinkNo]->mergeWith(N);
79 // mergeWith - Merge this node into the specified node, moving all links to and
80 // from the argument node into the current node. The specified node may be a
81 // null pointer (in which case, nothing happens).
83 void DSNode::mergeWith(DSNode *N) {
84 if (N == 0 || N == this) return; // Noop
85 assert(N->Ty == Ty && N->Links.size() == Links.size() &&
86 "Cannot merge nodes of two different types!");
88 // Remove all edges pointing at N, causing them to point to 'this' instead.
89 while (!N->Referrers.empty())
90 *N->Referrers.back() = this;
92 // Make all of the outgoing links of N now be outgoing links of this. This
93 // can cause recursive merging!
95 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
96 addEdgeTo(i, N->Links[i]);
97 N->Links[i] = 0; // Reduce unneccesary edges in graph. N is dead
100 // Merge the node types
101 NodeType |= N->NodeType;
102 N->NodeType = 0; // N is now a dead node.
104 // Merge the globals list...
105 if (!N->Globals.empty()) {
106 // Save the current globals off to the side...
107 vector<GlobalValue*> OldGlobals(Globals);
109 // Resize the globals vector to be big enough to hold both of them...
110 Globals.resize(Globals.size()+N->Globals.size());
112 // Merge the two sorted globals lists together...
113 std::merge(OldGlobals.begin(), OldGlobals.end(),
114 N->Globals.begin(), N->Globals.end(), Globals.begin());
116 // Erase duplicate entries from the globals list...
117 Globals.erase(std::unique(Globals.begin(), Globals.end()), Globals.end());
119 // Delete the globals from the old node...
124 //===----------------------------------------------------------------------===//
125 // DSGraph Implementation
126 //===----------------------------------------------------------------------===//
128 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(G.GlobalsGraph){
129 GlobalsGraph->addReference(this);
130 std::map<const DSNode*, DSNode*> NodeMap; // ignored
131 RetNode = cloneInto(G, ValueMap, NodeMap);
134 DSGraph::~DSGraph() {
135 GlobalsGraph->removeReference(this);
136 FunctionCalls.clear();
137 OrigFunctionCalls.clear();
142 // Drop all intra-node references, so that assertions don't fail...
143 std::for_each(Nodes.begin(), Nodes.end(),
144 std::mem_fun(&DSNode::dropAllReferences));
147 // Delete all of the nodes themselves...
148 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
151 // dump - Allow inspection of graph in a debugger.
152 void DSGraph::dump() const { print(std::cerr); }
155 // Helper function used to clone a function list.
156 // Each call really shd have an explicit representation as a separate class.
158 CopyFunctionCallsList(const std::vector<std::vector<DSNodeHandle> >& fromCalls,
159 std::vector<std::vector<DSNodeHandle> >& toCalls,
160 std::map<const DSNode*, DSNode*>& NodeMap) {
162 unsigned FC = toCalls.size(); // FirstCall
163 toCalls.reserve(FC+fromCalls.size());
164 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i) {
165 toCalls.push_back(std::vector<DSNodeHandle>());
166 toCalls[FC+i].reserve(fromCalls[i].size());
167 for (unsigned j = 0, ej = fromCalls[i].size(); j != ej; ++j)
168 toCalls[FC+i].push_back(NodeMap[fromCalls[i][j]]);
173 // cloneInto - Clone the specified DSGraph into the current graph, returning the
174 // Return node of the graph. The translated ValueMap for the old function is
175 // filled into the OldValMap member. If StripLocals is set to true, Scalar and
176 // Alloca markers are removed from the graph, as the graph is being cloned into
177 // a calling function's graph.
179 DSNode *DSGraph::cloneInto(const DSGraph &G,
180 std::map<Value*, DSNodeHandle> &OldValMap,
181 std::map<const DSNode*, DSNode*> &OldNodeMap,
182 bool StripScalars, bool StripAllocas,
183 bool CopyCallers, bool CopyOrigCalls) {
185 assert(OldNodeMap.size()==0 && "Return arg. OldNodeMap shd be empty");
187 OldNodeMap[0] = 0; // Null pointer maps to null
189 unsigned FN = Nodes.size(); // First new node...
191 // Duplicate all of the nodes, populating the node map...
192 Nodes.reserve(FN+G.Nodes.size());
193 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
194 DSNode *Old = G.Nodes[i], *New = new DSNode(*Old);
195 Nodes.push_back(New);
196 OldNodeMap[Old] = New;
199 // Rewrite the links in the new nodes to point into the current graph now.
200 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
201 for (unsigned j = 0, e = Nodes[i]->getNumLinks(); j != e; ++j)
202 Nodes[i]->setLink(j, OldNodeMap.find(Nodes[i]->getLink(j))->second);
204 // Remove local markers as specified
205 if (StripScalars || StripAllocas) {
206 char keepBits = ~((StripScalars? DSNode::ScalarNode : 0) |
207 (StripAllocas? DSNode::AllocaNode : 0));
208 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
209 Nodes[i]->NodeType &= keepBits;
212 // Copy the value map...
213 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
214 E = G.ValueMap.end(); I != E; ++I)
215 OldValMap[I->first] = OldNodeMap[I->second];
217 // Copy the function calls list...
218 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
220 CopyFunctionCallsList(G.OrigFunctionCalls, OrigFunctionCalls, OldNodeMap);
222 // Copy the list of unresolved callers
224 PendingCallers.insert(G.PendingCallers.begin(), G.PendingCallers.end());
226 // Return the returned node pointer...
227 return OldNodeMap[G.RetNode];
231 // cloneGlobalInto - Clone the given global node and all its target links
232 // (and all their llinks, recursively).
234 DSNode* DSGraph::cloneGlobalInto(const DSNode* GNode) {
235 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
237 // If a clone has already been created for GNode, return it.
238 DSNodeHandle& ValMapEntry = ValueMap[GNode->getGlobals()[0]];
239 if (ValMapEntry != 0)
242 // Clone the node and update the ValMap.
243 DSNode* NewNode = new DSNode(*GNode);
244 ValMapEntry = NewNode; // j=0 case of loop below!
245 Nodes.push_back(NewNode);
246 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
247 ValueMap[NewNode->getGlobals()[j]] = NewNode;
249 // Rewrite the links in the new node to point into the current graph.
250 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
251 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
257 // markIncompleteNodes - Mark the specified node as having contents that are not
258 // known with the current analysis we have performed. Because a node makes all
259 // of the nodes it can reach imcomplete if the node itself is incomplete, we
260 // must recursively traverse the data structure graph, marking all reachable
261 // nodes as incomplete.
263 static void markIncompleteNode(DSNode *N) {
264 // Stop recursion if no node, or if node already marked...
265 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
267 // Actually mark the node
268 N->NodeType |= DSNode::Incomplete;
270 // Recusively process children...
271 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
272 markIncompleteNode(N->getLink(i));
276 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
277 // modified by other functions that have not been resolved yet. This marks
278 // nodes that are reachable through three sources of "unknownness":
280 // Global Variables, Function Calls, and Incoming Arguments
282 // For any node that may have unknown components (because something outside the
283 // scope of current analysis may have modified it), the 'Incomplete' flag is
284 // added to the NodeType.
286 void DSGraph::markIncompleteNodes(bool markFormalArgs) {
287 // Mark any incoming arguments as incomplete...
289 for (Function::aiterator I = Func.abegin(), E = Func.aend(); I != E; ++I)
290 if (isa<PointerType>(I->getType()))
291 markIncompleteNode(ValueMap[I]->getLink(0));
293 // Mark stuff passed into functions calls as being incomplete...
294 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
295 vector<DSNodeHandle> &Args = FunctionCalls[i];
296 // Then the return value is certainly incomplete!
297 markIncompleteNode(Args[0]);
299 // The call does not make the function argument incomplete...
301 // All arguments to the function call are incomplete though!
302 for (unsigned i = 2, e = Args.size(); i != e; ++i)
303 markIncompleteNode(Args[i]);
306 // Mark all of the nodes pointed to by global or cast nodes as incomplete...
307 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
308 if (Nodes[i]->NodeType & (DSNode::GlobalNode | DSNode::CastNode)) {
309 DSNode *N = Nodes[i];
310 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
311 markIncompleteNode(N->getLink(i));
315 // removeRefsToGlobal - Helper function that removes globals from the
316 // ValueMap so that the referrer count will go down to zero.
318 removeRefsToGlobal(DSNode* N, std::map<Value*, DSNodeHandle>& ValueMap) {
319 while (!N->getGlobals().empty()) {
320 GlobalValue *GV = N->getGlobals().back();
321 N->getGlobals().pop_back();
327 // isNodeDead - This method checks to see if a node is dead, and if it isn't, it
328 // checks to see if there are simple transformations that it can do to make it
331 bool DSGraph::isNodeDead(DSNode *N) {
332 // Is it a trivially dead shadow node...
333 if (N->getReferrers().empty() && N->NodeType == 0)
336 // Is it a function node or some other trivially unused global?
337 if (N->NodeType != 0 &&
338 (N->NodeType & ~DSNode::GlobalNode) == 0 &&
339 N->getNumLinks() == 0 &&
340 N->getReferrers().size() == N->getGlobals().size()) {
342 // Remove the globals from the valuemap, so that the referrer count will go
344 removeRefsToGlobal(N, ValueMap);
345 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
352 static void removeIdenticalCalls(std::vector<std::vector<DSNodeHandle> > &Calls,
353 const std::string &where) {
354 // Remove trivially identical function calls
355 unsigned NumFns = Calls.size();
356 std::sort(Calls.begin(), Calls.end());
357 Calls.erase(std::unique(Calls.begin(), Calls.end()),
360 DEBUG(if (NumFns != Calls.size())
361 std::cerr << "Merged " << (NumFns-Calls.size())
362 << " call nodes in " << where << "\n";);
365 // removeTriviallyDeadNodes - After the graph has been constructed, this method
366 // removes all unreachable nodes that are created because they got merged with
367 // other nodes in the graph. These nodes will all be trivially unreachable, so
368 // we don't have to perform any non-trivial analysis here.
370 void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
371 for (unsigned i = 0; i != Nodes.size(); ++i)
372 if (! KeepAllGlobals || ! (Nodes[i]->NodeType & DSNode::GlobalNode))
373 if (isNodeDead(Nodes[i])) { // This node is dead!
374 delete Nodes[i]; // Free memory...
375 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
378 removeIdenticalCalls(FunctionCalls, Func.getName());
382 // markAlive - Simple graph traverser that recursively walks the graph marking
383 // stuff to be alive.
385 static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
389 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
390 if (N->getLink(i) && !Alive.count(N->getLink(i)))
391 markAlive(N->getLink(i), Alive);
394 static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
395 std::set<DSNode*> &Visiting) {
396 if (N == 0) return false;
398 if (Visiting.count(N) > 0) return false; // terminate recursion on a cycle
401 // If any immediate successor is alive, N is alive
402 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
403 if (N->getLink(i) && Alive.count(N->getLink(i)))
404 { Visiting.erase(N); return true; }
406 // Else if any successor reaches a live node, N is alive
407 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
408 if (N->getLink(i) && checkGlobalAlive(N->getLink(i), Alive, Visiting))
409 { Visiting.erase(N); return true; }
416 // markGlobalsIteration - Recursive helper function for markGlobalsAlive().
417 // This would be unnecessary if function calls were real nodes! In that case,
418 // the simple iterative loop in the first few lines below suffice.
420 static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
421 std::vector<std::vector<DSNodeHandle> > &Calls,
422 std::set<DSNode*> &Alive,
425 // Iterate, marking globals or cast nodes alive until no new live nodes
426 // are added to Alive
427 std::set<DSNode*> Visiting; // Used to identify cycles
428 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
429 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
430 liveCount = Alive.size();
432 if (Alive.count(*I) == 0) {
434 if (checkGlobalAlive(*I, Alive, Visiting))
435 markAlive(*I, Alive);
439 // Find function calls with some dead and some live nodes.
440 // Since all call nodes must be live if any one is live, we have to mark
441 // all nodes of the call as live and continue the iteration (via recursion).
443 bool recurse = false;
444 for (int i = 0, ei = Calls.size(); i < ei; ++i) {
445 bool CallIsDead = true, CallHasDeadArg = false;
446 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j) {
447 bool argIsDead = Calls[i][j] == 0 || Alive.count(Calls[i][j]) == 0;
448 CallHasDeadArg = CallHasDeadArg || (Calls[i][j] != 0 && argIsDead);
449 CallIsDead = CallIsDead && argIsDead;
451 if (!CallIsDead && CallHasDeadArg) {
452 // Some node in this call is live and another is dead.
453 // Mark all nodes of call as live and iterate once more.
455 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j)
456 markAlive(Calls[i][j], Alive);
460 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
465 // markGlobalsAlive - Mark global nodes and cast nodes alive if they
466 // can reach any other live node. Since this can produce new live nodes,
467 // we use a simple iterative algorithm.
469 static void markGlobalsAlive(DSGraph& G, std::set<DSNode*> &Alive,
471 // Add global and cast nodes to a set so we don't walk all nodes every time
472 std::set<DSNode*> GlobalNodes;
473 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
474 if (G.getNodes()[i]->NodeType & (DSNode::CastNode | DSNode::GlobalNode))
475 GlobalNodes.insert(G.getNodes()[i]);
477 // Add all call nodes to the same set
478 std::vector<std::vector<DSNodeHandle> > &Calls = G.getFunctionCalls();
480 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
481 for (unsigned j = 0, e = Calls[i].size(); j != e; ++j)
483 GlobalNodes.insert(Calls[i][j]);
486 // Iterate and recurse until no new live node are discovered.
487 // This would be a simple iterative loop if function calls were real nodes!
488 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
490 // Free up references to dead globals from the ValueMap
491 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
493 if (Alive.count(*I) == 0)
494 removeRefsToGlobal(*I, G.getValueMap());
496 // Delete dead function calls
498 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
499 bool CallIsDead = true;
500 for (unsigned j = 0, ej= Calls[i].size(); CallIsDead && j != ej; ++j)
501 CallIsDead = (Alive.count(Calls[i][j]) == 0);
503 Calls.erase(Calls.begin() + i); // remove the call entirely
507 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
508 // subgraphs that are unreachable. This often occurs because the data
509 // structure doesn't "escape" into it's caller, and thus should be eliminated
510 // from the caller's graph entirely. This is only appropriate to use when
513 void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
514 assert((!KeepAllGlobals || KeepCalls) &&
515 "KeepAllGlobals without KeepCalls is meaningless");
517 // Reduce the amount of work we have to do...
518 removeTriviallyDeadNodes(KeepAllGlobals);
520 // FIXME: Merge nontrivially identical call nodes...
522 // Alive - a set that holds all nodes found to be reachable/alive.
523 std::set<DSNode*> Alive;
525 // If KeepCalls, mark all nodes reachable by call nodes as alive...
527 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
528 for (unsigned j = 0, e = FunctionCalls[i].size(); j != e; ++j)
529 markAlive(FunctionCalls[i][j], Alive);
531 for (unsigned i = 0, e = OrigFunctionCalls.size(); i != e; ++i)
532 for (unsigned j = 0, e = OrigFunctionCalls[i].size(); j != e; ++j)
533 markAlive(OrigFunctionCalls[i][j], Alive);
535 // Mark all nodes reachable by scalar nodes (and global nodes, if
536 // keeping them was specified) as alive...
537 char keepBits = DSNode::ScalarNode | (KeepAllGlobals? DSNode::GlobalNode : 0);
538 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
539 if (Nodes[i]->NodeType & keepBits)
540 markAlive(Nodes[i], Alive);
542 // The return value is alive as well...
543 markAlive(RetNode, Alive);
545 // Mark all globals or cast nodes that can reach a live node as alive.
546 // This also marks all nodes reachable from such nodes as alive.
547 // Of course, if KeepAllGlobals is specified, they would be live already.
548 if (! KeepAllGlobals)
549 markGlobalsAlive(*this, Alive, ! KeepCalls);
551 // Loop over all unreachable nodes, dropping their references...
552 std::vector<DSNode*> DeadNodes;
553 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
554 for (unsigned i = 0; i != Nodes.size(); ++i)
555 if (!Alive.count(Nodes[i])) {
556 DSNode *N = Nodes[i];
557 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
558 DeadNodes.push_back(N); // Add node to our list of dead nodes
559 N->dropAllReferences(); // Drop all outgoing edges
562 // Delete all dead nodes...
563 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
568 // maskNodeTypes - Apply a mask to all of the node types in the graph. This
569 // is useful for clearing out markers like Scalar or Incomplete.
571 void DSGraph::maskNodeTypes(unsigned char Mask) {
572 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
573 Nodes[i]->NodeType &= Mask;
577 //===----------------------------------------------------------------------===//
578 // GlobalDSGraph Implementation
579 //===----------------------------------------------------------------------===//
581 GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
584 GlobalDSGraph::~GlobalDSGraph() {
585 assert(Referrers.size() == 0 &&
586 "Deleting global graph while references from other graphs exist");
589 void GlobalDSGraph::addReference(const DSGraph* referrer) {
590 if (referrer != this)
591 Referrers.insert(referrer);
594 void GlobalDSGraph::removeReference(const DSGraph* referrer) {
595 if (referrer != this) {
596 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
597 Referrers.erase(referrer);
598 if (Referrers.size() == 0)
603 // Bits used in the next function
604 static const char ExternalTypeBits = (DSNode::GlobalNode | DSNode::NewNode |
605 DSNode::SubElement | DSNode::CastNode);
608 // GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
609 // visible target links (and recursively their such links) into this graph.
610 // NodeCache maps the node being cloned to its clone in the Globals graph,
611 // in order to track cycles.
612 // GlobalsAreFinal is a flag that says whether it is safe to assume that
613 // an existing global node is complete. This is important to avoid
614 // reinserting all globals when inserting Calls to functions.
615 // This is a helper function for cloneGlobals and cloneCalls.
617 DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
618 std::map<const DSNode*, DSNode*> &NodeCache,
619 bool GlobalsAreFinal) {
620 if (OldNode == 0) return 0;
622 // The caller should check this is an external node. Just more efficient...
623 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
625 // If a clone has already been created for OldNode, return it.
626 DSNode*& CacheEntry = NodeCache[OldNode];
630 // The result value...
633 // If nodes already exist for any of the globals of OldNode,
634 // merge all such nodes together since they are merged in OldNode.
635 // If ValueCacheIsFinal==true, look for an existing node that has
636 // an identical list of globals and return it if it exists.
638 for (unsigned j = 0, N = OldNode->getGlobals().size(); j < N; ++j)
639 if (DSNode* PrevNode = ValueMap[OldNode->getGlobals()[j]]) {
641 NewNode = PrevNode; // first existing node found
642 if (GlobalsAreFinal && j == 0)
643 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
644 CacheEntry = NewNode;
648 else if (NewNode != PrevNode) { // found another, different from prev
649 // update ValMap *before* merging PrevNode into NewNode
650 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
651 ValueMap[PrevNode->getGlobals()[k]] = NewNode;
652 NewNode->mergeWith(PrevNode);
654 } else if (NewNode != 0) {
655 ValueMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
658 // If no existing node was found, clone the node and update the ValMap.
660 NewNode = new DSNode(*OldNode);
661 Nodes.push_back(NewNode);
662 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
663 NewNode->setLink(j, 0);
664 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
665 ValueMap[NewNode->getGlobals()[j]] = NewNode;
668 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
670 // Add the entry to NodeCache
671 CacheEntry = NewNode;
673 // Rewrite the links in the new node to point into the current graph,
674 // but only for links to external nodes. Set other links to NULL.
675 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
676 DSNode* OldTarget = OldNode->getLink(j);
677 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
678 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
679 if (NewNode->getLink(j))
680 NewNode->getLink(j)->mergeWith(NewLink);
682 NewNode->setLink(j, NewLink);
686 // Remove all local markers
687 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
693 // GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
694 // visible target links (and recursively their such links) into this graph.
696 void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
697 std::map<const DSNode*, DSNode*> NodeCache;
698 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
699 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
700 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
703 GlobalsGraph->cloneCalls(Graph);
705 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
709 // GlobalDSGraph::cloneCalls - Clone function calls and their visible target
710 // links (and recursively their such links) into this graph.
712 void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
713 std::map<const DSNode*, DSNode*> NodeCache;
714 std::vector<std::vector<DSNodeHandle> >& FromCalls =Graph.FunctionCalls;
716 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
718 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
719 FunctionCalls.push_back(std::vector<DSNodeHandle>());
720 FunctionCalls.back().reserve(FromCalls[i].size());
721 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
722 FunctionCalls.back().push_back
723 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
724 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
728 // remove trivially identical function calls
729 removeIdenticalCalls(FunctionCalls, "Globals Graph");
733 //===----------------------------------------------------------------------===//
734 // LocalDataStructures Implementation
735 //===----------------------------------------------------------------------===//
737 // releaseMemory - If the pass pipeline is done with this pass, we can release
738 // our memory... here...
740 void LocalDataStructures::releaseMemory() {
741 for (std::map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
742 E = DSInfo.end(); I != E; ++I)
745 // Empty map so next time memory is released, data structures are not
750 bool LocalDataStructures::run(Module &M) {
751 // Create a globals graph for the module. Deleted when all graphs go away.
752 GlobalDSGraph* GG = new GlobalDSGraph;
754 // Calculate all of the graphs...
755 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
756 if (!I->isExternal())
757 DSInfo.insert(std::make_pair(&*I, new DSGraph(*I, GG)));