move some functions, add a comment.
[oota-llvm.git] / lib / Transforms / Scalar / PredicateSimplifier.cpp
1 //===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Path-sensitive optimizer. In a branch where x == y, replace uses of
11 // x with y. Permits further optimization, such as the elimination of
12 // the unreachable call:
13 //
14 // void test(int *p, int *q)
15 // {
16 //   if (p != q)
17 //     return;
18 // 
19 //   if (*p != *q)
20 //     foo(); // unreachable
21 // }
22 //
23 //===----------------------------------------------------------------------===//
24 //
25 // The InequalityGraph focusses on four properties; equals, not equals,
26 // less-than and less-than-or-equals-to. The greater-than forms are also held
27 // just to allow walking from a lesser node to a greater one. These properties
28 // are stored in a lattice; LE can become LT or EQ, NE can become LT or GT.
29 //
30 // These relationships define a graph between values of the same type. Each
31 // Value is stored in a map table that retrieves the associated Node. This
32 // is how EQ relationships are stored; the map contains pointers from equal
33 // Value to the same node. The node contains a most canonical Value* form
34 // and the list of known relationships with other nodes.
35 //
36 // If two nodes are known to be inequal, then they will contain pointers to
37 // each other with an "NE" relationship. If node getNode(%x) is less than
38 // getNode(%y), then the %x node will contain <%y, GT> and %y will contain
39 // <%x, LT>. This allows us to tie nodes together into a graph like this:
40 //
41 //   %a < %b < %c < %d
42 //
43 // with four nodes representing the properties. The InequalityGraph provides
44 // querying with "isRelatedBy" and mutators "addEquality" and "addInequality".
45 // To find a relationship, we start with one of the nodes any binary search
46 // through its list to find where the relationships with the second node start.
47 // Then we iterate through those to find the first relationship that dominates
48 // our context node.
49 //
50 // To create these properties, we wait until a branch or switch instruction
51 // implies that a particular value is true (or false). The VRPSolver is
52 // responsible for analyzing the variable and seeing what new inferences
53 // can be made from each property. For example:
54 //
55 //   %P = icmp ne i32* %ptr, null
56 //   %a = and i1 %P, %Q
57 //   br i1 %a label %cond_true, label %cond_false
58 //
59 // For the true branch, the VRPSolver will start with %a EQ true and look at
60 // the definition of %a and find that it can infer that %P and %Q are both
61 // true. From %P being true, it can infer that %ptr NE null. For the false
62 // branch it can't infer anything from the "and" instruction.
63 //
64 // Besides branches, we can also infer properties from instruction that may
65 // have undefined behaviour in certain cases. For example, the dividend of
66 // a division may never be zero. After the division instruction, we may assume
67 // that the dividend is not equal to zero.
68 //
69 //===----------------------------------------------------------------------===//
70 //
71 // The ValueRanges class stores the known integer bounds of a Value. When we
72 // encounter i8 %a u< %b, the ValueRanges stores that %a = [1, 255] and
73 // %b = [0, 254].
74 //
75 // It never stores an empty range, because that means that the code is
76 // unreachable. It never stores a single-element range since that's an equality
77 // relationship and better stored in the InequalityGraph, nor an empty range
78 // since that is better stored in UnreachableBlocks.
79 //
80 //===----------------------------------------------------------------------===//
81
82 #define DEBUG_TYPE "predsimplify"
83 #include "llvm/Transforms/Scalar.h"
84 #include "llvm/Constants.h"
85 #include "llvm/DerivedTypes.h"
86 #include "llvm/Instructions.h"
87 #include "llvm/Pass.h"
88 #include "llvm/ADT/DepthFirstIterator.h"
89 #include "llvm/ADT/SetOperations.h"
90 #include "llvm/ADT/SetVector.h"
91 #include "llvm/ADT/Statistic.h"
92 #include "llvm/ADT/STLExtras.h"
93 #include "llvm/Analysis/Dominators.h"
94 #include "llvm/Assembly/Writer.h"
95 #include "llvm/Support/CFG.h"
96 #include "llvm/Support/ConstantRange.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/InstVisitor.h"
99 #include "llvm/Support/raw_ostream.h"
100 #include "llvm/Target/TargetData.h"
101 #include "llvm/Transforms/Utils/Local.h"
102 #include <algorithm>
103 #include <deque>
104 #include <stack>
105 using namespace llvm;
106
107 STATISTIC(NumVarsReplaced, "Number of argument substitutions");
108 STATISTIC(NumInstruction , "Number of instructions removed");
109 STATISTIC(NumSimple      , "Number of simple replacements");
110 STATISTIC(NumBlocks      , "Number of blocks marked unreachable");
111 STATISTIC(NumSnuggle     , "Number of comparisons snuggled");
112
113 static const ConstantRange empty(1, false);
114
115 namespace {
116   class DomTreeDFS {
117   public:
118     class Node {
119       friend class DomTreeDFS;
120     public:
121       typedef std::vector<Node *>::iterator       iterator;
122       typedef std::vector<Node *>::const_iterator const_iterator;
123
124       unsigned getDFSNumIn()  const { return DFSin;  }
125       unsigned getDFSNumOut() const { return DFSout; }
126
127       BasicBlock *getBlock() const { return BB; }
128
129       iterator begin() { return Children.begin(); }
130       iterator end()   { return Children.end();   }
131
132       const_iterator begin() const { return Children.begin(); }
133       const_iterator end()   const { return Children.end();   }
134
135       bool dominates(const Node *N) const {
136         return DFSin <= N->DFSin && DFSout >= N->DFSout;
137       }
138
139       bool DominatedBy(const Node *N) const {
140         return N->dominates(this);
141       }
142
143       /// Sorts by the number of descendants. With this, you can iterate
144       /// through a sorted list and the first matching entry is the most
145       /// specific match for your basic block. The order provided is stable;
146       /// DomTreeDFS::Nodes with the same number of descendants are sorted by
147       /// DFS in number.
148       bool operator<(const Node &N) const {
149         unsigned   spread =   DFSout -   DFSin;
150         unsigned N_spread = N.DFSout - N.DFSin;
151         if (spread == N_spread) return DFSin < N.DFSin;
152         return spread < N_spread;
153       }
154       bool operator>(const Node &N) const { return N < *this; }
155
156     private:
157       unsigned DFSin, DFSout;
158       BasicBlock *BB;
159
160       std::vector<Node *> Children;
161     };
162
163     // XXX: this may be slow. Instead of using "new" for each node, consider
164     // putting them in a vector to keep them contiguous.
165     explicit DomTreeDFS(DominatorTree *DT) {
166       std::stack<std::pair<Node *, DomTreeNode *> > S;
167
168       Entry = new Node;
169       Entry->BB = DT->getRootNode()->getBlock();
170       S.push(std::make_pair(Entry, DT->getRootNode()));
171
172       NodeMap[Entry->BB] = Entry;
173
174       while (!S.empty()) {
175         std::pair<Node *, DomTreeNode *> &Pair = S.top();
176         Node *N = Pair.first;
177         DomTreeNode *DTNode = Pair.second;
178         S.pop();
179
180         for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
181              I != E; ++I) {
182           Node *NewNode = new Node;
183           NewNode->BB = (*I)->getBlock();
184           N->Children.push_back(NewNode);
185           S.push(std::make_pair(NewNode, *I));
186
187           NodeMap[NewNode->BB] = NewNode;
188         }
189       }
190
191       renumber();
192
193 #ifndef NDEBUG
194       DEBUG(dump());
195 #endif
196     }
197
198 #ifndef NDEBUG
199     virtual
200 #endif
201     ~DomTreeDFS() {
202       std::stack<Node *> S;
203
204       S.push(Entry);
205       while (!S.empty()) {
206         Node *N = S.top(); S.pop();
207
208         for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
209           S.push(*I);
210
211         delete N;
212       }
213     }
214
215     /// getRootNode - This returns the entry node for the CFG of the function.
216     Node *getRootNode() const { return Entry; }
217
218     /// getNodeForBlock - return the node for the specified basic block.
219     Node *getNodeForBlock(BasicBlock *BB) const {
220       if (!NodeMap.count(BB)) return 0;
221       return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
222     }
223
224     /// dominates - returns true if the basic block for I1 dominates that of
225     /// the basic block for I2. If the instructions belong to the same basic
226     /// block, the instruction first instruction sequentially in the block is
227     /// considered dominating.
228     bool dominates(Instruction *I1, Instruction *I2) {
229       BasicBlock *BB1 = I1->getParent(),
230                  *BB2 = I2->getParent();
231       if (BB1 == BB2) {
232         if (isa<TerminatorInst>(I1)) return false;
233         if (isa<TerminatorInst>(I2)) return true;
234         if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
235         if (!isa<PHINode>(I1) &&  isa<PHINode>(I2)) return false;
236
237         for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
238              I != E; ++I) {
239           if (&*I == I1) return true;
240           else if (&*I == I2) return false;
241         }
242         assert(!"Instructions not found in parent BasicBlock?");
243       } else {
244         Node *Node1 = getNodeForBlock(BB1),
245              *Node2 = getNodeForBlock(BB2);
246         return Node1 && Node2 && Node1->dominates(Node2);
247       }
248       return false; // Not reached
249     }
250
251   private:
252     /// renumber - calculates the depth first search numberings and applies
253     /// them onto the nodes.
254     void renumber() {
255       std::stack<std::pair<Node *, Node::iterator> > S;
256       unsigned n = 0;
257
258       Entry->DFSin = ++n;
259       S.push(std::make_pair(Entry, Entry->begin()));
260
261       while (!S.empty()) {
262         std::pair<Node *, Node::iterator> &Pair = S.top();
263         Node *N = Pair.first;
264         Node::iterator &I = Pair.second;
265
266         if (I == N->end()) {
267           N->DFSout = ++n;
268           S.pop();
269         } else {
270           Node *Next = *I++;
271           Next->DFSin = ++n;
272           S.push(std::make_pair(Next, Next->begin()));
273         }
274       }
275     }
276
277 #ifndef NDEBUG
278     virtual void dump() const {
279       dump(errs());
280     }
281
282     void dump(raw_ostream &os) const {
283       os << "Predicate simplifier DomTreeDFS: \n";
284       dump(Entry, 0, os);
285       os << "\n\n";
286     }
287
288     void dump(Node *N, int depth, raw_ostream &os) const {
289       ++depth;
290       for (int i = 0; i < depth; ++i) { os << " "; }
291       os << "[" << depth << "] ";
292
293       os << N->getBlock()->getNameStr() << " (" << N->getDFSNumIn()
294          << ", " << N->getDFSNumOut() << ")\n";
295
296       for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
297         dump(*I, depth, os);
298     }
299 #endif
300
301     Node *Entry;
302     std::map<BasicBlock *, Node *> NodeMap;
303   };
304
305   // SLT SGT ULT UGT EQ
306   //   0   1   0   1  0 -- GT                  10
307   //   0   1   0   1  1 -- GE                  11
308   //   0   1   1   0  0 -- SGTULT              12
309   //   0   1   1   0  1 -- SGEULE              13
310   //   0   1   1   1  0 -- SGT                 14
311   //   0   1   1   1  1 -- SGE                 15
312   //   1   0   0   1  0 -- SLTUGT              18
313   //   1   0   0   1  1 -- SLEUGE              19
314   //   1   0   1   0  0 -- LT                  20
315   //   1   0   1   0  1 -- LE                  21
316   //   1   0   1   1  0 -- SLT                 22
317   //   1   0   1   1  1 -- SLE                 23
318   //   1   1   0   1  0 -- UGT                 26
319   //   1   1   0   1  1 -- UGE                 27
320   //   1   1   1   0  0 -- ULT                 28
321   //   1   1   1   0  1 -- ULE                 29
322   //   1   1   1   1  0 -- NE                  30
323   enum LatticeBits {
324     EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
325   };
326   enum LatticeVal {
327     GT = SGT_BIT | UGT_BIT,
328     GE = GT | EQ_BIT,
329     LT = SLT_BIT | ULT_BIT,
330     LE = LT | EQ_BIT,
331     NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
332     SGTULT = SGT_BIT | ULT_BIT,
333     SGEULE = SGTULT | EQ_BIT,
334     SLTUGT = SLT_BIT | UGT_BIT,
335     SLEUGE = SLTUGT | EQ_BIT,
336     ULT = SLT_BIT | SGT_BIT | ULT_BIT,
337     UGT = SLT_BIT | SGT_BIT | UGT_BIT,
338     SLT = SLT_BIT | ULT_BIT | UGT_BIT,
339     SGT = SGT_BIT | ULT_BIT | UGT_BIT,
340     SLE = SLT | EQ_BIT,
341     SGE = SGT | EQ_BIT,
342     ULE = ULT | EQ_BIT,
343     UGE = UGT | EQ_BIT
344   };
345
346 #ifndef NDEBUG
347   /// validPredicate - determines whether a given value is actually a lattice
348   /// value. Only used in assertions or debugging.
349   static bool validPredicate(LatticeVal LV) {
350     switch (LV) {
351       case GT: case GE: case LT: case LE: case NE:
352       case SGTULT: case SGT: case SGEULE:
353       case SLTUGT: case SLT: case SLEUGE:
354       case ULT: case UGT:
355       case SLE: case SGE: case ULE: case UGE:
356         return true;
357       default:
358         return false;
359     }
360   }
361 #endif
362
363   /// reversePredicate - reverse the direction of the inequality
364   static LatticeVal reversePredicate(LatticeVal LV) {
365     unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
366
367     if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
368       reverse |= (SLT_BIT|SGT_BIT);
369
370     if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
371       reverse |= (ULT_BIT|UGT_BIT);
372
373     LatticeVal Rev = static_cast<LatticeVal>(reverse);
374     assert(validPredicate(Rev) && "Failed reversing predicate.");
375     return Rev;
376   }
377
378   /// ValueNumbering stores the scope-specific value numbers for a given Value.
379   class ValueNumbering {
380
381     /// VNPair is a tuple of {Value, index number, DomTreeDFS::Node}. It
382     /// includes the comparison operators necessary to allow you to store it
383     /// in a sorted vector.
384     class VNPair {
385     public:
386       Value *V;
387       unsigned index;
388       DomTreeDFS::Node *Subtree;
389
390       VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
391         : V(V), index(index), Subtree(Subtree) {}
392
393       bool operator==(const VNPair &RHS) const {
394         return V == RHS.V && Subtree == RHS.Subtree;
395       }
396
397       bool operator<(const VNPair &RHS) const {
398         if (V != RHS.V) return V < RHS.V;
399         return *Subtree < *RHS.Subtree;
400       }
401
402       bool operator<(Value *RHS) const {
403         return V < RHS;
404       }
405
406       bool operator>(Value *RHS) const {
407         return V > RHS;
408       }
409
410       friend bool operator<(Value *RHS, const VNPair &pair) {
411         return pair.operator>(RHS);
412       }
413     };
414
415     typedef std::vector<VNPair> VNMapType;
416     VNMapType VNMap;
417
418     /// The canonical choice for value number at index.
419     std::vector<Value *> Values;
420
421     DomTreeDFS *DTDFS;
422
423   public:
424 #ifndef NDEBUG
425     virtual ~ValueNumbering() {}
426     virtual void dump() {
427       print(errs());
428     }
429
430     void print(raw_ostream &os) {
431       for (unsigned i = 1; i <= Values.size(); ++i) {
432         os << i << " = ";
433         WriteAsOperand(os, Values[i-1]);
434         os << " {";
435         for (unsigned j = 0; j < VNMap.size(); ++j) {
436           if (VNMap[j].index == i) {
437             WriteAsOperand(os, VNMap[j].V);
438             os << " (" << VNMap[j].Subtree->getDFSNumIn() << ")  ";
439           }
440         }
441         os << "}\n";
442       }
443     }
444 #endif
445
446     /// compare - returns true if V1 is a better canonical value than V2.
447     bool compare(Value *V1, Value *V2) const {
448       if (isa<Constant>(V1))
449         return !isa<Constant>(V2);
450       else if (isa<Constant>(V2))
451         return false;
452       else if (isa<Argument>(V1))
453         return !isa<Argument>(V2);
454       else if (isa<Argument>(V2))
455         return false;
456
457       Instruction *I1 = dyn_cast<Instruction>(V1);
458       Instruction *I2 = dyn_cast<Instruction>(V2);
459
460       if (!I1 || !I2)
461         return V1->getNumUses() < V2->getNumUses();
462
463       return DTDFS->dominates(I1, I2);
464     }
465
466     ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
467
468     /// valueNumber - finds the value number for V under the Subtree. If
469     /// there is no value number, returns zero.
470     unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
471       if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) || 
472           V->getType() == Type::getVoidTy(V->getContext())) return 0;
473
474       VNMapType::iterator E = VNMap.end();
475       VNPair pair(V, 0, Subtree);
476       VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
477       while (I != E && I->V == V) {
478         if (I->Subtree->dominates(Subtree))
479           return I->index;
480         ++I;
481       }
482       return 0;
483     }
484
485     /// getOrInsertVN - always returns a value number, creating it if necessary.
486     unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
487       if (unsigned n = valueNumber(V, Subtree))
488         return n;
489       else
490         return newVN(V);
491     }
492
493     /// newVN - creates a new value number. Value V must not already have a
494     /// value number assigned.
495     unsigned newVN(Value *V) {
496       assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
497              "Bad Value for value numbering.");
498       assert(V->getType() != Type::getVoidTy(V->getContext()) &&
499              "Won't value number a void value");
500
501       Values.push_back(V);
502
503       VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
504       VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
505       assert((I == VNMap.end() || value(I->index) != V) &&
506              "Attempt to create a duplicate value number.");
507       VNMap.insert(I, pair);
508
509       return Values.size();
510     }
511
512     /// value - returns the Value associated with a value number.
513     Value *value(unsigned index) const {
514       assert(index != 0 && "Zero index is reserved for not found.");
515       assert(index <= Values.size() && "Index out of range.");
516       return Values[index-1];
517     }
518
519     /// canonicalize - return a Value that is equal to V under Subtree.
520     Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
521       if (isa<Constant>(V)) return V;
522
523       if (unsigned n = valueNumber(V, Subtree))
524         return value(n);
525       else
526         return V;
527     }
528
529     /// addEquality - adds that value V belongs to the set of equivalent
530     /// values defined by value number n under Subtree.
531     void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
532       assert(canonicalize(value(n), Subtree) == value(n) &&
533              "Node's 'canonical' choice isn't best within this subtree.");
534
535       // Suppose that we are given "%x -> node #1 (%y)". The problem is that
536       // we may already have "%z -> node #2 (%x)" somewhere above us in the
537       // graph. We need to find those edges and add "%z -> node #1 (%y)"
538       // to keep the lookups canonical.
539
540       std::vector<Value *> ToRepoint(1, V);
541
542       if (unsigned Conflict = valueNumber(V, Subtree)) {
543         for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
544              I != E; ++I) {
545           if (I->index == Conflict && I->Subtree->dominates(Subtree))
546             ToRepoint.push_back(I->V);
547         }
548       }
549
550       for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
551            VE = ToRepoint.end(); VI != VE; ++VI) {
552         Value *V = *VI;
553
554         VNPair pair(V, n, Subtree);
555         VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
556         VNMapType::iterator I = std::lower_bound(B, E, pair);
557         if (I != E && I->V == V && I->Subtree == Subtree)
558           I->index = n; // Update best choice
559         else
560           VNMap.insert(I, pair); // New Value
561
562         // XXX: we currently don't have to worry about updating values with
563         // more specific Subtrees, but we will need to for PHI node support.
564
565 #ifndef NDEBUG
566         Value *V_n = value(n);
567         if (isa<Constant>(V) && isa<Constant>(V_n)) {
568           assert(V == V_n && "Constant equals different constant?");
569         }
570 #endif
571       }
572     }
573
574     /// remove - removes all references to value V.
575     void remove(Value *V) {
576       VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
577       VNPair pair(V, 0, DTDFS->getRootNode());
578       VNMapType::iterator J = std::upper_bound(B, E, pair);
579       VNMapType::iterator I = J;
580
581       while (I != B && (I == E || I->V == V)) --I;
582
583       VNMap.erase(I, J);
584     }
585   };
586
587   /// The InequalityGraph stores the relationships between values.
588   /// Each Value in the graph is assigned to a Node. Nodes are pointer
589   /// comparable for equality. The caller is expected to maintain the logical
590   /// consistency of the system.
591   ///
592   /// The InequalityGraph class may invalidate Node*s after any mutator call.
593   /// @brief The InequalityGraph stores the relationships between values.
594   class InequalityGraph {
595     ValueNumbering &VN;
596     DomTreeDFS::Node *TreeRoot;
597
598     InequalityGraph();                  // DO NOT IMPLEMENT
599     InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
600   public:
601     InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
602       : VN(VN), TreeRoot(TreeRoot) {}
603
604     class Node;
605
606     /// An Edge is contained inside a Node making one end of the edge implicit
607     /// and contains a pointer to the other end. The edge contains a lattice
608     /// value specifying the relationship and an DomTreeDFS::Node specifying
609     /// the root in the dominator tree to which this edge applies.
610     class Edge {
611     public:
612       Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
613         : To(T), LV(V), Subtree(ST) {}
614
615       unsigned To;
616       LatticeVal LV;
617       DomTreeDFS::Node *Subtree;
618
619       bool operator<(const Edge &edge) const {
620         if (To != edge.To) return To < edge.To;
621         return *Subtree < *edge.Subtree;
622       }
623
624       bool operator<(unsigned to) const {
625         return To < to;
626       }
627
628       bool operator>(unsigned to) const {
629         return To > to;
630       }
631
632       friend bool operator<(unsigned to, const Edge &edge) {
633         return edge.operator>(to);
634       }
635     };
636
637     /// A single node in the InequalityGraph. This stores the canonical Value
638     /// for the node, as well as the relationships with the neighbours.
639     ///
640     /// @brief A single node in the InequalityGraph.
641     class Node {
642       friend class InequalityGraph;
643
644       typedef SmallVector<Edge, 4> RelationsType;
645       RelationsType Relations;
646
647       // TODO: can this idea improve performance?
648       //friend class std::vector<Node>;
649       //Node(Node &N) { RelationsType.swap(N.RelationsType); }
650
651     public:
652       typedef RelationsType::iterator       iterator;
653       typedef RelationsType::const_iterator const_iterator;
654
655 #ifndef NDEBUG
656       virtual ~Node() {}
657       virtual void dump() const {
658         dump(errs());
659       }
660     private:
661       void dump(raw_ostream &os) const {
662         static const std::string names[32] =
663           { "000000", "000001", "000002", "000003", "000004", "000005",
664             "000006", "000007", "000008", "000009", "     >", "    >=",
665             "  s>u<", "s>=u<=", "    s>", "   s>=", "000016", "000017",
666             "  s<u>", "s<=u>=", "     <", "    <=", "    s<", "   s<=",
667             "000024", "000025", "    u>", "   u>=", "    u<", "   u<=",
668             "    !=", "000031" };
669         for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
670           os << names[NI->LV] << " " << NI->To
671              << " (" << NI->Subtree->getDFSNumIn() << "), ";
672         }
673       }
674     public:
675 #endif
676
677       iterator begin()             { return Relations.begin(); }
678       iterator end()               { return Relations.end();   }
679       const_iterator begin() const { return Relations.begin(); }
680       const_iterator end()   const { return Relations.end();   }
681
682       iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
683         iterator E = end();
684         for (iterator I = std::lower_bound(begin(), E, n);
685              I != E && I->To == n; ++I) {
686           if (Subtree->DominatedBy(I->Subtree))
687             return I;
688         }
689         return E;
690       }
691
692       const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
693         const_iterator E = end();
694         for (const_iterator I = std::lower_bound(begin(), E, n);
695              I != E && I->To == n; ++I) {
696           if (Subtree->DominatedBy(I->Subtree))
697             return I;
698         }
699         return E;
700       }
701
702       /// update - updates the lattice value for a given node, creating a new
703       /// entry if one doesn't exist. The new lattice value must not be
704       /// inconsistent with any previously existing value.
705       void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
706         assert(validPredicate(R) && "Invalid predicate.");
707
708         Edge edge(n, R, Subtree);
709         iterator B = begin(), E = end();
710         iterator I = std::lower_bound(B, E, edge);
711
712         iterator J = I;
713         while (J != E && J->To == n) {
714           if (Subtree->DominatedBy(J->Subtree))
715             break;
716           ++J;
717         }
718
719         if (J != E && J->To == n) {
720           edge.LV = static_cast<LatticeVal>(J->LV & R);
721           assert(validPredicate(edge.LV) && "Invalid union of lattice values.");
722
723           if (edge.LV == J->LV)
724             return; // This update adds nothing new.
725         }
726
727         if (I != B) {
728           // We also have to tighten any edge beneath our update.
729           for (iterator K = I - 1; K->To == n; --K) {
730             if (K->Subtree->DominatedBy(Subtree)) {
731               LatticeVal LV = static_cast<LatticeVal>(K->LV & edge.LV);
732               assert(validPredicate(LV) && "Invalid union of lattice values");
733               K->LV = LV;
734             }
735             if (K == B) break;
736           }
737         }
738
739         // Insert new edge at Subtree if it isn't already there.
740         if (I == E || I->To != n || Subtree != I->Subtree)
741           Relations.insert(I, edge);
742       }
743     };
744
745   private:
746
747     std::vector<Node> Nodes;
748
749   public:
750     /// node - returns the node object at a given value number. The pointer
751     /// returned may be invalidated on the next call to node().
752     Node *node(unsigned index) {
753       assert(VN.value(index)); // This triggers the necessary checks.
754       if (Nodes.size() < index) Nodes.resize(index);
755       return &Nodes[index-1];
756     }
757
758     /// isRelatedBy - true iff n1 op n2
759     bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
760                      LatticeVal LV) {
761       if (n1 == n2) return LV & EQ_BIT;
762
763       Node *N1 = node(n1);
764       Node::iterator I = N1->find(n2, Subtree), E = N1->end();
765       if (I != E) return (I->LV & LV) == I->LV;
766
767       return false;
768     }
769
770     // The add* methods assume that your input is logically valid and may 
771     // assertion-fail or infinitely loop if you attempt a contradiction.
772
773     /// addInequality - Sets n1 op n2.
774     /// It is also an error to call this on an inequality that is already true.
775     void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
776                        LatticeVal LV1) {
777       assert(n1 != n2 && "A node can't be inequal to itself.");
778
779       if (LV1 != NE)
780         assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
781                "Contradictory inequality.");
782
783       // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
784       // add %a < %n2 too. This keeps the graph fully connected.
785       if (LV1 != NE) {
786         // Break up the relationship into signed and unsigned comparison parts.
787         // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
788         // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
789         // should have the EQ_BIT iff it's set for both op1 and op2.
790
791         unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
792         unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
793
794         for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
795           if (I->LV != NE && I->To != n2) {
796
797             DomTreeDFS::Node *Local_Subtree = NULL;
798             if (Subtree->DominatedBy(I->Subtree))
799               Local_Subtree = Subtree;
800             else if (I->Subtree->DominatedBy(Subtree))
801               Local_Subtree = I->Subtree;
802
803             if (Local_Subtree) {
804               unsigned new_relationship = 0;
805               LatticeVal ILV = reversePredicate(I->LV);
806               unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
807               unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
808
809               if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
810                 new_relationship |= ILV_s;
811               if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
812                 new_relationship |= ILV_u;
813
814               if (new_relationship) {
815                 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
816                   new_relationship |= (SLT_BIT|SGT_BIT);
817                 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
818                   new_relationship |= (ULT_BIT|UGT_BIT);
819                 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
820                   new_relationship |= EQ_BIT;
821
822                 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
823
824                 node(I->To)->update(n2, NewLV, Local_Subtree);
825                 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
826               }
827             }
828           }
829         }
830
831         for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
832           if (I->LV != NE && I->To != n1) {
833             DomTreeDFS::Node *Local_Subtree = NULL;
834             if (Subtree->DominatedBy(I->Subtree))
835               Local_Subtree = Subtree;
836             else if (I->Subtree->DominatedBy(Subtree))
837               Local_Subtree = I->Subtree;
838
839             if (Local_Subtree) {
840               unsigned new_relationship = 0;
841               unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
842               unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
843
844               if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
845                 new_relationship |= ILV_s;
846
847               if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
848                 new_relationship |= ILV_u;
849
850               if (new_relationship) {
851                 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
852                   new_relationship |= (SLT_BIT|SGT_BIT);
853                 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
854                   new_relationship |= (ULT_BIT|UGT_BIT);
855                 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
856                   new_relationship |= EQ_BIT;
857
858                 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
859
860                 node(n1)->update(I->To, NewLV, Local_Subtree);
861                 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
862               }
863             }
864           }
865         }
866       }
867
868       node(n1)->update(n2, LV1, Subtree);
869       node(n2)->update(n1, reversePredicate(LV1), Subtree);
870     }
871
872     /// remove - removes a node from the graph by removing all references to
873     /// and from it.
874     void remove(unsigned n) {
875       Node *N = node(n);
876       for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
877         Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
878         do {
879           node(NI->To)->Relations.erase(Iter);
880           Iter = node(NI->To)->find(n, TreeRoot);
881         } while (Iter != node(NI->To)->end());
882       }
883       N->Relations.clear();
884     }
885
886 #ifndef NDEBUG
887     virtual ~InequalityGraph() {}
888     virtual void dump() {
889       dump(errs());
890     }
891
892     void dump(raw_ostream &os) {
893       for (unsigned i = 1; i <= Nodes.size(); ++i) {
894         os << i << " = {";
895         node(i)->dump(os);
896         os << "}\n";
897       }
898     }
899 #endif
900   };
901
902   class VRPSolver;
903
904   /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
905   /// in the InequalityGraph.
906   class ValueRanges {
907     ValueNumbering &VN;
908     TargetData *TD;
909     LLVMContext *Context;
910
911     class ScopedRange {
912       typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
913               RangeListType;
914       RangeListType RangeList;
915
916       static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
917                       const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
918         return *LHS.first < *RHS.first;
919       }
920
921     public:
922 #ifndef NDEBUG
923       virtual ~ScopedRange() {}
924       virtual void dump() const {
925         dump(errs());
926       }
927
928       void dump(raw_ostream &os) const {
929         os << "{";
930         for (const_iterator I = begin(), E = end(); I != E; ++I) {
931           os << &I->second << " (" << I->first->getDFSNumIn() << "), ";
932         }
933         os << "}";
934       }
935 #endif
936
937       typedef RangeListType::iterator       iterator;
938       typedef RangeListType::const_iterator const_iterator;
939
940       iterator begin() { return RangeList.begin(); }
941       iterator end()   { return RangeList.end(); }
942       const_iterator begin() const { return RangeList.begin(); }
943       const_iterator end()   const { return RangeList.end(); }
944
945       iterator find(DomTreeDFS::Node *Subtree) {
946         iterator E = end();
947         iterator I = std::lower_bound(begin(), E,
948                                       std::make_pair(Subtree, empty), swo);
949
950         while (I != E && !I->first->dominates(Subtree)) ++I;
951         return I;
952       }
953
954       const_iterator find(DomTreeDFS::Node *Subtree) const {
955         const_iterator E = end();
956         const_iterator I = std::lower_bound(begin(), E,
957                                             std::make_pair(Subtree, empty), swo);
958
959         while (I != E && !I->first->dominates(Subtree)) ++I;
960         return I;
961       }
962
963       void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
964         assert(!CR.isEmptySet() && "Empty ConstantRange.");
965         assert(!CR.isSingleElement() && "Refusing to store single element.");
966
967         iterator E = end();
968         iterator I =
969             std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
970
971         if (I != end() && I->first == Subtree) {
972           ConstantRange CR2 = I->second.intersectWith(CR);
973           assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
974                  "Invalid union of ranges.");
975           I->second = CR2;
976         } else
977           RangeList.insert(I, std::make_pair(Subtree, CR));
978       }
979     };
980
981     std::vector<ScopedRange> Ranges;
982
983     void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
984       if (CR.isFullSet()) return;
985       if (Ranges.size() < n) Ranges.resize(n);
986       Ranges[n-1].update(CR, Subtree);
987     }
988
989     /// create - Creates a ConstantRange that matches the given LatticeVal
990     /// relation with a given integer.
991     ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
992       assert(!CR.isEmptySet() && "Can't deal with empty set.");
993
994       if (LV == NE)
995         return ConstantRange::makeICmpRegion(ICmpInst::ICMP_NE, CR);
996
997       unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
998       unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
999       bool hasEQ = LV & EQ_BIT;
1000
1001       ConstantRange Range(CR.getBitWidth());
1002
1003       if (LV_s == SGT_BIT) {
1004         Range = Range.intersectWith(ConstantRange::makeICmpRegion(
1005                     hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
1006       } else if (LV_s == SLT_BIT) {
1007         Range = Range.intersectWith(ConstantRange::makeICmpRegion(
1008                     hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
1009       }
1010
1011       if (LV_u == UGT_BIT) {
1012         Range = Range.intersectWith(ConstantRange::makeICmpRegion(
1013                     hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
1014       } else if (LV_u == ULT_BIT) {
1015         Range = Range.intersectWith(ConstantRange::makeICmpRegion(
1016                     hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
1017       }
1018
1019       return Range;
1020     }
1021
1022 #ifndef NDEBUG
1023     bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
1024       return V == VN.canonicalize(V, Subtree);
1025     }
1026 #endif
1027
1028   public:
1029
1030     ValueRanges(ValueNumbering &VN, TargetData *TD, LLVMContext *C) :
1031       VN(VN), TD(TD), Context(C) {}
1032
1033 #ifndef NDEBUG
1034     virtual ~ValueRanges() {}
1035
1036     virtual void dump() const {
1037       dump(errs());
1038     }
1039
1040     void dump(raw_ostream &os) const {
1041       for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1042         os << (i+1) << " = ";
1043         Ranges[i].dump(os);
1044         os << "\n";
1045       }
1046     }
1047 #endif
1048
1049     /// range - looks up the ConstantRange associated with a value number.
1050     ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
1051       assert(VN.value(n)); // performs range checks
1052
1053       if (n <= Ranges.size()) {
1054         ScopedRange::iterator I = Ranges[n-1].find(Subtree);
1055         if (I != Ranges[n-1].end()) return I->second;
1056       }
1057
1058       Value *V = VN.value(n);
1059       ConstantRange CR = range(V);
1060       return CR;
1061     }
1062
1063     /// range - determine a range from a Value without performing any lookups.
1064     ConstantRange range(Value *V) const {
1065       if (ConstantInt *C = dyn_cast<ConstantInt>(V))
1066         return ConstantRange(C->getValue());
1067       else if (isa<ConstantPointerNull>(V))
1068         return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
1069       else
1070         return ConstantRange(typeToWidth(V->getType()));
1071     }
1072
1073     // typeToWidth - returns the number of bits necessary to store a value of
1074     // this type, or zero if unknown.
1075     uint32_t typeToWidth(const Type *Ty) const {
1076       if (TD)
1077         return TD->getTypeSizeInBits(Ty);
1078       else
1079         return Ty->getPrimitiveSizeInBits();
1080     }
1081
1082     static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
1083                             LatticeVal LV) {
1084       switch (LV) {
1085       default: assert(!"Impossible lattice value!");
1086       case NE:
1087         return CR1.intersectWith(CR2).isEmptySet();
1088       case ULT:
1089         return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1090       case ULE:
1091         return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1092       case UGT:
1093         return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1094       case UGE:
1095         return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1096       case SLT:
1097         return CR1.getSignedMax().slt(CR2.getSignedMin());
1098       case SLE:
1099         return CR1.getSignedMax().sle(CR2.getSignedMin());
1100       case SGT:
1101         return CR1.getSignedMin().sgt(CR2.getSignedMax());
1102       case SGE:
1103         return CR1.getSignedMin().sge(CR2.getSignedMax());
1104       case LT:
1105         return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1106                CR1.getSignedMax().slt(CR2.getUnsignedMin());
1107       case LE:
1108         return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1109                CR1.getSignedMax().sle(CR2.getUnsignedMin());
1110       case GT:
1111         return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1112                CR1.getSignedMin().sgt(CR2.getSignedMax());
1113       case GE:
1114         return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1115                CR1.getSignedMin().sge(CR2.getSignedMax());
1116       case SLTUGT:
1117         return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1118                CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1119       case SLEUGE:
1120         return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1121                CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1122       case SGTULT:
1123         return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1124                CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1125       case SGEULE:
1126         return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1127                CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1128       }
1129     }
1130
1131     bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1132                      LatticeVal LV) {
1133       ConstantRange CR1 = range(n1, Subtree);
1134       ConstantRange CR2 = range(n2, Subtree);
1135
1136       // True iff all values in CR1 are LV to all values in CR2.
1137       return isRelatedBy(CR1, CR2, LV);
1138     }
1139
1140     void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
1141                        VRPSolver *VRP);
1142     void markBlock(VRPSolver *VRP);
1143
1144     void mergeInto(Value **I, unsigned n, unsigned New,
1145                    DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1146       ConstantRange CR_New = range(New, Subtree);
1147       ConstantRange Merged = CR_New;
1148
1149       for (; n != 0; ++I, --n) {
1150         unsigned i = VN.valueNumber(*I, Subtree);
1151         ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
1152         if (CR_Kill.isFullSet()) continue;
1153         Merged = Merged.intersectWith(CR_Kill);
1154       }
1155
1156       if (Merged.isFullSet() || Merged == CR_New) return;
1157
1158       applyRange(New, Merged, Subtree, VRP);
1159     }
1160
1161     void applyRange(unsigned n, const ConstantRange &CR,
1162                     DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1163       ConstantRange Merged = CR.intersectWith(range(n, Subtree));
1164       if (Merged.isEmptySet()) {
1165         markBlock(VRP);
1166         return;
1167       }
1168
1169       if (const APInt *I = Merged.getSingleElement()) {
1170         Value *V = VN.value(n); // XXX: redesign worklist.
1171         const Type *Ty = V->getType();
1172         if (Ty->isInteger()) {
1173           addToWorklist(V, ConstantInt::get(*Context, *I),
1174                         ICmpInst::ICMP_EQ, VRP);
1175           return;
1176         } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1177           assert(*I == 0 && "Pointer is null but not zero?");
1178           addToWorklist(V, ConstantPointerNull::get(PTy),
1179                         ICmpInst::ICMP_EQ, VRP);
1180           return;
1181         }
1182       }
1183
1184       update(n, Merged, Subtree);
1185     }
1186
1187     void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1188                       VRPSolver *VRP) {
1189       ConstantRange CR1 = range(n1, Subtree);
1190       ConstantRange CR2 = range(n2, Subtree);
1191
1192       uint32_t W = CR1.getBitWidth();
1193
1194       if (const APInt *I = CR1.getSingleElement()) {
1195         if (CR2.isFullSet()) {
1196           ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
1197           applyRange(n2, NewCR2, Subtree, VRP);
1198         } else if (*I == CR2.getLower()) {
1199           APInt NewLower(CR2.getLower() + 1),
1200                 NewUpper(CR2.getUpper());
1201           if (NewLower == NewUpper)
1202             NewLower = NewUpper = APInt::getMinValue(W);
1203
1204           ConstantRange NewCR2(NewLower, NewUpper);
1205           applyRange(n2, NewCR2, Subtree, VRP);
1206         } else if (*I == CR2.getUpper() - 1) {
1207           APInt NewLower(CR2.getLower()),
1208                 NewUpper(CR2.getUpper() - 1);
1209           if (NewLower == NewUpper)
1210             NewLower = NewUpper = APInt::getMinValue(W);
1211
1212           ConstantRange NewCR2(NewLower, NewUpper);
1213           applyRange(n2, NewCR2, Subtree, VRP);
1214         }
1215       }
1216
1217       if (const APInt *I = CR2.getSingleElement()) {
1218         if (CR1.isFullSet()) {
1219           ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
1220           applyRange(n1, NewCR1, Subtree, VRP);
1221         } else if (*I == CR1.getLower()) {
1222           APInt NewLower(CR1.getLower() + 1),
1223                 NewUpper(CR1.getUpper());
1224           if (NewLower == NewUpper)
1225             NewLower = NewUpper = APInt::getMinValue(W);
1226
1227           ConstantRange NewCR1(NewLower, NewUpper);
1228           applyRange(n1, NewCR1, Subtree, VRP);
1229         } else if (*I == CR1.getUpper() - 1) {
1230           APInt NewLower(CR1.getLower()),
1231                 NewUpper(CR1.getUpper() - 1);
1232           if (NewLower == NewUpper)
1233             NewLower = NewUpper = APInt::getMinValue(W);
1234
1235           ConstantRange NewCR1(NewLower, NewUpper);
1236           applyRange(n1, NewCR1, Subtree, VRP);
1237         }
1238       }
1239     }
1240
1241     void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1242                        LatticeVal LV, VRPSolver *VRP) {
1243       assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
1244
1245       if (LV == NE) {
1246         addNotEquals(n1, n2, Subtree, VRP);
1247         return;
1248       }
1249
1250       ConstantRange CR1 = range(n1, Subtree);
1251       ConstantRange CR2 = range(n2, Subtree);
1252
1253       if (!CR1.isSingleElement()) {
1254         ConstantRange NewCR1 = CR1.intersectWith(create(LV, CR2));
1255         if (NewCR1 != CR1)
1256           applyRange(n1, NewCR1, Subtree, VRP);
1257       }
1258
1259       if (!CR2.isSingleElement()) {
1260         ConstantRange NewCR2 = CR2.intersectWith(
1261                                        create(reversePredicate(LV), CR1));
1262         if (NewCR2 != CR2)
1263           applyRange(n2, NewCR2, Subtree, VRP);
1264       }
1265     }
1266   };
1267
1268   /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1269   /// another discovered to be unreachable. This is used to cull the graph when
1270   /// analyzing instructions, and to mark blocks with the "unreachable"
1271   /// terminator instruction after the function has executed.
1272   class UnreachableBlocks {
1273   private:
1274     std::vector<BasicBlock *> DeadBlocks;
1275
1276   public:
1277     /// mark - mark a block as dead
1278     void mark(BasicBlock *BB) {
1279       std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1280       std::vector<BasicBlock *>::iterator I =
1281         std::lower_bound(DeadBlocks.begin(), E, BB);
1282
1283       if (I == E || *I != BB) DeadBlocks.insert(I, BB);
1284     }
1285
1286     /// isDead - returns whether a block is known to be dead already
1287     bool isDead(BasicBlock *BB) {
1288       std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1289       std::vector<BasicBlock *>::iterator I =
1290         std::lower_bound(DeadBlocks.begin(), E, BB);
1291
1292       return I != E && *I == BB;
1293     }
1294
1295     /// kill - replace the dead blocks' terminator with an UnreachableInst.
1296     bool kill() {
1297       bool modified = false;
1298       for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1299            E = DeadBlocks.end(); I != E; ++I) {
1300         BasicBlock *BB = *I;
1301
1302         DEBUG(errs() << "unreachable block: " << BB->getName() << "\n");
1303
1304         for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1305              SI != SE; ++SI) {
1306           BasicBlock *Succ = *SI;
1307           Succ->removePredecessor(BB);
1308         }
1309
1310         TerminatorInst *TI = BB->getTerminator();
1311         TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1312         TI->eraseFromParent();
1313         new UnreachableInst(BB->getContext(), BB);
1314         ++NumBlocks;
1315         modified = true;
1316       }
1317       DeadBlocks.clear();
1318       return modified;
1319     }
1320   };
1321
1322   /// VRPSolver keeps track of how changes to one variable affect other
1323   /// variables, and forwards changes along to the InequalityGraph. It
1324   /// also maintains the correct choice for "canonical" in the IG.
1325   /// @brief VRPSolver calculates inferences from a new relationship.
1326   class VRPSolver {
1327   private:
1328     friend class ValueRanges;
1329
1330     struct Operation {
1331       Value *LHS, *RHS;
1332       ICmpInst::Predicate Op;
1333
1334       BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
1335       Instruction *ContextInst;
1336     };
1337     std::deque<Operation> WorkList;
1338
1339     ValueNumbering &VN;
1340     InequalityGraph &IG;
1341     UnreachableBlocks &UB;
1342     ValueRanges &VR;
1343     DomTreeDFS *DTDFS;
1344     DomTreeDFS::Node *Top;
1345     BasicBlock *TopBB;
1346     Instruction *TopInst;
1347     bool &modified;
1348     LLVMContext *Context;
1349
1350     typedef InequalityGraph::Node Node;
1351
1352     // below - true if the Instruction is dominated by the current context
1353     // block or instruction
1354     bool below(Instruction *I) {
1355       BasicBlock *BB = I->getParent();
1356       if (TopInst && TopInst->getParent() == BB) {
1357         if (isa<TerminatorInst>(TopInst)) return false;
1358         if (isa<TerminatorInst>(I)) return true;
1359         if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1360         if (!isa<PHINode>(TopInst) &&  isa<PHINode>(I)) return false;
1361
1362         for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1363              Iter != E; ++Iter) {
1364           if (&*Iter == TopInst) return true;
1365           else if (&*Iter == I) return false;
1366         }
1367         assert(!"Instructions not found in parent BasicBlock?");
1368       } else {
1369         DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1370         if (!Node) return false;
1371         return Top->dominates(Node);
1372       }
1373       return false; // Not reached
1374     }
1375
1376     // aboveOrBelow - true if the Instruction either dominates or is dominated
1377     // by the current context block or instruction
1378     bool aboveOrBelow(Instruction *I) {
1379       BasicBlock *BB = I->getParent();
1380       DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1381       if (!Node) return false;
1382
1383       return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1384     }
1385
1386     bool makeEqual(Value *V1, Value *V2) {
1387       DEBUG(errs() << "makeEqual(" << *V1 << ", " << *V2 << ")\n");
1388       DEBUG(errs() << "context is ");
1389       DEBUG(if (TopInst) 
1390               errs() << "I: " << *TopInst << "\n";
1391             else 
1392               errs() << "BB: " << TopBB->getName()
1393                      << "(" << Top->getDFSNumIn() << ")\n");
1394
1395       assert(V1->getType() == V2->getType() &&
1396              "Can't make two values with different types equal.");
1397
1398       if (V1 == V2) return true;
1399
1400       if (isa<Constant>(V1) && isa<Constant>(V2))
1401         return false;
1402
1403       unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
1404
1405       if (n1 && n2) {
1406         if (n1 == n2) return true;
1407         if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1408       }
1409
1410       if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
1411       if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
1412
1413       assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
1414
1415       assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1416
1417       SetVector<unsigned> Remove;
1418       if (n2) Remove.insert(n2);
1419
1420       if (n1 && n2) {
1421         // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1422         // We can't just merge %x and %y because the relationship with %z would
1423         // be EQ and that's invalid. What we're doing is looking for any nodes
1424         // %z such that %x <= %z and %y >= %z, and vice versa.
1425
1426         Node::iterator end = IG.node(n2)->end();
1427
1428         // Find the intersection between N1 and N2 which is dominated by
1429         // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1430         // Remove.
1431         for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
1432              I != E; ++I) {
1433           if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1434
1435           unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1436           unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
1437           Node::iterator NI = IG.node(n2)->find(I->To, Top);
1438           if (NI != end) {
1439             LatticeVal NILV = reversePredicate(NI->LV);
1440             unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1441             unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1442
1443             if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1444                 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1445               Remove.insert(I->To);
1446           }
1447         }
1448
1449         // See if one of the nodes about to be removed is actually a better
1450         // canonical choice than n1.
1451         unsigned orig_n1 = n1;
1452         SetVector<unsigned>::iterator DontRemove = Remove.end();
1453         for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
1454              E = Remove.end(); I != E; ++I) {
1455           unsigned n = *I;
1456           Value *V = VN.value(n);
1457           if (VN.compare(V, V1)) {
1458             V1 = V;
1459             n1 = n;
1460             DontRemove = I;
1461           }
1462         }
1463         if (DontRemove != Remove.end()) {
1464           unsigned n = *DontRemove;
1465           Remove.remove(n);
1466           Remove.insert(orig_n1);
1467         }
1468       }
1469
1470       // We'd like to allow makeEqual on two values to perform a simple
1471       // substitution without creating nodes in the IG whenever possible.
1472       //
1473       // The first iteration through this loop operates on V2 before going
1474       // through the Remove list and operating on those too. If all of the
1475       // iterations performed simple replacements then we exit early.
1476       bool mergeIGNode = false;
1477       unsigned i = 0;
1478       for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1479         if (i) R = VN.value(Remove[i]); // skip n2.
1480
1481         // Try to replace the whole instruction. If we can, we're done.
1482         Instruction *I2 = dyn_cast<Instruction>(R);
1483         if (I2 && below(I2)) {
1484           std::vector<Instruction *> ToNotify;
1485           for (Value::use_iterator UI = I2->use_begin(), UE = I2->use_end();
1486                UI != UE;) {
1487             Use &TheUse = UI.getUse();
1488             ++UI;
1489             Instruction *I = cast<Instruction>(TheUse.getUser());
1490             ToNotify.push_back(I);
1491           }
1492
1493           DEBUG(errs() << "Simply removing " << *I2
1494                        << ", replacing with " << *V1 << "\n");
1495           I2->replaceAllUsesWith(V1);
1496           // leave it dead; it'll get erased later.
1497           ++NumInstruction;
1498           modified = true;
1499
1500           for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1501                IE = ToNotify.end(); II != IE; ++II) {
1502             opsToDef(*II);
1503           }
1504
1505           continue;
1506         }
1507
1508         // Otherwise, replace all dominated uses.
1509         for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1510              UI != UE;) {
1511           Use &TheUse = UI.getUse();
1512           ++UI;
1513           if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1514             if (below(I)) {
1515               TheUse.set(V1);
1516               modified = true;
1517               ++NumVarsReplaced;
1518               opsToDef(I);
1519             }
1520           }
1521         }
1522
1523         // If that killed the instruction, stop here.
1524         if (I2 && isInstructionTriviallyDead(I2)) {
1525           DEBUG(errs() << "Killed all uses of " << *I2
1526                        << ", replacing with " << *V1 << "\n");
1527           continue;
1528         }
1529
1530         // If we make it to here, then we will need to create a node for N1.
1531         // Otherwise, we can skip out early!
1532         mergeIGNode = true;
1533       }
1534
1535       if (!isa<Constant>(V1)) {
1536         if (Remove.empty()) {
1537           VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
1538         } else {
1539           std::vector<Value*> RemoveVals;
1540           RemoveVals.reserve(Remove.size());
1541
1542           for (SetVector<unsigned>::iterator I = Remove.begin(),
1543                E = Remove.end(); I != E; ++I) {
1544             Value *V = VN.value(*I);
1545             if (!V->use_empty())
1546               RemoveVals.push_back(V);
1547           }
1548           VR.mergeInto(&RemoveVals[0], RemoveVals.size(), 
1549                        VN.getOrInsertVN(V1, Top), Top, this);
1550         }
1551       }
1552
1553       if (mergeIGNode) {
1554         // Create N1.
1555         if (!n1) n1 = VN.getOrInsertVN(V1, Top);
1556         IG.node(n1); // Ensure that IG.Nodes won't get resized
1557
1558         // Migrate relationships from removed nodes to N1.
1559         for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1560              I != E; ++I) {
1561           unsigned n = *I;
1562           for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
1563                NI != NE; ++NI) {
1564             if (NI->Subtree->DominatedBy(Top)) {
1565               if (NI->To == n1) {
1566                 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1567                 continue;
1568               }
1569               if (Remove.count(NI->To))
1570                 continue;
1571
1572               IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1573               IG.node(n1)->update(NI->To, NI->LV, Top);
1574             }
1575           }
1576         }
1577
1578         // Point V2 (and all items in Remove) to N1.
1579         if (!n2)
1580           VN.addEquality(n1, V2, Top);
1581         else {
1582           for (SetVector<unsigned>::iterator I = Remove.begin(),
1583                E = Remove.end(); I != E; ++I) {
1584             VN.addEquality(n1, VN.value(*I), Top);
1585           }
1586         }
1587
1588         // If !Remove.empty() then V2 = Remove[0]->getValue().
1589         // Even when Remove is empty, we still want to process V2.
1590         i = 0;
1591         for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1592           if (i) R = VN.value(Remove[i]); // skip n2.
1593
1594           if (Instruction *I2 = dyn_cast<Instruction>(R)) {
1595             if (aboveOrBelow(I2))
1596             defToOps(I2);
1597           }
1598           for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1599                UI != UE;) {
1600             Use &TheUse = UI.getUse();
1601             ++UI;
1602             if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1603               if (aboveOrBelow(I))
1604                 opsToDef(I);
1605             }
1606           }
1607         }
1608       }
1609
1610       // re-opsToDef all dominated users of V1.
1611       if (Instruction *I = dyn_cast<Instruction>(V1)) {
1612         for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1613              UI != UE;) {
1614           Use &TheUse = UI.getUse();
1615           ++UI;
1616           Value *V = TheUse.getUser();
1617           if (!V->use_empty()) {
1618             Instruction *Inst = cast<Instruction>(V);
1619             if (aboveOrBelow(Inst))
1620               opsToDef(Inst);
1621           }
1622         }
1623       }
1624
1625       return true;
1626     }
1627
1628     /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1629     /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1630     static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1631       switch (Pred) {
1632         case ICmpInst::ICMP_EQ:
1633           assert(!"No matching lattice value.");
1634           return static_cast<LatticeVal>(EQ_BIT);
1635         default:
1636           assert(!"Invalid 'icmp' predicate.");
1637         case ICmpInst::ICMP_NE:
1638           return NE;
1639         case ICmpInst::ICMP_UGT:
1640           return UGT;
1641         case ICmpInst::ICMP_UGE:
1642           return UGE;
1643         case ICmpInst::ICMP_ULT:
1644           return ULT;
1645         case ICmpInst::ICMP_ULE:
1646           return ULE;
1647         case ICmpInst::ICMP_SGT:
1648           return SGT;
1649         case ICmpInst::ICMP_SGE:
1650           return SGE;
1651         case ICmpInst::ICMP_SLT:
1652           return SLT;
1653         case ICmpInst::ICMP_SLE:
1654           return SLE;
1655       }
1656     }
1657
1658   public:
1659     VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1660               ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1661               BasicBlock *TopBB)
1662       : VN(VN),
1663         IG(IG),
1664         UB(UB),
1665         VR(VR),
1666         DTDFS(DTDFS),
1667         Top(DTDFS->getNodeForBlock(TopBB)),
1668         TopBB(TopBB),
1669         TopInst(NULL),
1670         modified(modified),
1671         Context(&TopBB->getContext())
1672     {
1673       assert(Top && "VRPSolver created for unreachable basic block.");
1674     }
1675
1676     VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1677               ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1678               Instruction *TopInst)
1679       : VN(VN),
1680         IG(IG),
1681         UB(UB),
1682         VR(VR),
1683         DTDFS(DTDFS),
1684         Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1685         TopBB(TopInst->getParent()),
1686         TopInst(TopInst),
1687         modified(modified),
1688         Context(&TopInst->getContext())
1689     {
1690       assert(Top && "VRPSolver created for unreachable basic block.");
1691       assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
1692     }
1693
1694     bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1695       if (Constant *C1 = dyn_cast<Constant>(V1))
1696         if (Constant *C2 = dyn_cast<Constant>(V2))
1697           return ConstantExpr::getCompare(Pred, C1, C2) ==
1698                  ConstantInt::getTrue(*Context);
1699
1700       unsigned n1 = VN.valueNumber(V1, Top);
1701       unsigned n2 = VN.valueNumber(V2, Top);
1702
1703       if (n1 && n2) {
1704         if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1705                              Pred == ICmpInst::ICMP_ULE ||
1706                              Pred == ICmpInst::ICMP_UGE ||
1707                              Pred == ICmpInst::ICMP_SLE ||
1708                              Pred == ICmpInst::ICMP_SGE;
1709         if (Pred == ICmpInst::ICMP_EQ) return false;
1710         if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1711         if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1712       }
1713
1714       if ((n1 && !n2 && isa<Constant>(V2)) ||
1715           (n2 && !n1 && isa<Constant>(V1))) {
1716         ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
1717         ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
1718
1719         if (Pred == ICmpInst::ICMP_EQ)
1720           return CR1.isSingleElement() &&
1721                  CR1.getSingleElement() == CR2.getSingleElement();
1722
1723         return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
1724       }
1725       if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
1726       return false;
1727     }
1728
1729     /// add - adds a new property to the work queue
1730     void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1731              Instruction *I = NULL) {
1732       DEBUG(errs() << "adding " << *V1 << " " << Pred << " " << *V2);
1733       if (I)
1734         DEBUG(errs() << " context: " << *I);
1735       else 
1736         DEBUG(errs() << " default context (" << Top->getDFSNumIn() << ")");
1737       DEBUG(errs() << "\n");
1738
1739       assert(V1->getType() == V2->getType() &&
1740              "Can't relate two values with different types.");
1741
1742       WorkList.push_back(Operation());
1743       Operation &O = WorkList.back();
1744       O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1745       O.ContextBB = I ? I->getParent() : TopBB;
1746     }
1747
1748     /// defToOps - Given an instruction definition that we've learned something
1749     /// new about, find any new relationships between its operands.
1750     void defToOps(Instruction *I) {
1751       Instruction *NewContext = below(I) ? I : TopInst;
1752       Value *Canonical = VN.canonicalize(I, Top);
1753
1754       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1755         const Type *Ty = BO->getType();
1756         assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1757
1758         Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1759         Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1760
1761         // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
1762
1763         switch (BO->getOpcode()) {
1764           case Instruction::And: {
1765             // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
1766             ConstantInt *CI = cast<ConstantInt>(Constant::getAllOnesValue(Ty));
1767             if (Canonical == CI) {
1768               add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1769               add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
1770             }
1771           } break;
1772           case Instruction::Or: {
1773             // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
1774             Constant *Zero = Constant::getNullValue(Ty);
1775             if (Canonical == Zero) {
1776               add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1777               add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1778             }
1779           } break;
1780           case Instruction::Xor: {
1781             // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1782             // "xor i32 %c, %a" EQ %c then %a EQ 0
1783             // "xor i32 %c, %a" NE %c then %a NE 0
1784             // Repeat the above, with order of operands reversed.
1785             Value *LHS = Op0;
1786             Value *RHS = Op1;
1787             if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1788
1789             if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1790               if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
1791                 add(RHS,
1792                   ConstantInt::get(*Context, CI->getValue() ^ Arg->getValue()),
1793                     ICmpInst::ICMP_EQ, NewContext);
1794               }
1795             }
1796             if (Canonical == LHS) {
1797               if (isa<ConstantInt>(Canonical))
1798                 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1799                     NewContext);
1800             } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1801               add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1802                   NewContext);
1803             }
1804           } break;
1805           default:
1806             break;
1807         }
1808       } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1809         // "icmp ult i32 %a, %y" EQ true then %a u< y
1810         // etc.
1811
1812         if (Canonical == ConstantInt::getTrue(*Context)) {
1813           add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1814               NewContext);
1815         } else if (Canonical == ConstantInt::getFalse(*Context)) {
1816           add(IC->getOperand(0), IC->getOperand(1),
1817               ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1818         }
1819       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1820         if (I->getType()->isFPOrFPVector()) return;
1821
1822         // Given: "%a = select i1 %x, i32 %b, i32 %c"
1823         // %a EQ %b and %b NE %c then %x EQ true
1824         // %a EQ %c and %b NE %c then %x EQ false
1825
1826         Value *True  = SI->getTrueValue();
1827         Value *False = SI->getFalseValue();
1828         if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1829           if (Canonical == VN.canonicalize(True, Top) ||
1830               isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
1831             add(SI->getCondition(), ConstantInt::getTrue(*Context),
1832                 ICmpInst::ICMP_EQ, NewContext);
1833           else if (Canonical == VN.canonicalize(False, Top) ||
1834                    isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
1835             add(SI->getCondition(), ConstantInt::getFalse(*Context),
1836                 ICmpInst::ICMP_EQ, NewContext);
1837         }
1838       } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1839         for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1840              OE = GEPI->idx_end(); OI != OE; ++OI) {
1841           ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
1842           if (!Op || !Op->isZero()) return;
1843         }
1844         // TODO: The GEPI indices are all zero. Copy from definition to operand,
1845         // jumping the type plane as needed.
1846         if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1847                         ICmpInst::ICMP_NE)) {
1848           Value *Ptr = GEPI->getPointerOperand();
1849           add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1850               NewContext);
1851         }
1852       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1853         const Type *SrcTy = CI->getSrcTy();
1854
1855         unsigned ci = VN.getOrInsertVN(CI, Top);
1856         uint32_t W = VR.typeToWidth(SrcTy);
1857         if (!W) return;
1858         ConstantRange CR = VR.range(ci, Top);
1859
1860         if (CR.isFullSet()) return;
1861
1862         switch (CI->getOpcode()) {
1863           default: break;
1864           case Instruction::ZExt:
1865           case Instruction::SExt:
1866             VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1867                           CR.truncate(W), Top, this);
1868             break;
1869           case Instruction::BitCast:
1870             VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1871                           CR, Top, this);
1872             break;
1873         }
1874       }
1875     }
1876
1877     /// opsToDef - A new relationship was discovered involving one of this
1878     /// instruction's operands. Find any new relationship involving the
1879     /// definition, or another operand.
1880     void opsToDef(Instruction *I) {
1881       Instruction *NewContext = below(I) ? I : TopInst;
1882
1883       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1884         Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1885         Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1886
1887         if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1888           if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1889             add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1890                 ICmpInst::ICMP_EQ, NewContext);
1891             return;
1892           }
1893
1894         // "%y = and i1 true, %x" then %x EQ %y
1895         // "%y = or i1 false, %x" then %x EQ %y
1896         // "%x = add i32 %y, 0" then %x EQ %y
1897         // "%x = mul i32 %y, 0" then %x EQ 0
1898
1899         Instruction::BinaryOps Opcode = BO->getOpcode();
1900         const Type *Ty = BO->getType();
1901         assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1902
1903         Constant *Zero = Constant::getNullValue(Ty);
1904         Constant *One = ConstantInt::get(Ty, 1);
1905         ConstantInt *AllOnes = cast<ConstantInt>(Constant::getAllOnesValue(Ty));
1906
1907         switch (Opcode) {
1908           default: break;
1909           case Instruction::LShr:
1910           case Instruction::AShr:
1911           case Instruction::Shl:
1912             if (Op1 == Zero) {
1913               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1914               return;
1915             }
1916             break;
1917           case Instruction::Sub:
1918             if (Op1 == Zero) {
1919               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1920               return;
1921             }
1922             if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
1923               unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
1924               ConstantRange CR = VR.range(n_ci0, Top);
1925               if (!CR.isFullSet()) {
1926                 CR.subtract(CI0->getValue());
1927                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1928                 VR.applyRange(n_bo, CR, Top, this);
1929                 return;
1930               }
1931             }
1932             if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1933               unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
1934               ConstantRange CR = VR.range(n_ci1, Top);
1935               if (!CR.isFullSet()) {
1936                 CR.subtract(CI1->getValue());
1937                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1938                 VR.applyRange(n_bo, CR, Top, this);
1939                 return;
1940               }
1941             }
1942             break;
1943           case Instruction::Or:
1944             if (Op0 == AllOnes || Op1 == AllOnes) {
1945               add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1946               return;
1947             }
1948             if (Op0 == Zero) {
1949               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1950               return;
1951             } else if (Op1 == Zero) {
1952               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1953               return;
1954             }
1955             break;
1956           case Instruction::Add:
1957             if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
1958               unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
1959               ConstantRange CR = VR.range(n_ci0, Top);
1960               if (!CR.isFullSet()) {
1961                 CR.subtract(-CI0->getValue());
1962                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1963                 VR.applyRange(n_bo, CR, Top, this);
1964                 return;
1965               }
1966             }
1967             if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1968               unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
1969               ConstantRange CR = VR.range(n_ci1, Top);
1970               if (!CR.isFullSet()) {
1971                 CR.subtract(-CI1->getValue());
1972                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1973                 VR.applyRange(n_bo, CR, Top, this);
1974                 return;
1975               }
1976             }
1977             // fall-through
1978           case Instruction::Xor:
1979             if (Op0 == Zero) {
1980               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1981               return;
1982             } else if (Op1 == Zero) {
1983               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1984               return;
1985             }
1986             break;
1987           case Instruction::And:
1988             if (Op0 == AllOnes) {
1989               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1990               return;
1991             } else if (Op1 == AllOnes) {
1992               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1993               return;
1994             }
1995             if (Op0 == Zero || Op1 == Zero) {
1996               add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1997               return;
1998             }
1999             break;
2000           case Instruction::Mul:
2001             if (Op0 == Zero || Op1 == Zero) {
2002               add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
2003               return;
2004             }
2005             if (Op0 == One) {
2006               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
2007               return;
2008             } else if (Op1 == One) {
2009               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
2010               return;
2011             }
2012             break;
2013         }
2014
2015         // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
2016         // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
2017         // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
2018         // "%x = udiv i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 1
2019
2020         Value *Known = Op0, *Unknown = Op1,
2021               *TheBO = VN.canonicalize(BO, Top);
2022         if (Known != TheBO) std::swap(Known, Unknown);
2023         if (Known == TheBO) {
2024           switch (Opcode) {
2025             default: break;
2026             case Instruction::LShr:
2027             case Instruction::AShr:
2028             case Instruction::Shl:
2029               if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
2030               // otherwise, fall-through.
2031             case Instruction::Sub:
2032               if (Unknown == Op0) break;
2033               // otherwise, fall-through.
2034             case Instruction::Xor:
2035             case Instruction::Add:
2036               add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
2037               break;
2038             case Instruction::UDiv:
2039             case Instruction::SDiv:
2040               if (Unknown == Op1) break;
2041               if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE))
2042                 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
2043               break;
2044           }
2045         }
2046
2047         // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
2048
2049       } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
2050         // "%a = icmp ult i32 %b, %c" and %b u<  %c then %a EQ true
2051         // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
2052         // etc.
2053
2054         Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
2055         Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
2056
2057         ICmpInst::Predicate Pred = IC->getPredicate();
2058         if (isRelatedBy(Op0, Op1, Pred))
2059           add(IC, ConstantInt::getTrue(*Context), ICmpInst::ICMP_EQ, NewContext);
2060         else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
2061           add(IC, ConstantInt::getFalse(*Context),
2062               ICmpInst::ICMP_EQ, NewContext);
2063
2064       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
2065         if (I->getType()->isFPOrFPVector()) return;
2066
2067         // Given: "%a = select i1 %x, i32 %b, i32 %c"
2068         // %x EQ true  then %a EQ %b
2069         // %x EQ false then %a EQ %c
2070         // %b EQ %c then %a EQ %b
2071
2072         Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
2073         if (Canonical == ConstantInt::getTrue(*Context)) {
2074           add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2075         } else if (Canonical == ConstantInt::getFalse(*Context)) {
2076           add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
2077         } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
2078                    VN.canonicalize(SI->getFalseValue(), Top)) {
2079           add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2080         }
2081       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2082         const Type *DestTy = CI->getDestTy();
2083         if (DestTy->isFPOrFPVector()) return;
2084
2085         Value *Op = VN.canonicalize(CI->getOperand(0), Top);
2086         Instruction::CastOps Opcode = CI->getOpcode();
2087
2088         if (Constant *C = dyn_cast<Constant>(Op)) {
2089           add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
2090               ICmpInst::ICMP_EQ, NewContext);
2091         }
2092
2093         uint32_t W = VR.typeToWidth(DestTy);
2094         unsigned ci = VN.getOrInsertVN(CI, Top);
2095         ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
2096
2097         if (!CR.isFullSet()) {
2098           switch (Opcode) {
2099             default: break;
2100             case Instruction::ZExt:
2101               VR.applyRange(ci, CR.zeroExtend(W), Top, this);
2102               break;
2103             case Instruction::SExt:
2104               VR.applyRange(ci, CR.signExtend(W), Top, this);
2105               break;
2106             case Instruction::Trunc: {
2107               ConstantRange Result = CR.truncate(W);
2108               if (!Result.isFullSet())
2109                 VR.applyRange(ci, Result, Top, this);
2110             } break;
2111             case Instruction::BitCast:
2112               VR.applyRange(ci, CR, Top, this);
2113               break;
2114             // TODO: other casts?
2115           }
2116         }
2117       } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2118         for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2119              OE = GEPI->idx_end(); OI != OE; ++OI) {
2120           ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
2121           if (!Op || !Op->isZero()) return;
2122         }
2123         // TODO: The GEPI indices are all zero. Copy from operand to definition,
2124         // jumping the type plane as needed.
2125         Value *Ptr = GEPI->getPointerOperand();
2126         if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
2127                         ICmpInst::ICMP_NE)) {
2128           add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2129               NewContext);
2130         }
2131       }
2132     }
2133
2134     /// solve - process the work queue
2135     void solve() {
2136       //DEBUG(errs() << "WorkList entry, size: " << WorkList.size() << "\n");
2137       while (!WorkList.empty()) {
2138         //DEBUG(errs() << "WorkList size: " << WorkList.size() << "\n");
2139
2140         Operation &O = WorkList.front();
2141         TopInst = O.ContextInst;
2142         TopBB = O.ContextBB;
2143         Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
2144
2145         O.LHS = VN.canonicalize(O.LHS, Top);
2146         O.RHS = VN.canonicalize(O.RHS, Top);
2147
2148         assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2149         assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
2150
2151         DEBUG(errs() << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
2152               if (O.ContextInst) 
2153                 errs() << " context inst: " << *O.ContextInst;
2154               else
2155                 errs() << " context block: " << O.ContextBB->getName();
2156               errs() << "\n";
2157
2158               VN.dump();
2159               IG.dump();
2160               VR.dump(););
2161
2162         // If they're both Constant, skip it. Check for contradiction and mark
2163         // the BB as unreachable if so.
2164         if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2165           if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
2166             if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
2167                 ConstantInt::getFalse(*Context))
2168               UB.mark(TopBB);
2169
2170             WorkList.pop_front();
2171             continue;
2172           }
2173         }
2174
2175         if (VN.compare(O.LHS, O.RHS)) {
2176           std::swap(O.LHS, O.RHS);
2177           O.Op = ICmpInst::getSwappedPredicate(O.Op);
2178         }
2179
2180         if (O.Op == ICmpInst::ICMP_EQ) {
2181           if (!makeEqual(O.RHS, O.LHS))
2182             UB.mark(TopBB);
2183         } else {
2184           LatticeVal LV = cmpInstToLattice(O.Op);
2185
2186           if ((LV & EQ_BIT) &&
2187               isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
2188             if (!makeEqual(O.RHS, O.LHS))
2189               UB.mark(TopBB);
2190           } else {
2191             if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
2192               UB.mark(TopBB);
2193               WorkList.pop_front();
2194               continue;
2195             }
2196
2197             unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
2198             unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
2199
2200             if (n1 == n2) {
2201               if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2202                   O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2203                 UB.mark(TopBB);
2204
2205               WorkList.pop_front();
2206               continue;
2207             }
2208
2209             if (VR.isRelatedBy(n1, n2, Top, LV) ||
2210                 IG.isRelatedBy(n1, n2, Top, LV)) {
2211               WorkList.pop_front();
2212               continue;
2213             }
2214
2215             VR.addInequality(n1, n2, Top, LV, this);
2216             if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
2217                 LV == NE)
2218               IG.addInequality(n1, n2, Top, LV);
2219
2220             if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
2221               if (aboveOrBelow(I1))
2222                 defToOps(I1);
2223             }
2224             if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2225               for (Value::use_iterator UI = O.LHS->use_begin(),
2226                    UE = O.LHS->use_end(); UI != UE;) {
2227                 Use &TheUse = UI.getUse();
2228                 ++UI;
2229                 Instruction *I = cast<Instruction>(TheUse.getUser());
2230                 if (aboveOrBelow(I))
2231                   opsToDef(I);
2232               }
2233             }
2234             if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
2235               if (aboveOrBelow(I2))
2236               defToOps(I2);
2237             }
2238             if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2239               for (Value::use_iterator UI = O.RHS->use_begin(),
2240                    UE = O.RHS->use_end(); UI != UE;) {
2241                 Use &TheUse = UI.getUse();
2242                 ++UI;
2243                 Instruction *I = cast<Instruction>(TheUse.getUser());
2244                 if (aboveOrBelow(I))
2245                   opsToDef(I);
2246               }
2247             }
2248           }
2249         }
2250         WorkList.pop_front();
2251       }
2252     }
2253   };
2254
2255   void ValueRanges::addToWorklist(Value *V, Constant *C,
2256                                   ICmpInst::Predicate Pred, VRPSolver *VRP) {
2257     VRP->add(V, C, Pred, VRP->TopInst);
2258   }
2259
2260   void ValueRanges::markBlock(VRPSolver *VRP) {
2261     VRP->UB.mark(VRP->TopBB);
2262   }
2263
2264   /// PredicateSimplifier - This class is a simplifier that replaces
2265   /// one equivalent variable with another. It also tracks what
2266   /// can't be equal and will solve setcc instructions when possible.
2267   /// @brief Root of the predicate simplifier optimization.
2268   class PredicateSimplifier : public FunctionPass {
2269     DomTreeDFS *DTDFS;
2270     bool modified;
2271     ValueNumbering *VN;
2272     InequalityGraph *IG;
2273     UnreachableBlocks UB;
2274     ValueRanges *VR;
2275
2276     std::vector<DomTreeDFS::Node *> WorkList;
2277
2278     LLVMContext *Context;
2279   public:
2280     static char ID; // Pass identification, replacement for typeid
2281     PredicateSimplifier() : FunctionPass(&ID) {}
2282
2283     bool runOnFunction(Function &F);
2284
2285     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2286       AU.addRequiredID(BreakCriticalEdgesID);
2287       AU.addRequired<DominatorTree>();
2288     }
2289
2290   private:
2291     /// Forwards - Adds new properties to VRPSolver and uses them to
2292     /// simplify instructions. Because new properties sometimes apply to
2293     /// a transition from one BasicBlock to another, this will use the
2294     /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
2295     /// basic block.
2296     /// @brief Performs abstract execution of the program.
2297     class Forwards : public InstVisitor<Forwards> {
2298       friend class InstVisitor<Forwards>;
2299       PredicateSimplifier *PS;
2300       DomTreeDFS::Node *DTNode;
2301
2302     public:
2303       ValueNumbering &VN;
2304       InequalityGraph &IG;
2305       UnreachableBlocks &UB;
2306       ValueRanges &VR;
2307
2308       Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
2309         : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
2310           VR(*PS->VR) {}
2311
2312       void visitTerminatorInst(TerminatorInst &TI);
2313       void visitBranchInst(BranchInst &BI);
2314       void visitSwitchInst(SwitchInst &SI);
2315
2316       void visitAllocaInst(AllocaInst &AI);
2317       void visitLoadInst(LoadInst &LI);
2318       void visitStoreInst(StoreInst &SI);
2319
2320       void visitSExtInst(SExtInst &SI);
2321       void visitZExtInst(ZExtInst &ZI);
2322
2323       void visitBinaryOperator(BinaryOperator &BO);
2324       void visitICmpInst(ICmpInst &IC);
2325     };
2326   
2327     // Used by terminator instructions to proceed from the current basic
2328     // block to the next. Verifies that "current" dominates "next",
2329     // then calls visitBasicBlock.
2330     void proceedToSuccessors(DomTreeDFS::Node *Current) {
2331       for (DomTreeDFS::Node::iterator I = Current->begin(),
2332            E = Current->end(); I != E; ++I) {
2333         WorkList.push_back(*I);
2334       }
2335     }
2336
2337     void proceedToSuccessor(DomTreeDFS::Node *Next) {
2338       WorkList.push_back(Next);
2339     }
2340
2341     // Visits each instruction in the basic block.
2342     void visitBasicBlock(DomTreeDFS::Node *Node) {
2343       BasicBlock *BB = Node->getBlock();
2344       DEBUG(errs() << "Entering Basic Block: " << BB->getName()
2345             << " (" << Node->getDFSNumIn() << ")\n");
2346       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2347         visitInstruction(I++, Node);
2348       }
2349     }
2350
2351     // Tries to simplify each Instruction and add new properties.
2352     void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
2353       DEBUG(errs() << "Considering instruction " << *I << "\n");
2354       DEBUG(VN->dump());
2355       DEBUG(IG->dump());
2356       DEBUG(VR->dump());
2357
2358       // Sometimes instructions are killed in earlier analysis.
2359       if (isInstructionTriviallyDead(I)) {
2360         ++NumSimple;
2361         modified = true;
2362         if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2363           if (VN->value(n) == I) IG->remove(n);
2364         VN->remove(I);
2365         I->eraseFromParent();
2366         return;
2367       }
2368
2369 #ifndef NDEBUG
2370       // Try to replace the whole instruction.
2371       Value *V = VN->canonicalize(I, DT);
2372       assert(V == I && "Late instruction canonicalization.");
2373       if (V != I) {
2374         modified = true;
2375         ++NumInstruction;
2376         DEBUG(errs() << "Removing " << *I << ", replacing with " << *V << "\n");
2377         if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2378           if (VN->value(n) == I) IG->remove(n);
2379         VN->remove(I);
2380         I->replaceAllUsesWith(V);
2381         I->eraseFromParent();
2382         return;
2383       }
2384
2385       // Try to substitute operands.
2386       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2387         Value *Oper = I->getOperand(i);
2388         Value *V = VN->canonicalize(Oper, DT);
2389         assert(V == Oper && "Late operand canonicalization.");
2390         if (V != Oper) {
2391           modified = true;
2392           ++NumVarsReplaced;
2393           DEBUG(errs() << "Resolving " << *I);
2394           I->setOperand(i, V);
2395           DEBUG(errs() << " into " << *I);
2396         }
2397       }
2398 #endif
2399
2400       std::string name = I->getParent()->getName();
2401       DEBUG(errs() << "push (%" << name << ")\n");
2402       Forwards visit(this, DT);
2403       visit.visit(*I);
2404       DEBUG(errs() << "pop (%" << name << ")\n");
2405     }
2406   };
2407
2408   bool PredicateSimplifier::runOnFunction(Function &F) {
2409     DominatorTree *DT = &getAnalysis<DominatorTree>();
2410     DTDFS = new DomTreeDFS(DT);
2411     TargetData *TD = getAnalysisIfAvailable<TargetData>();
2412
2413     // FIXME: PredicateSimplifier should still be able to do basic
2414     // optimizations without TargetData. But for now, just exit if
2415     // it's not available.
2416     if (!TD) return false;
2417
2418     Context = &F.getContext();
2419
2420     DEBUG(errs() << "Entering Function: " << F.getName() << "\n");
2421
2422     modified = false;
2423     DomTreeDFS::Node *Root = DTDFS->getRootNode();
2424     VN = new ValueNumbering(DTDFS);
2425     IG = new InequalityGraph(*VN, Root);
2426     VR = new ValueRanges(*VN, TD, Context);
2427     WorkList.push_back(Root);
2428
2429     do {
2430       DomTreeDFS::Node *DTNode = WorkList.back();
2431       WorkList.pop_back();
2432       if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
2433     } while (!WorkList.empty());
2434
2435     delete DTDFS;
2436     delete VR;
2437     delete IG;
2438     delete VN;
2439
2440     modified |= UB.kill();
2441
2442     return modified;
2443   }
2444
2445   void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
2446     PS->proceedToSuccessors(DTNode);
2447   }
2448
2449   void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
2450     if (BI.isUnconditional()) {
2451       PS->proceedToSuccessors(DTNode);
2452       return;
2453     }
2454
2455     Value *Condition = BI.getCondition();
2456     BasicBlock *TrueDest  = BI.getSuccessor(0);
2457     BasicBlock *FalseDest = BI.getSuccessor(1);
2458
2459     if (isa<Constant>(Condition) || TrueDest == FalseDest) {
2460       PS->proceedToSuccessors(DTNode);
2461       return;
2462     }
2463
2464     LLVMContext *Context = &BI.getContext();
2465
2466     for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2467          I != E; ++I) {
2468       BasicBlock *Dest = (*I)->getBlock();
2469       DEBUG(errs() << "Branch thinking about %" << Dest->getName()
2470             << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n");
2471
2472       if (Dest == TrueDest) {
2473         DEBUG(errs() << "(" << DTNode->getBlock()->getName() 
2474               << ") true set:\n");
2475         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2476         VRP.add(ConstantInt::getTrue(*Context), Condition, ICmpInst::ICMP_EQ);
2477         VRP.solve();
2478         DEBUG(VN.dump());
2479         DEBUG(IG.dump());
2480         DEBUG(VR.dump());
2481       } else if (Dest == FalseDest) {
2482         DEBUG(errs() << "(" << DTNode->getBlock()->getName() 
2483               << ") false set:\n");
2484         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2485         VRP.add(ConstantInt::getFalse(*Context), Condition, ICmpInst::ICMP_EQ);
2486         VRP.solve();
2487         DEBUG(VN.dump());
2488         DEBUG(IG.dump());
2489         DEBUG(VR.dump());
2490       }
2491
2492       PS->proceedToSuccessor(*I);
2493     }
2494   }
2495
2496   void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2497     Value *Condition = SI.getCondition();
2498
2499     // Set the EQProperty in each of the cases BBs, and the NEProperties
2500     // in the default BB.
2501
2502     for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2503          I != E; ++I) {
2504       BasicBlock *BB = (*I)->getBlock();
2505       DEBUG(errs() << "Switch thinking about BB %" << BB->getName()
2506             << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n");
2507
2508       VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
2509       if (BB == SI.getDefaultDest()) {
2510         for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2511           if (SI.getSuccessor(i) != BB)
2512             VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2513         VRP.solve();
2514       } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
2515         VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2516         VRP.solve();
2517       }
2518       PS->proceedToSuccessor(*I);
2519     }
2520   }
2521
2522   void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
2523     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
2524     VRP.add(Constant::getNullValue(AI.getType()),
2525             &AI, ICmpInst::ICMP_NE);
2526     VRP.solve();
2527   }
2528
2529   void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2530     Value *Ptr = LI.getPointerOperand();
2531     // avoid "load i8* null" -> null NE null.
2532     if (isa<Constant>(Ptr)) return;
2533
2534     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
2535     VRP.add(Constant::getNullValue(Ptr->getType()),
2536             Ptr, ICmpInst::ICMP_NE);
2537     VRP.solve();
2538   }
2539
2540   void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2541     Value *Ptr = SI.getPointerOperand();
2542     if (isa<Constant>(Ptr)) return;
2543
2544     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2545     VRP.add(Constant::getNullValue(Ptr->getType()),
2546             Ptr, ICmpInst::ICMP_NE);
2547     VRP.solve();
2548   }
2549
2550   void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
2551     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2552     LLVMContext &Context = SI.getContext();
2553     uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2554     uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
2555     APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2556     APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
2557     VRP.add(ConstantInt::get(Context, Min), &SI, ICmpInst::ICMP_SLE);
2558     VRP.add(ConstantInt::get(Context, Max), &SI, ICmpInst::ICMP_SGE);
2559     VRP.solve();
2560   }
2561
2562   void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
2563     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
2564     LLVMContext &Context = ZI.getContext();
2565     uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2566     uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
2567     APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
2568     VRP.add(ConstantInt::get(Context, Max), &ZI, ICmpInst::ICMP_UGE);
2569     VRP.solve();
2570   }
2571
2572   void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2573     Instruction::BinaryOps ops = BO.getOpcode();
2574
2575     switch (ops) {
2576     default: break;
2577       case Instruction::URem:
2578       case Instruction::SRem:
2579       case Instruction::UDiv:
2580       case Instruction::SDiv: {
2581         Value *Divisor = BO.getOperand(1);
2582         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2583         VRP.add(Constant::getNullValue(Divisor->getType()), 
2584                 Divisor, ICmpInst::ICMP_NE);
2585         VRP.solve();
2586         break;
2587       }
2588     }
2589
2590     switch (ops) {
2591       default: break;
2592       case Instruction::Shl: {
2593         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2594         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2595         VRP.solve();
2596       } break;
2597       case Instruction::AShr: {
2598         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2599         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2600         VRP.solve();
2601       } break;
2602       case Instruction::LShr:
2603       case Instruction::UDiv: {
2604         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2605         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2606         VRP.solve();
2607       } break;
2608       case Instruction::URem: {
2609         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2610         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2611         VRP.solve();
2612       } break;
2613       case Instruction::And: {
2614         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2615         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2616         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2617         VRP.solve();
2618       } break;
2619       case Instruction::Or: {
2620         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2621         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2622         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2623         VRP.solve();
2624       } break;
2625     }
2626   }
2627
2628   void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2629     // If possible, squeeze the ICmp predicate into something simpler.
2630     // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2631     // the predicate to eq.
2632
2633     // XXX: once we do full PHI handling, modifying the instruction in the
2634     // Forwards visitor will cause missed optimizations.
2635
2636     ICmpInst::Predicate Pred = IC.getPredicate();
2637
2638     switch (Pred) {
2639       default: break;
2640       case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2641       case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2642       case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2643       case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2644     }
2645     if (Pred != IC.getPredicate()) {
2646       VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2647       if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2648                           ICmpInst::ICMP_NE)) {
2649         ++NumSnuggle;
2650         PS->modified = true;
2651         IC.setPredicate(Pred);
2652       }
2653     }
2654
2655     Pred = IC.getPredicate();
2656
2657     LLVMContext &Context = IC.getContext();
2658
2659     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2660       ConstantInt *NextVal = 0;
2661       switch (Pred) {
2662         default: break;
2663         case ICmpInst::ICMP_SLT:
2664         case ICmpInst::ICMP_ULT:
2665           if (Op1->getValue() != 0)
2666             NextVal = ConstantInt::get(Context, Op1->getValue()-1);
2667          break;
2668         case ICmpInst::ICMP_SGT:
2669         case ICmpInst::ICMP_UGT:
2670           if (!Op1->getValue().isAllOnesValue())
2671             NextVal = ConstantInt::get(Context, Op1->getValue()+1);
2672          break;
2673       }
2674
2675       if (NextVal) {
2676         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2677         if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2678                             ICmpInst::getInversePredicate(Pred))) {
2679           ICmpInst *NewIC = new ICmpInst(&IC, ICmpInst::ICMP_EQ, 
2680                                          IC.getOperand(0), NextVal, "");
2681           NewIC->takeName(&IC);
2682           IC.replaceAllUsesWith(NewIC);
2683
2684           // XXX: prove this isn't necessary
2685           if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
2686             if (VN.value(n) == &IC) IG.remove(n);
2687           VN.remove(&IC);
2688
2689           IC.eraseFromParent();
2690           ++NumSnuggle;
2691           PS->modified = true;
2692         }
2693       }
2694     }
2695   }
2696 }
2697
2698 char PredicateSimplifier::ID = 0;
2699 static RegisterPass<PredicateSimplifier>
2700 X("predsimplify", "Predicate Simplifier");
2701
2702 FunctionPass *llvm::createPredicateSimplifierPass() {
2703   return new PredicateSimplifier();
2704 }