1 //===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the BUDataStructures class, which represents the
11 // Bottom-Up Interprocedural closure of the data structure graph over the
12 // program. This is useful for applications like pool allocation, but **not**
13 // applications like alias analysis.
15 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "bu_dsa"
17 #include "llvm/Analysis/DataStructure/DataStructure.h"
18 #include "llvm/Analysis/DataStructure/DSGraph.h"
19 #include "llvm/Module.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Timer.h"
29 Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
30 Statistic<> NumBUInlines("budatastructures", "Number of graphs inlined");
31 Statistic<> NumCallEdges("budatastructures", "Number of 'actual' call edges");
34 AddGlobals("budatastructures-annotate-calls",
35 cl::desc("Annotate call sites with functions as they are resolved"));
37 UpdateGlobals("budatastructures-update-from-globals",
38 cl::desc("Update local graph from global graph when processing function"));
40 RegisterPass<BUDataStructures>
41 X("budatastructure", "Bottom-up Data Structure Analysis");
44 static bool GetAllCallees(const DSCallSite &CS,
45 std::vector<Function*> &Callees);
47 /// BuildGlobalECs - Look at all of the nodes in the globals graph. If any node
48 /// contains multiple globals, DSA will never, ever, be able to tell the globals
49 /// apart. Instead of maintaining this information in all of the graphs
50 /// throughout the entire program, store only a single global (the "leader") in
51 /// the graphs, and build equivalence classes for the rest of the globals.
52 static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
53 DSScalarMap &SM = GG.getScalarMap();
54 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
55 for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
57 if (I->getGlobalsList().size() <= 1) continue;
59 // First, build up the equivalence set for this block of globals.
60 const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
61 GlobalValue *First = GVs[0];
62 for (unsigned i = 1, e = GVs.size(); i != e; ++i)
63 GlobalECs.unionSets(First, GVs[i]);
65 // Next, get the leader element.
66 assert(First == GlobalECs.getLeaderValue(First) &&
67 "First did not end up being the leader?");
69 // Next, remove all globals from the scalar map that are not the leader.
70 assert(GVs[0] == First && "First had to be at the front!");
71 for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
72 ECGlobals.insert(GVs[i]);
73 SM.erase(SM.find(GVs[i]));
76 // Finally, change the global node to only contain the leader.
81 DEBUG(GG.AssertGraphOK());
84 /// EliminateUsesOfECGlobals - Once we have determined that some globals are in
85 /// really just equivalent to some other globals, remove the globals from the
86 /// specified DSGraph (if present), and merge any nodes with their leader nodes.
87 static void EliminateUsesOfECGlobals(DSGraph &G,
88 const std::set<GlobalValue*> &ECGlobals) {
89 DSScalarMap &SM = G.getScalarMap();
90 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
92 bool MadeChange = false;
93 for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
95 GlobalValue *GV = *GI++;
96 if (!ECGlobals.count(GV)) continue;
98 const DSNodeHandle &GVNH = SM[GV];
99 assert(!GVNH.isNull() && "Global has null NH!?");
101 // Okay, this global is in some equivalence class. Start by finding the
102 // leader of the class.
103 GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
105 // If the leader isn't already in the graph, insert it into the node
106 // corresponding to GV.
107 if (!SM.global_count(Leader)) {
108 GVNH.getNode()->addGlobal(Leader);
111 // Otherwise, the leader is in the graph, make sure the nodes are the
112 // merged in the specified graph.
113 const DSNodeHandle &LNH = SM[Leader];
114 if (LNH.getNode() != GVNH.getNode())
118 // Next step, remove the global from the DSNode.
119 GVNH.getNode()->removeGlobal(GV);
121 // Finally, remove the global from the ScalarMap.
126 DEBUG(if(MadeChange) G.AssertGraphOK());
129 static void AddGlobalToNode(BUDataStructures* B, DSCallSite D, Function* F) {
132 if(D.isIndirectCall()) {
133 DSGraph* GI = &B->getDSGraph(D.getCaller());
134 DSNodeHandle& NHF = GI->getNodeForValue(F);
135 DSCallSite DL = GI->getDSCallSiteForCallSite(D.getCallSite());
136 if (DL.getCalleeNode() != NHF.getNode() || NHF.isNull()) {
138 DSNode *N = new DSNode(F->getType()->getElementType(), GI); // Create the node
141 DEBUG(std::cerr << "Adding " << F->getName() << " to a call node in "
142 << D.getCaller().getName() << "\n");
144 DL.getCalleeNode()->mergeWith(NHF, 0);
149 // run - Calculate the bottom up data structure graphs for each function in the
152 bool BUDataStructures::runOnModule(Module &M) {
153 LocalDataStructures &LocalDSA = getAnalysis<LocalDataStructures>();
154 GlobalECs = LocalDSA.getGlobalECs();
156 GlobalsGraph = new DSGraph(LocalDSA.getGlobalsGraph(), GlobalECs);
157 GlobalsGraph->setPrintAuxCalls();
159 IndCallGraphMap = new std::map<std::vector<Function*>,
160 std::pair<DSGraph*, std::vector<DSNodeHandle> > >();
162 std::vector<Function*> Stack;
163 hash_map<Function*, unsigned> ValMap;
166 Function *MainFunc = M.getMainFunction();
169 calculateGraphs(MainFunc, Stack, NextID, ValMap);
171 // Calculate the graphs for any functions that are unreachable from main...
172 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
173 if (!I->isExternal() && !DSInfo.count(I)) {
175 DEBUG(std::cerr << "*** BU: Function unreachable from main: "
176 << I->getName() << "\n");
177 calculateGraphs(I, Stack, NextID, ValMap); // Calculate all graphs.
180 // If we computed any temporary indcallgraphs, free them now.
181 for (std::map<std::vector<Function*>,
182 std::pair<DSGraph*, std::vector<DSNodeHandle> > >::iterator I =
183 IndCallGraphMap->begin(), E = IndCallGraphMap->end(); I != E; ++I) {
184 I->second.second.clear(); // Drop arg refs into the graph.
185 delete I->second.first;
187 delete IndCallGraphMap;
189 // At the end of the bottom-up pass, the globals graph becomes complete.
190 // FIXME: This is not the right way to do this, but it is sorta better than
191 // nothing! In particular, externally visible globals and unresolvable call
192 // nodes at the end of the BU phase should make things that they point to
193 // incomplete in the globals graph.
195 GlobalsGraph->removeTriviallyDeadNodes();
196 GlobalsGraph->maskIncompleteMarkers();
198 // Mark external globals incomplete.
199 GlobalsGraph->markIncompleteNodes(DSGraph::IgnoreGlobals);
201 // Grow the equivalence classes for the globals to include anything that we
202 // now know to be aliased.
203 std::set<GlobalValue*> ECGlobals;
204 BuildGlobalECs(*GlobalsGraph, ECGlobals);
205 if (!ECGlobals.empty()) {
206 NamedRegionTimer X("Bottom-UP EC Cleanup");
207 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
208 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
209 E = DSInfo.end(); I != E; ++I)
210 EliminateUsesOfECGlobals(*I->second, ECGlobals);
213 // Merge the globals variables (not the calls) from the globals graph back
214 // into the main function's graph so that the main function contains all of
215 // the information about global pools and GV usage in the program.
216 if (MainFunc && !MainFunc->isExternal()) {
217 DSGraph &MainGraph = getOrCreateGraph(MainFunc);
218 const DSGraph &GG = *MainGraph.getGlobalsGraph();
219 ReachabilityCloner RC(MainGraph, GG, DSGraph::DontCloneCallNodes |
220 DSGraph::DontCloneAuxCallNodes);
222 // Clone the global nodes into this graph.
223 for (DSScalarMap::global_iterator I = GG.getScalarMap().global_begin(),
224 E = GG.getScalarMap().global_end(); I != E; ++I)
225 if (isa<GlobalVariable>(*I))
226 RC.getClonedNH(GG.getNodeForValue(*I));
228 MainGraph.maskIncompleteMarkers();
229 MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs |
230 DSGraph::IgnoreGlobals);
232 //Debug messages if along the way we didn't resolve a call site
233 //also update the call graph and callsites we did find.
234 for(DSGraph::afc_iterator ii = MainGraph.afc_begin(),
235 ee = MainGraph.afc_end(); ii != ee; ++ii) {
236 std::vector<Function*> Funcs;
237 GetAllCallees(*ii, Funcs);
238 DEBUG(std::cerr << "Lost site\n");
239 DEBUG(ii->getCallSite().getInstruction()->dump());
240 for (std::vector<Function*>::iterator iif = Funcs.begin(), eef = Funcs.end();
242 AddGlobalToNode(this, *ii, *iif);
243 DEBUG(std::cerr << "Adding\n");
244 ActualCallees.insert(std::make_pair(ii->getCallSite().getInstruction(), *iif));
250 NumCallEdges += ActualCallees.size();
255 DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
256 // Has the graph already been created?
257 DSGraph *&Graph = DSInfo[F];
258 if (Graph) return *Graph;
260 DSGraph &LocGraph = getAnalysis<LocalDataStructures>().getDSGraph(*F);
262 // Steal the local graph.
263 Graph = new DSGraph(GlobalECs, LocGraph.getTargetData());
264 Graph->spliceFrom(LocGraph);
266 Graph->setGlobalsGraph(GlobalsGraph);
267 Graph->setPrintAuxCalls();
269 // Start with a copy of the original call sites...
270 Graph->getAuxFunctionCalls() = Graph->getFunctionCalls();
274 static bool isVAHackFn(const Function *F) {
275 return F->getName() == "printf" || F->getName() == "sscanf" ||
276 F->getName() == "fprintf" || F->getName() == "open" ||
277 F->getName() == "sprintf" || F->getName() == "fputs" ||
278 F->getName() == "fscanf" || F->getName() == "malloc" ||
279 F->getName() == "free";
282 static bool isResolvableFunc(const Function* callee) {
283 return !callee->isExternal() || isVAHackFn(callee);
286 //returns true if all callees were resolved
287 static bool GetAllCallees(const DSCallSite &CS,
288 std::vector<Function*> &Callees) {
289 if (CS.isDirectCall()) {
290 if (isResolvableFunc(CS.getCalleeFunc())) {
291 Callees.push_back(CS.getCalleeFunc());
297 bool retval = CS.getCalleeNode()->isComplete();
298 unsigned OldSize = Callees.size();
299 CS.getCalleeNode()->addFullFunctionList(Callees);
301 // If any of the callees are unresolvable, remove that one
302 for (unsigned i = OldSize; i != Callees.size(); ++i)
303 if (!isResolvableFunc(Callees[i])) {
304 Callees.erase(Callees.begin()+i);
313 /// GetAllAuxCallees - Return a list containing all of the resolvable callees in
314 /// the aux list for the specified graph in the Callees vector.
315 static void GetAllAuxCallees(DSGraph &G, std::vector<Function*> &Callees) {
317 for (DSGraph::afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
318 GetAllCallees(*I, Callees);
321 unsigned BUDataStructures::calculateGraphs(Function *F,
322 std::vector<Function*> &Stack,
324 hash_map<Function*, unsigned> &ValMap) {
325 assert(!ValMap.count(F) && "Shouldn't revisit functions!");
326 unsigned Min = NextID++, MyID = Min;
330 // FIXME! This test should be generalized to be any function that we have
331 // already processed, in the case when there isn't a main or there are
332 // unreachable functions!
333 if (F->isExternal()) { // sprintf, fprintf, sscanf, etc...
340 DSGraph &Graph = getOrCreateGraph(F);
342 Graph.updateFromGlobalGraph();
344 // Find all callee functions.
345 std::vector<Function*> CalleeFunctions;
346 GetAllAuxCallees(Graph, CalleeFunctions);
348 // The edges out of the current node are the call site targets...
349 for (unsigned i = 0, e = CalleeFunctions.size(); i != e; ++i) {
350 Function *Callee = CalleeFunctions[i];
352 // Have we visited the destination function yet?
353 hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
354 if (It == ValMap.end()) // No, visit it now.
355 M = calculateGraphs(Callee, Stack, NextID, ValMap);
356 else // Yes, get it's number.
358 if (M < Min) Min = M;
361 assert(ValMap[F] == MyID && "SCC construction assumption wrong!");
363 return Min; // This is part of a larger SCC!
365 // If this is a new SCC, process it now.
366 if (Stack.back() == F) { // Special case the single "SCC" case here.
367 DEBUG(std::cerr << "Visiting single node SCC #: " << MyID << " fn: "
368 << F->getName() << "\n");
370 DSGraph &G = getDSGraph(*F);
371 DEBUG(std::cerr << " [BU] Calculating graph for: " << F->getName()<< "\n");
372 bool redo = calculateGraph(G);
373 DEBUG(std::cerr << " [BU] Done inlining: " << F->getName() << " ["
374 << G.getGraphSize() << "+" << G.getAuxFunctionCalls().size()
377 if (MaxSCC < 1) MaxSCC = 1;
379 // Should we revisit the graph? Only do it if there are now new resolvable
382 DEBUG(std::cerr << "Recalculating " << F->getName() << " due to new knowledge\n");
384 return calculateGraphs(F, Stack, NextID, ValMap);
391 // SCCFunctions - Keep track of the functions in the current SCC
393 std::vector<DSGraph*> SCCGraphs;
395 unsigned SCCSize = 1;
396 Function *NF = Stack.back();
398 DSGraph &SCCGraph = getDSGraph(*NF);
400 // First thing first, collapse all of the DSGraphs into a single graph for
401 // the entire SCC. Splice all of the graphs into one and discard all of the
409 DSGraph &NFG = getDSGraph(*NF);
411 // Update the Function -> DSG map.
412 for (DSGraph::retnodes_iterator I = NFG.retnodes_begin(),
413 E = NFG.retnodes_end(); I != E; ++I)
414 DSInfo[I->first] = &SCCGraph;
416 SCCGraph.spliceFrom(NFG);
423 DEBUG(std::cerr << "Calculating graph for SCC #: " << MyID << " of size: "
426 // Compute the Max SCC Size.
427 if (MaxSCC < SCCSize)
430 // Clean up the graph before we start inlining a bunch again...
431 SCCGraph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
433 // Now that we have one big happy family, resolve all of the call sites in
435 bool redo = calculateGraph(SCCGraph);
436 DEBUG(std::cerr << " [BU] Done inlining SCC [" << SCCGraph.getGraphSize()
437 << "+" << SCCGraph.getAuxFunctionCalls().size() << "]\n");
440 DEBUG(std::cerr << "MISSING REDO\n");
443 DEBUG(std::cerr << "DONE with SCC #: " << MyID << "\n");
445 // We never have to revisit "SCC" processed functions...
449 return MyID; // == Min
453 // releaseMemory - If the pass pipeline is done with this pass, we can release
454 // our memory... here...
456 void BUDataStructures::releaseMyMemory() {
457 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
458 E = DSInfo.end(); I != E; ++I) {
459 I->second->getReturnNodes().erase(I->first);
460 if (I->second->getReturnNodes().empty())
464 // Empty map so next time memory is released, data structures are not
471 DSGraph &BUDataStructures::CreateGraphForExternalFunction(const Function &Fn) {
472 Function *F = const_cast<Function*>(&Fn);
473 DSGraph *DSG = new DSGraph(GlobalECs, GlobalsGraph->getTargetData());
475 DSG->setGlobalsGraph(GlobalsGraph);
476 DSG->setPrintAuxCalls();
478 // Add function to the graph.
479 DSG->getReturnNodes().insert(std::make_pair(F, DSNodeHandle()));
481 if (F->getName() == "free") { // Taking the address of free.
483 // Free should take a single pointer argument, mark it as heap memory.
484 DSNode *N = new DSNode(0, DSG);
485 N->setHeapNodeMarker();
486 DSG->getNodeForValue(F->arg_begin()).mergeWith(N);
489 std::cerr << "Unrecognized external function: " << F->getName() << "\n";
497 bool BUDataStructures::calculateGraph(DSGraph &Graph) {
498 // If this graph contains the main function, clone the globals graph into this
499 // graph before we inline callees and other fun stuff.
500 bool ContainsMain = false;
501 DSGraph::ReturnNodesTy &ReturnNodes = Graph.getReturnNodes();
503 for (DSGraph::ReturnNodesTy::iterator I = ReturnNodes.begin(),
504 E = ReturnNodes.end(); I != E; ++I)
505 if (I->first->hasExternalLinkage() && I->first->getName() == "main") {
510 // If this graph contains main, copy the contents of the globals graph over.
511 // Note that this is *required* for correctness. If a callee contains a use
512 // of a global, we have to make sure to link up nodes due to global-argument
515 const DSGraph &GG = *Graph.getGlobalsGraph();
516 ReachabilityCloner RC(Graph, GG,
517 DSGraph::DontCloneCallNodes |
518 DSGraph::DontCloneAuxCallNodes);
520 // Clone the global nodes into this graph.
521 for (DSScalarMap::global_iterator I = GG.getScalarMap().global_begin(),
522 E = GG.getScalarMap().global_end(); I != E; ++I)
523 if (isa<GlobalVariable>(*I))
524 RC.getClonedNH(GG.getNodeForValue(*I));
528 // Move our call site list into TempFCs so that inline call sites go into the
529 // new call site list and doesn't invalidate our iterators!
530 std::list<DSCallSite> TempFCs;
531 std::list<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
532 TempFCs.swap(AuxCallsList);
533 //remember what we've seen (or will see)
534 unsigned oldSize = TempFCs.size();
536 bool Printed = false;
537 bool missingNode = false;
539 while (!TempFCs.empty()) {
540 DSCallSite &CS = *TempFCs.begin();
541 Instruction *TheCall = CS.getCallSite().getInstruction();
544 // Fast path for noop calls. Note that we don't care about merging globals
545 // in the callee with nodes in the caller here.
546 if (CS.isDirectCall()) {
547 if (!isVAHackFn(CS.getCalleeFunc()) && isResolvableFunc(CS.getCalleeFunc())) {
548 Function* Callee = CS.getCalleeFunc();
549 ActualCallees.insert(std::make_pair(TheCall, Callee));
551 assert(doneDSGraph(Callee) && "Direct calls should always be precomputed");
552 GI = &getDSGraph(*Callee); // Graph to inline
553 DEBUG(std::cerr << " Inlining graph for " << Callee->getName());
554 DEBUG(std::cerr << "[" << GI->getGraphSize() << "+"
555 << GI->getAuxFunctionCalls().size() << "] into '"
556 << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
557 << Graph.getAuxFunctionCalls().size() << "]\n");
558 Graph.mergeInGraph(CS, *Callee, *GI,
559 DSGraph::StripAllocaBit|DSGraph::DontCloneCallNodes);
562 DEBUG(std::cerr << "Graph " << Graph.getFunctionNames() << " Call Site " <<
563 CS.getCallSite().getInstruction() << " never resolvable\n");
569 std::vector<Function*> CalledFuncs;
570 bool resolved = GetAllCallees(CS, CalledFuncs);
572 if (CalledFuncs.empty()) {
573 DEBUG(std::cerr << "Graph " << Graph.getFunctionNames() << " Call Site " <<
574 CS.getCallSite().getInstruction() << " delayed\n");
578 std::cerr << "In Fns: " << Graph.getFunctionNames() << "\n";
579 std::cerr << " calls " << CalledFuncs.size()
580 << " fns from site: " << CS.getCallSite().getInstruction()
581 << " " << *CS.getCallSite().getInstruction();
582 std::cerr << " Fns =";
584 unsigned NumPrinted = 0;
586 for (std::vector<Function*>::iterator I = CalledFuncs.begin(),
587 E = CalledFuncs.end(); I != E; ++I) {
588 DEBUG(if (NumPrinted++ < 8) std::cerr << " " << (*I)->getName(););
590 // Add the call edges to the call graph.
591 ActualCallees.insert(std::make_pair(TheCall, *I));
593 DEBUG(std::cerr << "\n");
595 // See if we already computed a graph for this set of callees.
596 std::sort(CalledFuncs.begin(), CalledFuncs.end());
597 std::pair<DSGraph*, std::vector<DSNodeHandle> > &IndCallGraph =
598 (*IndCallGraphMap)[CalledFuncs];
600 if (IndCallGraph.first == 0) {
601 std::vector<Function*>::iterator I = CalledFuncs.begin(),
602 E = CalledFuncs.end();
604 // Start with a copy of the first graph.
605 if (!doneDSGraph(*I)) {
606 AuxCallsList.splice(AuxCallsList.end(), TempFCs, TempFCs.begin());
611 AddGlobalToNode(this, CS, *I);
613 GI = IndCallGraph.first = new DSGraph(getDSGraph(**I), GlobalECs);
614 GI->setGlobalsGraph(Graph.getGlobalsGraph());
615 std::vector<DSNodeHandle> &Args = IndCallGraph.second;
617 // Get the argument nodes for the first callee. The return value is
618 // the 0th index in the vector.
619 GI->getFunctionArgumentsForCall(*I, Args);
621 // Merge all of the other callees into this graph.
622 bool locMissing = false;
623 for (++I; I != E && !locMissing; ++I) {
624 AddGlobalToNode(this, CS, *I);
625 // If the graph already contains the nodes for the function, don't
626 // bother merging it in again.
627 if (!GI->containsFunction(*I)) {
628 if (!doneDSGraph(*I)) {
633 GI->cloneInto(getDSGraph(**I));
637 std::vector<DSNodeHandle> NextArgs;
638 GI->getFunctionArgumentsForCall(*I, NextArgs);
639 unsigned i = 0, e = Args.size();
640 for (; i != e; ++i) {
641 if (i == NextArgs.size()) break;
642 Args[i].mergeWith(NextArgs[i]);
644 for (e = NextArgs.size(); i != e; ++i)
645 Args.push_back(NextArgs[i]);
648 AuxCallsList.splice(AuxCallsList.end(), TempFCs, TempFCs.begin());
653 // Clean up the final graph!
654 GI->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
656 DEBUG(std::cerr << "***\n*** RECYCLED GRAPH ***\n***\n");
657 for (std::vector<Function*>::iterator I = CalledFuncs.begin(), E = CalledFuncs.end(); I != E; ++I) {
658 AddGlobalToNode(this, CS, *I);
662 GI = IndCallGraph.first;
664 if (AlreadyInlined[CS.getCallSite()] != CalledFuncs) {
665 AlreadyInlined[CS.getCallSite()].swap(CalledFuncs);
667 // Merge the unified graph into this graph now.
668 DEBUG(std::cerr << " Inlining multi callee graph "
669 << "[" << GI->getGraphSize() << "+"
670 << GI->getAuxFunctionCalls().size() << "] into '"
671 << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
672 << Graph.getAuxFunctionCalls().size() << "]\n");
674 Graph.mergeInGraph(CS, IndCallGraph.second, *GI,
675 DSGraph::StripAllocaBit |
676 DSGraph::DontCloneCallNodes);
680 DEBUG(std::cerr << " Skipping already inlined graph\n");
683 AuxCallsList.splice(AuxCallsList.end(), TempFCs, TempFCs.begin());
687 // Recompute the Incomplete markers
688 Graph.maskIncompleteMarkers();
689 Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
691 // Delete dead nodes. Treat globals that are unreachable but that can
692 // reach live nodes as live.
693 Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
695 // When this graph is finalized, clone the globals in the graph into the
696 // globals graph to make sure it has everything, from all graphs.
697 DSScalarMap &MainSM = Graph.getScalarMap();
698 ReachabilityCloner RC(*GlobalsGraph, Graph, DSGraph::StripAllocaBit);
700 // Clone everything reachable from globals in the function graph into the
702 for (DSScalarMap::global_iterator I = MainSM.global_begin(),
703 E = MainSM.global_end(); I != E; ++I)
704 RC.getClonedNH(MainSM[*I]);
706 //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
708 AuxCallsList.unique();
709 //conditionally prune the call list keeping only one copy of each actual
711 if (AuxCallsList.size() > 100) {
712 DEBUG(std::cerr << "Reducing Aux from " << AuxCallsList.size());
713 std::map<CallSite, std::list<DSCallSite>::iterator> keepers;
714 TempFCs.swap(AuxCallsList);
715 for( std::list<DSCallSite>::iterator ii = TempFCs.begin(), ee = TempFCs.end();
717 keepers[ii->getCallSite()] = ii;
718 for (std::map<CallSite, std::list<DSCallSite>::iterator>::iterator
719 ii = keepers.begin(), ee = keepers.end();
721 AuxCallsList.splice(AuxCallsList.end(), TempFCs, ii->second);
722 DEBUG(std::cerr << " to " << AuxCallsList.size() << "\n");
724 return missingNode || oldSize != AuxCallsList.size();
727 static const Function *getFnForValue(const Value *V) {
728 if (const Instruction *I = dyn_cast<Instruction>(V))
729 return I->getParent()->getParent();
730 else if (const Argument *A = dyn_cast<Argument>(V))
731 return A->getParent();
732 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
733 return BB->getParent();
737 /// deleteValue/copyValue - Interfaces to update the DSGraphs in the program.
738 /// These correspond to the interfaces defined in the AliasAnalysis class.
739 void BUDataStructures::deleteValue(Value *V) {
740 if (const Function *F = getFnForValue(V)) { // Function local value?
741 // If this is a function local value, just delete it from the scalar map!
742 getDSGraph(*F).getScalarMap().eraseIfExists(V);
746 if (Function *F = dyn_cast<Function>(V)) {
747 assert(getDSGraph(*F).getReturnNodes().size() == 1 &&
748 "cannot handle scc's");
754 assert(!isa<GlobalVariable>(V) && "Do not know how to delete GV's yet!");
757 void BUDataStructures::copyValue(Value *From, Value *To) {
758 if (From == To) return;
759 if (const Function *F = getFnForValue(From)) { // Function local value?
760 // If this is a function local value, just delete it from the scalar map!
761 getDSGraph(*F).getScalarMap().copyScalarIfExists(From, To);
765 if (Function *FromF = dyn_cast<Function>(From)) {
766 Function *ToF = cast<Function>(To);
767 assert(!DSInfo.count(ToF) && "New Function already exists!");
768 DSGraph *NG = new DSGraph(getDSGraph(*FromF), GlobalECs);
770 assert(NG->getReturnNodes().size() == 1 && "Cannot copy SCC's yet!");
772 // Change the Function* is the returnnodes map to the ToF.
773 DSNodeHandle Ret = NG->retnodes_begin()->second;
774 NG->getReturnNodes().clear();
775 NG->getReturnNodes()[ToF] = Ret;
779 if (const Function *F = getFnForValue(To)) {
780 DSGraph &G = getDSGraph(*F);
781 G.getScalarMap().copyScalarIfExists(From, To);
787 assert(0 && "Do not know how to copy this yet!");