Remove trailing whitespace
[oota-llvm.git] / lib / Analysis / DataStructure / BottomUpClosure.cpp
index 591cefb15b9dd54aa228cd705ffda520e1ccc42b..aa5144437d8380fc3bd25c61a96298e0773a4b73 100644 (file)
@@ -1,5 +1,12 @@
 //===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
 //
+//                     The LLVM Compiler Infrastructure
+//
+// This file was developed by the LLVM research group and is distributed under
+// the University of Illinois Open Source License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
 // This file implements the BUDataStructures class, which represents the
 // Bottom-Up Interprocedural closure of the data structure graph over the
 // program.  This is useful for applications like pool allocation, but **not**
 //
 //===----------------------------------------------------------------------===//
 
-#include "llvm/Analysis/DataStructure.h"
-#include "llvm/Analysis/DSGraph.h"
+#include "llvm/Analysis/DataStructure/DataStructure.h"
+#include "llvm/Analysis/DataStructure/DSGraph.h"
 #include "llvm/Module.h"
-#include "Support/Statistic.h"
-#include "Support/hash_map"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/Timer.h"
+using namespace llvm;
 
 namespace {
   Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
-  
+  Statistic<> NumBUInlines("budatastructures", "Number of graphs inlined");
+  Statistic<> NumCallEdges("budatastructures", "Number of 'actual' call edges");
+
   RegisterAnalysis<BUDataStructures>
   X("budatastructure", "Bottom-up Data Structure Analysis");
 }
 
-using namespace DS;
-
-static bool isVAHackFn(const Function *F) {
-  return F->getName() == "printf"  || F->getName() == "sscanf" ||
-         F->getName() == "fprintf" || F->getName() == "open" ||
-         F->getName() == "sprintf" || F->getName() == "fputs" ||
-         F->getName() == "fscanf";
-}
-
-// isCompleteNode - Return true if we know all of the targets of this node, and
-// if the call sites are not external.
-//
-static inline bool isCompleteNode(DSNode *N) {
-  if (N->isIncomplete()) return false;
-  const std::vector<GlobalValue*> &Callees = N->getGlobals();
-  for (unsigned i = 0, e = Callees.size(); i != e; ++i)
-    if (Callees[i]->isExternal())
-      if (!isVAHackFn(cast<Function>(Callees[i])))
-        return false;  // External function found...
-  return true;  // otherwise ok
-}
-
-struct CallSiteIterator {
-  // FCs are the edges out of the current node are the call site targets...
-  std::vector<DSCallSite> *FCs;
-  unsigned CallSite;
-  unsigned CallSiteEntry;
-
-  CallSiteIterator(std::vector<DSCallSite> &CS) : FCs(&CS) {
-    CallSite = 0; CallSiteEntry = 0;
-    advanceToValidCallee();
-  }
-
-  // End iterator ctor...
-  CallSiteIterator(std::vector<DSCallSite> &CS, bool) : FCs(&CS) {
-    CallSite = FCs->size(); CallSiteEntry = 0;
-  }
-
-  void advanceToValidCallee() {
-    while (CallSite < FCs->size()) {
-      if ((*FCs)[CallSite].isDirectCall()) {
-        if (CallSiteEntry == 0 &&        // direct call only has one target...
-            (!(*FCs)[CallSite].getCalleeFunc()->isExternal() ||
-             isVAHackFn((*FCs)[CallSite].getCalleeFunc()))) // If not external
-          return;
-      } else {
-        DSNode *CalleeNode = (*FCs)[CallSite].getCalleeNode();
-        if (CallSiteEntry || isCompleteNode(CalleeNode)) {
-          const std::vector<GlobalValue*> &Callees = CalleeNode->getGlobals();
-          
-          if (CallSiteEntry < Callees.size())
-            return;
-        }
-      }
-      CallSiteEntry = 0;
-      ++CallSite;
+/// BuildGlobalECs - Look at all of the nodes in the globals graph.  If any node
+/// contains multiple globals, DSA will never, ever, be able to tell the globals
+/// apart.  Instead of maintaining this information in all of the graphs
+/// throughout the entire program, store only a single global (the "leader") in
+/// the graphs, and build equivalence classes for the rest of the globals.
+static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
+  DSScalarMap &SM = GG.getScalarMap();
+  EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
+  for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
+       I != E; ++I) {
+    if (I->getGlobalsList().size() <= 1) continue;
+
+    // First, build up the equivalence set for this block of globals.
+    const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
+    GlobalValue *First = GVs[0];
+    for (unsigned i = 1, e = GVs.size(); i != e; ++i)
+      GlobalECs.unionSets(First, GVs[i]);
+
+    // Next, get the leader element.
+    assert(First == GlobalECs.getLeaderValue(First) &&
+           "First did not end up being the leader?");
+
+    // Next, remove all globals from the scalar map that are not the leader.
+    assert(GVs[0] == First && "First had to be at the front!");
+    for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
+      ECGlobals.insert(GVs[i]);
+      SM.erase(SM.find(GVs[i]));
     }
+
+    // Finally, change the global node to only contain the leader.
+    I->clearGlobals();
+    I->addGlobal(First);
   }
-public:
-  static CallSiteIterator begin(DSGraph &G) { return G.getAuxFunctionCalls(); }
-  static CallSiteIterator end(DSGraph &G) {
-    return CallSiteIterator(G.getAuxFunctionCalls(), true);
-  }
-  static CallSiteIterator begin(std::vector<DSCallSite> &CSs) { return CSs; }
-  static CallSiteIterator end(std::vector<DSCallSite> &CSs) {
-    return CallSiteIterator(CSs, true);
-  }
-  bool operator==(const CallSiteIterator &CSI) const {
-    return CallSite == CSI.CallSite && CallSiteEntry == CSI.CallSiteEntry;
-  }
-  bool operator!=(const CallSiteIterator &CSI) const { return !operator==(CSI);}
 
-  unsigned getCallSiteIdx() const { return CallSite; }
-  DSCallSite &getCallSite() const { return (*FCs)[CallSite]; }
+  DEBUG(GG.AssertGraphOK());
+}
 
-  Function *operator*() const {
-    if ((*FCs)[CallSite].isDirectCall()) {
-      return (*FCs)[CallSite].getCalleeFunc();
+/// EliminateUsesOfECGlobals - Once we have determined that some globals are in
+/// really just equivalent to some other globals, remove the globals from the
+/// specified DSGraph (if present), and merge any nodes with their leader nodes.
+static void EliminateUsesOfECGlobals(DSGraph &G,
+                                     const std::set<GlobalValue*> &ECGlobals) {
+  DSScalarMap &SM = G.getScalarMap();
+  EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
+
+  bool MadeChange = false;
+  for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
+       GI != E; ) {
+    GlobalValue *GV = *GI++;
+    if (!ECGlobals.count(GV)) continue;
+
+    const DSNodeHandle &GVNH = SM[GV];
+    assert(!GVNH.isNull() && "Global has null NH!?");
+
+    // Okay, this global is in some equivalence class.  Start by finding the
+    // leader of the class.
+    GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
+
+    // If the leader isn't already in the graph, insert it into the node
+    // corresponding to GV.
+    if (!SM.global_count(Leader)) {
+      GVNH.getNode()->addGlobal(Leader);
+      SM[Leader] = GVNH;
     } else {
-      DSNode *Node = (*FCs)[CallSite].getCalleeNode();
-      return cast<Function>(Node->getGlobals()[CallSiteEntry]);
+      // Otherwise, the leader is in the graph, make sure the nodes are the
+      // merged in the specified graph.
+      const DSNodeHandle &LNH = SM[Leader];
+      if (LNH.getNode() != GVNH.getNode())
+        LNH.mergeWith(GVNH);
     }
-  }
 
-  CallSiteIterator& operator++() {                // Preincrement
-    ++CallSiteEntry;
-    advanceToValidCallee();
-    return *this;
-  }
-  CallSiteIterator operator++(int) { // Postincrement
-    CallSiteIterator tmp = *this; ++*this; return tmp; 
-  }
-};
+    // Next step, remove the global from the DSNode.
+    GVNH.getNode()->removeGlobal(GV);
 
+    // Finally, remove the global from the ScalarMap.
+    SM.erase(GV);
+    MadeChange = true;
+  }
 
+  DEBUG(if(MadeChange) G.AssertGraphOK());
+}
 
 // run - Calculate the bottom up data structure graphs for each function in the
 // program.
 //
-bool BUDataStructures::run(Module &M) {
+bool BUDataStructures::runOnModule(Module &M) {
   LocalDataStructures &LocalDSA = getAnalysis<LocalDataStructures>();
-  GlobalsGraph = new DSGraph(LocalDSA.getGlobalsGraph());
+  GlobalECs = LocalDSA.getGlobalECs();
+
+  GlobalsGraph = new DSGraph(LocalDSA.getGlobalsGraph(), GlobalECs);
   GlobalsGraph->setPrintAuxCalls();
 
+  IndCallGraphMap = new std::map<std::vector<Function*>,
+                           std::pair<DSGraph*, std::vector<DSNodeHandle> > >();
+
+  std::vector<Function*> Stack;
+  hash_map<Function*, unsigned> ValMap;
+  unsigned NextID = 1;
+
   Function *MainFunc = M.getMainFunction();
   if (MainFunc)
-    calculateReachableGraphs(MainFunc);
+    calculateGraphs(MainFunc, Stack, NextID, ValMap);
 
   // Calculate the graphs for any functions that are unreachable from main...
   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
-    if (!I->isExternal() && DSInfo.find(I) == DSInfo.end()) {
+    if (!I->isExternal() && !DSInfo.count(I)) {
 #ifndef NDEBUG
       if (MainFunc)
         std::cerr << "*** Function unreachable from main: "
                   << I->getName() << "\n";
 #endif
-      calculateReachableGraphs(I);    // Calculate all graphs...
+      calculateGraphs(I, Stack, NextID, ValMap);     // Calculate all graphs.
     }
-  return false;
-}
 
-void BUDataStructures::calculateReachableGraphs(Function *F) {
-  std::vector<Function*> Stack;
-  hash_map<Function*, unsigned> ValMap;
-  unsigned NextID = 1;
-  calculateGraphs(F, Stack, NextID, ValMap);
+  NumCallEdges += ActualCallees.size();
+
+  // If we computed any temporary indcallgraphs, free them now.
+  for (std::map<std::vector<Function*>,
+         std::pair<DSGraph*, std::vector<DSNodeHandle> > >::iterator I =
+         IndCallGraphMap->begin(), E = IndCallGraphMap->end(); I != E; ++I) {
+    I->second.second.clear();  // Drop arg refs into the graph.
+    delete I->second.first;
+  }
+  delete IndCallGraphMap;
+
+  // At the end of the bottom-up pass, the globals graph becomes complete.
+  // FIXME: This is not the right way to do this, but it is sorta better than
+  // nothing!  In particular, externally visible globals and unresolvable call
+  // nodes at the end of the BU phase should make things that they point to
+  // incomplete in the globals graph.
+  //
+  GlobalsGraph->removeTriviallyDeadNodes();
+  GlobalsGraph->maskIncompleteMarkers();
+
+  // Mark external globals incomplete.
+  GlobalsGraph->markIncompleteNodes(DSGraph::IgnoreGlobals);
+
+  // Grow the equivalence classes for the globals to include anything that we
+  // now know to be aliased.
+  std::set<GlobalValue*> ECGlobals;
+  BuildGlobalECs(*GlobalsGraph, ECGlobals);
+  if (!ECGlobals.empty()) {
+    NamedRegionTimer X("Bottom-UP EC Cleanup");
+    std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n";
+    for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
+           E = DSInfo.end(); I != E; ++I)
+      EliminateUsesOfECGlobals(*I->second, ECGlobals);
+  }
+
+  // Merge the globals variables (not the calls) from the globals graph back
+  // into the main function's graph so that the main function contains all of
+  // the information about global pools and GV usage in the program.
+  if (MainFunc && !MainFunc->isExternal()) {
+    DSGraph &MainGraph = getOrCreateGraph(MainFunc);
+    const DSGraph &GG = *MainGraph.getGlobalsGraph();
+    ReachabilityCloner RC(MainGraph, GG,
+                          DSGraph::DontCloneCallNodes |
+                          DSGraph::DontCloneAuxCallNodes);
+
+    // Clone the global nodes into this graph.
+    for (DSScalarMap::global_iterator I = GG.getScalarMap().global_begin(),
+           E = GG.getScalarMap().global_end(); I != E; ++I)
+      if (isa<GlobalVariable>(*I))
+        RC.getClonedNH(GG.getNodeForValue(*I));
+
+    MainGraph.maskIncompleteMarkers();
+    MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs |
+                                  DSGraph::IgnoreGlobals);
+  }
+
+  return false;
 }
 
 DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
@@ -153,8 +209,11 @@ DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
   DSGraph *&Graph = DSInfo[F];
   if (Graph) return *Graph;
 
-  // Copy the local version into DSInfo...
-  Graph = new DSGraph(getAnalysis<LocalDataStructures>().getDSGraph(*F));
+  DSGraph &LocGraph = getAnalysis<LocalDataStructures>().getDSGraph(*F);
+
+  // Steal the local graph.
+  Graph = new DSGraph(GlobalECs, LocGraph.getTargetData());
+  Graph->spliceFrom(LocGraph);
 
   Graph->setGlobalsGraph(GlobalsGraph);
   Graph->setPrintAuxCalls();
@@ -164,15 +223,58 @@ DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
   return *Graph;
 }
 
+static bool isVAHackFn(const Function *F) {
+  return F->getName() == "printf"  || F->getName() == "sscanf" ||
+    F->getName() == "fprintf" || F->getName() == "open" ||
+    F->getName() == "sprintf" || F->getName() == "fputs" ||
+    F->getName() == "fscanf" || F->getName() == "malloc" ||
+    F->getName() == "free";
+}
+
+static bool isResolvableFunc(const Function* callee) {
+  return !callee->isExternal() || isVAHackFn(callee);
+}
+
+static void GetAllCallees(const DSCallSite &CS,
+                          std::vector<Function*> &Callees) {
+  if (CS.isDirectCall()) {
+    if (isResolvableFunc(CS.getCalleeFunc()))
+      Callees.push_back(CS.getCalleeFunc());
+  } else if (!CS.getCalleeNode()->isIncomplete()) {
+    // Get all callees.
+    unsigned OldSize = Callees.size();
+    CS.getCalleeNode()->addFullFunctionList(Callees);
+
+    // If any of the callees are unresolvable, remove the whole batch!
+    for (unsigned i = OldSize, e = Callees.size(); i != e; ++i)
+      if (!isResolvableFunc(Callees[i])) {
+        Callees.erase(Callees.begin()+OldSize, Callees.end());
+        return;
+      }
+  }
+}
+
+
+/// GetAllAuxCallees - Return a list containing all of the resolvable callees in
+/// the aux list for the specified graph in the Callees vector.
+static void GetAllAuxCallees(DSGraph &G, std::vector<Function*> &Callees) {
+  Callees.clear();
+  for (DSGraph::afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
+    GetAllCallees(*I, Callees);
+}
+
 unsigned BUDataStructures::calculateGraphs(Function *F,
                                            std::vector<Function*> &Stack,
-                                           unsigned &NextID, 
+                                           unsigned &NextID,
                                      hash_map<Function*, unsigned> &ValMap) {
-  assert(ValMap.find(F) == ValMap.end() && "Shouldn't revisit functions!");
+  assert(!ValMap.count(F) && "Shouldn't revisit functions!");
   unsigned Min = NextID++, MyID = Min;
   ValMap[F] = Min;
   Stack.push_back(F);
 
+  // FIXME!  This test should be generalized to be any function that we have
+  // already processed, in the case when there isn't a main or there are
+  // unreachable functions!
   if (F->isExternal()) {   // sprintf, fprintf, sscanf, etc...
     // No callees!
     Stack.pop_back();
@@ -182,10 +284,13 @@ unsigned BUDataStructures::calculateGraphs(Function *F,
 
   DSGraph &Graph = getOrCreateGraph(F);
 
+  // Find all callee functions.
+  std::vector<Function*> CalleeFunctions;
+  GetAllAuxCallees(Graph, CalleeFunctions);
+
   // The edges out of the current node are the call site targets...
-  for (CallSiteIterator I = CallSiteIterator::begin(Graph),
-         E = CallSiteIterator::end(Graph); I != E; ++I) {
-    Function *Callee = *I;
+  for (unsigned i = 0, e = CalleeFunctions.size(); i != e; ++i) {
+    Function *Callee = CalleeFunctions[i];
     unsigned M;
     // Have we visited the destination function yet?
     hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
@@ -205,12 +310,19 @@ unsigned BUDataStructures::calculateGraphs(Function *F,
     DEBUG(std::cerr << "Visiting single node SCC #: " << MyID << " fn: "
                     << F->getName() << "\n");
     Stack.pop_back();
-    DSGraph &G = calculateGraph(*F);
+    DSGraph &G = getDSGraph(*F);
+    DEBUG(std::cerr << "  [BU] Calculating graph for: " << F->getName()<< "\n");
+    calculateGraph(G);
+    DEBUG(std::cerr << "  [BU] Done inlining: " << F->getName() << " ["
+                    << G.getGraphSize() << "+" << G.getAuxFunctionCalls().size()
+                    << "]\n");
 
     if (MaxSCC < 1) MaxSCC = 1;
 
-    // Should we revisit the graph?
-    if (CallSiteIterator::begin(G) != CallSiteIterator::end(G)) {
+    // Should we revisit the graph?  Only do it if there are now new resolvable
+    // callees.
+    GetAllAuxCallees(Graph, CalleeFunctions);
+    if (!CalleeFunctions.empty()) {
       ValMap.erase(F);
       return calculateGraphs(F, Stack, NextID, ValMap);
     } else {
@@ -221,72 +333,55 @@ unsigned BUDataStructures::calculateGraphs(Function *F,
   } else {
     // SCCFunctions - Keep track of the functions in the current SCC
     //
-    hash_set<Function*> SCCFunctions;
+    std::vector<DSGraph*> SCCGraphs;
 
-    Function *NF;
-    std::vector<Function*>::iterator FirstInSCC = Stack.end();
-    do {
-      NF = *--FirstInSCC;
+    unsigned SCCSize = 1;
+    Function *NF = Stack.back();
+    ValMap[NF] = ~0U;
+    DSGraph &SCCGraph = getDSGraph(*NF);
+
+    // First thing first, collapse all of the DSGraphs into a single graph for
+    // the entire SCC.  Splice all of the graphs into one and discard all of the
+    // old graphs.
+    //
+    while (NF != F) {
+      Stack.pop_back();
+      NF = Stack.back();
       ValMap[NF] = ~0U;
-      SCCFunctions.insert(NF);
-    } while (NF != F);
 
-    std::cerr << "Identified SCC #: " << MyID << " of size: "
-              << (Stack.end()-FirstInSCC) << "\n";
+      DSGraph &NFG = getDSGraph(*NF);
 
-    // Compute the Max SCC Size...
-    if (MaxSCC < unsigned(Stack.end()-FirstInSCC))
-      MaxSCC = Stack.end()-FirstInSCC;
+      // Update the Function -> DSG map.
+      for (DSGraph::retnodes_iterator I = NFG.retnodes_begin(),
+             E = NFG.retnodes_end(); I != E; ++I)
+        DSInfo[I->first] = &SCCGraph;
 
-    std::vector<Function*>::iterator I = Stack.end();
-    do {
-      --I;
-#ifndef NDEBUG
-      /*DEBUG*/(std::cerr << "  Fn #" << (Stack.end()-I) << "/"
-            << (Stack.end()-FirstInSCC) << " in SCC: "
-            << (*I)->getName());
-      DSGraph &G = getDSGraph(**I);
-      std::cerr << " [" << G.getGraphSize() << "+"
-                << G.getAuxFunctionCalls().size() << "] ";
-#endif
+      SCCGraph.spliceFrom(NFG);
+      delete &NFG;
 
-      // Eliminate all call sites in the SCC that are not to functions that are
-      // in the SCC.
-      inlineNonSCCGraphs(**I, SCCFunctions);
+      ++SCCSize;
+    }
+    Stack.pop_back();
 
-#ifndef NDEBUG
-      std::cerr << "after Non-SCC's [" << G.getGraphSize() << "+"
-                << G.getAuxFunctionCalls().size() << "]\n";
-#endif
-    } while (I != FirstInSCC);
+    std::cerr << "Calculating graph for SCC #: " << MyID << " of size: "
+              << SCCSize << "\n";
 
-    I = Stack.end();
-    do {
-      --I;
-#ifndef NDEBUG
-      /*DEBUG*/(std::cerr << "  Fn #" << (Stack.end()-I) << "/"
-            << (Stack.end()-FirstInSCC) << " in SCC: "
-            << (*I)->getName());
-      DSGraph &G = getDSGraph(**I);
-      std::cerr << " [" << G.getGraphSize() << "+"
-                << G.getAuxFunctionCalls().size() << "] ";
-#endif
-      // Inline all graphs into the SCC nodes...
-      calculateSCCGraph(**I, SCCFunctions);
+    // Compute the Max SCC Size.
+    if (MaxSCC < SCCSize)
+      MaxSCC = SCCSize;
 
-#ifndef NDEBUG
-      std::cerr << "after [" << G.getGraphSize() << "+"
-                << G.getAuxFunctionCalls().size() << "]\n";
-#endif
-    } while (I != FirstInSCC);
+    // Clean up the graph before we start inlining a bunch again...
+    SCCGraph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
 
+    // Now that we have one big happy family, resolve all of the call sites in
+    // the graph...
+    calculateGraph(SCCGraph);
+    DEBUG(std::cerr << "  [BU] Done inlining SCC  [" << SCCGraph.getGraphSize()
+                    << "+" << SCCGraph.getAuxFunctionCalls().size() << "]\n");
 
     std::cerr << "DONE with SCC #: " << MyID << "\n";
 
     // We never have to revisit "SCC" processed functions...
-    
-    // Drop the stuff we don't need from the end of the stack
-    Stack.erase(FirstInSCC, Stack.end());
     return MyID;
   }
 
@@ -297,10 +392,13 @@ unsigned BUDataStructures::calculateGraphs(Function *F,
 // releaseMemory - If the pass pipeline is done with this pass, we can release
 // our memory... here...
 //
-void BUDataStructures::releaseMemory() {
-  for (hash_map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
-         E = DSInfo.end(); I != E; ++I)
-    delete I->second;
+void BUDataStructures::releaseMyMemory() {
+  for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
+         E = DSInfo.end(); I != E; ++I) {
+    I->second->getReturnNodes().erase(I->first);
+    if (I->second->getReturnNodes().empty())
+      delete I->second;
+  }
 
   // Empty map so next time memory is released, data structures are not
   // re-deleted.
@@ -309,261 +407,245 @@ void BUDataStructures::releaseMemory() {
   GlobalsGraph = 0;
 }
 
-DSGraph &BUDataStructures::calculateGraph(Function &F) {
-  DSGraph &Graph = getDSGraph(F);
-  DEBUG(std::cerr << "  [BU] Calculating graph for: " << F.getName() << "\n");
+DSGraph &BUDataStructures::CreateGraphForExternalFunction(const Function &Fn) {
+  Function *F = const_cast<Function*>(&Fn);
+  DSGraph *DSG = new DSGraph(GlobalECs, GlobalsGraph->getTargetData());
+  DSInfo[F] = DSG;
+  DSG->setGlobalsGraph(GlobalsGraph);
+  DSG->setPrintAuxCalls();
+
+  // Add function to the graph.
+  DSG->getReturnNodes().insert(std::make_pair(F, DSNodeHandle()));
+
+  if (F->getName() == "free") { // Taking the address of free.
+    
+    // Free should take a single pointer argument, mark it as heap memory.
+    DSNode *N = new DSNode(0, DSG);
+    N->setHeapNodeMarker();
+    DSG->getNodeForValue(F->arg_begin()).mergeWith(N);
+
+  } else {
+    std::cerr << "Unrecognized external function: " << F->getName() << "\n";
+    abort();
+  }
+
+  return *DSG;
+}
+
 
+void BUDataStructures::calculateGraph(DSGraph &Graph) {
   // Move our call site list into TempFCs so that inline call sites go into the
   // new call site list and doesn't invalidate our iterators!
-  std::vector<DSCallSite> TempFCs;
-  std::vector<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
+  std::list<DSCallSite> TempFCs;
+  std::list<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
   TempFCs.swap(AuxCallsList);
 
-  // Loop over all of the resolvable call sites
-  unsigned LastCallSiteIdx = ~0U;
-  for (CallSiteIterator I = CallSiteIterator::begin(TempFCs),
-         E = CallSiteIterator::end(TempFCs); I != E; ++I) {
-    // If we skipped over any call sites, they must be unresolvable, copy them
-    // to the real call site list.
-    LastCallSiteIdx++;
-    for (; LastCallSiteIdx < I.getCallSiteIdx(); ++LastCallSiteIdx)
-      AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
-    LastCallSiteIdx = I.getCallSiteIdx();
-    
-    // Resolve the current call...
-    Function *Callee = *I;
-    DSCallSite &CS = I.getCallSite();
+  DSGraph::ReturnNodesTy &ReturnNodes = Graph.getReturnNodes();
 
-    if (Callee->isExternal()) {
-      // Ignore this case, simple varargs functions we cannot stub out!
-    } else if (Callee == &F) {
-      // Self recursion... simply link up the formal arguments with the
-      // actual arguments...
-      DEBUG(std::cerr << "    Self Inlining: " << F.getName() << "\n");
+  bool Printed = false;
+  std::vector<Function*> CalledFuncs;
+  while (!TempFCs.empty()) {
+    DSCallSite &CS = *TempFCs.begin();
 
-      // Handle self recursion by resolving the arguments and return value
-      Graph.mergeInGraph(CS, F, Graph, 0);
+    CalledFuncs.clear();
 
-    } else {
-      // Get the data structure graph for the called function.
-      //
-      DSGraph &GI = getDSGraph(*Callee);  // Graph to inline
-      
-      DEBUG(std::cerr << "    Inlining graph for " << Callee->getName()
-            << "[" << GI.getGraphSize() << "+"
-            << GI.getAuxFunctionCalls().size() << "] into: " << F.getName()
-            << "[" << Graph.getGraphSize() << "+"
-            << Graph.getAuxFunctionCalls().size() << "]\n");
-#if 0
-      Graph.writeGraphToFile(std::cerr, "bu_" + F.getName() + "_before_" +
-                             Callee->getName());
-#endif
-      
-      // Handle self recursion by resolving the arguments and return value
-      Graph.mergeInGraph(CS, *Callee, GI,
-                         DSGraph::KeepModRefBits | 
-                         DSGraph::StripAllocaBit | DSGraph::DontCloneCallNodes);
-
-#if 0
-      Graph.writeGraphToFile(std::cerr, "bu_" + F.getName() + "_after_" +
-                             Callee->getName());
-#endif
+    // Fast path for noop calls.  Note that we don't care about merging globals
+    // in the callee with nodes in the caller here.
+    if (CS.getRetVal().isNull() && CS.getNumPtrArgs() == 0) {
+      TempFCs.erase(TempFCs.begin());
+      continue;
+    } else if (CS.isDirectCall() && isVAHackFn(CS.getCalleeFunc())) {
+      TempFCs.erase(TempFCs.begin());
+      continue;
     }
-  }
-
-  // Make sure to catch any leftover unresolvable calls...
-  for (++LastCallSiteIdx; LastCallSiteIdx < TempFCs.size(); ++LastCallSiteIdx)
-    AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
 
-  TempFCs.clear();
+    GetAllCallees(CS, CalledFuncs);
 
-  // Recompute the Incomplete markers.  If there are any function calls left
-  // now that are complete, we must loop!
-  Graph.maskIncompleteMarkers();
-  Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
-  // FIXME: materialize nodes from the globals graph as neccesary...
-  Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
+    if (CalledFuncs.empty()) {
+      // Remember that we could not resolve this yet!
+      AuxCallsList.splice(AuxCallsList.end(), TempFCs, TempFCs.begin());
+      continue;
+    } else {
+      DSGraph *GI;
+      Instruction *TheCall = CS.getCallSite().getInstruction();
 
-  DEBUG(std::cerr << "  [BU] Done inlining: " << F.getName() << " ["
-        << Graph.getGraphSize() << "+" << Graph.getAuxFunctionCalls().size()
-        << "]\n");
+      if (CalledFuncs.size() == 1) {
+        Function *Callee = CalledFuncs[0];
+        ActualCallees.insert(std::make_pair(TheCall, Callee));
 
-  //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
+        // Get the data structure graph for the called function.
+        GI = &getDSGraph(*Callee);  // Graph to inline
+        DEBUG(std::cerr << "    Inlining graph for " << Callee->getName());
 
-  return Graph;
-}
+        DEBUG(std::cerr << "[" << GI->getGraphSize() << "+"
+              << GI->getAuxFunctionCalls().size() << "] into '"
+              << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
+              << Graph.getAuxFunctionCalls().size() << "]\n");
+        Graph.mergeInGraph(CS, *Callee, *GI,
+                           DSGraph::StripAllocaBit|DSGraph::DontCloneCallNodes);
+        ++NumBUInlines;
+      } else {
+        if (!Printed)
+          std::cerr << "In Fns: " << Graph.getFunctionNames() << "\n";
+        std::cerr << "  calls " << CalledFuncs.size()
+                  << " fns from site: " << CS.getCallSite().getInstruction()
+                  << "  " << *CS.getCallSite().getInstruction();
+        std::cerr << "   Fns =";
+        unsigned NumPrinted = 0;
+
+        for (std::vector<Function*>::iterator I = CalledFuncs.begin(),
+               E = CalledFuncs.end(); I != E; ++I) {
+          if (NumPrinted++ < 8) std::cerr << " " << (*I)->getName();
+
+          // Add the call edges to the call graph.
+          ActualCallees.insert(std::make_pair(TheCall, *I));
+        }
+        std::cerr << "\n";
+
+        // See if we already computed a graph for this set of callees.
+        std::sort(CalledFuncs.begin(), CalledFuncs.end());
+        std::pair<DSGraph*, std::vector<DSNodeHandle> > &IndCallGraph =
+          (*IndCallGraphMap)[CalledFuncs];
+
+        if (IndCallGraph.first == 0) {
+          std::vector<Function*>::iterator I = CalledFuncs.begin(),
+            E = CalledFuncs.end();
+
+          // Start with a copy of the first graph.
+          GI = IndCallGraph.first = new DSGraph(getDSGraph(**I), GlobalECs);
+          GI->setGlobalsGraph(Graph.getGlobalsGraph());
+          std::vector<DSNodeHandle> &Args = IndCallGraph.second;
+
+          // Get the argument nodes for the first callee.  The return value is
+          // the 0th index in the vector.
+          GI->getFunctionArgumentsForCall(*I, Args);
+
+          // Merge all of the other callees into this graph.
+          for (++I; I != E; ++I) {
+            // If the graph already contains the nodes for the function, don't
+            // bother merging it in again.
+            if (!GI->containsFunction(*I)) {
+              GI->cloneInto(getDSGraph(**I));
+              ++NumBUInlines;
+            }
+
+            std::vector<DSNodeHandle> NextArgs;
+            GI->getFunctionArgumentsForCall(*I, NextArgs);
+            unsigned i = 0, e = Args.size();
+            for (; i != e; ++i) {
+              if (i == NextArgs.size()) break;
+              Args[i].mergeWith(NextArgs[i]);
+            }
+            for (e = NextArgs.size(); i != e; ++i)
+              Args.push_back(NextArgs[i]);
+          }
+
+          // Clean up the final graph!
+          GI->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
+        } else {
+          std::cerr << "***\n*** RECYCLED GRAPH ***\n***\n";
+        }
 
+        GI = IndCallGraph.first;
 
-// inlineNonSCCGraphs - This method is almost like the other two calculate graph
-// methods.  This one is used to inline function graphs (from functions outside
-// of the SCC) into functions in the SCC.  It is not supposed to touch functions
-// IN the SCC at all.
-//
-DSGraph &BUDataStructures::inlineNonSCCGraphs(Function &F,
-                                             hash_set<Function*> &SCCFunctions){
-  DSGraph &Graph = getDSGraph(F);
-  DEBUG(std::cerr << "  [BU] Inlining Non-SCC graphs for: "
-                  << F.getName() << "\n");
-
-  // Move our call site list into TempFCs so that inline call sites go into the
-  // new call site list and doesn't invalidate our iterators!
-  std::vector<DSCallSite> TempFCs;
-  std::vector<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
-  TempFCs.swap(AuxCallsList);
+        // Merge the unified graph into this graph now.
+        DEBUG(std::cerr << "    Inlining multi callee graph "
+              << "[" << GI->getGraphSize() << "+"
+              << GI->getAuxFunctionCalls().size() << "] into '"
+              << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
+              << Graph.getAuxFunctionCalls().size() << "]\n");
 
-  // Loop over all of the resolvable call sites
-  unsigned LastCallSiteIdx = ~0U;
-  for (CallSiteIterator I = CallSiteIterator::begin(TempFCs),
-         E = CallSiteIterator::end(TempFCs); I != E; ++I) {
-    // If we skipped over any call sites, they must be unresolvable, copy them
-    // to the real call site list.
-    LastCallSiteIdx++;
-    for (; LastCallSiteIdx < I.getCallSiteIdx(); ++LastCallSiteIdx)
-      AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
-    LastCallSiteIdx = I.getCallSiteIdx();
-    
-    // Resolve the current call...
-    Function &Callee = **I;
-    DSCallSite &CS = I.getCallSite();
-
-    if (Callee.isExternal()) {
-      // Ignore this case, simple varargs functions we cannot stub out!
-    } else if (SCCFunctions.count(&Callee)) {
-      // Calling a function in the SCC, ignore it for now!
-      DEBUG(std::cerr << "    SCC CallSite for: " << Callee.getName() << "\n");
-      AuxCallsList.push_back(CS);
-    } else {
-      // Get the data structure graph for the called function.
-      //
-      DSGraph &GI = getDSGraph(Callee);  // Graph to inline
-
-      DEBUG(std::cerr << "    Inlining graph for " << Callee.getName()
-            << "[" << GI.getGraphSize() << "+"
-            << GI.getAuxFunctionCalls().size() << "] into: " << F.getName()
-            << "[" << Graph.getGraphSize() << "+"
-            << Graph.getAuxFunctionCalls().size() << "]\n");
-
-      // Handle self recursion by resolving the arguments and return value
-      Graph.mergeInGraph(CS, Callee, GI,
-                         DSGraph::KeepModRefBits | DSGraph::StripAllocaBit |
-                         DSGraph::DontCloneCallNodes);
+        Graph.mergeInGraph(CS, IndCallGraph.second, *GI,
+                           DSGraph::StripAllocaBit |
+                           DSGraph::DontCloneCallNodes);
+        ++NumBUInlines;
+      }
     }
+    TempFCs.erase(TempFCs.begin());
   }
 
-  // Make sure to catch any leftover unresolvable calls...
-  for (++LastCallSiteIdx; LastCallSiteIdx < TempFCs.size(); ++LastCallSiteIdx)
-    AuxCallsList.push_back(TempFCs[LastCallSiteIdx]);
-
-  TempFCs.clear();
-
-  // Recompute the Incomplete markers.  If there are any function calls left
-  // now that are complete, we must loop!
+  // Recompute the Incomplete markers
   Graph.maskIncompleteMarkers();
   Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
+
+  // Delete dead nodes.  Treat globals that are unreachable but that can
+  // reach live nodes as live.
   Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
 
-  DEBUG(std::cerr << "  [BU] Done Non-SCC inlining: " << F.getName() << " ["
-        << Graph.getGraphSize() << "+" << Graph.getAuxFunctionCalls().size()
-        << "]\n");
-  //Graph.writeGraphToFile(std::cerr, "nscc_" + F.getName());
-  return Graph;
-}
+  // When this graph is finalized, clone the globals in the graph into the
+  // globals graph to make sure it has everything, from all graphs.
+  DSScalarMap &MainSM = Graph.getScalarMap();
+  ReachabilityCloner RC(*GlobalsGraph, Graph, DSGraph::StripAllocaBit);
 
+  // Clone everything reachable from globals in the function graph into the
+  // globals graph.
+  for (DSScalarMap::global_iterator I = MainSM.global_begin(),
+         E = MainSM.global_end(); I != E; ++I)
+    RC.getClonedNH(MainSM[*I]);
 
-DSGraph &BUDataStructures::calculateSCCGraph(Function &F,
-                                             hash_set<Function*> &SCCFunctions){
-  DSGraph &Graph = getDSGraph(F);
-  DEBUG(std::cerr << "  [BU] Calculating SCC graph for: " << F.getName()<<"\n");
-
-  std::vector<DSCallSite> UnresolvableCalls;
-  hash_map<Function*, DSCallSite> SCCCallSiteMap;
-  std::vector<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
-
-  while (1) {  // Loop until we run out of resolvable call sites!
-    // Move our call site list into TempFCs so that inline call sites go into
-    // the new call site list and doesn't invalidate our iterators!
-    std::vector<DSCallSite> TempFCs;
-    TempFCs.swap(AuxCallsList);
-
-    // Loop over all of the resolvable call sites
-    unsigned LastCallSiteIdx = ~0U;
-    CallSiteIterator I = CallSiteIterator::begin(TempFCs),
-      E = CallSiteIterator::end(TempFCs);
-    if (I == E) {
-      TempFCs.swap(AuxCallsList);
-      break;  // Done when no resolvable call sites exist
-    }
+  //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
+}
 
-    for (; I != E; ++I) {
-      // If we skipped over any call sites, they must be unresolvable, copy them
-      // to the unresolvable site list.
-      LastCallSiteIdx++;
-      for (; LastCallSiteIdx < I.getCallSiteIdx(); ++LastCallSiteIdx)
-        UnresolvableCalls.push_back(TempFCs[LastCallSiteIdx]);
-      LastCallSiteIdx = I.getCallSiteIdx();
-      
-      // Resolve the current call...
-      Function *Callee = *I;
-      DSCallSite &CS = I.getCallSite();
-      
-      if (Callee->isExternal()) {
-        // Ignore this case, simple varargs functions we cannot stub out!
-      } else if (Callee == &F) {
-        // Self recursion... simply link up the formal arguments with the
-        // actual arguments...
-        DEBUG(std::cerr << "    Self Inlining: " << F.getName() << "\n");
-        
-        // Handle self recursion by resolving the arguments and return value
-        Graph.mergeInGraph(CS, *Callee, Graph, 0);
-      } else if (SCCCallSiteMap.count(Callee)) {
-        // We have already seen a call site in the SCC for this function, just
-        // merge the two call sites together and we are done.
-        SCCCallSiteMap.find(Callee)->second.mergeWith(CS);
-      } else {
-        // Get the data structure graph for the called function.
-        //
-        DSGraph &GI = getDSGraph(*Callee);  // Graph to inline
-        DEBUG(std::cerr << "    Inlining graph for " << Callee->getName()
-              << "[" << GI.getGraphSize() << "+"
-              << GI.getAuxFunctionCalls().size() << "] into: " << F.getName()
-              << "[" << Graph.getGraphSize() << "+"
-              << Graph.getAuxFunctionCalls().size() << "]\n");
-        
-        // Handle self recursion by resolving the arguments and return value
-        Graph.mergeInGraph(CS, *Callee, GI,
-                           DSGraph::KeepModRefBits | DSGraph::StripAllocaBit |
-                           DSGraph::DontCloneCallNodes);
+static const Function *getFnForValue(const Value *V) {
+  if (const Instruction *I = dyn_cast<Instruction>(V))
+    return I->getParent()->getParent();
+  else if (const Argument *A = dyn_cast<Argument>(V))
+    return A->getParent();
+  else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
+    return BB->getParent();
+  return 0;
+}
 
-        if (SCCFunctions.count(Callee))
-          SCCCallSiteMap.insert(std::make_pair(Callee, CS));
-      }
-    }
-    
-    // Make sure to catch any leftover unresolvable calls...
-    for (++LastCallSiteIdx; LastCallSiteIdx < TempFCs.size(); ++LastCallSiteIdx)
-      UnresolvableCalls.push_back(TempFCs[LastCallSiteIdx]);
+/// deleteValue/copyValue - Interfaces to update the DSGraphs in the program.
+/// These correspond to the interfaces defined in the AliasAnalysis class.
+void BUDataStructures::deleteValue(Value *V) {
+  if (const Function *F = getFnForValue(V)) {  // Function local value?
+    // If this is a function local value, just delete it from the scalar map!
+    getDSGraph(*F).getScalarMap().eraseIfExists(V);
+    return;
   }
 
-  // Reset the SCCCallSiteMap...
-  SCCCallSiteMap.clear();
-
-  AuxCallsList.insert(AuxCallsList.end(), UnresolvableCalls.begin(),
-                      UnresolvableCalls.end());
-  UnresolvableCalls.clear();
+  if (Function *F = dyn_cast<Function>(V)) {
+    assert(getDSGraph(*F).getReturnNodes().size() == 1 &&
+           "cannot handle scc's");
+    delete DSInfo[F];
+    DSInfo.erase(F);
+    return;
+  }
 
+  assert(!isa<GlobalVariable>(V) && "Do not know how to delete GV's yet!");
+}
 
-  // Recompute the Incomplete markers.  If there are any function calls left
-  // now that are complete, we must loop!
-  Graph.maskIncompleteMarkers();
-  Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
+void BUDataStructures::copyValue(Value *From, Value *To) {
+  if (From == To) return;
+  if (const Function *F = getFnForValue(From)) {  // Function local value?
+    // If this is a function local value, just delete it from the scalar map!
+    getDSGraph(*F).getScalarMap().copyScalarIfExists(From, To);
+    return;
+  }
 
-  // FIXME: materialize nodes from the globals graph as neccesary...
+  if (Function *FromF = dyn_cast<Function>(From)) {
+    Function *ToF = cast<Function>(To);
+    assert(!DSInfo.count(ToF) && "New Function already exists!");
+    DSGraph *NG = new DSGraph(getDSGraph(*FromF), GlobalECs);
+    DSInfo[ToF] = NG;
+    assert(NG->getReturnNodes().size() == 1 && "Cannot copy SCC's yet!");
+
+    // Change the Function* is the returnnodes map to the ToF.
+    DSNodeHandle Ret = NG->retnodes_begin()->second;
+    NG->getReturnNodes().clear();
+    NG->getReturnNodes()[ToF] = Ret;
+    return;
+  }
 
-  Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
+  if (const Function *F = getFnForValue(To)) {
+    DSGraph &G = getDSGraph(*F);
+    G.getScalarMap().copyScalarIfExists(From, To);
+    return;
+  }
 
-  DEBUG(std::cerr << "  [BU] Done inlining: " << F.getName() << " ["
-        << Graph.getGraphSize() << "+" << Graph.getAuxFunctionCalls().size()
-        << "]\n");
-  //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
-  return Graph;
+  std::cerr << *From;
+  std::cerr << *To;
+  assert(0 && "Do not know how to copy this yet!");
+  abort();
 }