Add comment.
[oota-llvm.git] / lib / Transforms / Scalar / PredicateSimplifier.cpp
index 91a3344f989d64d9987557ac6455ba9f28dba224..42ffc0edc2564b47fed8a7dc91ace9da390a7a43 100644 (file)
@@ -2,8 +2,8 @@
 //
 //                     The LLVM Compiler Infrastructure
 //
-// This file was developed by Nick Lewycky and is distributed under the
-// University of Illinois Open Source License. See LICENSE.TXT for details.
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
 //
 //===----------------------------------------------------------------------===//
 //
@@ -70,8 +70,7 @@
 //
 // The ValueRanges class stores the known integer bounds of a Value. When we
 // encounter i8 %a u< %b, the ValueRanges stores that %a = [1, 255] and
-// %b = [0, 254]. Because we store these by Value*, you should always
-// canonicalize through the InequalityGraph first.
+// %b = [0, 254].
 //
 // It never stores an empty range, because that means that the code is
 // unreachable. It never stores a single-element range since that's an equality
@@ -92,6 +91,7 @@
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Analysis/Dominators.h"
+#include "llvm/Assembly/Writer.h"
 #include "llvm/Support/CFG.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/ConstantRange.h"
@@ -148,7 +148,7 @@ namespace {
         unsigned   spread =   DFSout -   DFSin;
         unsigned N_spread = N.DFSout - N.DFSin;
         if (spread == N_spread) return DFSin < N.DFSin;
-        else return DFSout - DFSin < N.DFSout - N.DFSin;
+        return spread < N_spread;
       }
       bool operator>(const Node &N) const { return N < *this; }
 
@@ -211,13 +211,19 @@ namespace {
       }
     }
 
+    /// getRootNode - This returns the entry node for the CFG of the function.
     Node *getRootNode() const { return Entry; }
 
+    /// getNodeForBlock - return the node for the specified basic block.
     Node *getNodeForBlock(BasicBlock *BB) const {
       if (!NodeMap.count(BB)) return 0;
-      else return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
+      return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
     }
 
+    /// dominates - returns true if the basic block for I1 dominates that of
+    /// the basic block for I2. If the instructions belong to the same basic
+    /// block, the instruction first instruction sequentially in the block is
+    /// considered dominating.
     bool dominates(Instruction *I1, Instruction *I2) {
       BasicBlock *BB1 = I1->getParent(),
                  *BB2 = I2->getParent();
@@ -236,11 +242,13 @@ namespace {
       } else {
         Node *Node1 = getNodeForBlock(BB1),
              *Node2 = getNodeForBlock(BB2);
-        if (!Node1 || !Node2) return false;
-        return Node1->dominates(Node2);
+        return Node1 && Node2 && Node1->dominates(Node2);
       }
     }
+
   private:
+    /// renumber - calculates the depth first search numberings and applies
+    /// them onto the nodes.
     void renumber() {
       std::stack<std::pair<Node *, Node::iterator> > S;
       unsigned n = 0;
@@ -333,6 +341,8 @@ namespace {
     UGE = UGT | EQ_BIT
   };
 
+  /// validPredicate - determines whether a given value is actually a lattice
+  /// value. Only used in assertions or debugging.
   static bool validPredicate(LatticeVal LV) {
     switch (LV) {
       case GT: case GE: case LT: case LE: case NE:
@@ -361,6 +371,214 @@ namespace {
     return Rev;
   }
 
+  /// ValueNumbering stores the scope-specific value numbers for a given Value.
+  class VISIBILITY_HIDDEN ValueNumbering {
+
+    /// VNPair is a tuple of {Value, index number, DomTreeDFS::Node}. It
+    /// includes the comparison operators necessary to allow you to store it
+    /// in a sorted vector.
+    class VISIBILITY_HIDDEN VNPair {
+    public:
+      Value *V;
+      unsigned index;
+      DomTreeDFS::Node *Subtree;
+
+      VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
+        : V(V), index(index), Subtree(Subtree) {}
+
+      bool operator==(const VNPair &RHS) const {
+        return V == RHS.V && Subtree == RHS.Subtree;
+      }
+
+      bool operator<(const VNPair &RHS) const {
+        if (V != RHS.V) return V < RHS.V;
+        return *Subtree < *RHS.Subtree;
+      }
+
+      bool operator<(Value *RHS) const {
+        return V < RHS;
+      }
+
+      bool operator>(Value *RHS) const {
+        return V > RHS;
+      }
+
+      friend bool operator<(Value *RHS, const VNPair &pair) {
+        return pair.operator>(RHS);
+      }
+    };
+
+    typedef std::vector<VNPair> VNMapType;
+    VNMapType VNMap;
+
+    /// The canonical choice for value number at index.
+    std::vector<Value *> Values;
+
+    DomTreeDFS *DTDFS;
+
+  public:
+#ifndef NDEBUG
+    virtual ~ValueNumbering() {}
+    virtual void dump() {
+      dump(*cerr.stream());
+    }
+
+    void dump(std::ostream &os) {
+      for (unsigned i = 1; i <= Values.size(); ++i) {
+        os << i << " = ";
+        WriteAsOperand(os, Values[i-1]);
+        os << " {";
+        for (unsigned j = 0; j < VNMap.size(); ++j) {
+          if (VNMap[j].index == i) {
+            WriteAsOperand(os, VNMap[j].V);
+            os << " (" << VNMap[j].Subtree->getDFSNumIn() << ")  ";
+          }
+        }
+        os << "}\n";
+      }
+    }
+#endif
+
+    /// compare - returns true if V1 is a better canonical value than V2.
+    bool compare(Value *V1, Value *V2) const {
+      if (isa<Constant>(V1))
+        return !isa<Constant>(V2);
+      else if (isa<Constant>(V2))
+        return false;
+      else if (isa<Argument>(V1))
+        return !isa<Argument>(V2);
+      else if (isa<Argument>(V2))
+        return false;
+
+      Instruction *I1 = dyn_cast<Instruction>(V1);
+      Instruction *I2 = dyn_cast<Instruction>(V2);
+
+      if (!I1 || !I2)
+        return V1->getNumUses() < V2->getNumUses();
+
+      return DTDFS->dominates(I1, I2);
+    }
+
+    ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
+
+    /// valueNumber - finds the value number for V under the Subtree. If
+    /// there is no value number, returns zero.
+    unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
+      if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V))
+          || V->getType() == Type::VoidTy) return 0;
+
+      VNMapType::iterator E = VNMap.end();
+      VNPair pair(V, 0, Subtree);
+      VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
+      while (I != E && I->V == V) {
+        if (I->Subtree->dominates(Subtree))
+          return I->index;
+        ++I;
+      }
+      return 0;
+    }
+
+    /// getOrInsertVN - always returns a value number, creating it if necessary.
+    unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
+      if (unsigned n = valueNumber(V, Subtree))
+        return n;
+      else
+        return newVN(V);
+    }
+
+    /// newVN - creates a new value number. Value V must not already have a
+    /// value number assigned.
+    unsigned newVN(Value *V) {
+      assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
+             "Bad Value for value numbering.");
+      assert(V->getType() != Type::VoidTy && "Won't value number a void value");
+
+      Values.push_back(V);
+
+      VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
+      VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
+      assert((I == VNMap.end() || value(I->index) != V) &&
+             "Attempt to create a duplicate value number.");
+      VNMap.insert(I, pair);
+
+      return Values.size();
+    }
+
+    /// value - returns the Value associated with a value number.
+    Value *value(unsigned index) const {
+      assert(index != 0 && "Zero index is reserved for not found.");
+      assert(index <= Values.size() && "Index out of range.");
+      return Values[index-1];
+    }
+
+    /// canonicalize - return a Value that is equal to V under Subtree.
+    Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
+      if (isa<Constant>(V)) return V;
+
+      if (unsigned n = valueNumber(V, Subtree))
+        return value(n);
+      else
+        return V;
+    }
+
+    /// addEquality - adds that value V belongs to the set of equivalent
+    /// values defined by value number n under Subtree.
+    void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
+      assert(canonicalize(value(n), Subtree) == value(n) &&
+             "Node's 'canonical' choice isn't best within this subtree.");
+
+      // Suppose that we are given "%x -> node #1 (%y)". The problem is that
+      // we may already have "%z -> node #2 (%x)" somewhere above us in the
+      // graph. We need to find those edges and add "%z -> node #1 (%y)"
+      // to keep the lookups canonical.
+
+      std::vector<Value *> ToRepoint(1, V);
+
+      if (unsigned Conflict = valueNumber(V, Subtree)) {
+        for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
+             I != E; ++I) {
+          if (I->index == Conflict && I->Subtree->dominates(Subtree))
+            ToRepoint.push_back(I->V);
+        }
+      }
+
+      for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
+           VE = ToRepoint.end(); VI != VE; ++VI) {
+        Value *V = *VI;
+
+        VNPair pair(V, n, Subtree);
+        VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
+        VNMapType::iterator I = std::lower_bound(B, E, pair);
+        if (I != E && I->V == V && I->Subtree == Subtree)
+          I->index = n; // Update best choice
+        else
+          VNMap.insert(I, pair); // New Value
+
+        // XXX: we currently don't have to worry about updating values with
+        // more specific Subtrees, but we will need to for PHI node support.
+
+#ifndef NDEBUG
+        Value *V_n = value(n);
+        if (isa<Constant>(V) && isa<Constant>(V_n)) {
+          assert(V == V_n && "Constant equals different constant?");
+        }
+#endif
+      }
+    }
+
+    /// remove - removes all references to value V.
+    void remove(Value *V) {
+      VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
+      VNPair pair(V, 0, DTDFS->getRootNode());
+      VNMapType::iterator J = std::upper_bound(B, E, pair);
+      VNMapType::iterator I = J;
+
+      while (I != B && (I == E || I->V == V)) --I;
+
+      VNMap.erase(I, J);
+    }
+  };
+
   /// The InequalityGraph stores the relationships between values.
   /// Each Value in the graph is assigned to a Node. Nodes are pointer
   /// comparable for equality. The caller is expected to maintain the logical
@@ -369,12 +587,14 @@ namespace {
   /// The InequalityGraph class may invalidate Node*s after any mutator call.
   /// @brief The InequalityGraph stores the relationships between values.
   class VISIBILITY_HIDDEN InequalityGraph {
+    ValueNumbering &VN;
     DomTreeDFS::Node *TreeRoot;
 
     InequalityGraph();                  // DO NOT IMPLEMENT
     InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
   public:
-    explicit InequalityGraph(DomTreeDFS::Node *TreeRoot) : TreeRoot(TreeRoot){}
+    InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
+      : VN(VN), TreeRoot(TreeRoot) {}
 
     class Node;
 
@@ -393,7 +613,7 @@ namespace {
 
       bool operator<(const Edge &edge) const {
         if (To != edge.To) return To < edge.To;
-        else return *Subtree < *edge.Subtree;
+        return *Subtree < *edge.Subtree;
       }
 
       bool operator<(unsigned to) const {
@@ -419,8 +639,6 @@ namespace {
       typedef SmallVector<Edge, 4> RelationsType;
       RelationsType Relations;
 
-      Value *Canonical;
-
       // TODO: can this idea improve performance?
       //friend class std::vector<Node>;
       //Node(Node &N) { RelationsType.swap(N.RelationsType); }
@@ -429,33 +647,28 @@ namespace {
       typedef RelationsType::iterator       iterator;
       typedef RelationsType::const_iterator const_iterator;
 
-      Node(Value *V) : Canonical(V) {}
-
-    private:
 #ifndef NDEBUG
-    public:
       virtual ~Node() {}
       virtual void dump() const {
         dump(*cerr.stream());
       }
     private:
-      void dump(std::ostream &os) const  {
-        os << *getValue() << ":\n";
+      void dump(std::ostream &os) const {
+        static const std::string names[32] =
+          { "000000", "000001", "000002", "000003", "000004", "000005",
+            "000006", "000007", "000008", "000009", "     >", "    >=",
+            "  s>u<", "s>=u<=", "    s>", "   s>=", "000016", "000017",
+            "  s<u>", "s<=u>=", "     <", "    <=", "    s<", "   s<=",
+            "000024", "000025", "    u>", "   u>=", "    u<", "   u<=",
+            "    !=", "000031" };
         for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
-          static const std::string names[32] =
-            { "000000", "000001", "000002", "000003", "000004", "000005",
-              "000006", "000007", "000008", "000009", "     >", "    >=",
-              "  s>u<", "s>=u<=", "    s>", "   s>=", "000016", "000017",
-              "  s<u>", "s<=u>=", "     <", "    <=", "    s<", "   s<=",
-              "000024", "000025", "    u>", "   u>=", "    u<", "   u<=",
-              "    !=", "000031" };
-          os << "  " << names[NI->LV] << " " << NI->To
-             << " (" << NI->Subtree->getDFSNumIn() << ")\n";
+          os << names[NI->LV] << " " << NI->To
+             << " (" << NI->Subtree->getDFSNumIn() << "), ";
         }
       }
+    public:
 #endif
 
-    public:
       iterator begin()             { return Relations.begin(); }
       iterator end()               { return Relations.end();   }
       const_iterator begin() const { return Relations.begin(); }
@@ -481,137 +694,62 @@ namespace {
         return E;
       }
 
-      Value *getValue() const
-      {
-        return Canonical;
-      }
-
-      /// Updates the lattice value for a given node. Create a new entry if
-      /// one doesn't exist, otherwise it merges the values. The new lattice
-      /// value must not be inconsistent with any previously existing value.
+      /// update - updates the lattice value for a given node, creating a new
+      /// entry if one doesn't exist. The new lattice value must not be
+      /// inconsistent with any previously existing value.
       void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
         assert(validPredicate(R) && "Invalid predicate.");
-        iterator I = find(n, Subtree);
-        if (I == end()) {
-          Edge edge(n, R, Subtree);
-          iterator Insert = std::lower_bound(begin(), end(), edge);
-          Relations.insert(Insert, edge);
-        } else {
-          LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
-          assert(validPredicate(LV) && "Invalid union of lattice values.");
-          if (LV != I->LV) {
-            if (Subtree != I->Subtree) {
-              assert(Subtree->DominatedBy(I->Subtree) &&
-                     "Find returned subtree that doesn't apply.");
-
-              Edge edge(n, R, Subtree);
-              iterator Insert = std::lower_bound(begin(), end(), edge);
-              Relations.insert(Insert, edge); // invalidates I
-              I = find(n, Subtree);
-            }
 
-            // Also, we have to tighten any edge that Subtree dominates.
-            for (iterator B = begin(); I->To == n; --I) {
-              if (I->Subtree->DominatedBy(Subtree)) {
-                LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
-                assert(validPredicate(LV) && "Invalid union of lattice values");
-                I->LV = LV;
-              }
-              if (I == B) break;
-            }
-          }
-        }
-      }
-    };
+        Edge edge(n, R, Subtree);
+        iterator B = begin(), E = end();
+        iterator I = std::lower_bound(B, E, edge);
 
-  private:
-    struct VISIBILITY_HIDDEN NodeMapEdge {
-      Value *V;
-      unsigned index;
-      DomTreeDFS::Node *Subtree;
+        iterator J = I;
+        while (J != E && J->To == n) {
+          if (Subtree->DominatedBy(J->Subtree))
+            break;
+          ++J;
+        }
 
-      NodeMapEdge(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
-        : V(V), index(index), Subtree(Subtree) {}
+        if (J != E && J->To == n) {
+          edge.LV = static_cast<LatticeVal>(J->LV & R);
+          assert(validPredicate(edge.LV) && "Invalid union of lattice values.");
 
-      bool operator==(const NodeMapEdge &RHS) const {
-        return V == RHS.V &&
-               Subtree == RHS.Subtree;
-      }
+          if (edge.LV == J->LV)
+            return; // This update adds nothing new.
+        }
 
-      bool operator<(const NodeMapEdge &RHS) const {
-        if (V != RHS.V) return V < RHS.V;
-        else return *Subtree < *RHS.Subtree;
-      }
+        if (I != B) {
+          // We also have to tighten any edge beneath our update.
+          for (iterator K = I - 1; K->To == n; --K) {
+            if (K->Subtree->DominatedBy(Subtree)) {
+              LatticeVal LV = static_cast<LatticeVal>(K->LV & edge.LV);
+              assert(validPredicate(LV) && "Invalid union of lattice values");
+              K->LV = LV;
+            }
+            if (K == B) break;
+          }
+        }
 
-      bool operator<(Value *RHS) const {
-        return V < RHS;
+        // Insert new edge at Subtree if it isn't already there.
+        if (I == E || I->To != n || Subtree != I->Subtree)
+          Relations.insert(I, edge);
       }
     };
 
-    typedef std::vector<NodeMapEdge> NodeMapType;
-    NodeMapType NodeMap;
+  private:
 
     std::vector<Node> Nodes;
 
   public:
-    /// node - returns the node object at a given index retrieved from getNode.
-    /// Index zero is reserved and may not be passed in here. The pointer
-    /// returned is valid until the next call to newNode or getOrInsertNode.
+    /// node - returns the node object at a given value number. The pointer
+    /// returned may be invalidated on the next call to node().
     Node *node(unsigned index) {
-      assert(index != 0 && "Zero index is reserved for not found.");
-      assert(index <= Nodes.size() && "Index out of range.");
+      assert(VN.value(index)); // This triggers the necessary checks.
+      if (Nodes.size() < index) Nodes.resize(index);
       return &Nodes[index-1];
     }
 
-    /// Returns the node currently representing Value V, or zero if no such
-    /// node exists.
-    unsigned getNode(Value *V, DomTreeDFS::Node *Subtree) {
-      NodeMapType::iterator E = NodeMap.end();
-      NodeMapEdge Edge(V, 0, Subtree);
-      NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
-      while (I != E && I->V == V) {
-        if (Subtree->DominatedBy(I->Subtree))
-          return I->index;
-        ++I;
-      }
-      return 0;
-    }
-
-    /// getOrInsertNode - always returns a valid node index, creating a node
-    /// to match the Value if needed.
-    unsigned getOrInsertNode(Value *V, DomTreeDFS::Node *Subtree) {
-      if (unsigned n = getNode(V, Subtree))
-        return n;
-      else
-        return newNode(V);
-    }
-
-    /// newNode - creates a new node for a given Value and returns the index.
-    unsigned newNode(Value *V) {
-      assert(!isa<BasicBlock>(V) && "BBs may not be nodes.");
-      assert(V->getType() != Type::VoidTy && "Void node?");
-
-      Nodes.push_back(Node(V));
-
-      NodeMapEdge MapEntry = NodeMapEdge(V, Nodes.size(), TreeRoot);
-      assert(!std::binary_search(NodeMap.begin(), NodeMap.end(), MapEntry) &&
-             "Attempt to create a duplicate Node.");
-      NodeMap.insert(std::lower_bound(NodeMap.begin(), NodeMap.end(),
-                                      MapEntry), MapEntry);
-      return MapEntry.index;
-    }
-
-    /// If the Value is in the graph, return the canonical form. Otherwise,
-    /// return the original Value.
-    Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
-      if (isa<Constant>(V)) return V;
-
-      if (unsigned n = getNode(V, Subtree))
-        return node(n)->getValue();
-      else 
-        return V;
-    }
-
     /// isRelatedBy - true iff n1 op n2
     bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
                      LatticeVal LV) {
@@ -627,53 +765,6 @@ namespace {
     // The add* methods assume that your input is logically valid and may 
     // assertion-fail or infinitely loop if you attempt a contradiction.
 
-    void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
-      assert(canonicalize(node(n)->getValue(), Subtree) == node(n)->getValue()
-             && "Node's 'canonical' choice isn't best within this subtree.");
-
-      // Suppose that we are given "%x -> node #1 (%y)". The problem is that
-      // we may already have "%z -> node #2 (%x)" somewhere above us in the
-      // graph. We need to find those edges and add "%z -> node #1 (%y)"
-      // to keep the lookups canonical.
-
-      std::vector<Value *> ToRepoint;
-      ToRepoint.push_back(V);
-
-      if (unsigned Conflict = getNode(V, Subtree)) {
-        for (NodeMapType::iterator I = NodeMap.begin(), E = NodeMap.end();
-             I != E; ++I) {
-          if (I->index == Conflict && Subtree->DominatedBy(I->Subtree))
-            ToRepoint.push_back(I->V);
-        }
-      }
-
-      for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
-           VE = ToRepoint.end(); VI != VE; ++VI) {
-        Value *V = *VI;
-
-        // XXX: review this code. This may be doing too many insertions.
-        NodeMapEdge Edge(V, n, Subtree);
-        NodeMapType::iterator E = NodeMap.end();
-        NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
-        if (I == E || I->V != V || I->Subtree != Subtree) {
-          // New Value
-          NodeMap.insert(I, Edge);
-        } else if (I != E && I->V == V && I->Subtree == Subtree) {
-          // Update best choice
-          I->index = n;
-        }
-
-#ifndef NDEBUG
-        Node *N = node(n);
-        if (isa<Constant>(V)) {
-          if (isa<Constant>(N->getValue())) {
-            assert(V == N->getValue() && "Constant equals different constant?");
-          }
-        }
-#endif
-      }
-    }
-
     /// addInequality - Sets n1 op n2.
     /// It is also an error to call this on an inequality that is already true.
     void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
@@ -684,9 +775,6 @@ namespace {
         assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
                "Contradictory inequality.");
 
-      Node *N1 = node(n1);
-      Node *N2 = node(n2);
-
       // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
       // add %a < %n2 too. This keeps the graph fully connected.
       if (LV1 != NE) {
@@ -698,7 +786,7 @@ namespace {
         unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
         unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
 
-        for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
+        for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
           if (I->LV != NE && I->To != n2) {
 
             DomTreeDFS::Node *Local_Subtree = NULL;
@@ -729,13 +817,13 @@ namespace {
                 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
 
                 node(I->To)->update(n2, NewLV, Local_Subtree);
-                N2->update(I->To, reversePredicate(NewLV), Local_Subtree);
+                node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
               }
             }
           }
         }
 
-        for (Node::iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
+        for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
           if (I->LV != NE && I->To != n1) {
             DomTreeDFS::Node *Local_Subtree = NULL;
             if (Subtree->DominatedBy(I->Subtree))
@@ -764,7 +852,7 @@ namespace {
 
                 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
 
-                N1->update(I->To, NewLV, Local_Subtree);
+                node(n1)->update(I->To, NewLV, Local_Subtree);
                 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
               }
             }
@@ -772,32 +860,22 @@ namespace {
         }
       }
 
-      N1->update(n2, LV1, Subtree);
-      N2->update(n1, reversePredicate(LV1), Subtree);
+      node(n1)->update(n2, LV1, Subtree);
+      node(n2)->update(n1, reversePredicate(LV1), Subtree);
     }
 
-    /// remove - Removes a Value from the graph. If the value is the canonical
-    /// choice for a Node, destroys the Node from the graph deleting all edges
-    /// to and from it. This method does not renumber the nodes.
-    void remove(Value *V) {
-      for (unsigned i = 0; i < NodeMap.size();) {
-        NodeMapType::iterator I = NodeMap.begin()+i;
-        if (I->V == V) {
-          Node *N = node(I->index);
-          if (node(I->index)->getValue() == V) {
-            for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI){
-              Node::iterator Iter = node(NI->To)->find(I->index, TreeRoot);
-              do {
-                node(NI->To)->Relations.erase(Iter);
-                Iter = node(NI->To)->find(I->index, TreeRoot);
-              } while (Iter != node(NI->To)->end());
-            }
-            N->Canonical = NULL;
-          }
-          N->Relations.clear();
-          NodeMap.erase(I);
-        } else ++i;
-      }
+    /// remove - removes a node from the graph by removing all references to
+    /// and from it.
+    void remove(unsigned n) {
+      Node *N = node(n);
+      for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
+        Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
+        do {
+          node(NI->To)->Relations.erase(Iter);
+          Iter = node(NI->To)->find(n, TreeRoot);
+        } while (Iter != node(NI->To)->end());
+      }
+      N->Relations.clear();
     }
 
 #ifndef NDEBUG
@@ -807,19 +885,12 @@ namespace {
     }
 
     void dump(std::ostream &os) {
-    std::set<Node *> VisitedNodes;
-    for (NodeMapType::const_iterator I = NodeMap.begin(), E = NodeMap.end();
-         I != E; ++I) {
-      Node *N = node(I->index);
-      os << *I->V << " == " << I->index
-         << "(" << I->Subtree->getDFSNumIn() << ")\n";
-      if (VisitedNodes.insert(N).second) {
-        os << I->index << ". ";
-        if (!N->getValue()) os << "(deleted node)\n";
-        else N->dump(os);
+      for (unsigned i = 1; i <= Nodes.size(); ++i) {
+        os << i << " = {";
+        node(i)->dump(os);
+        os << "}\n";
       }
     }
-  }
 #endif
   };
 
@@ -828,101 +899,130 @@ namespace {
   /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
   /// in the InequalityGraph.
   class VISIBILITY_HIDDEN ValueRanges {
+    ValueNumbering &VN;
+    TargetData *TD;
 
-    /// A ScopedRange ties an InequalityGraph node with a ConstantRange under
-    /// the scope of a rooted subtree in the dominator tree.
     class VISIBILITY_HIDDEN ScopedRange {
-    public:
-      ScopedRange(Value *V, ConstantRange CR, DomTreeDFS::Node *ST)
-        : V(V), CR(CR), Subtree(ST) {}
-
-      Value *V;
-      ConstantRange CR;
-      DomTreeDFS::Node *Subtree;
+      typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
+              RangeListType;
+      RangeListType RangeList;
 
-      bool operator<(const ScopedRange &range) const {
-        if (V != range.V) return V < range.V;
-        else return *Subtree < *range.Subtree;
+      static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
+                      const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
+        return *LHS.first < *RHS.first;
       }
 
-      bool operator<(const Value *value) const {
-        return V < value;
+    public:
+#ifndef NDEBUG
+      virtual ~ScopedRange() {}
+      virtual void dump() const {
+        dump(*cerr.stream());
       }
 
-      bool operator>(const Value *value) const {
-          return V > value;
+      void dump(std::ostream &os) const {
+        os << "{";
+        for (const_iterator I = begin(), E = end(); I != E; ++I) {
+          os << I->second << " (" << I->first->getDFSNumIn() << "), ";
+        }
+        os << "}";
       }
+#endif
 
-      friend bool operator<(const Value *value, const ScopedRange &range) {
-          return range.operator>(value);
+      typedef RangeListType::iterator       iterator;
+      typedef RangeListType::const_iterator const_iterator;
+
+      iterator begin() { return RangeList.begin(); }
+      iterator end()   { return RangeList.end(); }
+      const_iterator begin() const { return RangeList.begin(); }
+      const_iterator end()   const { return RangeList.end(); }
+
+      iterator find(DomTreeDFS::Node *Subtree) {
+        static ConstantRange empty(1, false);
+        iterator E = end();
+        iterator I = std::lower_bound(begin(), E,
+                                      std::make_pair(Subtree, empty), swo);
+
+        while (I != E && !I->first->dominates(Subtree)) ++I;
+        return I;
       }
-    };
 
-    TargetData *TD;
+      const_iterator find(DomTreeDFS::Node *Subtree) const {
+        static const ConstantRange empty(1, false);
+        const_iterator E = end();
+        const_iterator I = std::lower_bound(begin(), E,
+                                            std::make_pair(Subtree, empty), swo);
 
-    std::vector<ScopedRange> Ranges;
-    typedef std::vector<ScopedRange>::iterator iterator;
+        while (I != E && !I->first->dominates(Subtree)) ++I;
+        return I;
+      }
 
-    // XXX: this is a copy of the code in InequalityGraph::Node. Perhaps a
-    // intrusive domtree-scoped container is in order?
+      void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
+        assert(!CR.isEmptySet() && "Empty ConstantRange.");
+        assert(!CR.isSingleElement() && "Refusing to store single element.");
 
-    iterator begin() { return Ranges.begin(); }
-    iterator end()   { return Ranges.end();   }
+        static ConstantRange empty(1, false);
+        iterator E = end();
+        iterator I =
+            std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
 
-    iterator find(Value *V, DomTreeDFS::Node *Subtree) {
-      iterator E = end();
-      for (iterator I = std::lower_bound(begin(), E, V);
-           I != E && I->V == V; ++I) {
-        if (Subtree->DominatedBy(I->Subtree))
-          return I;
+        if (I != end() && I->first == Subtree) {
+          ConstantRange CR2 = I->second.maximalIntersectWith(CR);
+          assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
+                 "Invalid union of ranges.");
+          I->second = CR2;
+        } else
+          RangeList.insert(I, std::make_pair(Subtree, CR));
       }
-      return E;
-    }
+    };
+
+    std::vector<ScopedRange> Ranges;
 
-    void update(Value *V, ConstantRange CR, DomTreeDFS::Node *Subtree) {
-      assert(!CR.isEmptySet() && "Empty ConstantRange!");
+    void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
       if (CR.isFullSet()) return;
+      if (Ranges.size() < n) Ranges.resize(n);
+      Ranges[n-1].update(CR, Subtree);
+    }
 
-      iterator I = find(V, Subtree);
-      if (I == end()) {
-        ScopedRange range(V, CR, Subtree);
-        iterator Insert = std::lower_bound(begin(), end(), range);
-        Ranges.insert(Insert, range);
-      } else {
-        CR = CR.intersectWith(I->CR);
-        assert(!CR.isEmptySet() && "Empty intersection of ConstantRanges!");
-
-        if (CR != I->CR) {
-          if (Subtree != I->Subtree) {
-            assert(Subtree->DominatedBy(I->Subtree) &&
-                   "Find returned subtree that doesn't apply.");
-
-            ScopedRange range(V, CR, Subtree);
-            iterator Insert = std::lower_bound(begin(), end(), range);
-            Ranges.insert(Insert, range); // invalidates I
-            I = find(V, Subtree);
-          }
+    /// create - Creates a ConstantRange that matches the given LatticeVal
+    /// relation with a given integer.
+    ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
+      assert(!CR.isEmptySet() && "Can't deal with empty set.");
 
-          // Also, we have to tighten any edge that Subtree dominates.
-          for (iterator B = begin(); I->V == V; --I) {
-            if (I->Subtree->DominatedBy(Subtree)) {
-              I->CR = CR.intersectWith(I->CR);
-              assert(!I->CR.isEmptySet() &&
-                     "Empty intersection of ConstantRanges!");
-            }
-            if (I == B) break;
-          }
-        }
+      if (LV == NE)
+        return makeConstantRange(ICmpInst::ICMP_NE, CR);
+
+      unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
+      unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
+      bool hasEQ = LV & EQ_BIT;
+
+      ConstantRange Range(CR.getBitWidth());
+
+      if (LV_s == SGT_BIT) {
+        Range = Range.maximalIntersectWith(makeConstantRange(
+                    hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
+      } else if (LV_s == SLT_BIT) {
+        Range = Range.maximalIntersectWith(makeConstantRange(
+                    hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
       }
+
+      if (LV_u == UGT_BIT) {
+        Range = Range.maximalIntersectWith(makeConstantRange(
+                    hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
+      } else if (LV_u == ULT_BIT) {
+        Range = Range.maximalIntersectWith(makeConstantRange(
+                    hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
+      }
+
+      return Range;
     }
 
-    /// range - Creates a ConstantRange representing the set of all values
-    /// that match the ICmpInst::Predicate with any of the values in CR.
-    ConstantRange range(ICmpInst::Predicate ICmpOpcode,
-                        const ConstantRange &CR) {
+    /// makeConstantRange - Creates a ConstantRange representing the set of all
+    /// value that match the ICmpInst::Predicate with any of the values in CR.
+    ConstantRange makeConstantRange(ICmpInst::Predicate ICmpOpcode,
+                                    const ConstantRange &CR) {
       uint32_t W = CR.getBitWidth();
       switch (ICmpOpcode) {
-        default: assert(!"Invalid ICmp opcode to range()");
+        default: assert(!"Invalid ICmp opcode to makeConstantRange()");
         case ICmpInst::ICMP_EQ:
           return ConstantRange(CR.getLower(), CR.getUpper());
         case ICmpInst::ICMP_NE:
@@ -965,63 +1065,54 @@ namespace {
       }
     }
 
-    /// create - Creates a ConstantRange that matches the given LatticeVal
-    /// relation with a given integer.
-    ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
-      assert(!CR.isEmptySet() && "Can't deal with empty set.");
+#ifndef NDEBUG
+    bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
+      return V == VN.canonicalize(V, Subtree);
+    }
+#endif
 
-      if (LV == NE)
-        return range(ICmpInst::ICMP_NE, CR);
+  public:
 
-      unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
-      unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
-      bool hasEQ = LV & EQ_BIT;
+    ValueRanges(ValueNumbering &VN, TargetData *TD) : VN(VN), TD(TD) {}
 
-      ConstantRange Range(CR.getBitWidth());
+#ifndef NDEBUG
+    virtual ~ValueRanges() {}
 
-      if (LV_s == SGT_BIT) {
-        Range = Range.intersectWith(range(
-                    hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
-      } else if (LV_s == SLT_BIT) {
-        Range = Range.intersectWith(range(
-                    hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
-      }
+    virtual void dump() const {
+      dump(*cerr.stream());
+    }
 
-      if (LV_u == UGT_BIT) {
-        Range = Range.intersectWith(range(
-                    hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
-      } else if (LV_u == ULT_BIT) {
-        Range = Range.intersectWith(range(
-                    hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
+    void dump(std::ostream &os) const {
+      for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
+        os << (i+1) << " = ";
+        Ranges[i].dump(os);
+        os << "\n";
       }
-
-      return Range;
     }
-
-#ifndef NDEBUG
-    bool isCanonical(Value *V, DomTreeDFS::Node *Subtree, VRPSolver *VRP);
 #endif
 
-  public:
+    /// range - looks up the ConstantRange associated with a value number.
+    ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
+      assert(VN.value(n)); // performs range checks
 
-    explicit ValueRanges(TargetData *TD) : TD(TD) {}
+      if (n <= Ranges.size()) {
+        ScopedRange::iterator I = Ranges[n-1].find(Subtree);
+        if (I != Ranges[n-1].end()) return I->second;
+      }
+
+      Value *V = VN.value(n);
+      ConstantRange CR = range(V);
+      return CR;
+    }
 
-    // rangeFromValue - converts a Value into a range. If the value is a
-    // constant it constructs the single element range, otherwise it performs
-    // a lookup. The width W must be retrieved from typeToWidth and may not
-    // be zero.
-    ConstantRange rangeFromValue(Value *V, DomTreeDFS::Node *Subtree,
-                                 uint32_t W) {
-      if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
+    /// range - determine a range from a Value without performing any lookups.
+    ConstantRange range(Value *V) const {
+      if (ConstantInt *C = dyn_cast<ConstantInt>(V))
         return ConstantRange(C->getValue());
-      } else if (isa<ConstantPointerNull>(V)) {
-        return ConstantRange(APInt::getNullValue(W));
-      } else {
-        iterator I = find(V, Subtree);
-        if (I != end())
-          return I->CR;
-      }
-      return ConstantRange(W);
+      else if (isa<ConstantPointerNull>(V))
+        return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
+      else
+        return ConstantRange(typeToWidth(V->getType()));
     }
 
     // typeToWidth - returns the number of bits necessary to store a value of
@@ -1029,26 +1120,16 @@ namespace {
     uint32_t typeToWidth(const Type *Ty) const {
       if (TD)
         return TD->getTypeSizeInBits(Ty);
-
-      if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
-        return ITy->getBitWidth();
-
-      return 0;
+      else
+        return Ty->getPrimitiveSizeInBits();
     }
 
-    bool isRelatedBy(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
-                     LatticeVal LV) {
-      uint32_t W = typeToWidth(V1->getType());
-      if (!W) return false;
-
-      ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
-      ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
-
-      // True iff all values in CR1 are LV to all values in CR2.
+    static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
+                            LatticeVal LV) {
       switch (LV) {
       default: assert(!"Impossible lattice value!");
       case NE:
-        return CR1.intersectWith(CR2).isEmptySet();
+        return CR1.maximalIntersectWith(CR2).isEmptySet();
       case ULT:
         return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
       case ULE:
@@ -1092,24 +1173,29 @@ namespace {
       }
     }
 
+    bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
+                     LatticeVal LV) {
+      ConstantRange CR1 = range(n1, Subtree);
+      ConstantRange CR2 = range(n2, Subtree);
+
+      // True iff all values in CR1 are LV to all values in CR2.
+      return isRelatedBy(CR1, CR2, LV);
+    }
+
     void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
                        VRPSolver *VRP);
     void markBlock(VRPSolver *VRP);
 
-    void mergeInto(Value **I, unsigned n, Value *New,
+    void mergeInto(Value **I, unsigned n, unsigned New,
                    DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
-      assert(isCanonical(New, Subtree, VRP) && "Best choice not canonical?");
-
-      uint32_t W = typeToWidth(New->getType());
-      if (!W) return;
-
-      ConstantRange CR_New = rangeFromValue(New, Subtree, W);
+      ConstantRange CR_New = range(New, Subtree);
       ConstantRange Merged = CR_New;
 
       for (; n != 0; ++I, --n) {
-        ConstantRange CR_Kill = rangeFromValue(*I, Subtree, W);
+        unsigned i = VN.valueNumber(*I, Subtree);
+        ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
         if (CR_Kill.isFullSet()) continue;
-        Merged = Merged.intersectWith(CR_Kill);
+        Merged = Merged.maximalIntersectWith(CR_Kill);
       }
 
       if (Merged.isFullSet() || Merged == CR_New) return;
@@ -1117,11 +1203,16 @@ namespace {
       applyRange(New, Merged, Subtree, VRP);
     }
 
-    void applyRange(Value *V, const ConstantRange &CR,
+    void applyRange(unsigned n, const ConstantRange &CR,
                     DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
-      assert(isCanonical(V, Subtree, VRP) && "Value not canonical.");
+      ConstantRange Merged = CR.maximalIntersectWith(range(n, Subtree));
+      if (Merged.isEmptySet()) {
+        markBlock(VRP);
+        return;
+      }
 
-      if (const APInt *I = CR.getSingleElement()) {
+      if (const APInt *I = Merged.getSingleElement()) {
+        Value *V = VN.value(n); // XXX: redesign worklist.
         const Type *Ty = V->getType();
         if (Ty->isInteger()) {
           addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
@@ -1129,33 +1220,25 @@ namespace {
         } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
           assert(*I == 0 && "Pointer is null but not zero?");
           addToWorklist(V, ConstantPointerNull::get(PTy),
-                      ICmpInst::ICMP_EQ, VRP);
+                        ICmpInst::ICMP_EQ, VRP);
           return;
         }
       }
 
-      ConstantRange Merged = CR.intersectWith(
-                                rangeFromValue(V, Subtree, CR.getBitWidth()));
-      if (Merged.isEmptySet()) {
-        markBlock(VRP);
-        return;
-      }
-
-      update(V, Merged, Subtree);
+      update(n, Merged, Subtree);
     }
 
-    void addNotEquals(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
+    void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
                       VRPSolver *VRP) {
-      uint32_t W = typeToWidth(V1->getType());
-      if (!W) return;
+      ConstantRange CR1 = range(n1, Subtree);
+      ConstantRange CR2 = range(n2, Subtree);
 
-      ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
-      ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
+      uint32_t W = CR1.getBitWidth();
 
       if (const APInt *I = CR1.getSingleElement()) {
         if (CR2.isFullSet()) {
           ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
-          applyRange(V2, NewCR2, Subtree, VRP);
+          applyRange(n2, NewCR2, Subtree, VRP);
         } else if (*I == CR2.getLower()) {
           APInt NewLower(CR2.getLower() + 1),
                 NewUpper(CR2.getUpper());
@@ -1163,7 +1246,7 @@ namespace {
             NewLower = NewUpper = APInt::getMinValue(W);
 
           ConstantRange NewCR2(NewLower, NewUpper);
-          applyRange(V2, NewCR2, Subtree, VRP);
+          applyRange(n2, NewCR2, Subtree, VRP);
         } else if (*I == CR2.getUpper() - 1) {
           APInt NewLower(CR2.getLower()),
                 NewUpper(CR2.getUpper() - 1);
@@ -1171,14 +1254,14 @@ namespace {
             NewLower = NewUpper = APInt::getMinValue(W);
 
           ConstantRange NewCR2(NewLower, NewUpper);
-          applyRange(V2, NewCR2, Subtree, VRP);
+          applyRange(n2, NewCR2, Subtree, VRP);
         }
       }
 
       if (const APInt *I = CR2.getSingleElement()) {
         if (CR1.isFullSet()) {
           ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
-          applyRange(V1, NewCR1, Subtree, VRP);
+          applyRange(n1, NewCR1, Subtree, VRP);
         } else if (*I == CR1.getLower()) {
           APInt NewLower(CR1.getLower() + 1),
                 NewUpper(CR1.getUpper());
@@ -1186,7 +1269,7 @@ namespace {
             NewLower = NewUpper = APInt::getMinValue(W);
 
           ConstantRange NewCR1(NewLower, NewUpper);
-          applyRange(V1, NewCR1, Subtree, VRP);
+          applyRange(n1, NewCR1, Subtree, VRP);
         } else if (*I == CR1.getUpper() - 1) {
           APInt NewLower(CR1.getLower()),
                 NewUpper(CR1.getUpper() - 1);
@@ -1194,40 +1277,34 @@ namespace {
             NewLower = NewUpper = APInt::getMinValue(W);
 
           ConstantRange NewCR1(NewLower, NewUpper);
-          applyRange(V1, NewCR1, Subtree, VRP);
+          applyRange(n1, NewCR1, Subtree, VRP);
         }
       }
     }
 
-    void addInequality(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
+    void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
                        LatticeVal LV, VRPSolver *VRP) {
-      assert(!isRelatedBy(V1, V2, Subtree, LV) && "Asked to do useless work.");
-
-      assert(isCanonical(V1, Subtree, VRP) && "Value not canonical.");
-      assert(isCanonical(V2, Subtree, VRP) && "Value not canonical.");
+      assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
 
       if (LV == NE) {
-        addNotEquals(V1, V2, Subtree, VRP);
+        addNotEquals(n1, n2, Subtree, VRP);
         return;
       }
 
-      uint32_t W = typeToWidth(V1->getType());
-      if (!W) return;
-
-      ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
-      ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
+      ConstantRange CR1 = range(n1, Subtree);
+      ConstantRange CR2 = range(n2, Subtree);
 
       if (!CR1.isSingleElement()) {
-        ConstantRange NewCR1 = CR1.intersectWith(create(LV, CR2));
+        ConstantRange NewCR1 = CR1.maximalIntersectWith(create(LV, CR2));
         if (NewCR1 != CR1)
-          applyRange(V1, NewCR1, Subtree, VRP);
+          applyRange(n1, NewCR1, Subtree, VRP);
       }
 
       if (!CR2.isSingleElement()) {
-        ConstantRange NewCR2 = CR2.intersectWith(create(reversePredicate(LV),
-                                                        CR1));
+        ConstantRange NewCR2 = CR2.maximalIntersectWith(
+                                       create(reversePredicate(LV), CR1));
         if (NewCR2 != CR2)
-          applyRange(V2, NewCR2, Subtree, VRP);
+          applyRange(n2, NewCR2, Subtree, VRP);
       }
     }
   };
@@ -1303,6 +1380,7 @@ namespace {
     };
     std::deque<Operation> WorkList;
 
+    ValueNumbering &VN;
     InequalityGraph &IG;
     UnreachableBlocks &UB;
     ValueRanges &VR;
@@ -1314,26 +1392,6 @@ namespace {
 
     typedef InequalityGraph::Node Node;
 
-    /// Returns true if V1 is a better canonical value than V2.
-    bool compare(Value *V1, Value *V2) const {
-      if (isa<Constant>(V1))
-        return !isa<Constant>(V2);
-      else if (isa<Constant>(V2))
-        return false;
-      else if (isa<Argument>(V1))
-        return !isa<Argument>(V2);
-      else if (isa<Argument>(V2))
-        return false;
-
-      Instruction *I1 = dyn_cast<Instruction>(V1);
-      Instruction *I2 = dyn_cast<Instruction>(V2);
-
-      if (!I1 || !I2)
-        return V1->getNumUses() < V2->getNumUses();
-
-      return DTDFS->dominates(I1, I2);
-    }
-
     // below - true if the Instruction is dominated by the current context
     // block or instruction
     bool below(Instruction *I) {
@@ -1382,17 +1440,17 @@ namespace {
       if (isa<Constant>(V1) && isa<Constant>(V2))
         return false;
 
-      unsigned n1 = IG.getNode(V1, Top), n2 = IG.getNode(V2, Top);
+      unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
 
       if (n1 && n2) {
         if (n1 == n2) return true;
         if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
       }
 
-      if (n1) assert(V1 == IG.node(n1)->getValue() && "Value isn't canonical.");
-      if (n2) assert(V2 == IG.node(n2)->getValue() && "Value isn't canonical.");
+      if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
+      if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
 
-      assert(!compare(V2, V1) && "Please order parameters to makeEqual.");
+      assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
 
       assert(!isa<Constant>(V2) && "Tried to remove a constant.");
 
@@ -1405,19 +1463,18 @@ namespace {
         // be EQ and that's invalid. What we're doing is looking for any nodes
         // %z such that %x <= %z and %y >= %z, and vice versa.
 
-        Node *N1 = IG.node(n1);
-        Node *N2 = IG.node(n2);
-        Node::iterator end = N2->end();
+        Node::iterator end = IG.node(n2)->end();
 
         // Find the intersection between N1 and N2 which is dominated by
         // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
         // Remove.
-        for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
+        for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
+             I != E; ++I) {
           if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
 
           unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
           unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
-          Node::iterator NI = N2->find(I->To, Top);
+          Node::iterator NI = IG.node(n2)->find(I->To, Top);
           if (NI != end) {
             LatticeVal NILV = reversePredicate(NI->LV);
             unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
@@ -1436,8 +1493,8 @@ namespace {
         for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
              E = Remove.end(); I != E; ++I) {
           unsigned n = *I;
-          Value *V = IG.node(n)->getValue();
-          if (compare(V, V1)) {
+          Value *V = VN.value(n);
+          if (VN.compare(V, V1)) {
             V1 = V;
             n1 = n;
             DontRemove = I;
@@ -1459,7 +1516,7 @@ namespace {
       bool mergeIGNode = false;
       unsigned i = 0;
       for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
-        if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
+        if (i) R = VN.value(Remove[i]); // skip n2.
 
         // Try to replace the whole instruction. If we can, we're done.
         Instruction *I2 = dyn_cast<Instruction>(R);
@@ -1517,32 +1574,32 @@ namespace {
 
       if (!isa<Constant>(V1)) {
         if (Remove.empty()) {
-          VR.mergeInto(&V2, 1, V1, Top, this);
+          VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
         } else {
           std::vector<Value*> RemoveVals;
           RemoveVals.reserve(Remove.size());
 
           for (SetVector<unsigned>::iterator I = Remove.begin(),
                E = Remove.end(); I != E; ++I) {
-            Value *V = IG.node(*I)->getValue();
+            Value *V = VN.value(*I);
             if (!V->use_empty())
               RemoveVals.push_back(V);
           }
-          VR.mergeInto(&RemoveVals[0], RemoveVals.size(), V1, Top, this);
+          VR.mergeInto(&RemoveVals[0], RemoveVals.size(), 
+                       VN.getOrInsertVN(V1, Top), Top, this);
         }
       }
 
       if (mergeIGNode) {
         // Create N1.
-        if (!n1) n1 = IG.newNode(V1);
+        if (!n1) n1 = VN.getOrInsertVN(V1, Top);
 
         // Migrate relationships from removed nodes to N1.
-        Node *N1 = IG.node(n1);
         for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
              I != E; ++I) {
           unsigned n = *I;
-          Node *N = IG.node(n);
-          for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
+          for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
+               NI != NE; ++NI) {
             if (NI->Subtree->DominatedBy(Top)) {
               if (NI->To == n1) {
                 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
@@ -1552,18 +1609,18 @@ namespace {
                 continue;
 
               IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
-              N1->update(NI->To, NI->LV, Top);
+              IG.node(n1)->update(NI->To, NI->LV, Top);
             }
           }
         }
 
         // Point V2 (and all items in Remove) to N1.
         if (!n2)
-          IG.addEquality(n1, V2, Top);
+          VN.addEquality(n1, V2, Top);
         else {
           for (SetVector<unsigned>::iterator I = Remove.begin(),
                E = Remove.end(); I != E; ++I) {
-            IG.addEquality(n1, IG.node(*I)->getValue(), Top);
+            VN.addEquality(n1, VN.value(*I), Top);
           }
         }
 
@@ -1571,7 +1628,7 @@ namespace {
         // Even when Remove is empty, we still want to process V2.
         i = 0;
         for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
-          if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
+          if (i) R = VN.value(Remove[i]); // skip n2.
 
           if (Instruction *I2 = dyn_cast<Instruction>(R)) {
             if (aboveOrBelow(I2))
@@ -1639,9 +1696,11 @@ namespace {
     }
 
   public:
-    VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ValueRanges &VR,
-              DomTreeDFS *DTDFS, bool &modified, BasicBlock *TopBB)
-      : IG(IG),
+    VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
+              ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
+              BasicBlock *TopBB)
+      : VN(VN),
+        IG(IG),
         UB(UB),
         VR(VR),
         DTDFS(DTDFS),
@@ -1653,9 +1712,11 @@ namespace {
       assert(Top && "VRPSolver created for unreachable basic block.");
     }
 
-    VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ValueRanges &VR,
-              DomTreeDFS *DTDFS, bool &modified, Instruction *TopInst)
-      : IG(IG),
+    VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
+              ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
+              Instruction *TopInst)
+      : VN(VN),
+        IG(IG),
         UB(UB),
         VR(VR),
         DTDFS(DTDFS),
@@ -1674,19 +1735,33 @@ namespace {
           return ConstantExpr::getCompare(Pred, C1, C2) ==
                  ConstantInt::getTrue();
 
-      if (unsigned n1 = IG.getNode(V1, Top))
-        if (unsigned n2 = IG.getNode(V2, Top)) {
-          if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
-                               Pred == ICmpInst::ICMP_ULE ||
-                               Pred == ICmpInst::ICMP_UGE ||
-                               Pred == ICmpInst::ICMP_SLE ||
-                               Pred == ICmpInst::ICMP_SGE;
-          if (Pred == ICmpInst::ICMP_EQ) return false;
-          if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
-        }
+      unsigned n1 = VN.valueNumber(V1, Top);
+      unsigned n2 = VN.valueNumber(V2, Top);
+
+      if (n1 && n2) {
+        if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
+                             Pred == ICmpInst::ICMP_ULE ||
+                             Pred == ICmpInst::ICMP_UGE ||
+                             Pred == ICmpInst::ICMP_SLE ||
+                             Pred == ICmpInst::ICMP_SGE;
+        if (Pred == ICmpInst::ICMP_EQ) return false;
+        if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
+        if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
+      }
+
+      if ((n1 && !n2 && isa<Constant>(V2)) ||
+          (n2 && !n1 && isa<Constant>(V1))) {
+        ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
+        ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
+
+        if (Pred == ICmpInst::ICMP_EQ)
+          return CR1.isSingleElement() &&
+                 CR1.getSingleElement() == CR2.getSingleElement();
 
+        return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
+      }
       if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
-      return VR.isRelatedBy(V1, V2, Top, cmpInstToLattice(Pred));
+      return false;
     }
 
     /// add - adds a new property to the work queue
@@ -1710,14 +1785,14 @@ namespace {
     /// new about, find any new relationships between its operands.
     void defToOps(Instruction *I) {
       Instruction *NewContext = below(I) ? I : TopInst;
-      Value *Canonical = IG.canonicalize(I, Top);
+      Value *Canonical = VN.canonicalize(I, Top);
 
       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
         const Type *Ty = BO->getType();
         assert(!Ty->isFPOrFPVector() && "Float in work queue!");
 
-        Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
-        Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
+        Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
+        Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
 
         // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
 
@@ -1786,11 +1861,11 @@ namespace {
         Value *True  = SI->getTrueValue();
         Value *False = SI->getFalseValue();
         if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
-          if (Canonical == IG.canonicalize(True, Top) ||
+          if (Canonical == VN.canonicalize(True, Top) ||
               isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
             add(SI->getCondition(), ConstantInt::getTrue(),
                 ICmpInst::ICMP_EQ, NewContext);
-          else if (Canonical == IG.canonicalize(False, Top) ||
+          else if (Canonical == VN.canonicalize(False, Top) ||
                    isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
             add(SI->getCondition(), ConstantInt::getFalse(),
                 ICmpInst::ICMP_EQ, NewContext);
@@ -1798,7 +1873,7 @@ namespace {
       } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
         for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
              OE = GEPI->idx_end(); OI != OE; ++OI) {
-          ConstantInt *Op = dyn_cast<ConstantInt>(IG.canonicalize(*OI, Top));
+          ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
           if (!Op || !Op->isZero()) return;
         }
         // TODO: The GEPI indices are all zero. Copy from definition to operand,
@@ -1812,10 +1887,10 @@ namespace {
       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
         const Type *SrcTy = CI->getSrcTy();
 
-        Value *TheCI = IG.canonicalize(CI, Top);
+        unsigned ci = VN.getOrInsertVN(CI, Top);
         uint32_t W = VR.typeToWidth(SrcTy);
         if (!W) return;
-        ConstantRange CR = VR.rangeFromValue(TheCI, Top, W);
+        ConstantRange CR = VR.range(ci, Top);
 
         if (CR.isFullSet()) return;
 
@@ -1823,11 +1898,11 @@ namespace {
           default: break;
           case Instruction::ZExt:
           case Instruction::SExt:
-            VR.applyRange(IG.canonicalize(CI->getOperand(0), Top),
+            VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
                           CR.truncate(W), Top, this);
             break;
           case Instruction::BitCast:
-            VR.applyRange(IG.canonicalize(CI->getOperand(0), Top),
+            VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
                           CR, Top, this);
             break;
         }
@@ -1841,8 +1916,8 @@ namespace {
       Instruction *NewContext = below(I) ? I : TopInst;
 
       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
-        Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
-        Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
+        Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
+        Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
 
         if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
           if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
@@ -1912,7 +1987,7 @@ namespace {
         // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
 
         Value *Known = Op0, *Unknown = Op1,
-              *TheBO = IG.canonicalize(BO, Top);
+              *TheBO = VN.canonicalize(BO, Top);
         if (Known != TheBO) std::swap(Known, Unknown);
         if (Known == TheBO) {
           switch (Opcode) {
@@ -1923,7 +1998,7 @@ namespace {
               if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
               // otherwise, fall-through.
             case Instruction::Sub:
-              if (Unknown == Op1) break;
+              if (Unknown == Op0) break;
               // otherwise, fall-through.
             case Instruction::Xor:
             case Instruction::Add:
@@ -1947,15 +2022,14 @@ namespace {
         // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
         // etc.
 
-        Value *Op0 = IG.canonicalize(IC->getOperand(0), Top);
-        Value *Op1 = IG.canonicalize(IC->getOperand(1), Top);
+        Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
+        Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
 
         ICmpInst::Predicate Pred = IC->getPredicate();
-        if (isRelatedBy(Op0, Op1, Pred)) {
+        if (isRelatedBy(Op0, Op1, Pred))
           add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
-        } else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred))) {
+        else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
           add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
-        }
 
       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
         if (I->getType()->isFPOrFPVector()) return;
@@ -1965,20 +2039,20 @@ namespace {
         // %x EQ false then %a EQ %c
         // %b EQ %c then %a EQ %b
 
-        Value *Canonical = IG.canonicalize(SI->getCondition(), Top);
+        Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
         if (Canonical == ConstantInt::getTrue()) {
           add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
         } else if (Canonical == ConstantInt::getFalse()) {
           add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
-        } else if (IG.canonicalize(SI->getTrueValue(), Top) ==
-                   IG.canonicalize(SI->getFalseValue(), Top)) {
+        } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
+                   VN.canonicalize(SI->getFalseValue(), Top)) {
           add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
         }
       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
         const Type *DestTy = CI->getDestTy();
         if (DestTy->isFPOrFPVector()) return;
 
-        Value *Op = IG.canonicalize(CI->getOperand(0), Top);
+        Value *Op = VN.canonicalize(CI->getOperand(0), Top);
         Instruction::CastOps Opcode = CI->getOpcode();
 
         if (Constant *C = dyn_cast<Constant>(Op)) {
@@ -1987,25 +2061,25 @@ namespace {
         }
 
         uint32_t W = VR.typeToWidth(DestTy);
-        Value *TheCI = IG.canonicalize(CI, Top);
-        ConstantRange CR = VR.rangeFromValue(Op, Top, W);
+        unsigned ci = VN.getOrInsertVN(CI, Top);
+        ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
 
         if (!CR.isFullSet()) {
           switch (Opcode) {
             default: break;
             case Instruction::ZExt:
-              VR.applyRange(TheCI, CR.zeroExtend(W), Top, this);
+              VR.applyRange(ci, CR.zeroExtend(W), Top, this);
               break;
             case Instruction::SExt:
-              VR.applyRange(TheCI, CR.signExtend(W), Top, this);
+              VR.applyRange(ci, CR.signExtend(W), Top, this);
               break;
             case Instruction::Trunc: {
               ConstantRange Result = CR.truncate(W);
               if (!Result.isFullSet())
-                VR.applyRange(TheCI, Result, Top, this);
+                VR.applyRange(ci, Result, Top, this);
             } break;
             case Instruction::BitCast:
-              VR.applyRange(TheCI, CR, Top, this);
+              VR.applyRange(ci, CR, Top, this);
               break;
             // TODO: other casts?
           }
@@ -2013,7 +2087,7 @@ namespace {
       } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
         for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
              OE = GEPI->idx_end(); OI != OE; ++OI) {
-          ConstantInt *Op = dyn_cast<ConstantInt>(IG.canonicalize(*OI, Top));
+          ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
           if (!Op || !Op->isZero()) return;
         }
         // TODO: The GEPI indices are all zero. Copy from operand to definition,
@@ -2038,18 +2112,20 @@ namespace {
         TopBB = O.ContextBB;
         Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
 
-        O.LHS = IG.canonicalize(O.LHS, Top);
-        O.RHS = IG.canonicalize(O.RHS, Top);
+        O.LHS = VN.canonicalize(O.LHS, Top);
+        O.RHS = VN.canonicalize(O.RHS, Top);
 
-        assert(O.LHS == IG.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
-        assert(O.RHS == IG.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
+        assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
+        assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
 
         DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
         if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
         else DOUT << " context block: " << O.ContextBB->getName();
         DOUT << "\n";
 
+        DEBUG(VN.dump());
         DEBUG(IG.dump());
+        DEBUG(VR.dump());
 
         // If they're both Constant, skip it. Check for contradiction and mark
         // the BB as unreachable if so.
@@ -2064,7 +2140,7 @@ namespace {
           }
         }
 
-        if (compare(O.LHS, O.RHS)) {
+        if (VN.compare(O.LHS, O.RHS)) {
           std::swap(O.LHS, O.RHS);
           O.Op = ICmpInst::getSwappedPredicate(O.Op);
         }
@@ -2086,10 +2162,10 @@ namespace {
               continue;
             }
 
-            unsigned n1 = IG.getNode(O.LHS, Top);
-            unsigned n2 = IG.getNode(O.RHS, Top);
+            unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
+            unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
 
-            if (n1 && n1 == n2) {
+            if (n1 == n2) {
               if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
                   O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
                 UB.mark(TopBB);
@@ -2098,19 +2174,16 @@ namespace {
               continue;
             }
 
-            if (VR.isRelatedBy(O.LHS, O.RHS, Top, LV) ||
-                (n1 && n2 && IG.isRelatedBy(n1, n2, Top, LV))) {
+            if (VR.isRelatedBy(n1, n2, Top, LV) ||
+                IG.isRelatedBy(n1, n2, Top, LV)) {
               WorkList.pop_front();
               continue;
             }
 
-            VR.addInequality(O.LHS, O.RHS, Top, LV, this);
+            VR.addInequality(n1, n2, Top, LV, this);
             if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
-                LV == NE) {
-              if (!n1) n1 = IG.newNode(O.LHS);
-              if (!n2) n2 = IG.newNode(O.RHS);
+                LV == NE)
               IG.addInequality(n1, n2, Top, LV);
-            }
 
             if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
               if (aboveOrBelow(I1))
@@ -2158,13 +2231,6 @@ namespace {
     VRP->UB.mark(VRP->TopBB);
   }
 
-#ifndef NDEBUG
-  bool ValueRanges::isCanonical(Value *V, DomTreeDFS::Node *Subtree,
-                                VRPSolver *VRP) {
-    return V == VRP->IG.canonicalize(V, Subtree);
-  }
-#endif
-
   /// PredicateSimplifier - This class is a simplifier that replaces
   /// one equivalent variable with another. It also tracks what
   /// can't be equal and will solve setcc instructions when possible.
@@ -2172,6 +2238,7 @@ namespace {
   class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
     DomTreeDFS *DTDFS;
     bool modified;
+    ValueNumbering *VN;
     InequalityGraph *IG;
     UnreachableBlocks UB;
     ValueRanges *VR;
@@ -2192,11 +2259,11 @@ namespace {
     }
 
   private:
-    /// Forwards - Adds new properties into PropertySet and uses them to
+    /// Forwards - Adds new properties to VRPSolver and uses them to
     /// simplify instructions. Because new properties sometimes apply to
     /// a transition from one BasicBlock to another, this will use the
     /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
-    /// basic block with the new PropertySet.
+    /// basic block.
     /// @brief Performs abstract execution of the program.
     class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
       friend class InstVisitor<Forwards>;
@@ -2204,12 +2271,14 @@ namespace {
       DomTreeDFS::Node *DTNode;
 
     public:
+      ValueNumbering &VN;
       InequalityGraph &IG;
       UnreachableBlocks &UB;
       ValueRanges &VR;
 
       Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
-        : PS(PS), DTNode(DTNode), IG(*PS->IG), UB(PS->UB), VR(*PS->VR) {}
+        : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
+          VR(*PS->VR) {}
 
       void visitTerminatorInst(TerminatorInst &TI);
       void visitBranchInst(BranchInst &BI);
@@ -2250,30 +2319,35 @@ namespace {
       }
     }
 
-    // Tries to simplify each Instruction and add new properties to
-    // the PropertySet.
+    // Tries to simplify each Instruction and add new properties.
     void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
       DOUT << "Considering instruction " << *I << "\n";
+      DEBUG(VN->dump());
       DEBUG(IG->dump());
+      DEBUG(VR->dump());
 
       // Sometimes instructions are killed in earlier analysis.
       if (isInstructionTriviallyDead(I)) {
         ++NumSimple;
         modified = true;
-        IG->remove(I);
+        if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
+          if (VN->value(n) == I) IG->remove(n);
+        VN->remove(I);
         I->eraseFromParent();
         return;
       }
 
 #ifndef NDEBUG
       // Try to replace the whole instruction.
-      Value *V = IG->canonicalize(I, DT);
+      Value *V = VN->canonicalize(I, DT);
       assert(V == I && "Late instruction canonicalization.");
       if (V != I) {
         modified = true;
         ++NumInstruction;
         DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
-        IG->remove(I);
+        if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
+          if (VN->value(n) == I) IG->remove(n);
+        VN->remove(I);
         I->replaceAllUsesWith(V);
         I->eraseFromParent();
         return;
@@ -2282,7 +2356,7 @@ namespace {
       // Try to substitute operands.
       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
         Value *Oper = I->getOperand(i);
-        Value *V = IG->canonicalize(Oper, DT);
+        Value *V = VN->canonicalize(Oper, DT);
         assert(V == Oper && "Late operand canonicalization.");
         if (V != Oper) {
           modified = true;
@@ -2311,8 +2385,9 @@ namespace {
 
     modified = false;
     DomTreeDFS::Node *Root = DTDFS->getRootNode();
-    IG = new InequalityGraph(Root);
-    VR = new ValueRanges(TD);
+    VN = new ValueNumbering(DTDFS);
+    IG = new InequalityGraph(*VN, Root);
+    VR = new ValueRanges(*VN, TD);
     WorkList.push_back(Root);
 
     do {
@@ -2357,16 +2432,20 @@ namespace {
 
       if (Dest == TrueDest) {
         DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
-        VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, Dest);
+        VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
         VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
         VRP.solve();
+        DEBUG(VN.dump());
         DEBUG(IG.dump());
+        DEBUG(VR.dump());
       } else if (Dest == FalseDest) {
         DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
-        VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, Dest);
+        VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
         VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
         VRP.solve();
+        DEBUG(VN.dump());
         DEBUG(IG.dump());
+        DEBUG(VR.dump());
       }
 
       PS->proceedToSuccessor(*I);
@@ -2385,7 +2464,7 @@ namespace {
       DOUT << "Switch thinking about BB %" << BB->getName()
            << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
 
-      VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, BB);
+      VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
       if (BB == SI.getDefaultDest()) {
         for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
           if (SI.getSuccessor(i) != BB)
@@ -2400,7 +2479,7 @@ namespace {
   }
 
   void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
-    VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &AI);
+    VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
     VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
     VRP.solve();
   }
@@ -2410,7 +2489,7 @@ namespace {
     // avoid "load uint* null" -> null NE null.
     if (isa<Constant>(Ptr)) return;
 
-    VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &LI);
+    VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
     VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
     VRP.solve();
   }
@@ -2419,13 +2498,13 @@ namespace {
     Value *Ptr = SI.getPointerOperand();
     if (isa<Constant>(Ptr)) return;
 
-    VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &SI);
+    VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
     VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
     VRP.solve();
   }
 
   void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
-    VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &SI);
+    VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
     uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
     uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
     APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
@@ -2436,7 +2515,7 @@ namespace {
   }
 
   void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
-    VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
+    VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
     uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
     uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
     APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
@@ -2454,7 +2533,7 @@ namespace {
       case Instruction::UDiv:
       case Instruction::SDiv: {
         Value *Divisor = BO.getOperand(1);
-        VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
+        VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
         VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
                 ICmpInst::ICMP_NE);
         VRP.solve();
@@ -2465,34 +2544,34 @@ namespace {
     switch (ops) {
       default: break;
       case Instruction::Shl: {
-        VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
+        VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
         VRP.solve();
       } break;
       case Instruction::AShr: {
-        VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
+        VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
         VRP.solve();
       } break;
       case Instruction::LShr:
       case Instruction::UDiv: {
-        VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
+        VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
         VRP.solve();
       } break;
       case Instruction::URem: {
-        VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
+        VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
         VRP.solve();
       } break;
       case Instruction::And: {
-        VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
+        VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
         VRP.solve();
       } break;
       case Instruction::Or: {
-        VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
+        VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
         VRP.solve();
@@ -2518,7 +2597,7 @@ namespace {
       case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
     }
     if (Pred != IC.getPredicate()) {
-      VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &IC);
+      VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
       if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
                           ICmpInst::ICMP_NE)) {
         ++NumSnuggle;
@@ -2546,14 +2625,19 @@ namespace {
 
       }
       if (NextVal) {
-        VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &IC);
+        VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
         if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
                             ICmpInst::getInversePredicate(Pred))) {
           ICmpInst *NewIC = new ICmpInst(ICmpInst::ICMP_EQ, IC.getOperand(0),
                                          NextVal, "", &IC);
           NewIC->takeName(&IC);
           IC.replaceAllUsesWith(NewIC);
-          IG.remove(&IC); // XXX: prove this isn't necessary
+
+          // XXX: prove this isn't necessary
+          if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
+            if (VN.value(n) == &IC) IG.remove(n);
+          VN.remove(&IC);
+
           IC.eraseFromParent();
           ++NumSnuggle;
           PS->modified = true;