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