LLVM API Documentation

PredicateSimplifier.cpp

Go to the documentation of this file.
00001 //===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Path-sensitive optimizer. In a branch where x == y, replace uses of
00011 // x with y. Permits further optimization, such as the elimination of
00012 // the unreachable call:
00013 //
00014 // void test(int *p, int *q)
00015 // {
00016 //   if (p != q)
00017 //     return;
00018 // 
00019 //   if (*p != *q)
00020 //     foo(); // unreachable
00021 // }
00022 //
00023 //===----------------------------------------------------------------------===//
00024 //
00025 // The InequalityGraph focusses on four properties; equals, not equals,
00026 // less-than and less-than-or-equals-to. The greater-than forms are also held
00027 // just to allow walking from a lesser node to a greater one. These properties
00028 // are stored in a lattice; LE can become LT or EQ, NE can become LT or GT.
00029 //
00030 // These relationships define a graph between values of the same type. Each
00031 // Value is stored in a map table that retrieves the associated Node. This
00032 // is how EQ relationships are stored; the map contains pointers from equal
00033 // Value to the same node. The node contains a most canonical Value* form
00034 // and the list of known relationships with other nodes.
00035 //
00036 // If two nodes are known to be inequal, then they will contain pointers to
00037 // each other with an "NE" relationship. If node getNode(%x) is less than
00038 // getNode(%y), then the %x node will contain <%y, GT> and %y will contain
00039 // <%x, LT>. This allows us to tie nodes together into a graph like this:
00040 //
00041 //   %a < %b < %c < %d
00042 //
00043 // with four nodes representing the properties. The InequalityGraph provides
00044 // querying with "isRelatedBy" and mutators "addEquality" and "addInequality".
00045 // To find a relationship, we start with one of the nodes any binary search
00046 // through its list to find where the relationships with the second node start.
00047 // Then we iterate through those to find the first relationship that dominates
00048 // our context node.
00049 //
00050 // To create these properties, we wait until a branch or switch instruction
00051 // implies that a particular value is true (or false). The VRPSolver is
00052 // responsible for analyzing the variable and seeing what new inferences
00053 // can be made from each property. For example:
00054 //
00055 //   %P = icmp ne i32* %ptr, null
00056 //   %a = and i1 %P, %Q
00057 //   br i1 %a label %cond_true, label %cond_false
00058 //
00059 // For the true branch, the VRPSolver will start with %a EQ true and look at
00060 // the definition of %a and find that it can infer that %P and %Q are both
00061 // true. From %P being true, it can infer that %ptr NE null. For the false
00062 // branch it can't infer anything from the "and" instruction.
00063 //
00064 // Besides branches, we can also infer properties from instruction that may
00065 // have undefined behaviour in certain cases. For example, the dividend of
00066 // a division may never be zero. After the division instruction, we may assume
00067 // that the dividend is not equal to zero.
00068 //
00069 //===----------------------------------------------------------------------===//
00070 //
00071 // The ValueRanges class stores the known integer bounds of a Value. When we
00072 // encounter i8 %a u< %b, the ValueRanges stores that %a = [1, 255] and
00073 // %b = [0, 254].
00074 //
00075 // It never stores an empty range, because that means that the code is
00076 // unreachable. It never stores a single-element range since that's an equality
00077 // relationship and better stored in the InequalityGraph, nor an empty range
00078 // since that is better stored in UnreachableBlocks.
00079 //
00080 //===----------------------------------------------------------------------===//
00081 
00082 #define DEBUG_TYPE "predsimplify"
00083 #include "llvm/Transforms/Scalar.h"
00084 #include "llvm/Constants.h"
00085 #include "llvm/DerivedTypes.h"
00086 #include "llvm/Instructions.h"
00087 #include "llvm/Pass.h"
00088 #include "llvm/ADT/DepthFirstIterator.h"
00089 #include "llvm/ADT/SetOperations.h"
00090 #include "llvm/ADT/SetVector.h"
00091 #include "llvm/ADT/Statistic.h"
00092 #include "llvm/ADT/STLExtras.h"
00093 #include "llvm/Analysis/Dominators.h"
00094 #include "llvm/Assembly/Writer.h"
00095 #include "llvm/Support/CFG.h"
00096 #include "llvm/Support/Compiler.h"
00097 #include "llvm/Support/ConstantRange.h"
00098 #include "llvm/Support/Debug.h"
00099 #include "llvm/Support/InstVisitor.h"
00100 #include "llvm/Target/TargetData.h"
00101 #include "llvm/Transforms/Utils/Local.h"
00102 #include <algorithm>
00103 #include <deque>
00104 #include <stack>
00105 using namespace llvm;
00106 
00107 STATISTIC(NumVarsReplaced, "Number of argument substitutions");
00108 STATISTIC(NumInstruction , "Number of instructions removed");
00109 STATISTIC(NumSimple      , "Number of simple replacements");
00110 STATISTIC(NumBlocks      , "Number of blocks marked unreachable");
00111 STATISTIC(NumSnuggle     , "Number of comparisons snuggled");
00112 
00113 namespace {
00114   class DomTreeDFS {
00115   public:
00116     class Node {
00117       friend class DomTreeDFS;
00118     public:
00119       typedef std::vector<Node *>::iterator       iterator;
00120       typedef std::vector<Node *>::const_iterator const_iterator;
00121 
00122       unsigned getDFSNumIn()  const { return DFSin;  }
00123       unsigned getDFSNumOut() const { return DFSout; }
00124 
00125       BasicBlock *getBlock() const { return BB; }
00126 
00127       iterator begin() { return Children.begin(); }
00128       iterator end()   { return Children.end();   }
00129 
00130       const_iterator begin() const { return Children.begin(); }
00131       const_iterator end()   const { return Children.end();   }
00132 
00133       bool dominates(const Node *N) const {
00134         return DFSin <= N->DFSin && DFSout >= N->DFSout;
00135       }
00136 
00137       bool DominatedBy(const Node *N) const {
00138         return N->dominates(this);
00139       }
00140 
00141       /// Sorts by the number of descendants. With this, you can iterate
00142       /// through a sorted list and the first matching entry is the most
00143       /// specific match for your basic block. The order provided is stable;
00144       /// DomTreeDFS::Nodes with the same number of descendants are sorted by
00145       /// DFS in number.
00146       bool operator<(const Node &N) const {
00147         unsigned   spread =   DFSout -   DFSin;
00148         unsigned N_spread = N.DFSout - N.DFSin;
00149         if (spread == N_spread) return DFSin < N.DFSin;
00150         return spread < N_spread;
00151       }
00152       bool operator>(const Node &N) const { return N < *this; }
00153 
00154     private:
00155       unsigned DFSin, DFSout;
00156       BasicBlock *BB;
00157 
00158       std::vector<Node *> Children;
00159     };
00160 
00161     // XXX: this may be slow. Instead of using "new" for each node, consider
00162     // putting them in a vector to keep them contiguous.
00163     explicit DomTreeDFS(DominatorTree *DT) {
00164       std::stack<std::pair<Node *, DomTreeNode *> > S;
00165 
00166       Entry = new Node;
00167       Entry->BB = DT->getRootNode()->getBlock();
00168       S.push(std::make_pair(Entry, DT->getRootNode()));
00169 
00170       NodeMap[Entry->BB] = Entry;
00171 
00172       while (!S.empty()) {
00173         std::pair<Node *, DomTreeNode *> &Pair = S.top();
00174         Node *N = Pair.first;
00175         DomTreeNode *DTNode = Pair.second;
00176         S.pop();
00177 
00178         for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
00179              I != E; ++I) {
00180           Node *NewNode = new Node;
00181           NewNode->BB = (*I)->getBlock();
00182           N->Children.push_back(NewNode);
00183           S.push(std::make_pair(NewNode, *I));
00184 
00185           NodeMap[NewNode->BB] = NewNode;
00186         }
00187       }
00188 
00189       renumber();
00190 
00191 #ifndef NDEBUG
00192       DEBUG(dump());
00193 #endif
00194     }
00195 
00196 #ifndef NDEBUG
00197     virtual
00198 #endif
00199     ~DomTreeDFS() {
00200       std::stack<Node *> S;
00201 
00202       S.push(Entry);
00203       while (!S.empty()) {
00204         Node *N = S.top(); S.pop();
00205 
00206         for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
00207           S.push(*I);
00208 
00209         delete N;
00210       }
00211     }
00212 
00213     /// getRootNode - This returns the entry node for the CFG of the function.
00214     Node *getRootNode() const { return Entry; }
00215 
00216     /// getNodeForBlock - return the node for the specified basic block.
00217     Node *getNodeForBlock(BasicBlock *BB) const {
00218       if (!NodeMap.count(BB)) return 0;
00219       return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
00220     }
00221 
00222     /// dominates - returns true if the basic block for I1 dominates that of
00223     /// the basic block for I2. If the instructions belong to the same basic
00224     /// block, the instruction first instruction sequentially in the block is
00225     /// considered dominating.
00226     bool dominates(Instruction *I1, Instruction *I2) {
00227       BasicBlock *BB1 = I1->getParent(),
00228                  *BB2 = I2->getParent();
00229       if (BB1 == BB2) {
00230         if (isa<TerminatorInst>(I1)) return false;
00231         if (isa<TerminatorInst>(I2)) return true;
00232         if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
00233         if (!isa<PHINode>(I1) &&  isa<PHINode>(I2)) return false;
00234 
00235         for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
00236              I != E; ++I) {
00237           if (&*I == I1) return true;
00238           else if (&*I == I2) return false;
00239         }
00240         assert(!"Instructions not found in parent BasicBlock?");
00241       } else {
00242         Node *Node1 = getNodeForBlock(BB1),
00243              *Node2 = getNodeForBlock(BB2);
00244         return Node1 && Node2 && Node1->dominates(Node2);
00245       }
00246       return false; // Not reached
00247     }
00248 
00249   private:
00250     /// renumber - calculates the depth first search numberings and applies
00251     /// them onto the nodes.
00252     void renumber() {
00253       std::stack<std::pair<Node *, Node::iterator> > S;
00254       unsigned n = 0;
00255 
00256       Entry->DFSin = ++n;
00257       S.push(std::make_pair(Entry, Entry->begin()));
00258 
00259       while (!S.empty()) {
00260         std::pair<Node *, Node::iterator> &Pair = S.top();
00261         Node *N = Pair.first;
00262         Node::iterator &I = Pair.second;
00263 
00264         if (I == N->end()) {
00265           N->DFSout = ++n;
00266           S.pop();
00267         } else {
00268           Node *Next = *I++;
00269           Next->DFSin = ++n;
00270           S.push(std::make_pair(Next, Next->begin()));
00271         }
00272       }
00273     }
00274 
00275 #ifndef NDEBUG
00276     virtual void dump() const {
00277       dump(*cerr.stream());
00278     }
00279 
00280     void dump(std::ostream &os) const {
00281       os << "Predicate simplifier DomTreeDFS: \n";
00282       dump(Entry, 0, os);
00283       os << "\n\n";
00284     }
00285 
00286     void dump(Node *N, int depth, std::ostream &os) const {
00287       ++depth;
00288       for (int i = 0; i < depth; ++i) { os << " "; }
00289       os << "[" << depth << "] ";
00290 
00291       os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
00292          << ", " << N->getDFSNumOut() << ")\n";
00293 
00294       for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
00295         dump(*I, depth, os);
00296     }
00297 #endif
00298 
00299     Node *Entry;
00300     std::map<BasicBlock *, Node *> NodeMap;
00301   };
00302 
00303   // SLT SGT ULT UGT EQ
00304   //   0   1   0   1  0 -- GT                  10
00305   //   0   1   0   1  1 -- GE                  11
00306   //   0   1   1   0  0 -- SGTULT              12
00307   //   0   1   1   0  1 -- SGEULE              13
00308   //   0   1   1   1  0 -- SGT                 14
00309   //   0   1   1   1  1 -- SGE                 15
00310   //   1   0   0   1  0 -- SLTUGT              18
00311   //   1   0   0   1  1 -- SLEUGE              19
00312   //   1   0   1   0  0 -- LT                  20
00313   //   1   0   1   0  1 -- LE                  21
00314   //   1   0   1   1  0 -- SLT                 22
00315   //   1   0   1   1  1 -- SLE                 23
00316   //   1   1   0   1  0 -- UGT                 26
00317   //   1   1   0   1  1 -- UGE                 27
00318   //   1   1   1   0  0 -- ULT                 28
00319   //   1   1   1   0  1 -- ULE                 29
00320   //   1   1   1   1  0 -- NE                  30
00321   enum LatticeBits {
00322     EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
00323   };
00324   enum LatticeVal {
00325     GT = SGT_BIT | UGT_BIT,
00326     GE = GT | EQ_BIT,
00327     LT = SLT_BIT | ULT_BIT,
00328     LE = LT | EQ_BIT,
00329     NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
00330     SGTULT = SGT_BIT | ULT_BIT,
00331     SGEULE = SGTULT | EQ_BIT,
00332     SLTUGT = SLT_BIT | UGT_BIT,
00333     SLEUGE = SLTUGT | EQ_BIT,
00334     ULT = SLT_BIT | SGT_BIT | ULT_BIT,
00335     UGT = SLT_BIT | SGT_BIT | UGT_BIT,
00336     SLT = SLT_BIT | ULT_BIT | UGT_BIT,
00337     SGT = SGT_BIT | ULT_BIT | UGT_BIT,
00338     SLE = SLT | EQ_BIT,
00339     SGE = SGT | EQ_BIT,
00340     ULE = ULT | EQ_BIT,
00341     UGE = UGT | EQ_BIT
00342   };
00343 
00344 #ifndef NDEBUG
00345   /// validPredicate - determines whether a given value is actually a lattice
00346   /// value. Only used in assertions or debugging.
00347   static bool validPredicate(LatticeVal LV) {
00348     switch (LV) {
00349       case GT: case GE: case LT: case LE: case NE:
00350       case SGTULT: case SGT: case SGEULE:
00351       case SLTUGT: case SLT: case SLEUGE:
00352       case ULT: case UGT:
00353       case SLE: case SGE: case ULE: case UGE:
00354         return true;
00355       default:
00356         return false;
00357     }
00358   }
00359 #endif
00360 
00361   /// reversePredicate - reverse the direction of the inequality
00362   static LatticeVal reversePredicate(LatticeVal LV) {
00363     unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
00364 
00365     if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
00366       reverse |= (SLT_BIT|SGT_BIT);
00367 
00368     if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
00369       reverse |= (ULT_BIT|UGT_BIT);
00370 
00371     LatticeVal Rev = static_cast<LatticeVal>(reverse);
00372     assert(validPredicate(Rev) && "Failed reversing predicate.");
00373     return Rev;
00374   }
00375 
00376   /// ValueNumbering stores the scope-specific value numbers for a given Value.
00377   class VISIBILITY_HIDDEN ValueNumbering {
00378 
00379     /// VNPair is a tuple of {Value, index number, DomTreeDFS::Node}. It
00380     /// includes the comparison operators necessary to allow you to store it
00381     /// in a sorted vector.
00382     class VISIBILITY_HIDDEN VNPair {
00383     public:
00384       Value *V;
00385       unsigned index;
00386       DomTreeDFS::Node *Subtree;
00387 
00388       VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
00389         : V(V), index(index), Subtree(Subtree) {}
00390 
00391       bool operator==(const VNPair &RHS) const {
00392         return V == RHS.V && Subtree == RHS.Subtree;
00393       }
00394 
00395       bool operator<(const VNPair &RHS) const {
00396         if (V != RHS.V) return V < RHS.V;
00397         return *Subtree < *RHS.Subtree;
00398       }
00399 
00400       bool operator<(Value *RHS) const {
00401         return V < RHS;
00402       }
00403 
00404       bool operator>(Value *RHS) const {
00405         return V > RHS;
00406       }
00407 
00408       friend bool operator<(Value *RHS, const VNPair &pair) {
00409         return pair.operator>(RHS);
00410       }
00411     };
00412 
00413     typedef std::vector<VNPair> VNMapType;
00414     VNMapType VNMap;
00415 
00416     /// The canonical choice for value number at index.
00417     std::vector<Value *> Values;
00418 
00419     DomTreeDFS *DTDFS;
00420 
00421   public:
00422 #ifndef NDEBUG
00423     virtual ~ValueNumbering() {}
00424     virtual void dump() {
00425       dump(*cerr.stream());
00426     }
00427 
00428     void dump(std::ostream &os) {
00429       for (unsigned i = 1; i <= Values.size(); ++i) {
00430         os << i << " = ";
00431         WriteAsOperand(os, Values[i-1]);
00432         os << " {";
00433         for (unsigned j = 0; j < VNMap.size(); ++j) {
00434           if (VNMap[j].index == i) {
00435             WriteAsOperand(os, VNMap[j].V);
00436             os << " (" << VNMap[j].Subtree->getDFSNumIn() << ")  ";
00437           }
00438         }
00439         os << "}\n";
00440       }
00441     }
00442 #endif
00443 
00444     /// compare - returns true if V1 is a better canonical value than V2.
00445     bool compare(Value *V1, Value *V2) const {
00446       if (isa<Constant>(V1))
00447         return !isa<Constant>(V2);
00448       else if (isa<Constant>(V2))
00449         return false;
00450       else if (isa<Argument>(V1))
00451         return !isa<Argument>(V2);
00452       else if (isa<Argument>(V2))
00453         return false;
00454 
00455       Instruction *I1 = dyn_cast<Instruction>(V1);
00456       Instruction *I2 = dyn_cast<Instruction>(V2);
00457 
00458       if (!I1 || !I2)
00459         return V1->getNumUses() < V2->getNumUses();
00460 
00461       return DTDFS->dominates(I1, I2);
00462     }
00463 
00464     ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
00465 
00466     /// valueNumber - finds the value number for V under the Subtree. If
00467     /// there is no value number, returns zero.
00468     unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
00469       if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V))
00470           || V->getType() == Type::VoidTy) return 0;
00471 
00472       VNMapType::iterator E = VNMap.end();
00473       VNPair pair(V, 0, Subtree);
00474       VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
00475       while (I != E && I->V == V) {
00476         if (I->Subtree->dominates(Subtree))
00477           return I->index;
00478         ++I;
00479       }
00480       return 0;
00481     }
00482 
00483     /// getOrInsertVN - always returns a value number, creating it if necessary.
00484     unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
00485       if (unsigned n = valueNumber(V, Subtree))
00486         return n;
00487       else
00488         return newVN(V);
00489     }
00490 
00491     /// newVN - creates a new value number. Value V must not already have a
00492     /// value number assigned.
00493     unsigned newVN(Value *V) {
00494       assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
00495              "Bad Value for value numbering.");
00496       assert(V->getType() != Type::VoidTy && "Won't value number a void value");
00497 
00498       Values.push_back(V);
00499 
00500       VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
00501       VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
00502       assert((I == VNMap.end() || value(I->index) != V) &&
00503              "Attempt to create a duplicate value number.");
00504       VNMap.insert(I, pair);
00505 
00506       return Values.size();
00507     }
00508 
00509     /// value - returns the Value associated with a value number.
00510     Value *value(unsigned index) const {
00511       assert(index != 0 && "Zero index is reserved for not found.");
00512       assert(index <= Values.size() && "Index out of range.");
00513       return Values[index-1];
00514     }
00515 
00516     /// canonicalize - return a Value that is equal to V under Subtree.
00517     Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
00518       if (isa<Constant>(V)) return V;
00519 
00520       if (unsigned n = valueNumber(V, Subtree))
00521         return value(n);
00522       else
00523         return V;
00524     }
00525 
00526     /// addEquality - adds that value V belongs to the set of equivalent
00527     /// values defined by value number n under Subtree.
00528     void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
00529       assert(canonicalize(value(n), Subtree) == value(n) &&
00530              "Node's 'canonical' choice isn't best within this subtree.");
00531 
00532       // Suppose that we are given "%x -> node #1 (%y)". The problem is that
00533       // we may already have "%z -> node #2 (%x)" somewhere above us in the
00534       // graph. We need to find those edges and add "%z -> node #1 (%y)"
00535       // to keep the lookups canonical.
00536 
00537       std::vector<Value *> ToRepoint(1, V);
00538 
00539       if (unsigned Conflict = valueNumber(V, Subtree)) {
00540         for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
00541              I != E; ++I) {
00542           if (I->index == Conflict && I->Subtree->dominates(Subtree))
00543             ToRepoint.push_back(I->V);
00544         }
00545       }
00546 
00547       for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
00548            VE = ToRepoint.end(); VI != VE; ++VI) {
00549         Value *V = *VI;
00550 
00551         VNPair pair(V, n, Subtree);
00552         VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
00553         VNMapType::iterator I = std::lower_bound(B, E, pair);
00554         if (I != E && I->V == V && I->Subtree == Subtree)
00555           I->index = n; // Update best choice
00556         else
00557           VNMap.insert(I, pair); // New Value
00558 
00559         // XXX: we currently don't have to worry about updating values with
00560         // more specific Subtrees, but we will need to for PHI node support.
00561 
00562 #ifndef NDEBUG
00563         Value *V_n = value(n);
00564         if (isa<Constant>(V) && isa<Constant>(V_n)) {
00565           assert(V == V_n && "Constant equals different constant?");
00566         }
00567 #endif
00568       }
00569     }
00570 
00571     /// remove - removes all references to value V.
00572     void remove(Value *V) {
00573       VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
00574       VNPair pair(V, 0, DTDFS->getRootNode());
00575       VNMapType::iterator J = std::upper_bound(B, E, pair);
00576       VNMapType::iterator I = J;
00577 
00578       while (I != B && (I == E || I->V == V)) --I;
00579 
00580       VNMap.erase(I, J);
00581     }
00582   };
00583 
00584   /// The InequalityGraph stores the relationships between values.
00585   /// Each Value in the graph is assigned to a Node. Nodes are pointer
00586   /// comparable for equality. The caller is expected to maintain the logical
00587   /// consistency of the system.
00588   ///
00589   /// The InequalityGraph class may invalidate Node*s after any mutator call.
00590   /// @brief The InequalityGraph stores the relationships between values.
00591   class VISIBILITY_HIDDEN InequalityGraph {
00592     ValueNumbering &VN;
00593     DomTreeDFS::Node *TreeRoot;
00594 
00595     InequalityGraph();                  // DO NOT IMPLEMENT
00596     InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
00597   public:
00598     InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
00599       : VN(VN), TreeRoot(TreeRoot) {}
00600 
00601     class Node;
00602 
00603     /// An Edge is contained inside a Node making one end of the edge implicit
00604     /// and contains a pointer to the other end. The edge contains a lattice
00605     /// value specifying the relationship and an DomTreeDFS::Node specifying
00606     /// the root in the dominator tree to which this edge applies.
00607     class VISIBILITY_HIDDEN Edge {
00608     public:
00609       Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
00610         : To(T), LV(V), Subtree(ST) {}
00611 
00612       unsigned To;
00613       LatticeVal LV;
00614       DomTreeDFS::Node *Subtree;
00615 
00616       bool operator<(const Edge &edge) const {
00617         if (To != edge.To) return To < edge.To;
00618         return *Subtree < *edge.Subtree;
00619       }
00620 
00621       bool operator<(unsigned to) const {
00622         return To < to;
00623       }
00624 
00625       bool operator>(unsigned to) const {
00626         return To > to;
00627       }
00628 
00629       friend bool operator<(unsigned to, const Edge &edge) {
00630         return edge.operator>(to);
00631       }
00632     };
00633 
00634     /// A single node in the InequalityGraph. This stores the canonical Value
00635     /// for the node, as well as the relationships with the neighbours.
00636     ///
00637     /// @brief A single node in the InequalityGraph.
00638     class VISIBILITY_HIDDEN Node {
00639       friend class InequalityGraph;
00640 
00641       typedef SmallVector<Edge, 4> RelationsType;
00642       RelationsType Relations;
00643 
00644       // TODO: can this idea improve performance?
00645       //friend class std::vector<Node>;
00646       //Node(Node &N) { RelationsType.swap(N.RelationsType); }
00647 
00648     public:
00649       typedef RelationsType::iterator       iterator;
00650       typedef RelationsType::const_iterator const_iterator;
00651 
00652 #ifndef NDEBUG
00653       virtual ~Node() {}
00654       virtual void dump() const {
00655         dump(*cerr.stream());
00656       }
00657     private:
00658       void dump(std::ostream &os) const {
00659         static const std::string names[32] =
00660           { "000000", "000001", "000002", "000003", "000004", "000005",
00661             "000006", "000007", "000008", "000009", "     >", "    >=",
00662             "  s>u<", "s>=u<=", "    s>", "   s>=", "000016", "000017",
00663             "  s<u>", "s<=u>=", "     <", "    <=", "    s<", "   s<=",
00664             "000024", "000025", "    u>", "   u>=", "    u<", "   u<=",
00665             "    !=", "000031" };
00666         for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
00667           os << names[NI->LV] << " " << NI->To
00668              << " (" << NI->Subtree->getDFSNumIn() << "), ";
00669         }
00670       }
00671     public:
00672 #endif
00673 
00674       iterator begin()             { return Relations.begin(); }
00675       iterator end()               { return Relations.end();   }
00676       const_iterator begin() const { return Relations.begin(); }
00677       const_iterator end()   const { return Relations.end();   }
00678 
00679       iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
00680         iterator E = end();
00681         for (iterator I = std::lower_bound(begin(), E, n);
00682              I != E && I->To == n; ++I) {
00683           if (Subtree->DominatedBy(I->Subtree))
00684             return I;
00685         }
00686         return E;
00687       }
00688 
00689       const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
00690         const_iterator E = end();
00691         for (const_iterator I = std::lower_bound(begin(), E, n);
00692              I != E && I->To == n; ++I) {
00693           if (Subtree->DominatedBy(I->Subtree))
00694             return I;
00695         }
00696         return E;
00697       }
00698 
00699       /// update - updates the lattice value for a given node, creating a new
00700       /// entry if one doesn't exist. The new lattice value must not be
00701       /// inconsistent with any previously existing value.
00702       void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
00703         assert(validPredicate(R) && "Invalid predicate.");
00704 
00705         Edge edge(n, R, Subtree);
00706         iterator B = begin(), E = end();
00707         iterator I = std::lower_bound(B, E, edge);
00708 
00709         iterator J = I;
00710         while (J != E && J->To == n) {
00711           if (Subtree->DominatedBy(J->Subtree))
00712             break;
00713           ++J;
00714         }
00715 
00716         if (J != E && J->To == n) {
00717           edge.LV = static_cast<LatticeVal>(J->LV & R);
00718           assert(validPredicate(edge.LV) && "Invalid union of lattice values.");
00719 
00720           if (edge.LV == J->LV)
00721             return; // This update adds nothing new.
00722         }
00723 
00724         if (I != B) {
00725           // We also have to tighten any edge beneath our update.
00726           for (iterator K = I - 1; K->To == n; --K) {
00727             if (K->Subtree->DominatedBy(Subtree)) {
00728               LatticeVal LV = static_cast<LatticeVal>(K->LV & edge.LV);
00729               assert(validPredicate(LV) && "Invalid union of lattice values");
00730               K->LV = LV;
00731             }
00732             if (K == B) break;
00733           }
00734         }
00735 
00736         // Insert new edge at Subtree if it isn't already there.
00737         if (I == E || I->To != n || Subtree != I->Subtree)
00738           Relations.insert(I, edge);
00739       }
00740     };
00741 
00742   private:
00743 
00744     std::vector<Node> Nodes;
00745 
00746   public:
00747     /// node - returns the node object at a given value number. The pointer
00748     /// returned may be invalidated on the next call to node().
00749     Node *node(unsigned index) {
00750       assert(VN.value(index)); // This triggers the necessary checks.
00751       if (Nodes.size() < index) Nodes.resize(index);
00752       return &Nodes[index-1];
00753     }
00754 
00755     /// isRelatedBy - true iff n1 op n2
00756     bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
00757                      LatticeVal LV) {
00758       if (n1 == n2) return LV & EQ_BIT;
00759 
00760       Node *N1 = node(n1);
00761       Node::iterator I = N1->find(n2, Subtree), E = N1->end();
00762       if (I != E) return (I->LV & LV) == I->LV;
00763 
00764       return false;
00765     }
00766 
00767     // The add* methods assume that your input is logically valid and may 
00768     // assertion-fail or infinitely loop if you attempt a contradiction.
00769 
00770     /// addInequality - Sets n1 op n2.
00771     /// It is also an error to call this on an inequality that is already true.
00772     void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
00773                        LatticeVal LV1) {
00774       assert(n1 != n2 && "A node can't be inequal to itself.");
00775 
00776       if (LV1 != NE)
00777         assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
00778                "Contradictory inequality.");
00779 
00780       // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
00781       // add %a < %n2 too. This keeps the graph fully connected.
00782       if (LV1 != NE) {
00783         // Break up the relationship into signed and unsigned comparison parts.
00784         // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
00785         // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
00786         // should have the EQ_BIT iff it's set for both op1 and op2.
00787 
00788         unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
00789         unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
00790 
00791         for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
00792           if (I->LV != NE && I->To != n2) {
00793 
00794             DomTreeDFS::Node *Local_Subtree = NULL;
00795             if (Subtree->DominatedBy(I->Subtree))
00796               Local_Subtree = Subtree;
00797             else if (I->Subtree->DominatedBy(Subtree))
00798               Local_Subtree = I->Subtree;
00799 
00800             if (Local_Subtree) {
00801               unsigned new_relationship = 0;
00802               LatticeVal ILV = reversePredicate(I->LV);
00803               unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
00804               unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
00805 
00806               if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
00807                 new_relationship |= ILV_s;
00808               if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
00809                 new_relationship |= ILV_u;
00810 
00811               if (new_relationship) {
00812                 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
00813                   new_relationship |= (SLT_BIT|SGT_BIT);
00814                 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
00815                   new_relationship |= (ULT_BIT|UGT_BIT);
00816                 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
00817                   new_relationship |= EQ_BIT;
00818 
00819                 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
00820 
00821                 node(I->To)->update(n2, NewLV, Local_Subtree);
00822                 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
00823               }
00824             }
00825           }
00826         }
00827 
00828         for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
00829           if (I->LV != NE && I->To != n1) {
00830             DomTreeDFS::Node *Local_Subtree = NULL;
00831             if (Subtree->DominatedBy(I->Subtree))
00832               Local_Subtree = Subtree;
00833             else if (I->Subtree->DominatedBy(Subtree))
00834               Local_Subtree = I->Subtree;
00835 
00836             if (Local_Subtree) {
00837               unsigned new_relationship = 0;
00838               unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
00839               unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
00840 
00841               if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
00842                 new_relationship |= ILV_s;
00843 
00844               if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
00845                 new_relationship |= ILV_u;
00846 
00847               if (new_relationship) {
00848                 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
00849                   new_relationship |= (SLT_BIT|SGT_BIT);
00850                 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
00851                   new_relationship |= (ULT_BIT|UGT_BIT);
00852                 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
00853                   new_relationship |= EQ_BIT;
00854 
00855                 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
00856 
00857                 node(n1)->update(I->To, NewLV, Local_Subtree);
00858                 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
00859               }
00860             }
00861           }
00862         }
00863       }
00864 
00865       node(n1)->update(n2, LV1, Subtree);
00866       node(n2)->update(n1, reversePredicate(LV1), Subtree);
00867     }
00868 
00869     /// remove - removes a node from the graph by removing all references to
00870     /// and from it.
00871     void remove(unsigned n) {
00872       Node *N = node(n);
00873       for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
00874         Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
00875         do {
00876           node(NI->To)->Relations.erase(Iter);
00877           Iter = node(NI->To)->find(n, TreeRoot);
00878         } while (Iter != node(NI->To)->end());
00879       }
00880       N->Relations.clear();
00881     }
00882 
00883 #ifndef NDEBUG
00884     virtual ~InequalityGraph() {}
00885     virtual void dump() {
00886       dump(*cerr.stream());
00887     }
00888 
00889     void dump(std::ostream &os) {
00890       for (unsigned i = 1; i <= Nodes.size(); ++i) {
00891         os << i << " = {";
00892         node(i)->dump(os);
00893         os << "}\n";
00894       }
00895     }
00896 #endif
00897   };
00898 
00899   class VRPSolver;
00900 
00901   /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
00902   /// in the InequalityGraph.
00903   class VISIBILITY_HIDDEN ValueRanges {
00904     ValueNumbering &VN;
00905     TargetData *TD;
00906 
00907     class VISIBILITY_HIDDEN ScopedRange {
00908       typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
00909               RangeListType;
00910       RangeListType RangeList;
00911 
00912       static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
00913                       const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
00914         return *LHS.first < *RHS.first;
00915       }
00916 
00917     public:
00918 #ifndef NDEBUG
00919       virtual ~ScopedRange() {}
00920       virtual void dump() const {
00921         dump(*cerr.stream());
00922       }
00923 
00924       void dump(std::ostream &os) const {
00925         os << "{";
00926         for (const_iterator I = begin(), E = end(); I != E; ++I) {
00927           os << &I->second << " (" << I->first->getDFSNumIn() << "), ";
00928         }
00929         os << "}";
00930       }
00931 #endif
00932 
00933       typedef RangeListType::iterator       iterator;
00934       typedef RangeListType::const_iterator const_iterator;
00935 
00936       iterator begin() { return RangeList.begin(); }
00937       iterator end()   { return RangeList.end(); }
00938       const_iterator begin() const { return RangeList.begin(); }
00939       const_iterator end()   const { return RangeList.end(); }
00940 
00941       iterator find(DomTreeDFS::Node *Subtree) {
00942         static ConstantRange empty(1, false);
00943         iterator E = end();
00944         iterator I = std::lower_bound(begin(), E,
00945                                       std::make_pair(Subtree, empty), swo);
00946 
00947         while (I != E && !I->first->dominates(Subtree)) ++I;
00948         return I;
00949       }
00950 
00951       const_iterator find(DomTreeDFS::Node *Subtree) const {
00952         static const ConstantRange empty(1, false);
00953         const_iterator E = end();
00954         const_iterator I = std::lower_bound(begin(), E,
00955                                             std::make_pair(Subtree, empty), swo);
00956 
00957         while (I != E && !I->first->dominates(Subtree)) ++I;
00958         return I;
00959       }
00960 
00961       void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
00962         assert(!CR.isEmptySet() && "Empty ConstantRange.");
00963         assert(!CR.isSingleElement() && "Refusing to store single element.");
00964 
00965         static ConstantRange empty(1, false);
00966         iterator E = end();
00967         iterator I =
00968             std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
00969 
00970         if (I != end() && I->first == Subtree) {
00971           ConstantRange CR2 = I->second.maximalIntersectWith(CR);
00972           assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
00973                  "Invalid union of ranges.");
00974           I->second = CR2;
00975         } else
00976           RangeList.insert(I, std::make_pair(Subtree, CR));
00977       }
00978     };
00979 
00980     std::vector<ScopedRange> Ranges;
00981 
00982     void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
00983       if (CR.isFullSet()) return;
00984       if (Ranges.size() < n) Ranges.resize(n);
00985       Ranges[n-1].update(CR, Subtree);
00986     }
00987 
00988     /// create - Creates a ConstantRange that matches the given LatticeVal
00989     /// relation with a given integer.
00990     ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
00991       assert(!CR.isEmptySet() && "Can't deal with empty set.");
00992 
00993       if (LV == NE)
00994         return makeConstantRange(ICmpInst::ICMP_NE, CR);
00995 
00996       unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
00997       unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
00998       bool hasEQ = LV & EQ_BIT;
00999 
01000       ConstantRange Range(CR.getBitWidth());
01001 
01002       if (LV_s == SGT_BIT) {
01003         Range = Range.maximalIntersectWith(makeConstantRange(
01004                     hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
01005       } else if (LV_s == SLT_BIT) {
01006         Range = Range.maximalIntersectWith(makeConstantRange(
01007                     hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
01008       }
01009 
01010       if (LV_u == UGT_BIT) {
01011         Range = Range.maximalIntersectWith(makeConstantRange(
01012                     hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
01013       } else if (LV_u == ULT_BIT) {
01014         Range = Range.maximalIntersectWith(makeConstantRange(
01015                     hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
01016       }
01017 
01018       return Range;
01019     }
01020 
01021     /// makeConstantRange - Creates a ConstantRange representing the set of all
01022     /// value that match the ICmpInst::Predicate with any of the values in CR.
01023     ConstantRange makeConstantRange(ICmpInst::Predicate ICmpOpcode,
01024                                     const ConstantRange &CR) {
01025       uint32_t W = CR.getBitWidth();
01026       switch (ICmpOpcode) {
01027         default: assert(!"Invalid ICmp opcode to makeConstantRange()");
01028         case ICmpInst::ICMP_EQ:
01029           return ConstantRange(CR.getLower(), CR.getUpper());
01030         case ICmpInst::ICMP_NE:
01031           if (CR.isSingleElement())
01032             return ConstantRange(CR.getUpper(), CR.getLower());
01033           return ConstantRange(W);
01034         case ICmpInst::ICMP_ULT:
01035           return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
01036         case ICmpInst::ICMP_SLT:
01037           return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
01038         case ICmpInst::ICMP_ULE: {
01039           APInt UMax(CR.getUnsignedMax());
01040           if (UMax.isMaxValue())
01041             return ConstantRange(W);
01042           return ConstantRange(APInt::getMinValue(W), UMax + 1);
01043         }
01044         case ICmpInst::ICMP_SLE: {
01045           APInt SMax(CR.getSignedMax());
01046           if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
01047             return ConstantRange(W);
01048           return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
01049         }
01050         case ICmpInst::ICMP_UGT:
01051           return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
01052         case ICmpInst::ICMP_SGT:
01053           return ConstantRange(CR.getSignedMin() + 1,
01054                                APInt::getSignedMinValue(W));
01055         case ICmpInst::ICMP_UGE: {
01056           APInt UMin(CR.getUnsignedMin());
01057           if (UMin.isMinValue())
01058             return ConstantRange(W);
01059           return ConstantRange(UMin, APInt::getNullValue(W));
01060         }
01061         case ICmpInst::ICMP_SGE: {
01062           APInt SMin(CR.getSignedMin());
01063           if (SMin.isMinSignedValue())
01064             return ConstantRange(W);
01065           return ConstantRange(SMin, APInt::getSignedMinValue(W));
01066         }
01067       }
01068     }
01069 
01070 #ifndef NDEBUG
01071     bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
01072       return V == VN.canonicalize(V, Subtree);
01073     }
01074 #endif
01075 
01076   public:
01077 
01078     ValueRanges(ValueNumbering &VN, TargetData *TD) : VN(VN), TD(TD) {}
01079 
01080 #ifndef NDEBUG
01081     virtual ~ValueRanges() {}
01082 
01083     virtual void dump() const {
01084       dump(*cerr.stream());
01085     }
01086 
01087     void dump(std::ostream &os) const {
01088       for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
01089         os << (i+1) << " = ";
01090         Ranges[i].dump(os);
01091         os << "\n";
01092       }
01093     }
01094 #endif
01095 
01096     /// range - looks up the ConstantRange associated with a value number.
01097     ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
01098       assert(VN.value(n)); // performs range checks
01099 
01100       if (n <= Ranges.size()) {
01101         ScopedRange::iterator I = Ranges[n-1].find(Subtree);
01102         if (I != Ranges[n-1].end()) return I->second;
01103       }
01104 
01105       Value *V = VN.value(n);
01106       ConstantRange CR = range(V);
01107       return CR;
01108     }
01109 
01110     /// range - determine a range from a Value without performing any lookups.
01111     ConstantRange range(Value *V) const {
01112       if (ConstantInt *C = dyn_cast<ConstantInt>(V))
01113         return ConstantRange(C->getValue());
01114       else if (isa<ConstantPointerNull>(V))
01115         return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
01116       else
01117         return ConstantRange(typeToWidth(V->getType()));
01118     }
01119 
01120     // typeToWidth - returns the number of bits necessary to store a value of
01121     // this type, or zero if unknown.
01122     uint32_t typeToWidth(const Type *Ty) const {
01123       if (TD)
01124         return TD->getTypeSizeInBits(Ty);
01125       else
01126         return Ty->getPrimitiveSizeInBits();
01127     }
01128 
01129     static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
01130                             LatticeVal LV) {
01131       switch (LV) {
01132       default: assert(!"Impossible lattice value!");
01133       case NE:
01134         return CR1.maximalIntersectWith(CR2).isEmptySet();
01135       case ULT:
01136         return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
01137       case ULE:
01138         return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
01139       case UGT:
01140         return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
01141       case UGE:
01142         return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
01143       case SLT:
01144         return CR1.getSignedMax().slt(CR2.getSignedMin());
01145       case SLE:
01146         return CR1.getSignedMax().sle(CR2.getSignedMin());
01147       case SGT:
01148         return CR1.getSignedMin().sgt(CR2.getSignedMax());
01149       case SGE:
01150         return CR1.getSignedMin().sge(CR2.getSignedMax());
01151       case LT:
01152         return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
01153                CR1.getSignedMax().slt(CR2.getUnsignedMin());
01154       case LE:
01155         return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
01156                CR1.getSignedMax().sle(CR2.getUnsignedMin());
01157       case GT:
01158         return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
01159                CR1.getSignedMin().sgt(CR2.getSignedMax());
01160       case GE:
01161         return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
01162                CR1.getSignedMin().sge(CR2.getSignedMax());
01163       case SLTUGT:
01164         return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
01165                CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
01166       case SLEUGE:
01167         return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
01168                CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
01169       case SGTULT:
01170         return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
01171                CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
01172       case SGEULE:
01173         return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
01174                CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
01175       }
01176     }
01177 
01178     bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
01179                      LatticeVal LV) {
01180       ConstantRange CR1 = range(n1, Subtree);
01181       ConstantRange CR2 = range(n2, Subtree);
01182 
01183       // True iff all values in CR1 are LV to all values in CR2.
01184       return isRelatedBy(CR1, CR2, LV);
01185     }
01186 
01187     void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
01188                        VRPSolver *VRP);
01189     void markBlock(VRPSolver *VRP);
01190 
01191     void mergeInto(Value **I, unsigned n, unsigned New,
01192                    DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
01193       ConstantRange CR_New = range(New, Subtree);
01194       ConstantRange Merged = CR_New;
01195 
01196       for (; n != 0; ++I, --n) {
01197         unsigned i = VN.valueNumber(*I, Subtree);
01198         ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
01199         if (CR_Kill.isFullSet()) continue;
01200         Merged = Merged.maximalIntersectWith(CR_Kill);
01201       }
01202 
01203       if (Merged.isFullSet() || Merged == CR_New) return;
01204 
01205       applyRange(New, Merged, Subtree, VRP);
01206     }
01207 
01208     void applyRange(unsigned n, const ConstantRange &CR,
01209                     DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
01210       ConstantRange Merged = CR.maximalIntersectWith(range(n, Subtree));
01211       if (Merged.isEmptySet()) {
01212         markBlock(VRP);
01213         return;
01214       }
01215 
01216       if (const APInt *I = Merged.getSingleElement()) {
01217         Value *V = VN.value(n); // XXX: redesign worklist.
01218         const Type *Ty = V->getType();
01219         if (Ty->isInteger()) {
01220           addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
01221           return;
01222         } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
01223           assert(*I == 0 && "Pointer is null but not zero?");
01224           addToWorklist(V, ConstantPointerNull::get(PTy),
01225                         ICmpInst::ICMP_EQ, VRP);
01226           return;
01227         }
01228       }
01229 
01230       update(n, Merged, Subtree);
01231     }
01232 
01233     void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
01234                       VRPSolver *VRP) {
01235       ConstantRange CR1 = range(n1, Subtree);
01236       ConstantRange CR2 = range(n2, Subtree);
01237 
01238       uint32_t W = CR1.getBitWidth();
01239 
01240       if (const APInt *I = CR1.getSingleElement()) {
01241         if (CR2.isFullSet()) {
01242           ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
01243           applyRange(n2, NewCR2, Subtree, VRP);
01244         } else if (*I == CR2.getLower()) {
01245           APInt NewLower(CR2.getLower() + 1),
01246                 NewUpper(CR2.getUpper());
01247           if (NewLower == NewUpper)
01248             NewLower = NewUpper = APInt::getMinValue(W);
01249 
01250           ConstantRange NewCR2(NewLower, NewUpper);
01251           applyRange(n2, NewCR2, Subtree, VRP);
01252         } else if (*I == CR2.getUpper() - 1) {
01253           APInt NewLower(CR2.getLower()),
01254                 NewUpper(CR2.getUpper() - 1);
01255           if (NewLower == NewUpper)
01256             NewLower = NewUpper = APInt::getMinValue(W);
01257 
01258           ConstantRange NewCR2(NewLower, NewUpper);
01259           applyRange(n2, NewCR2, Subtree, VRP);
01260         }
01261       }
01262 
01263       if (const APInt *I = CR2.getSingleElement()) {
01264         if (CR1.isFullSet()) {
01265           ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
01266           applyRange(n1, NewCR1, Subtree, VRP);
01267         } else if (*I == CR1.getLower()) {
01268           APInt NewLower(CR1.getLower() + 1),
01269                 NewUpper(CR1.getUpper());
01270           if (NewLower == NewUpper)
01271             NewLower = NewUpper = APInt::getMinValue(W);
01272 
01273           ConstantRange NewCR1(NewLower, NewUpper);
01274           applyRange(n1, NewCR1, Subtree, VRP);
01275         } else if (*I == CR1.getUpper() - 1) {
01276           APInt NewLower(CR1.getLower()),
01277                 NewUpper(CR1.getUpper() - 1);
01278           if (NewLower == NewUpper)
01279             NewLower = NewUpper = APInt::getMinValue(W);
01280 
01281           ConstantRange NewCR1(NewLower, NewUpper);
01282           applyRange(n1, NewCR1, Subtree, VRP);
01283         }
01284       }
01285     }
01286 
01287     void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
01288                        LatticeVal LV, VRPSolver *VRP) {
01289       assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
01290 
01291       if (LV == NE) {
01292         addNotEquals(n1, n2, Subtree, VRP);
01293         return;
01294       }
01295 
01296       ConstantRange CR1 = range(n1, Subtree);
01297       ConstantRange CR2 = range(n2, Subtree);
01298 
01299       if (!CR1.isSingleElement()) {
01300         ConstantRange NewCR1 = CR1.maximalIntersectWith(create(LV, CR2));
01301         if (NewCR1 != CR1)
01302           applyRange(n1, NewCR1, Subtree, VRP);
01303       }
01304 
01305       if (!CR2.isSingleElement()) {
01306         ConstantRange NewCR2 = CR2.maximalIntersectWith(
01307                                        create(reversePredicate(LV), CR1));
01308         if (NewCR2 != CR2)
01309           applyRange(n2, NewCR2, Subtree, VRP);
01310       }
01311     }
01312   };
01313 
01314   /// UnreachableBlocks keeps tracks of blocks that are for one reason or
01315   /// another discovered to be unreachable. This is used to cull the graph when
01316   /// analyzing instructions, and to mark blocks with the "unreachable"
01317   /// terminator instruction after the function has executed.
01318   class VISIBILITY_HIDDEN UnreachableBlocks {
01319   private:
01320     std::vector<BasicBlock *> DeadBlocks;
01321 
01322   public:
01323     /// mark - mark a block as dead
01324     void mark(BasicBlock *BB) {
01325       std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
01326       std::vector<BasicBlock *>::iterator I =
01327         std::lower_bound(DeadBlocks.begin(), E, BB);
01328 
01329       if (I == E || *I != BB) DeadBlocks.insert(I, BB);
01330     }
01331 
01332     /// isDead - returns whether a block is known to be dead already
01333     bool isDead(BasicBlock *BB) {
01334       std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
01335       std::vector<BasicBlock *>::iterator I =
01336         std::lower_bound(DeadBlocks.begin(), E, BB);
01337 
01338       return I != E && *I == BB;
01339     }
01340 
01341     /// kill - replace the dead blocks' terminator with an UnreachableInst.
01342     bool kill() {
01343       bool modified = false;
01344       for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
01345            E = DeadBlocks.end(); I != E; ++I) {
01346         BasicBlock *BB = *I;
01347 
01348         DOUT << "unreachable block: " << BB->getName() << "\n";
01349 
01350         for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
01351              SI != SE; ++SI) {
01352           BasicBlock *Succ = *SI;
01353           Succ->removePredecessor(BB);
01354         }
01355 
01356         TerminatorInst *TI = BB->getTerminator();
01357         TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
01358         TI->eraseFromParent();
01359         new UnreachableInst(BB);
01360         ++NumBlocks;
01361         modified = true;
01362       }
01363       DeadBlocks.clear();
01364       return modified;
01365     }
01366   };
01367 
01368   /// VRPSolver keeps track of how changes to one variable affect other
01369   /// variables, and forwards changes along to the InequalityGraph. It
01370   /// also maintains the correct choice for "canonical" in the IG.
01371   /// @brief VRPSolver calculates inferences from a new relationship.
01372   class VISIBILITY_HIDDEN VRPSolver {
01373   private:
01374     friend class ValueRanges;
01375 
01376     struct Operation {
01377       Value *LHS, *RHS;
01378       ICmpInst::Predicate Op;
01379 
01380       BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
01381       Instruction *ContextInst;
01382     };
01383     std::deque<Operation> WorkList;
01384 
01385     ValueNumbering &VN;
01386     InequalityGraph &IG;
01387     UnreachableBlocks &UB;
01388     ValueRanges &VR;
01389     DomTreeDFS *DTDFS;
01390     DomTreeDFS::Node *Top;
01391     BasicBlock *TopBB;
01392     Instruction *TopInst;
01393     bool &modified;
01394 
01395     typedef InequalityGraph::Node Node;
01396 
01397     // below - true if the Instruction is dominated by the current context
01398     // block or instruction
01399     bool below(Instruction *I) {
01400       BasicBlock *BB = I->getParent();
01401       if (TopInst && TopInst->getParent() == BB) {
01402         if (isa<TerminatorInst>(TopInst)) return false;
01403         if (isa<TerminatorInst>(I)) return true;
01404         if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
01405         if (!isa<PHINode>(TopInst) &&  isa<PHINode>(I)) return false;
01406 
01407         for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
01408              Iter != E; ++Iter) {
01409           if (&*Iter == TopInst) return true;
01410           else if (&*Iter == I) return false;
01411         }
01412         assert(!"Instructions not found in parent BasicBlock?");
01413       } else {
01414         DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
01415         if (!Node) return false;
01416         return Top->dominates(Node);
01417       }
01418       return false; // Not reached
01419     }
01420 
01421     // aboveOrBelow - true if the Instruction either dominates or is dominated
01422     // by the current context block or instruction
01423     bool aboveOrBelow(Instruction *I) {
01424       BasicBlock *BB = I->getParent();
01425       DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
01426       if (!Node) return false;
01427 
01428       return Top == Node || Top->dominates(Node) || Node->dominates(Top);
01429     }
01430 
01431     bool makeEqual(Value *V1, Value *V2) {
01432       DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
01433       DOUT << "context is ";
01434       if (TopInst) DOUT << "I: " << *TopInst << "\n";
01435       else DOUT << "BB: " << TopBB->getName()
01436                 << "(" << Top->getDFSNumIn() << ")\n";
01437 
01438       assert(V1->getType() == V2->getType() &&
01439              "Can't make two values with different types equal.");
01440 
01441       if (V1 == V2) return true;
01442 
01443       if (isa<Constant>(V1) && isa<Constant>(V2))
01444         return false;
01445 
01446       unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
01447 
01448       if (n1 && n2) {
01449         if (n1 == n2) return true;
01450         if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
01451       }
01452 
01453       if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
01454       if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
01455 
01456       assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
01457 
01458       assert(!isa<Constant>(V2) && "Tried to remove a constant.");
01459 
01460       SetVector<unsigned> Remove;
01461       if (n2) Remove.insert(n2);
01462 
01463       if (n1 && n2) {
01464         // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
01465         // We can't just merge %x and %y because the relationship with %z would
01466         // be EQ and that's invalid. What we're doing is looking for any nodes
01467         // %z such that %x <= %z and %y >= %z, and vice versa.
01468 
01469         Node::iterator end = IG.node(n2)->end();
01470 
01471         // Find the intersection between N1 and N2 which is dominated by
01472         // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
01473         // Remove.
01474         for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
01475              I != E; ++I) {
01476           if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
01477 
01478           unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
01479           unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
01480           Node::iterator NI = IG.node(n2)->find(I->To, Top);
01481           if (NI != end) {
01482             LatticeVal NILV = reversePredicate(NI->LV);
01483             unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
01484             unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
01485 
01486             if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
01487                 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
01488               Remove.insert(I->To);
01489           }
01490         }
01491 
01492         // See if one of the nodes about to be removed is actually a better
01493         // canonical choice than n1.
01494         unsigned orig_n1 = n1;
01495         SetVector<unsigned>::iterator DontRemove = Remove.end();
01496         for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
01497              E = Remove.end(); I != E; ++I) {
01498           unsigned n = *I;
01499           Value *V = VN.value(n);
01500           if (VN.compare(V, V1)) {
01501             V1 = V;
01502             n1 = n;
01503             DontRemove = I;
01504           }
01505         }
01506         if (DontRemove != Remove.end()) {
01507           unsigned n = *DontRemove;
01508           Remove.remove(n);
01509           Remove.insert(orig_n1);
01510         }
01511       }
01512 
01513       // We'd like to allow makeEqual on two values to perform a simple
01514       // substitution without creating nodes in the IG whenever possible.
01515       //
01516       // The first iteration through this loop operates on V2 before going
01517       // through the Remove list and operating on those too. If all of the
01518       // iterations performed simple replacements then we exit early.
01519       bool mergeIGNode = false;
01520       unsigned i = 0;
01521       for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
01522         if (i) R = VN.value(Remove[i]); // skip n2.
01523 
01524         // Try to replace the whole instruction. If we can, we're done.
01525         Instruction *I2 = dyn_cast<Instruction>(R);
01526         if (I2 && below(I2)) {
01527           std::vector<Instruction *> ToNotify;
01528           for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
01529                UI != UE;) {
01530             Use &TheUse = UI.getUse();
01531             ++UI;
01532             if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
01533               ToNotify.push_back(I);
01534           }
01535 
01536           DOUT << "Simply removing " << *I2
01537                << ", replacing with " << *V1 << "\n";
01538           I2->replaceAllUsesWith(V1);
01539           // leave it dead; it'll get erased later.
01540           ++NumInstruction;
01541           modified = true;
01542 
01543           for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
01544                IE = ToNotify.end(); II != IE; ++II) {
01545             opsToDef(*II);
01546           }
01547 
01548           continue;
01549         }
01550 
01551         // Otherwise, replace all dominated uses.
01552         for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
01553              UI != UE;) {
01554           Use &TheUse = UI.getUse();
01555           ++UI;
01556           if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
01557             if (below(I)) {
01558               TheUse.set(V1);
01559               modified = true;
01560               ++NumVarsReplaced;
01561               opsToDef(I);
01562             }
01563           }
01564         }
01565 
01566         // If that killed the instruction, stop here.
01567         if (I2 && isInstructionTriviallyDead(I2)) {
01568           DOUT << "Killed all uses of " << *I2
01569                << ", replacing with " << *V1 << "\n";
01570           continue;
01571         }
01572 
01573         // If we make it to here, then we will need to create a node for N1.
01574         // Otherwise, we can skip out early!
01575         mergeIGNode = true;
01576       }
01577 
01578       if (!isa<Constant>(V1)) {
01579         if (Remove.empty()) {
01580           VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
01581         } else {
01582           std::vector<Value*> RemoveVals;
01583           RemoveVals.reserve(Remove.size());
01584 
01585           for (SetVector<unsigned>::iterator I = Remove.begin(),
01586                E = Remove.end(); I != E; ++I) {
01587             Value *V = VN.value(*I);
01588             if (!V->use_empty())
01589               RemoveVals.push_back(V);
01590           }
01591           VR.mergeInto(&RemoveVals[0], RemoveVals.size(), 
01592                        VN.getOrInsertVN(V1, Top), Top, this);
01593         }
01594       }
01595 
01596       if (mergeIGNode) {
01597         // Create N1.
01598         if (!n1) n1 = VN.getOrInsertVN(V1, Top);
01599         IG.node(n1); // Ensure that IG.Nodes won't get resized
01600 
01601         // Migrate relationships from removed nodes to N1.
01602         for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
01603              I != E; ++I) {
01604           unsigned n = *I;
01605           for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
01606                NI != NE; ++NI) {
01607             if (NI->Subtree->DominatedBy(Top)) {
01608               if (NI->To == n1) {
01609                 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
01610                 continue;
01611               }
01612               if (Remove.count(NI->To))
01613                 continue;
01614 
01615               IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
01616               IG.node(n1)->update(NI->To, NI->LV, Top);
01617             }
01618           }
01619         }
01620 
01621         // Point V2 (and all items in Remove) to N1.
01622         if (!n2)
01623           VN.addEquality(n1, V2, Top);
01624         else {
01625           for (SetVector<unsigned>::iterator I = Remove.begin(),
01626                E = Remove.end(); I != E; ++I) {
01627             VN.addEquality(n1, VN.value(*I), Top);
01628           }
01629         }
01630 
01631         // If !Remove.empty() then V2 = Remove[0]->getValue().
01632         // Even when Remove is empty, we still want to process V2.
01633         i = 0;
01634         for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
01635           if (i) R = VN.value(Remove[i]); // skip n2.
01636 
01637           if (Instruction *I2 = dyn_cast<Instruction>(R)) {
01638             if (aboveOrBelow(I2))
01639             defToOps(I2);
01640           }
01641           for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
01642                UI != UE;) {
01643             Use &TheUse = UI.getUse();
01644             ++UI;
01645             if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
01646               if (aboveOrBelow(I))
01647                 opsToDef(I);
01648             }
01649           }
01650         }
01651       }
01652 
01653       // re-opsToDef all dominated users of V1.
01654       if (Instruction *I = dyn_cast<Instruction>(V1)) {
01655         for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
01656              UI != UE;) {
01657           Use &TheUse = UI.getUse();
01658           ++UI;
01659           Value *V = TheUse.getUser();
01660           if (!V->use_empty()) {
01661             if (Instruction *Inst = dyn_cast<Instruction>(V)) {
01662               if (aboveOrBelow(Inst))
01663                 opsToDef(Inst);
01664             }
01665           }
01666         }
01667       }
01668 
01669       return true;
01670     }
01671 
01672     /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
01673     /// Requires that the lattice value be valid; does not accept ICMP_EQ.
01674     static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
01675       switch (Pred) {
01676         case ICmpInst::ICMP_EQ:
01677           assert(!"No matching lattice value.");
01678           return static_cast<LatticeVal>(EQ_BIT);
01679         default:
01680           assert(!"Invalid 'icmp' predicate.");
01681         case ICmpInst::ICMP_NE:
01682           return NE;
01683         case ICmpInst::ICMP_UGT:
01684           return UGT;
01685         case ICmpInst::ICMP_UGE:
01686           return UGE;
01687         case ICmpInst::ICMP_ULT:
01688           return ULT;
01689         case ICmpInst::ICMP_ULE:
01690           return ULE;
01691         case ICmpInst::ICMP_SGT:
01692           return SGT;
01693         case ICmpInst::ICMP_SGE:
01694           return SGE;
01695         case ICmpInst::ICMP_SLT:
01696           return SLT;
01697         case ICmpInst::ICMP_SLE:
01698           return SLE;
01699       }
01700     }
01701 
01702   public:
01703     VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
01704               ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
01705               BasicBlock *TopBB)
01706       : VN(VN),
01707         IG(IG),
01708         UB(UB),
01709         VR(VR),
01710         DTDFS(DTDFS),
01711         Top(DTDFS->getNodeForBlock(TopBB)),
01712         TopBB(TopBB),
01713         TopInst(NULL),
01714         modified(modified)
01715     {
01716       assert(Top && "VRPSolver created for unreachable basic block.");
01717     }
01718 
01719     VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
01720               ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
01721               Instruction *TopInst)
01722       : VN(VN),
01723         IG(IG),
01724         UB(UB),
01725         VR(VR),
01726         DTDFS(DTDFS),
01727         Top(DTDFS->getNodeForBlock(TopInst->getParent())),
01728         TopBB(TopInst->getParent()),
01729         TopInst(TopInst),
01730         modified(modified)
01731     {
01732       assert(Top && "VRPSolver created for unreachable basic block.");
01733       assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
01734     }
01735 
01736     bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
01737       if (Constant *C1 = dyn_cast<Constant>(V1))
01738         if (Constant *C2 = dyn_cast<Constant>(V2))
01739           return ConstantExpr::getCompare(Pred, C1, C2) ==
01740                  ConstantInt::getTrue();
01741 
01742       unsigned n1 = VN.valueNumber(V1, Top);
01743       unsigned n2 = VN.valueNumber(V2, Top);
01744 
01745       if (n1 && n2) {
01746         if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
01747                              Pred == ICmpInst::ICMP_ULE ||
01748                              Pred == ICmpInst::ICMP_UGE ||
01749                              Pred == ICmpInst::ICMP_SLE ||
01750                              Pred == ICmpInst::ICMP_SGE;
01751         if (Pred == ICmpInst::ICMP_EQ) return false;
01752         if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
01753         if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
01754       }
01755 
01756       if ((n1 && !n2 && isa<Constant>(V2)) ||
01757           (n2 && !n1 && isa<Constant>(V1))) {
01758         ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
01759         ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
01760 
01761         if (Pred == ICmpInst::ICMP_EQ)
01762           return CR1.isSingleElement() &&
01763                  CR1.getSingleElement() == CR2.getSingleElement();
01764 
01765         return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
01766       }
01767       if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
01768       return false;
01769     }
01770 
01771     /// add - adds a new property to the work queue
01772     void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
01773              Instruction *I = NULL) {
01774       DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
01775       if (I) DOUT << " context: " << *I;
01776       else DOUT << " default context (" << Top->getDFSNumIn() << ")";
01777       DOUT << "\n";
01778 
01779       assert(V1->getType() == V2->getType() &&
01780              "Can't relate two values with different types.");
01781 
01782       WorkList.push_back(Operation());
01783       Operation &O = WorkList.back();
01784       O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
01785       O.ContextBB = I ? I->getParent() : TopBB;
01786     }
01787 
01788     /// defToOps - Given an instruction definition that we've learned something
01789     /// new about, find any new relationships between its operands.
01790     void defToOps(Instruction *I) {
01791       Instruction *NewContext = below(I) ? I : TopInst;
01792       Value *Canonical = VN.canonicalize(I, Top);
01793 
01794       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
01795         const Type *Ty = BO->getType();
01796         assert(!Ty->isFPOrFPVector() && "Float in work queue!");
01797 
01798         Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
01799         Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
01800 
01801         // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
01802 
01803         switch (BO->getOpcode()) {
01804           case Instruction::And: {
01805             // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
01806             ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
01807             if (Canonical == CI) {
01808               add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
01809               add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
01810             }
01811           } break;
01812           case Instruction::Or: {
01813             // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
01814             Constant *Zero = Constant::getNullValue(Ty);
01815             if (Canonical == Zero) {
01816               add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
01817               add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
01818             }
01819           } break;
01820           case Instruction::Xor: {
01821             // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
01822             // "xor i32 %c, %a" EQ %c then %a EQ 0
01823             // "xor i32 %c, %a" NE %c then %a NE 0
01824             // Repeat the above, with order of operands reversed.
01825             Value *LHS = Op0;
01826             Value *RHS = Op1;
01827             if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
01828 
01829             if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
01830               if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
01831                 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
01832                     ICmpInst::ICMP_EQ, NewContext);
01833               }
01834             }
01835             if (Canonical == LHS) {
01836               if (isa<ConstantInt>(Canonical))
01837                 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
01838                     NewContext);
01839             } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
01840               add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
01841                   NewContext);
01842             }
01843           } break;
01844           default:
01845             break;
01846         }
01847       } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
01848         // "icmp ult i32 %a, %y" EQ true then %a u< y
01849         // etc.
01850 
01851         if (Canonical == ConstantInt::getTrue()) {
01852           add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
01853               NewContext);
01854         } else if (Canonical == ConstantInt::getFalse()) {
01855           add(IC->getOperand(0), IC->getOperand(1),
01856               ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
01857         }
01858       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
01859         if (I->getType()->isFPOrFPVector()) return;
01860 
01861         // Given: "%a = select i1 %x, i32 %b, i32 %c"
01862         // %a EQ %b and %b NE %c then %x EQ true
01863         // %a EQ %c and %b NE %c then %x EQ false
01864 
01865         Value *True  = SI->getTrueValue();
01866         Value *False = SI->getFalseValue();
01867         if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
01868           if (Canonical == VN.canonicalize(True, Top) ||
01869               isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
01870             add(SI->getCondition(), ConstantInt::getTrue(),
01871                 ICmpInst::ICMP_EQ, NewContext);
01872           else if (Canonical == VN.canonicalize(False, Top) ||
01873                    isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
01874             add(SI->getCondition(), ConstantInt::getFalse(),
01875                 ICmpInst::ICMP_EQ, NewContext);
01876         }
01877       } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
01878         for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
01879              OE = GEPI->idx_end(); OI != OE; ++OI) {
01880           ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
01881           if (!Op || !Op->isZero()) return;
01882         }
01883         // TODO: The GEPI indices are all zero. Copy from definition to operand,
01884         // jumping the type plane as needed.
01885         if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
01886                         ICmpInst::ICMP_NE)) {
01887           Value *Ptr = GEPI->getPointerOperand();
01888           add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
01889               NewContext);
01890         }
01891       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
01892         const Type *SrcTy = CI->getSrcTy();
01893 
01894         unsigned ci = VN.getOrInsertVN(CI, Top);
01895         uint32_t W = VR.typeToWidth(SrcTy);
01896         if (!W) return;
01897         ConstantRange CR = VR.range(ci, Top);
01898 
01899         if (CR.isFullSet()) return;
01900 
01901         switch (CI->getOpcode()) {
01902           default: break;
01903           case Instruction::ZExt:
01904           case Instruction::SExt:
01905             VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
01906                           CR.truncate(W), Top, this);
01907             break;
01908           case Instruction::BitCast:
01909             VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
01910                           CR, Top, this);
01911             break;
01912         }
01913       }
01914     }
01915 
01916     /// opsToDef - A new relationship was discovered involving one of this
01917     /// instruction's operands. Find any new relationship involving the
01918     /// definition, or another operand.
01919     void opsToDef(Instruction *I) {
01920       Instruction *NewContext = below(I) ? I : TopInst;
01921 
01922       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
01923         Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
01924         Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
01925 
01926         if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
01927           if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
01928             add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
01929                 ICmpInst::ICMP_EQ, NewContext);
01930             return;
01931           }
01932 
01933         // "%y = and i1 true, %x" then %x EQ %y
01934         // "%y = or i1 false, %x" then %x EQ %y
01935         // "%x = add i32 %y, 0" then %x EQ %y
01936         // "%x = mul i32 %y, 0" then %x EQ 0
01937 
01938         Instruction::BinaryOps Opcode = BO->getOpcode();
01939         const Type *Ty = BO->getType();
01940         assert(!Ty->isFPOrFPVector() && "Float in work queue!");
01941 
01942         Constant *Zero = Constant::getNullValue(Ty);
01943         Constant *One = ConstantInt::get(Ty, 1);
01944         ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
01945 
01946         switch (Opcode) {
01947           default: break;
01948           case Instruction::LShr:
01949           case Instruction::AShr:
01950           case Instruction::Shl:
01951             if (Op1 == Zero) {
01952               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
01953               return;
01954             }
01955             break;
01956           case Instruction::Sub:
01957             if (Op1 == Zero) {
01958               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
01959               return;
01960             }
01961             if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
01962               unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
01963               ConstantRange CR = VR.range(n_ci0, Top);
01964               if (!CR.isFullSet()) {
01965                 CR.subtract(CI0->getValue());
01966                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
01967                 VR.applyRange(n_bo, CR, Top, this);
01968                 return;
01969               }
01970             }
01971             if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
01972               unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
01973               ConstantRange CR = VR.range(n_ci1, Top);
01974               if (!CR.isFullSet()) {
01975                 CR.subtract(CI1->getValue());
01976                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
01977                 VR.applyRange(n_bo, CR, Top, this);
01978                 return;
01979               }
01980             }
01981             break;
01982           case Instruction::Or:
01983             if (Op0 == AllOnes || Op1 == AllOnes) {
01984               add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
01985               return;
01986             }
01987             if (Op0 == Zero) {
01988               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
01989               return;
01990             } else if (Op1 == Zero) {
01991               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
01992               return;
01993             }
01994             break;
01995           case Instruction::Add:
01996             if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
01997               unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
01998               ConstantRange CR = VR.range(n_ci0, Top);
01999               if (!CR.isFullSet()) {
02000                 CR.subtract(-CI0->getValue());
02001                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
02002                 VR.applyRange(n_bo, CR, Top, this);
02003                 return;
02004               }
02005             }
02006             if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
02007               unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
02008               ConstantRange CR = VR.range(n_ci1, Top);
02009               if (!CR.isFullSet()) {
02010                 CR.subtract(-CI1->getValue());
02011                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
02012                 VR.applyRange(n_bo, CR, Top, this);
02013                 return;
02014               }
02015             }
02016             // fall-through
02017           case Instruction::Xor:
02018             if (Op0 == Zero) {
02019               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
02020               return;
02021             } else if (Op1 == Zero) {
02022               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
02023               return;
02024             }
02025             break;
02026           case Instruction::And:
02027             if (Op0 == AllOnes) {
02028               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
02029               return;
02030             } else if (Op1 == AllOnes) {
02031               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
02032               return;
02033             }
02034             if (Op0 == Zero || Op1 == Zero) {
02035               add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
02036               return;
02037             }
02038             break;
02039           case Instruction::Mul:
02040             if (Op0 == Zero || Op1 == Zero) {
02041               add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
02042               return;
02043             }
02044             if (Op0 == One) {
02045               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
02046               return;
02047             } else if (Op1 == One) {
02048               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
02049               return;
02050             }
02051             break;
02052         }
02053 
02054         // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
02055         // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
02056         // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
02057         // "%x = udiv i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 1
02058 
02059         Value *Known = Op0, *Unknown = Op1,
02060               *TheBO = VN.canonicalize(BO, Top);
02061         if (Known != TheBO) std::swap(Known, Unknown);
02062         if (Known == TheBO) {
02063           switch (Opcode) {
02064             default: break;
02065             case Instruction::LShr:
02066             case Instruction::AShr:
02067             case Instruction::Shl:
02068               if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
02069               // otherwise, fall-through.
02070             case Instruction::Sub:
02071               if (Unknown == Op0) break;
02072               // otherwise, fall-through.
02073             case Instruction::Xor:
02074             case Instruction::Add:
02075               add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
02076               break;
02077             case Instruction::UDiv:
02078             case Instruction::SDiv:
02079               if (Unknown == Op1) break;
02080               if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE))
02081                 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
02082               break;
02083           }
02084         }
02085 
02086         // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
02087 
02088       } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
02089         // "%a = icmp ult i32 %b, %c" and %b u<  %c then %a EQ true
02090         // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
02091         // etc.
02092 
02093         Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
02094         Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
02095 
02096         ICmpInst::Predicate Pred = IC->getPredicate();
02097         if (isRelatedBy(Op0, Op1, Pred))
02098           add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
02099         else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
02100           add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
02101 
02102       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
02103         if (I->getType()->isFPOrFPVector()) return;
02104 
02105         // Given: "%a = select i1 %x, i32 %b, i32 %c"
02106         // %x EQ true  then %a EQ %b
02107         // %x EQ false then %a EQ %c
02108         // %b EQ %c then %a EQ %b
02109 
02110         Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
02111         if (Canonical == ConstantInt::getTrue()) {
02112           add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
02113         } else if (Canonical == ConstantInt::getFalse()) {
02114           add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
02115         } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
02116                    VN.canonicalize(SI->getFalseValue(), Top)) {
02117           add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
02118         }
02119       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
02120         const Type *DestTy = CI->getDestTy();
02121         if (DestTy->isFPOrFPVector()) return;
02122 
02123         Value *Op = VN.canonicalize(CI->getOperand(0), Top);
02124         Instruction::CastOps Opcode = CI->getOpcode();
02125 
02126         if (Constant *C = dyn_cast<Constant>(Op)) {
02127           add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
02128               ICmpInst::ICMP_EQ, NewContext);
02129         }
02130 
02131         uint32_t W = VR.typeToWidth(DestTy);
02132         unsigned ci = VN.getOrInsertVN(CI, Top);
02133         ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
02134 
02135         if (!CR.isFullSet()) {
02136           switch (Opcode) {
02137             default: break;
02138             case Instruction::ZExt:
02139               VR.applyRange(ci, CR.zeroExtend(W), Top, this);
02140               break;
02141             case Instruction::SExt:
02142               VR.applyRange(ci, CR.signExtend(W), Top, this);
02143               break;
02144             case Instruction::Trunc: {
02145               ConstantRange Result = CR.truncate(W);
02146               if (!Result.isFullSet())
02147                 VR.applyRange(ci, Result, Top, this);
02148             } break;
02149             case Instruction::BitCast:
02150               VR.applyRange(ci, CR, Top, this);
02151               break;
02152             // TODO: other casts?
02153           }
02154         }
02155       } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
02156         for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
02157              OE = GEPI->idx_end(); OI != OE; ++OI) {
02158           ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
02159           if (!Op || !Op->isZero()) return;
02160         }
02161         // TODO: The GEPI indices are all zero. Copy from operand to definition,
02162         // jumping the type plane as needed.
02163         Value *Ptr = GEPI->getPointerOperand();
02164         if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
02165                         ICmpInst::ICMP_NE)) {
02166           add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
02167               NewContext);
02168         }
02169       }
02170     }
02171 
02172     /// solve - process the work queue
02173     void solve() {
02174       //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
02175       while (!WorkList.empty()) {
02176         //DOUT << "WorkList size: " << WorkList.size() << "\n";
02177 
02178         Operation &O = WorkList.front();
02179         TopInst = O.ContextInst;
02180         TopBB = O.ContextBB;
02181         Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
02182 
02183         O.LHS = VN.canonicalize(O.LHS, Top);
02184         O.RHS = VN.canonicalize(O.RHS, Top);
02185 
02186         assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
02187         assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
02188 
02189         DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
02190         if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
02191         else DOUT << " context block: " << O.ContextBB->getName();
02192         DOUT << "\n";
02193 
02194         DEBUG(VN.dump());
02195         DEBUG(IG.dump());
02196         DEBUG(VR.dump());
02197 
02198         // If they're both Constant, skip it. Check for contradiction and mark
02199         // the BB as unreachable if so.
02200         if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
02201           if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
02202             if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
02203                 ConstantInt::getFalse())
02204               UB.mark(TopBB);
02205 
02206             WorkList.pop_front();
02207             continue;
02208           }
02209         }
02210 
02211         if (VN.compare(O.LHS, O.RHS)) {
02212           std::swap(O.LHS, O.RHS);
02213           O.Op = ICmpInst::getSwappedPredicate(O.Op);
02214         }
02215 
02216         if (O.Op == ICmpInst::ICMP_EQ) {
02217           if (!makeEqual(O.RHS, O.LHS))
02218             UB.mark(TopBB);
02219         } else {
02220           LatticeVal LV = cmpInstToLattice(O.Op);
02221 
02222           if ((LV & EQ_BIT) &&
02223               isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
02224             if (!makeEqual(O.RHS, O.LHS))
02225               UB.mark(TopBB);
02226           } else {
02227             if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
02228               UB.mark(TopBB);
02229               WorkList.pop_front();
02230               continue;
02231             }
02232 
02233             unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
02234             unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
02235 
02236             if (n1 == n2) {
02237               if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
02238                   O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
02239                 UB.mark(TopBB);
02240 
02241               WorkList.pop_front();
02242               continue;
02243             }
02244 
02245             if (VR.isRelatedBy(n1, n2, Top, LV) ||
02246                 IG.isRelatedBy(n1, n2, Top, LV)) {
02247               WorkList.pop_front();
02248               continue;
02249             }
02250 
02251             VR.addInequality(n1, n2, Top, LV, this);
02252             if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
02253                 LV == NE)
02254               IG.addInequality(n1, n2, Top, LV);
02255 
02256             if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
02257               if (aboveOrBelow(I1))
02258                 defToOps(I1);
02259             }
02260             if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
02261               for (Value::use_iterator UI = O.LHS->use_begin(),
02262                    UE = O.LHS->use_end(); UI != UE;) {
02263                 Use &TheUse = UI.getUse();
02264                 ++UI;
02265                 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
02266                   if (aboveOrBelow(I))
02267                     opsToDef(I);
02268                 }
02269               }
02270             }
02271             if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
02272               if (aboveOrBelow(I2))
02273               defToOps(I2);
02274             }
02275             if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
02276               for (Value::use_iterator UI = O.RHS->use_begin(),
02277                    UE = O.RHS->use_end(); UI != UE;) {
02278                 Use &TheUse = UI.getUse();
02279                 ++UI;
02280                 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
02281                   if (aboveOrBelow(I))
02282                     opsToDef(I);
02283                 }
02284               }
02285             }
02286           }
02287         }
02288         WorkList.pop_front();
02289       }
02290     }
02291   };
02292 
02293   void ValueRanges::addToWorklist(Value *V, Constant *C,
02294                                   ICmpInst::Predicate Pred, VRPSolver *VRP) {
02295     VRP->add(V, C, Pred, VRP->TopInst);
02296   }
02297 
02298   void ValueRanges::markBlock(VRPSolver *VRP) {
02299     VRP->UB.mark(VRP->TopBB);
02300   }
02301 
02302   /// PredicateSimplifier - This class is a simplifier that replaces
02303   /// one equivalent variable with another. It also tracks what
02304   /// can't be equal and will solve setcc instructions when possible.
02305   /// @brief Root of the predicate simplifier optimization.
02306   class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
02307     DomTreeDFS *DTDFS;
02308     bool modified;
02309     ValueNumbering *VN;
02310     InequalityGraph *IG;
02311     UnreachableBlocks UB;
02312     ValueRanges *VR;
02313 
02314     std::vector<DomTreeDFS::Node *> WorkList;
02315 
02316   public:
02317     static char ID; // Pass identification, replacement for typeid
02318     PredicateSimplifier() : FunctionPass(&ID) {}
02319 
02320     bool runOnFunction(Function &F);
02321 
02322     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
02323       AU.addRequiredID(BreakCriticalEdgesID);
02324       AU.addRequired<DominatorTree>();
02325       AU.addRequired<TargetData>();
02326       AU.addPreserved<TargetData>();
02327     }
02328 
02329   private:
02330     /// Forwards - Adds new properties to VRPSolver and uses them to
02331     /// simplify instructions. Because new properties sometimes apply to
02332     /// a transition from one BasicBlock to another, this will use the
02333     /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
02334     /// basic block.
02335     /// @brief Performs abstract execution of the program.
02336     class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
02337       friend class InstVisitor<Forwards>;
02338       PredicateSimplifier *PS;
02339       DomTreeDFS::Node *DTNode;
02340 
02341     public:
02342       ValueNumbering &VN;
02343       InequalityGraph &IG;
02344       UnreachableBlocks &UB;
02345       ValueRanges &VR;
02346 
02347       Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
02348         : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
02349           VR(*PS->VR) {}
02350 
02351       void visitTerminatorInst(TerminatorInst &TI);
02352       void visitBranchInst(BranchInst &BI);
02353       void visitSwitchInst(SwitchInst &SI);
02354 
02355       void visitAllocaInst(AllocaInst &AI);
02356       void visitLoadInst(LoadInst &LI);
02357       void visitStoreInst(StoreInst &SI);
02358 
02359       void visitSExtInst(SExtInst &SI);
02360       void visitZExtInst(ZExtInst &ZI);
02361 
02362       void visitBinaryOperator(BinaryOperator &BO);
02363       void visitICmpInst(ICmpInst &IC);
02364     };
02365   
02366     // Used by terminator instructions to proceed from the current basic
02367     // block to the next. Verifies that "current" dominates "next",
02368     // then calls visitBasicBlock.
02369     void proceedToSuccessors(DomTreeDFS::Node *Current) {
02370       for (DomTreeDFS::Node::iterator I = Current->begin(),
02371            E = Current->end(); I != E; ++I) {
02372         WorkList.push_back(*I);
02373       }
02374     }
02375 
02376     void proceedToSuccessor(DomTreeDFS::Node *Next) {
02377       WorkList.push_back(Next);
02378     }
02379 
02380     // Visits each instruction in the basic block.
02381     void visitBasicBlock(DomTreeDFS::Node *Node) {
02382       BasicBlock *BB = Node->getBlock();
02383       DOUT << "Entering Basic Block: " << BB->getName()
02384            << " (" << Node->getDFSNumIn() << ")\n";
02385       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
02386         visitInstruction(I++, Node);
02387       }
02388     }
02389 
02390     // Tries to simplify each Instruction and add new properties.
02391     void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
02392       DOUT << "Considering instruction " << *I << "\n";
02393       DEBUG(VN->dump());
02394       DEBUG(IG->dump());
02395       DEBUG(VR->dump());
02396 
02397       // Sometimes instructions are killed in earlier analysis.
02398       if (isInstructionTriviallyDead(I)) {
02399         ++NumSimple;
02400         modified = true;
02401         if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
02402           if (VN->value(n) == I) IG->remove(n);
02403         VN->remove(I);
02404         I->eraseFromParent();
02405         return;
02406       }
02407 
02408 #ifndef NDEBUG
02409       // Try to replace the whole instruction.
02410       Value *V = VN->canonicalize(I, DT);
02411       assert(V == I && "Late instruction canonicalization.");
02412       if (V != I) {
02413         modified = true;
02414         ++NumInstruction;
02415         DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
02416         if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
02417           if (VN->value(n) == I) IG->remove(n);
02418         VN->remove(I);
02419         I->replaceAllUsesWith(V);
02420         I->eraseFromParent();
02421         return;
02422       }
02423 
02424       // Try to substitute operands.
02425       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
02426         Value *Oper = I->getOperand(i);
02427         Value *V = VN->canonicalize(Oper, DT);
02428         assert(V == Oper && "Late operand canonicalization.");
02429         if (V != Oper) {
02430           modified = true;
02431           ++NumVarsReplaced;
02432           DOUT << "Resolving " << *I;
02433           I->setOperand(i, V);
02434           DOUT << " into " << *I;
02435         }
02436       }
02437 #endif
02438 
02439       std::string name = I->getParent()->getName();
02440       DOUT << "push (%" << name << ")\n";
02441       Forwards visit(this, DT);
02442       visit.visit(*I);
02443       DOUT << "pop (%" << name << ")\n";
02444     }
02445   };
02446 
02447   bool PredicateSimplifier::runOnFunction(Function &F) {
02448     DominatorTree *DT = &getAnalysis<DominatorTree>();
02449     DTDFS = new DomTreeDFS(DT);
02450     TargetData *TD = &getAnalysis<TargetData>();
02451 
02452     DOUT << "Entering Function: " << F.getName() << "\n";
02453 
02454     modified = false;
02455     DomTreeDFS::Node *Root = DTDFS->getRootNode();
02456     VN = new ValueNumbering(DTDFS);
02457     IG = new InequalityGraph(*VN, Root);
02458     VR = new ValueRanges(*VN, TD);
02459     WorkList.push_back(Root);
02460 
02461     do {
02462       DomTreeDFS::Node *DTNode = WorkList.back();
02463       WorkList.pop_back();
02464       if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
02465     } while (!WorkList.empty());
02466 
02467     delete DTDFS;
02468     delete VR;
02469     delete IG;
02470     delete VN;
02471 
02472     modified |= UB.kill();
02473 
02474     return modified;
02475   }
02476 
02477   void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
02478     PS->proceedToSuccessors(DTNode);
02479   }
02480 
02481   void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
02482     if (BI.isUnconditional()) {
02483       PS->proceedToSuccessors(DTNode);
02484       return;
02485     }
02486 
02487     Value *Condition = BI.getCondition();
02488     BasicBlock *TrueDest  = BI.getSuccessor(0);
02489     BasicBlock *FalseDest = BI.getSuccessor(1);
02490 
02491     if (isa<Constant>(Condition) || TrueDest == FalseDest) {
02492       PS->proceedToSuccessors(DTNode);
02493       return;
02494     }
02495 
02496     for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
02497          I != E; ++I) {
02498       BasicBlock *Dest = (*I)->getBlock();
02499       DOUT << "Branch thinking about %" << Dest->getName()
02500            << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
02501 
02502       if (Dest == TrueDest) {
02503         DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
02504         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
02505         VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
02506         VRP.solve();
02507         DEBUG(VN.dump());
02508         DEBUG(IG.dump());
02509         DEBUG(VR.dump());
02510       } else if (Dest == FalseDest) {
02511         DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
02512         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
02513         VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
02514         VRP.solve();
02515         DEBUG(VN.dump());
02516         DEBUG(IG.dump());
02517         DEBUG(VR.dump());
02518       }
02519 
02520       PS->proceedToSuccessor(*I);
02521     }
02522   }
02523 
02524   void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
02525     Value *Condition = SI.getCondition();
02526 
02527     // Set the EQProperty in each of the cases BBs, and the NEProperties
02528     // in the default BB.
02529 
02530     for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
02531          I != E; ++I) {
02532       BasicBlock *BB = (*I)->getBlock();
02533       DOUT << "Switch thinking about BB %" << BB->getName()
02534            << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
02535 
02536       VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
02537       if (BB == SI.getDefaultDest()) {
02538         for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
02539           if (SI.getSuccessor(i) != BB)
02540             VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
02541         VRP.solve();
02542       } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
02543         VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
02544         VRP.solve();
02545       }
02546       PS->proceedToSuccessor(*I);
02547     }
02548   }
02549 
02550   void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
02551     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
02552     VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
02553     VRP.solve();
02554   }
02555 
02556   void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
02557     Value *Ptr = LI.getPointerOperand();
02558     // avoid "load i8* null" -> null NE null.
02559     if (isa<Constant>(Ptr)) return;
02560 
02561     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
02562     VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
02563     VRP.solve();
02564   }
02565 
02566   void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
02567     Value *Ptr = SI.getPointerOperand();
02568     if (isa<Constant>(Ptr)) return;
02569 
02570     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
02571     VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
02572     VRP.solve();
02573   }
02574 
02575   void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
02576     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
02577     uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
02578     uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
02579     APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
02580     APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
02581     VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
02582     VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
02583     VRP.solve();
02584   }
02585 
02586   void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
02587     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
02588     uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
02589     uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
02590     APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
02591     VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
02592     VRP.solve();
02593   }
02594 
02595   void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
02596     Instruction::BinaryOps ops = BO.getOpcode();
02597 
02598     switch (ops) {
02599     default: break;
02600       case Instruction::URem:
02601       case Instruction::SRem:
02602       case Instruction::UDiv:
02603       case Instruction::SDiv: {
02604         Value *Divisor = BO.getOperand(1);
02605         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02606         VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
02607                 ICmpInst::ICMP_NE);
02608         VRP.solve();
02609         break;
02610       }
02611     }
02612 
02613     switch (ops) {
02614       default: break;
02615       case Instruction::Shl: {
02616         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02617         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
02618         VRP.solve();
02619       } break;
02620       case Instruction::AShr: {
02621         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02622         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
02623         VRP.solve();
02624       } break;
02625       case Instruction::LShr:
02626       case Instruction::UDiv: {
02627         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02628         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
02629         VRP.solve();
02630       } break;
02631       case Instruction::URem: {
02632         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02633         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
02634         VRP.solve();
02635       } break;
02636       case Instruction::And: {
02637         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02638         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
02639         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
02640         VRP.solve();
02641       } break;
02642       case Instruction::Or: {
02643         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02644         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
02645         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
02646         VRP.solve();
02647       } break;
02648     }
02649   }
02650 
02651   void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
02652     // If possible, squeeze the ICmp predicate into something simpler.
02653     // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
02654     // the predicate to eq.
02655 
02656     // XXX: once we do full PHI handling, modifying the instruction in the
02657     // Forwards visitor will cause missed optimizations.
02658 
02659     ICmpInst::Predicate Pred = IC.getPredicate();
02660 
02661     switch (Pred) {
02662       default: break;
02663       case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
02664       case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
02665       case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
02666       case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
02667     }
02668     if (Pred != IC.getPredicate()) {
02669       VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
02670       if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
02671                           ICmpInst::ICMP_NE)) {
02672         ++NumSnuggle;
02673         PS->modified = true;
02674         IC.setPredicate(Pred);
02675       }
02676     }
02677 
02678     Pred = IC.getPredicate();
02679 
02680     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
02681       ConstantInt *NextVal = 0;
02682       switch (Pred) {
02683         default: break;
02684         case ICmpInst::ICMP_SLT:
02685         case ICmpInst::ICMP_ULT:
02686           if (Op1->getValue() != 0)
02687             NextVal = ConstantInt::get(Op1->getValue()-1);
02688          break;
02689         case ICmpInst::ICMP_SGT:
02690         case ICmpInst::ICMP_UGT:
02691           if (!Op1->getValue().isAllOnesValue())
02692             NextVal = ConstantInt::get(Op1->getValue()+1);
02693          break;
02694       }
02695 
02696       if (NextVal) {
02697         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
02698         if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
02699                             ICmpInst::getInversePredicate(Pred))) {
02700           ICmpInst *NewIC = new ICmpInst(ICmpInst::ICMP_EQ, IC.getOperand(0),
02701                                          NextVal, "", &IC);
02702           NewIC->takeName(&IC);
02703           IC.replaceAllUsesWith(NewIC);
02704 
02705           // XXX: prove this isn't necessary
02706           if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
02707             if (VN.value(n) == &IC) IG.remove(n);
02708           VN.remove(&IC);
02709 
02710           IC.eraseFromParent();
02711           ++NumSnuggle;
02712           PS->modified = true;
02713         }
02714       }
02715     }
02716   }
02717 }
02718 
02719 char PredicateSimplifier::ID = 0;
02720 static RegisterPass<PredicateSimplifier>
02721 X("predsimplify", "Predicate Simplifier");
02722 
02723 FunctionPass *llvm::createPredicateSimplifierPass() {
02724   return new PredicateSimplifier();
02725 }