Fix unionSets so that it can merge correctly.
[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 // This optimization works by substituting %q for %p when protected by a
26 // conditional that assures us of that fact. Properties are stored as
27 // relationships between two values.
28 //
29 //===------------------------------------------------------------------===//
30
31 #define DEBUG_TYPE "predsimplify"
32 #include "llvm/Transforms/Scalar.h"
33 #include "llvm/Constants.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/Pass.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/Analysis/Dominators.h"
39 #include "llvm/Support/CFG.h"
40 #include "llvm/Support/Debug.h"
41 #include <iostream>
42 using namespace llvm;
43
44 typedef DominatorTree::Node DTNodeType;
45
46 namespace {
47   Statistic<>
48   NumVarsReplaced("predsimplify", "Number of argument substitutions");
49   Statistic<>
50   NumInstruction("predsimplify", "Number of instructions removed");
51   Statistic<>
52   NumSwitchCases("predsimplify", "Number of switch cases removed");
53   Statistic<>
54   NumBranches("predsimplify", "Number of branches made unconditional");
55
56   /// Returns true if V1 is a better choice than V2. Note that it is
57   /// not a total ordering.
58   struct compare {
59     bool operator()(Value *V1, Value *V2) const {
60       if (isa<Constant>(V1)) {
61         if (!isa<Constant>(V2)) {
62           return true;
63         }
64       } else if (isa<Argument>(V1)) {
65         if (!isa<Constant>(V2) && !isa<Argument>(V2)) {
66           return true;
67         }
68       }
69       if (User *U = dyn_cast<User>(V2)) {
70         for (User::const_op_iterator I = U->op_begin(), E = U->op_end();
71              I != E; ++I) {
72           if (*I == V1) {
73             return true;
74           }
75         }
76       }
77       return false;
78     }
79   };
80
81   /// Used for choosing the canonical Value in a synonym set.
82   /// Leaves the better choice in V1.
83   static void order(Value *&V1, Value *&V2) {
84     static compare c;
85     if (c(V2, V1))
86       std::swap(V1, V2);
87   }
88
89   /// Similar to EquivalenceClasses, this stores the set of equivalent
90   /// types. Beyond EquivalenceClasses, it allows the user to specify
91   /// which element will act as leader through a StrictWeakOrdering
92   /// function.
93   template<typename ElemTy, typename StrictWeak>
94   class VISIBILITY_HIDDEN Synonyms {
95     std::map<ElemTy, unsigned> mapping;
96     std::vector<ElemTy> leaders;
97     StrictWeak swo;
98
99   public:
100     typedef unsigned iterator;
101     typedef const unsigned const_iterator;
102
103     // Inspection
104
105     bool empty() const {
106       return leaders.empty();
107     }
108
109     iterator findLeader(ElemTy e) {
110       typename std::map<ElemTy, unsigned>::iterator MI = mapping.find(e);
111       if (MI == mapping.end()) return 0;
112
113       return MI->second;
114     }
115
116     const_iterator findLeader(ElemTy e) const {
117       typename std::map<ElemTy, unsigned>::const_iterator MI =
118           mapping.find(e);
119       if (MI == mapping.end()) return 0;
120
121       return MI->second;
122     }
123
124     ElemTy &getLeader(iterator I) {
125       assert(I != 0 && "Element zero is out of range.");
126       return leaders[I-1];
127     }
128
129     const ElemTy &getLeader(const_iterator I) const {
130       assert(I != 0 && "Element zero is out of range.");
131       return leaders[I-1];
132     }
133
134 #ifdef DEBUG
135     void debug(std::ostream &os) const {
136       for (unsigned i = 1, e = leaders.size()+1; i != e; ++i) {
137         os << i << ". " << *leaders[i-1] << ": [";
138         for (std::map<Value *, unsigned>::const_iterator
139              I = mapping.begin(), E = mapping.end(); I != E; ++I) {
140           if ((*I).second == i && (*I).first != leaders[i-1]) {
141             os << *(*I).first << "  ";
142           }
143         }
144         os << "]\n";
145       }
146     }
147 #endif
148
149     // Mutators
150
151     /// Combine two sets referring to the same element, inserting the
152     /// elements as needed. Returns a valid iterator iff two already
153     /// existing disjoint synonym sets were combined. The iterator
154     /// points to the removed element.
155     iterator unionSets(ElemTy E1, ElemTy E2) {
156       if (swo(E2, E1)) std::swap(E1, E2);
157
158       iterator I1 = findLeader(E1),
159                I2 = findLeader(E2);
160
161       if (!I1 && !I2) { // neither entry is in yet
162         leaders.push_back(E1);
163         I1 = leaders.size();
164         mapping[E1] = I1;
165         mapping[E2] = I1;
166         return 0;
167       }
168
169       if (!I1 && I2) {
170         mapping[E1] = I2;
171         std::swap(getLeader(I2), E1);
172         return 0;
173       }
174
175       if (I1 && !I2) {
176         mapping[E2] = I1;
177         return 0;
178       }
179
180       if (I1 == I2) return 0;
181
182       // This is the case where we have two sets, [%a1, %a2, %a3] and
183       // [%p1, %p2, %p3] and someone says that %a2 == %p3. We need to
184       // combine the two synsets.
185
186       if (I1 > I2) --I1;
187
188       for (std::map<Value *, unsigned>::iterator I = mapping.begin(),
189            E = mapping.end(); I != E; ++I) {
190         if (I->second == I2) I->second = I1;
191         else if (I->second > I2) --I->second;
192       }
193
194       leaders.erase(leaders.begin() + I2 - 1);
195
196       return I2;
197     }
198
199     /// Returns an iterator pointing to the synonym set containing
200     /// element e. If none exists, a new one is created and returned.
201     iterator findOrInsert(ElemTy e) {
202       iterator I = findLeader(e);
203       if (I) return I;
204
205       leaders.push_back(e);
206       I = leaders.size();
207       mapping[e] = I;
208       return I;
209     }
210   };
211
212   /// Represents the set of equivalent Value*s and provides insertion
213   /// and fast lookup. Also stores the set of inequality relationships.
214   class PropertySet {
215     struct Property;
216   public:
217     class Synonyms<Value *, compare> union_find;
218
219     typedef std::vector<Property>::iterator       PropertyIterator;
220     typedef std::vector<Property>::const_iterator ConstPropertyIterator;
221     typedef Synonyms<Value *, compare>::iterator  SynonymIterator;
222
223     enum Ops {
224       EQ,
225       NE
226     };
227
228     Value *canonicalize(Value *V) const {
229       Value *C = lookup(V);
230       return C ? C : V;
231     }
232
233     Value *lookup(Value *V) const {
234       Synonyms<Value *, compare>::iterator SI = union_find.findLeader(V);
235       if (!SI) return NULL;
236       return union_find.getLeader(SI);
237     }
238
239     bool empty() const {
240       return union_find.empty();
241     }
242
243     void addEqual(Value *V1, Value *V2) {
244       // If %x = 0. and %y = -0., seteq %x, %y is true, but
245       // copysign(%x) is not the same as copysign(%y).
246       if (V1->getType()->isFloatingPoint()) return;
247
248       order(V1, V2);
249       if (isa<Constant>(V2)) return; // refuse to set false == true.
250
251       DEBUG(std::cerr << "equal: " << *V1 << " and " << *V2 << "\n");
252       SynonymIterator deleted = union_find.unionSets(V1, V2);
253       if (deleted) {
254         SynonymIterator replacement = union_find.findLeader(V1);
255         // Move Properties
256         for (PropertyIterator I = Properties.begin(), E = Properties.end();
257              I != E; ++I) {
258           if (I->I1 == deleted) I->I1 = replacement;
259           else if (I->I1 > deleted) --I->I1;
260           if (I->I2 == deleted) I->I2 = replacement;
261           else if (I->I2 > deleted) --I->I2;
262         }
263       }
264       addImpliedProperties(EQ, V1, V2);
265     }
266
267     void addNotEqual(Value *V1, Value *V2) {
268       // If %x = NAN then seteq %x, %x is false.
269       if (V1->getType()->isFloatingPoint()) return;
270
271       // For example, %x = setne int 0, 0 causes "0 != 0".
272       if (isa<Constant>(V1) && isa<Constant>(V2)) return;
273
274       DEBUG(std::cerr << "not equal: " << *V1 << " and " << *V2 << "\n");
275       if (findProperty(NE, V1, V2) != Properties.end())
276         return; // found.
277
278       // Add the property.
279       SynonymIterator I1 = union_find.findOrInsert(V1),
280                       I2 = union_find.findOrInsert(V2);
281
282       // Technically this means that the block is unreachable.
283       if (I1 == I2) return;
284
285       Properties.push_back(Property(NE, I1, I2));
286       addImpliedProperties(NE, V1, V2);
287     }
288
289     PropertyIterator findProperty(Ops Opcode, Value *V1, Value *V2) {
290       assert(Opcode != EQ && "Can't findProperty on EQ."
291              "Use the lookup method instead.");
292
293       SynonymIterator I1 = union_find.findLeader(V1),
294                       I2 = union_find.findLeader(V2);
295       if (!I1 || !I2) return Properties.end();
296
297       return
298       find(Properties.begin(), Properties.end(), Property(Opcode, I1, I2));
299     }
300
301     ConstPropertyIterator
302     findProperty(Ops Opcode, Value *V1, Value *V2) const {
303       assert(Opcode != EQ && "Can't findProperty on EQ."
304              "Use the lookup method instead.");
305
306       SynonymIterator I1 = union_find.findLeader(V1),
307                       I2 = union_find.findLeader(V2);
308       if (!I1 || !I2) return Properties.end();
309
310       return
311       find(Properties.begin(), Properties.end(), Property(Opcode, I1, I2));
312     }
313
314   private:
315     // Represents Head OP [Tail1, Tail2, ...]
316     // For example: %x != %a, %x != %b.
317     struct VISIBILITY_HIDDEN Property {
318       typedef Synonyms<Value *, compare>::iterator Iter;
319
320       Property(Ops opcode, Iter i1, Iter i2)
321         : Opcode(opcode), I1(i1), I2(i2)
322       { assert(opcode != EQ && "Equality belongs in the synonym set, "
323                                "not a property."); }
324
325       bool operator==(const Property &P) const {
326         return (Opcode == P.Opcode) &&
327                ((I1 == P.I1 && I2 == P.I2) ||
328                 (I1 == P.I2 && I2 == P.I1));
329       }
330
331       Ops Opcode;
332       Iter I1, I2;
333     };
334
335     void add(Ops Opcode, Value *V1, Value *V2, bool invert) {
336       switch (Opcode) {
337         case EQ:
338           if (invert) addNotEqual(V1, V2);
339           else        addEqual(V1, V2);
340           break;
341         case NE:
342           if (invert) addEqual(V1, V2);
343           else        addNotEqual(V1, V2);
344           break;
345         default:
346           assert(0 && "Unknown property opcode.");
347       }
348     }
349
350     // Finds the properties implied by an equivalence and adds them too.
351     // Example: ("seteq %a, %b", true,  EQ) --> (%a, %b, EQ)
352     //          ("seteq %a, %b", false, EQ) --> (%a, %b, NE)
353     void addImpliedProperties(Ops Opcode, Value *V1, Value *V2) {
354       order(V1, V2);
355
356       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V2)) {
357         switch (BO->getOpcode()) {
358         case Instruction::SetEQ:
359           if (V1 == ConstantBool::True)
360             add(Opcode, BO->getOperand(0), BO->getOperand(1), false);
361           if (V1 == ConstantBool::False)
362             add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
363           break;
364         case Instruction::SetNE:
365           if (V1 == ConstantBool::True)
366             add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
367           if (V1 == ConstantBool::False)
368             add(Opcode, BO->getOperand(0), BO->getOperand(1), false);
369           break;
370         case Instruction::SetLT:
371         case Instruction::SetGT:
372           if (V1 == ConstantBool::True)
373             add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
374           break;
375         case Instruction::SetLE:
376         case Instruction::SetGE:
377           if (V1 == ConstantBool::False)
378             add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
379           break;
380         case Instruction::And:
381           if (V1 == ConstantBool::True) {
382             add(Opcode, ConstantBool::True, BO->getOperand(0), false);
383             add(Opcode, ConstantBool::True, BO->getOperand(1), false);
384           }
385           break;
386         case Instruction::Or:
387           if (V1 == ConstantBool::False) {
388             add(Opcode, ConstantBool::False, BO->getOperand(0), false);
389             add(Opcode, ConstantBool::False, BO->getOperand(1), false);
390           }
391           break;
392         case Instruction::Xor:
393           if (V1 == ConstantBool::True) {
394             if (BO->getOperand(0) == ConstantBool::True)
395               add(Opcode, ConstantBool::False, BO->getOperand(1), false);
396             if (BO->getOperand(1) == ConstantBool::True)
397               add(Opcode, ConstantBool::False, BO->getOperand(0), false);
398           }
399           if (V1 == ConstantBool::False) {
400             if (BO->getOperand(0) == ConstantBool::True)
401               add(Opcode, ConstantBool::True, BO->getOperand(1), false);
402             if (BO->getOperand(1) == ConstantBool::True)
403               add(Opcode, ConstantBool::True, BO->getOperand(0), false);
404           }
405           break;
406         default:
407           break;
408         }
409       } else if (SelectInst *SI = dyn_cast<SelectInst>(V2)) {
410         if (Opcode != EQ && Opcode != NE) return;
411
412         ConstantBool *True  = (Opcode==EQ) ? ConstantBool::True
413                                            : ConstantBool::False,
414                      *False = (Opcode==EQ) ? ConstantBool::False
415                                            : ConstantBool::True;
416
417         if (V1 == SI->getTrueValue())
418           addEqual(SI->getCondition(), True);
419         else if (V1 == SI->getFalseValue())
420           addEqual(SI->getCondition(), False);
421         else if (Opcode == EQ)
422           assert("Result of select not equal to either value.");
423       }
424     }
425
426   public:
427 #ifdef DEBUG
428     void debug(std::ostream &os) const {
429       static const char *OpcodeTable[] = { "EQ", "NE" };
430
431       union_find.debug(os);
432       for (std::vector<Property>::const_iterator I = Properties.begin(),
433            E = Properties.end(); I != E; ++I) {
434         os << (*I).I1 << " " << OpcodeTable[(*I).Opcode] << " "
435            << (*I).I2 << "\n";
436       }
437       os << "\n";
438     }
439 #endif
440
441     std::vector<Property> Properties;
442   };
443
444   /// PredicateSimplifier - This class is a simplifier that replaces
445   /// one equivalent variable with another. It also tracks what
446   /// can't be equal and will solve setcc instructions when possible.
447   class PredicateSimplifier : public FunctionPass {
448   public:
449     bool runOnFunction(Function &F);
450     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
451
452   private:
453     // Try to replace the Use of the instruction with something simpler.
454     Value *resolve(SetCondInst *SCI, const PropertySet &);
455     Value *resolve(BinaryOperator *BO, const PropertySet &);
456     Value *resolve(SelectInst *SI, const PropertySet &);
457     Value *resolve(Value *V, const PropertySet &);
458
459     // Used by terminator instructions to proceed from the current basic
460     // block to the next. Verifies that "current" dominates "next",
461     // then calls visitBasicBlock.
462     void proceedToSuccessor(PropertySet &CurrentPS, PropertySet &NextPS,
463                             DTNodeType *Current, DTNodeType *Next);
464     void proceedToSuccessor(PropertySet &CurrentPS,
465                             DTNodeType *Current, DTNodeType *Next);
466
467     // Visits each instruction in the basic block.
468     void visitBasicBlock(DTNodeType *DTNode, PropertySet &KnownProperties);
469
470     // Tries to simplify each Instruction and add new properties to
471     // the PropertySet. Returns true if it erase the instruction.
472     void visitInstruction(Instruction *I, DTNodeType *, PropertySet &);
473     // For each instruction, add the properties to KnownProperties.
474
475     void visit(TerminatorInst *TI, DTNodeType *, PropertySet &);
476     void visit(BranchInst *BI, DTNodeType *, PropertySet &);
477     void visit(SwitchInst *SI, DTNodeType *, PropertySet);
478     void visit(LoadInst *LI, DTNodeType *, PropertySet &);
479     void visit(StoreInst *SI, DTNodeType *, PropertySet &);
480     void visit(BinaryOperator *BO, DTNodeType *, PropertySet &);
481
482     DominatorTree *DT;
483     bool modified;
484   };
485
486   RegisterPass<PredicateSimplifier> X("predsimplify",
487                                       "Predicate Simplifier");
488 }
489
490 FunctionPass *llvm::createPredicateSimplifierPass() {
491   return new PredicateSimplifier();
492 }
493
494 bool PredicateSimplifier::runOnFunction(Function &F) {
495   DT = &getAnalysis<DominatorTree>();
496
497   modified = false;
498   PropertySet KnownProperties;
499   visitBasicBlock(DT->getRootNode(), KnownProperties);
500   return modified;
501 }
502
503 void PredicateSimplifier::getAnalysisUsage(AnalysisUsage &AU) const {
504   AU.addRequired<DominatorTree>();
505 }
506
507 // resolve catches cases addProperty won't because it wasn't used as a
508 // condition in the branch, and that visit won't, because the instruction
509 // was defined outside of the scope that the properties apply to.
510 Value *PredicateSimplifier::resolve(SetCondInst *SCI,
511                                     const PropertySet &KP) {
512   // Attempt to resolve the SetCondInst to a boolean.
513
514   Value *SCI0 = resolve(SCI->getOperand(0), KP),
515         *SCI1 = resolve(SCI->getOperand(1), KP);
516
517   ConstantIntegral *CI1 = dyn_cast<ConstantIntegral>(SCI0),
518                    *CI2 = dyn_cast<ConstantIntegral>(SCI1);
519
520   if (!CI1 || !CI2) {
521     PropertySet::ConstPropertyIterator NE =
522         KP.findProperty(PropertySet::NE, SCI0, SCI1);
523
524     if (NE != KP.Properties.end()) {
525       switch (SCI->getOpcode()) {
526         case Instruction::SetEQ:
527           return ConstantBool::False;
528         case Instruction::SetNE:
529           return ConstantBool::True;
530         case Instruction::SetLE:
531         case Instruction::SetGE:
532         case Instruction::SetLT:
533         case Instruction::SetGT:
534           break;
535         default:
536           assert(0 && "Unknown opcode in SetCondInst.");
537           break;
538       }
539     }
540     return SCI;
541   }
542
543   switch(SCI->getOpcode()) {
544     case Instruction::SetLE:
545     case Instruction::SetGE:
546     case Instruction::SetEQ:
547       if (CI1->getRawValue() == CI2->getRawValue())
548         return ConstantBool::True;
549       else
550         return ConstantBool::False;
551     case Instruction::SetLT:
552     case Instruction::SetGT:
553     case Instruction::SetNE:
554       if (CI1->getRawValue() == CI2->getRawValue())
555         return ConstantBool::False;
556       else
557         return ConstantBool::True;
558     default:
559       assert(0 && "Unknown opcode in SetContInst.");
560       break;
561   }
562 }
563
564 Value *PredicateSimplifier::resolve(BinaryOperator *BO,
565                                     const PropertySet &KP) {
566   if (SetCondInst *SCI = dyn_cast<SetCondInst>(BO))
567     return resolve(SCI, KP);
568
569   Value *lhs = resolve(BO->getOperand(0), KP),
570         *rhs = resolve(BO->getOperand(1), KP);
571   ConstantIntegral *CI1 = dyn_cast<ConstantIntegral>(lhs);
572   ConstantIntegral *CI2 = dyn_cast<ConstantIntegral>(rhs);
573
574   if (!CI1 || !CI2) return BO;
575
576   Value *V = ConstantExpr::get(BO->getOpcode(), CI1, CI2);
577   if (V) return V;
578   return BO;
579 }
580
581 Value *PredicateSimplifier::resolve(SelectInst *SI, const PropertySet &KP) {
582   Value *Condition = resolve(SI->getCondition(), KP);
583   if (Condition == ConstantBool::True)
584     return resolve(SI->getTrueValue(), KP);
585   else if (Condition == ConstantBool::False)
586     return resolve(SI->getFalseValue(), KP);
587   return SI;
588 }
589
590 Value *PredicateSimplifier::resolve(Value *V, const PropertySet &KP) {
591   if (isa<Constant>(V) || isa<BasicBlock>(V) || KP.empty()) return V;
592
593   V = KP.canonicalize(V);
594
595   DEBUG(std::cerr << "peering into " << *V << "\n");
596
597   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
598     return resolve(BO, KP);
599   else if (SelectInst *SI = dyn_cast<SelectInst>(V))
600     return resolve(SI, KP);
601
602   return V;
603 }
604
605 void PredicateSimplifier::visitBasicBlock(DTNodeType *DTNode,
606                                           PropertySet &KnownProperties) {
607   BasicBlock *BB = DTNode->getBlock();
608   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
609     visitInstruction(I++, DTNode, KnownProperties);
610   }
611 }
612
613 void PredicateSimplifier::visitInstruction(Instruction *I,
614                                            DTNodeType *DTNode,
615                                            PropertySet &KnownProperties) {
616
617   DEBUG(std::cerr << "Considering instruction " << *I << "\n");
618   DEBUG(KnownProperties.debug(std::cerr));
619
620   // Try to replace the whole instruction.
621   Value *V = resolve(I, KnownProperties);
622   assert(V->getType() == I->getType() && "Instruction type mutated!");
623   if (V != I) {
624     modified = true;
625     ++NumInstruction;
626     I->replaceAllUsesWith(V);
627     I->eraseFromParent();
628     return;
629   }
630
631   // Try to substitute operands.
632   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
633     Value *Oper = I->getOperand(i);
634     Value *V = resolve(Oper, KnownProperties);
635     assert(V->getType() == Oper->getType() && "Operand type mutated!");
636     if (V != Oper) {
637       modified = true;
638       ++NumVarsReplaced;
639       DEBUG(std::cerr << "resolving " << *I);
640       I->setOperand(i, V);
641       DEBUG(std::cerr << "into " << *I);
642     }
643   }
644
645   if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I))
646     visit(TI, DTNode, KnownProperties);
647   else if (LoadInst *LI = dyn_cast<LoadInst>(I))
648     visit(LI, DTNode, KnownProperties);
649   else if (StoreInst *SI = dyn_cast<StoreInst>(I))
650     visit(SI, DTNode, KnownProperties);
651   else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
652     visit(BO, DTNode, KnownProperties);
653 }
654
655 void PredicateSimplifier::proceedToSuccessor(PropertySet &CurrentPS,
656                                              PropertySet &NextPS,
657                                              DTNodeType *Current,
658                                              DTNodeType *Next) {
659   if (Next->getBlock()->getSinglePredecessor() == Current->getBlock())
660     proceedToSuccessor(NextPS, Current, Next);
661   else
662     proceedToSuccessor(CurrentPS, Current, Next);
663 }
664
665 void PredicateSimplifier::proceedToSuccessor(PropertySet &KP,
666                                              DTNodeType *Current,
667                                              DTNodeType *Next) {
668   if (Current->properlyDominates(Next))
669     visitBasicBlock(Next, KP);
670 }
671
672 void PredicateSimplifier::visit(TerminatorInst *TI, DTNodeType *Node,
673                                 PropertySet &KP) {
674   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
675     visit(BI, Node, KP);
676     return;
677   }
678   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
679     visit(SI, Node, KP);
680     return;
681   }
682
683   for (unsigned i = 0, E = TI->getNumSuccessors(); i != E; ++i) {
684     BasicBlock *BB = TI->getSuccessor(i);
685     PropertySet KPcopy(KP);
686     proceedToSuccessor(KPcopy, Node, DT->getNode(TI->getSuccessor(i)));
687   }
688 }
689
690 void PredicateSimplifier::visit(BranchInst *BI, DTNodeType *Node,
691                                 PropertySet &KP) {
692   if (BI->isUnconditional()) {
693     proceedToSuccessor(KP, Node, DT->getNode(BI->getSuccessor(0)));
694     return;
695   }
696
697   Value *Condition = BI->getCondition();
698
699   BasicBlock *TrueDest  = BI->getSuccessor(0),
700              *FalseDest = BI->getSuccessor(1);
701
702   if (Condition == ConstantBool::True) {
703     FalseDest->removePredecessor(BI->getParent());
704     BI->setUnconditionalDest(TrueDest);
705     modified = true;
706     ++NumBranches;
707     proceedToSuccessor(KP, Node, DT->getNode(TrueDest));
708     return;
709   } else if (Condition == ConstantBool::False) {
710     TrueDest->removePredecessor(BI->getParent());
711     BI->setUnconditionalDest(FalseDest);
712     modified = true;
713     ++NumBranches;
714     proceedToSuccessor(KP, Node, DT->getNode(FalseDest));
715     return;
716   }
717
718   PropertySet TrueProperties(KP), FalseProperties(KP);
719   DEBUG(std::cerr << "true set:\n");
720   TrueProperties.addEqual(ConstantBool::True,   Condition);
721   DEBUG(TrueProperties.debug(std::cerr));
722   DEBUG(std::cerr << "false set:\n");
723   FalseProperties.addEqual(ConstantBool::False, Condition);
724   DEBUG(FalseProperties.debug(std::cerr));
725
726   PropertySet KPcopy(KP);
727   proceedToSuccessor(KP,     TrueProperties,  Node, DT->getNode(TrueDest));
728   proceedToSuccessor(KPcopy, FalseProperties, Node, DT->getNode(FalseDest));
729 }
730
731 void PredicateSimplifier::visit(SwitchInst *SI, DTNodeType *DTNode,
732                                 PropertySet KP) {
733   Value *Condition = SI->getCondition();
734   assert(Condition == KP.canonicalize(Condition) &&
735          "Instruction wasn't already canonicalized?");
736
737   // If there's an NEProperty covering this SwitchInst, we may be able to
738   // eliminate one of the cases.
739   for (PropertySet::ConstPropertyIterator I = KP.Properties.begin(),
740        E = KP.Properties.end(); I != E; ++I) {
741     if (I->Opcode != PropertySet::NE) continue;
742     Value *V1 = KP.union_find.getLeader(I->I1),
743           *V2 = KP.union_find.getLeader(I->I2);
744
745     // Find a Property with a ConstantInt on one side and our
746     // Condition on the other.
747     ConstantInt *CI = NULL;
748     if (V1 == Condition)
749       CI = dyn_cast<ConstantInt>(V2);
750     else if (V2 == Condition)
751       CI = dyn_cast<ConstantInt>(V1);
752
753     if (!CI) continue;
754
755     unsigned i = SI->findCaseValue(CI);
756     if (i != 0) { // zero is reserved for the default case.
757       SI->getSuccessor(i)->removePredecessor(SI->getParent());
758       SI->removeCase(i);
759       modified = true;
760       ++NumSwitchCases;
761     }
762   }
763
764   // Set the EQProperty in each of the cases BBs,
765   // and the NEProperties in the default BB.
766   PropertySet DefaultProperties(KP);
767
768   DTNodeType *Node        = DT->getNode(SI->getParent()),
769              *DefaultNode = DT->getNode(SI->getSuccessor(0));
770   if (!Node->dominates(DefaultNode)) DefaultNode = NULL;
771
772   for (unsigned I = 1, E = SI->getNumCases(); I < E; ++I) {
773     ConstantInt *CI = SI->getCaseValue(I);
774
775     BasicBlock *SuccBB = SI->getSuccessor(I);
776     PropertySet copy(KP);
777     if (SuccBB->getSinglePredecessor()) {
778       PropertySet NewProperties(KP);
779       NewProperties.addEqual(Condition, CI);
780       proceedToSuccessor(copy, NewProperties, DTNode, DT->getNode(SuccBB));
781     } else
782       proceedToSuccessor(copy, DTNode, DT->getNode(SuccBB));
783
784     if (DefaultNode)
785       DefaultProperties.addNotEqual(Condition, CI);
786   }
787
788   if (DefaultNode)
789     proceedToSuccessor(DefaultProperties, DTNode, DefaultNode);
790 }
791
792 void PredicateSimplifier::visit(LoadInst *LI, DTNodeType *,
793                                 PropertySet &KP) {
794   Value *Ptr = LI->getPointerOperand();
795   KP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
796 }
797
798 void PredicateSimplifier::visit(StoreInst *SI, DTNodeType *,
799                                 PropertySet &KP) {
800   Value *Ptr = SI->getPointerOperand();
801   KP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
802 }
803
804 void PredicateSimplifier::visit(BinaryOperator *BO, DTNodeType *,
805                                 PropertySet &KP) {
806   Instruction::BinaryOps ops = BO->getOpcode();
807
808   switch (ops) {
809     case Instruction::Div:
810     case Instruction::Rem: {
811       Value *Divisor = BO->getOperand(1);
812       KP.addNotEqual(Constant::getNullValue(Divisor->getType()), Divisor);
813       break;
814     }
815     default:
816       break;
817   }
818 }