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