88a2c53e806e7d8f202765dbf14e67a428db793c
[oota-llvm.git] / lib / Analysis / InstructionSimplify.cpp
1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements routines for folding instructions into simpler forms
11 // that do not require creating new instructions.  This does constant folding
12 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
14 // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
15 // simplified: This is usually true and assuming it simplifies the logic (if
16 // they have not been simplified then results are correct but maybe suboptimal).
17 //
18 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "instsimplify"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Support/ConstantRange.h"
28 #include "llvm/Support/PatternMatch.h"
29 #include "llvm/Support/ValueHandle.h"
30 #include "llvm/Target/TargetData.h"
31 using namespace llvm;
32 using namespace llvm::PatternMatch;
33
34 enum { RecursionLimit = 3 };
35
36 STATISTIC(NumExpand,  "Number of expansions");
37 STATISTIC(NumFactor , "Number of factorizations");
38 STATISTIC(NumReassoc, "Number of reassociations");
39
40 static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
41                               const TargetLibraryInfo *, const DominatorTree *,
42                               unsigned);
43 static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
44                             const TargetLibraryInfo *, const DominatorTree *,
45                             unsigned);
46 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
47                               const TargetLibraryInfo *, const DominatorTree *,
48                               unsigned);
49 static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
50                              const TargetLibraryInfo *, const DominatorTree *,
51                              unsigned);
52 static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
53                               const TargetLibraryInfo *, const DominatorTree *,
54                               unsigned);
55
56 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
57 /// a vector with every element false, as appropriate for the type.
58 static Constant *getFalse(Type *Ty) {
59   assert(Ty->getScalarType()->isIntegerTy(1) &&
60          "Expected i1 type or a vector of i1!");
61   return Constant::getNullValue(Ty);
62 }
63
64 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
65 /// a vector with every element true, as appropriate for the type.
66 static Constant *getTrue(Type *Ty) {
67   assert(Ty->getScalarType()->isIntegerTy(1) &&
68          "Expected i1 type or a vector of i1!");
69   return Constant::getAllOnesValue(Ty);
70 }
71
72 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
73 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
74                           Value *RHS) {
75   CmpInst *Cmp = dyn_cast<CmpInst>(V);
76   if (!Cmp)
77     return false;
78   CmpInst::Predicate CPred = Cmp->getPredicate();
79   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
80   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
81     return true;
82   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
83     CRHS == LHS;
84 }
85
86 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
87 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
88   Instruction *I = dyn_cast<Instruction>(V);
89   if (!I)
90     // Arguments and constants dominate all instructions.
91     return true;
92
93   // If we have a DominatorTree then do a precise test.
94   if (DT)
95     return DT->dominates(I, P);
96
97   // Otherwise, if the instruction is in the entry block, and is not an invoke,
98   // then it obviously dominates all phi nodes.
99   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
100       !isa<InvokeInst>(I))
101     return true;
102
103   return false;
104 }
105
106 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
107 /// it into "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
108 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
109 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
110 /// Returns the simplified value, or null if no simplification was performed.
111 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
112                           unsigned OpcToExpand, const TargetData *TD,
113                           const TargetLibraryInfo *TLI, const DominatorTree *DT,
114                           unsigned MaxRecurse) {
115   Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
116   // Recursion is always used, so bail out at once if we already hit the limit.
117   if (!MaxRecurse--)
118     return 0;
119
120   // Check whether the expression has the form "(A op' B) op C".
121   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
122     if (Op0->getOpcode() == OpcodeToExpand) {
123       // It does!  Try turning it into "(A op C) op' (B op C)".
124       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
125       // Do "A op C" and "B op C" both simplify?
126       if (Value *L = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse))
127         if (Value *R = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
128           // They do! Return "L op' R" if it simplifies or is already available.
129           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
130           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
131                                      && L == B && R == A)) {
132             ++NumExpand;
133             return LHS;
134           }
135           // Otherwise return "L op' R" if it simplifies.
136           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
137                                        MaxRecurse)) {
138             ++NumExpand;
139             return V;
140           }
141         }
142     }
143
144   // Check whether the expression has the form "A op (B op' C)".
145   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
146     if (Op1->getOpcode() == OpcodeToExpand) {
147       // It does!  Try turning it into "(A op B) op' (A op C)".
148       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
149       // Do "A op B" and "A op C" both simplify?
150       if (Value *L = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse))
151         if (Value *R = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse)) {
152           // They do! Return "L op' R" if it simplifies or is already available.
153           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
154           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
155                                      && L == C && R == B)) {
156             ++NumExpand;
157             return RHS;
158           }
159           // Otherwise return "L op' R" if it simplifies.
160           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
161                                        MaxRecurse)) {
162             ++NumExpand;
163             return V;
164           }
165         }
166     }
167
168   return 0;
169 }
170
171 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
172 /// using the operation OpCodeToExtract.  For example, when Opcode is Add and
173 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
174 /// Returns the simplified value, or null if no simplification was performed.
175 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
176                              unsigned OpcToExtract, const TargetData *TD, 
177                              const TargetLibraryInfo *TLI,
178                              const DominatorTree *DT,
179                              unsigned MaxRecurse) {
180   Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
181   // Recursion is always used, so bail out at once if we already hit the limit.
182   if (!MaxRecurse--)
183     return 0;
184
185   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
186   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
187
188   if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
189       !Op1 || Op1->getOpcode() != OpcodeToExtract)
190     return 0;
191
192   // The expression has the form "(A op' B) op (C op' D)".
193   Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
194   Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
195
196   // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
197   // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
198   // commutative case, "(A op' B) op (C op' A)"?
199   if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
200     Value *DD = A == C ? D : C;
201     // Form "A op' (B op DD)" if it simplifies completely.
202     // Does "B op DD" simplify?
203     if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, TLI, DT, MaxRecurse)) {
204       // It does!  Return "A op' V" if it simplifies or is already available.
205       // If V equals B then "A op' V" is just the LHS.  If V equals DD then
206       // "A op' V" is just the RHS.
207       if (V == B || V == DD) {
208         ++NumFactor;
209         return V == B ? LHS : RHS;
210       }
211       // Otherwise return "A op' V" if it simplifies.
212       if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, TLI, DT,
213                                    MaxRecurse)) {
214         ++NumFactor;
215         return W;
216       }
217     }
218   }
219
220   // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
221   // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
222   // commutative case, "(A op' B) op (B op' D)"?
223   if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
224     Value *CC = B == D ? C : D;
225     // Form "(A op CC) op' B" if it simplifies completely..
226     // Does "A op CC" simplify?
227     if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, TLI, DT, MaxRecurse)) {
228       // It does!  Return "V op' B" if it simplifies or is already available.
229       // If V equals A then "V op' B" is just the LHS.  If V equals CC then
230       // "V op' B" is just the RHS.
231       if (V == A || V == CC) {
232         ++NumFactor;
233         return V == A ? LHS : RHS;
234       }
235       // Otherwise return "V op' B" if it simplifies.
236       if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, TLI, DT,
237                                    MaxRecurse)) {
238         ++NumFactor;
239         return W;
240       }
241     }
242   }
243
244   return 0;
245 }
246
247 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
248 /// operations.  Returns the simpler value, or null if none was found.
249 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
250                                        const TargetData *TD,
251                                        const TargetLibraryInfo *TLI,
252                                        const DominatorTree *DT,
253                                        unsigned MaxRecurse) {
254   Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
255   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
256
257   // Recursion is always used, so bail out at once if we already hit the limit.
258   if (!MaxRecurse--)
259     return 0;
260
261   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
262   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
263
264   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
265   if (Op0 && Op0->getOpcode() == Opcode) {
266     Value *A = Op0->getOperand(0);
267     Value *B = Op0->getOperand(1);
268     Value *C = RHS;
269
270     // Does "B op C" simplify?
271     if (Value *V = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
272       // It does!  Return "A op V" if it simplifies or is already available.
273       // If V equals B then "A op V" is just the LHS.
274       if (V == B) return LHS;
275       // Otherwise return "A op V" if it simplifies.
276       if (Value *W = SimplifyBinOp(Opcode, A, V, TD, TLI, DT, MaxRecurse)) {
277         ++NumReassoc;
278         return W;
279       }
280     }
281   }
282
283   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
284   if (Op1 && Op1->getOpcode() == Opcode) {
285     Value *A = LHS;
286     Value *B = Op1->getOperand(0);
287     Value *C = Op1->getOperand(1);
288
289     // Does "A op B" simplify?
290     if (Value *V = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse)) {
291       // It does!  Return "V op C" if it simplifies or is already available.
292       // If V equals B then "V op C" is just the RHS.
293       if (V == B) return RHS;
294       // Otherwise return "V op C" if it simplifies.
295       if (Value *W = SimplifyBinOp(Opcode, V, C, TD, TLI, DT, MaxRecurse)) {
296         ++NumReassoc;
297         return W;
298       }
299     }
300   }
301
302   // The remaining transforms require commutativity as well as associativity.
303   if (!Instruction::isCommutative(Opcode))
304     return 0;
305
306   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
307   if (Op0 && Op0->getOpcode() == Opcode) {
308     Value *A = Op0->getOperand(0);
309     Value *B = Op0->getOperand(1);
310     Value *C = RHS;
311
312     // Does "C op A" simplify?
313     if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
314       // It does!  Return "V op B" if it simplifies or is already available.
315       // If V equals A then "V op B" is just the LHS.
316       if (V == A) return LHS;
317       // Otherwise return "V op B" if it simplifies.
318       if (Value *W = SimplifyBinOp(Opcode, V, B, TD, TLI, DT, MaxRecurse)) {
319         ++NumReassoc;
320         return W;
321       }
322     }
323   }
324
325   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
326   if (Op1 && Op1->getOpcode() == Opcode) {
327     Value *A = LHS;
328     Value *B = Op1->getOperand(0);
329     Value *C = Op1->getOperand(1);
330
331     // Does "C op A" simplify?
332     if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
333       // It does!  Return "B op V" if it simplifies or is already available.
334       // If V equals C then "B op V" is just the RHS.
335       if (V == C) return RHS;
336       // Otherwise return "B op V" if it simplifies.
337       if (Value *W = SimplifyBinOp(Opcode, B, V, TD, TLI, DT, MaxRecurse)) {
338         ++NumReassoc;
339         return W;
340       }
341     }
342   }
343
344   return 0;
345 }
346
347 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
348 /// instruction as an operand, try to simplify the binop by seeing whether
349 /// evaluating it on both branches of the select results in the same value.
350 /// Returns the common value if so, otherwise returns null.
351 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
352                                     const TargetData *TD,
353                                     const TargetLibraryInfo *TLI,
354                                     const DominatorTree *DT,
355                                     unsigned MaxRecurse) {
356   // Recursion is always used, so bail out at once if we already hit the limit.
357   if (!MaxRecurse--)
358     return 0;
359
360   SelectInst *SI;
361   if (isa<SelectInst>(LHS)) {
362     SI = cast<SelectInst>(LHS);
363   } else {
364     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
365     SI = cast<SelectInst>(RHS);
366   }
367
368   // Evaluate the BinOp on the true and false branches of the select.
369   Value *TV;
370   Value *FV;
371   if (SI == LHS) {
372     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, TLI, DT, MaxRecurse);
373     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, TLI, DT, MaxRecurse);
374   } else {
375     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, TLI, DT, MaxRecurse);
376     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, TLI, DT, MaxRecurse);
377   }
378
379   // If they simplified to the same value, then return the common value.
380   // If they both failed to simplify then return null.
381   if (TV == FV)
382     return TV;
383
384   // If one branch simplified to undef, return the other one.
385   if (TV && isa<UndefValue>(TV))
386     return FV;
387   if (FV && isa<UndefValue>(FV))
388     return TV;
389
390   // If applying the operation did not change the true and false select values,
391   // then the result of the binop is the select itself.
392   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
393     return SI;
394
395   // If one branch simplified and the other did not, and the simplified
396   // value is equal to the unsimplified one, return the simplified value.
397   // For example, select (cond, X, X & Z) & Z -> X & Z.
398   if ((FV && !TV) || (TV && !FV)) {
399     // Check that the simplified value has the form "X op Y" where "op" is the
400     // same as the original operation.
401     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
402     if (Simplified && Simplified->getOpcode() == Opcode) {
403       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
404       // We already know that "op" is the same as for the simplified value.  See
405       // if the operands match too.  If so, return the simplified value.
406       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
407       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
408       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
409       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
410           Simplified->getOperand(1) == UnsimplifiedRHS)
411         return Simplified;
412       if (Simplified->isCommutative() &&
413           Simplified->getOperand(1) == UnsimplifiedLHS &&
414           Simplified->getOperand(0) == UnsimplifiedRHS)
415         return Simplified;
416     }
417   }
418
419   return 0;
420 }
421
422 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
423 /// try to simplify the comparison by seeing whether both branches of the select
424 /// result in the same value.  Returns the common value if so, otherwise returns
425 /// null.
426 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
427                                   Value *RHS, const TargetData *TD,
428                                   const TargetLibraryInfo *TLI,
429                                   const DominatorTree *DT,
430                                   unsigned MaxRecurse) {
431   // Recursion is always used, so bail out at once if we already hit the limit.
432   if (!MaxRecurse--)
433     return 0;
434
435   // Make sure the select is on the LHS.
436   if (!isa<SelectInst>(LHS)) {
437     std::swap(LHS, RHS);
438     Pred = CmpInst::getSwappedPredicate(Pred);
439   }
440   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
441   SelectInst *SI = cast<SelectInst>(LHS);
442   Value *Cond = SI->getCondition();
443   Value *TV = SI->getTrueValue();
444   Value *FV = SI->getFalseValue();
445
446   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
447   // Does "cmp TV, RHS" simplify?
448   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, TD, TLI, DT, MaxRecurse);
449   if (TCmp == Cond) {
450     // It not only simplified, it simplified to the select condition.  Replace
451     // it with 'true'.
452     TCmp = getTrue(Cond->getType());
453   } else if (!TCmp) {
454     // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
455     // condition then we can replace it with 'true'.  Otherwise give up.
456     if (!isSameCompare(Cond, Pred, TV, RHS))
457       return 0;
458     TCmp = getTrue(Cond->getType());
459   }
460
461   // Does "cmp FV, RHS" simplify?
462   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, TD, TLI, DT, MaxRecurse);
463   if (FCmp == Cond) {
464     // It not only simplified, it simplified to the select condition.  Replace
465     // it with 'false'.
466     FCmp = getFalse(Cond->getType());
467   } else if (!FCmp) {
468     // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
469     // condition then we can replace it with 'false'.  Otherwise give up.
470     if (!isSameCompare(Cond, Pred, FV, RHS))
471       return 0;
472     FCmp = getFalse(Cond->getType());
473   }
474
475   // If both sides simplified to the same value, then use it as the result of
476   // the original comparison.
477   if (TCmp == FCmp)
478     return TCmp;
479
480   // The remaining cases only make sense if the select condition has the same
481   // type as the result of the comparison, so bail out if this is not so.
482   if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
483     return 0;
484   // If the false value simplified to false, then the result of the compare
485   // is equal to "Cond && TCmp".  This also catches the case when the false
486   // value simplified to false and the true value to true, returning "Cond".
487   if (match(FCmp, m_Zero()))
488     if (Value *V = SimplifyAndInst(Cond, TCmp, TD, TLI, DT, MaxRecurse))
489       return V;
490   // If the true value simplified to true, then the result of the compare
491   // is equal to "Cond || FCmp".
492   if (match(TCmp, m_One()))
493     if (Value *V = SimplifyOrInst(Cond, FCmp, TD, TLI, DT, MaxRecurse))
494       return V;
495   // Finally, if the false value simplified to true and the true value to
496   // false, then the result of the compare is equal to "!Cond".
497   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
498     if (Value *V =
499         SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
500                         TD, TLI, DT, MaxRecurse))
501       return V;
502
503   return 0;
504 }
505
506 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
507 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
508 /// it on the incoming phi values yields the same result for every value.  If so
509 /// returns the common value, otherwise returns null.
510 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
511                                  const TargetData *TD,
512                                  const TargetLibraryInfo *TLI, 
513                                  const DominatorTree *DT,
514                                  unsigned MaxRecurse) {
515   // Recursion is always used, so bail out at once if we already hit the limit.
516   if (!MaxRecurse--)
517     return 0;
518
519   PHINode *PI;
520   if (isa<PHINode>(LHS)) {
521     PI = cast<PHINode>(LHS);
522     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
523     if (!ValueDominatesPHI(RHS, PI, DT))
524       return 0;
525   } else {
526     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
527     PI = cast<PHINode>(RHS);
528     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
529     if (!ValueDominatesPHI(LHS, PI, DT))
530       return 0;
531   }
532
533   // Evaluate the BinOp on the incoming phi values.
534   Value *CommonValue = 0;
535   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
536     Value *Incoming = PI->getIncomingValue(i);
537     // If the incoming value is the phi node itself, it can safely be skipped.
538     if (Incoming == PI) continue;
539     Value *V = PI == LHS ?
540       SimplifyBinOp(Opcode, Incoming, RHS, TD, TLI, DT, MaxRecurse) :
541       SimplifyBinOp(Opcode, LHS, Incoming, TD, TLI, DT, MaxRecurse);
542     // If the operation failed to simplify, or simplified to a different value
543     // to previously, then give up.
544     if (!V || (CommonValue && V != CommonValue))
545       return 0;
546     CommonValue = V;
547   }
548
549   return CommonValue;
550 }
551
552 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
553 /// try to simplify the comparison by seeing whether comparing with all of the
554 /// incoming phi values yields the same result every time.  If so returns the
555 /// common result, otherwise returns null.
556 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
557                                const TargetData *TD,
558                                const TargetLibraryInfo *TLI,
559                                const DominatorTree *DT,
560                                unsigned MaxRecurse) {
561   // Recursion is always used, so bail out at once if we already hit the limit.
562   if (!MaxRecurse--)
563     return 0;
564
565   // Make sure the phi is on the LHS.
566   if (!isa<PHINode>(LHS)) {
567     std::swap(LHS, RHS);
568     Pred = CmpInst::getSwappedPredicate(Pred);
569   }
570   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
571   PHINode *PI = cast<PHINode>(LHS);
572
573   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
574   if (!ValueDominatesPHI(RHS, PI, DT))
575     return 0;
576
577   // Evaluate the BinOp on the incoming phi values.
578   Value *CommonValue = 0;
579   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
580     Value *Incoming = PI->getIncomingValue(i);
581     // If the incoming value is the phi node itself, it can safely be skipped.
582     if (Incoming == PI) continue;
583     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, TLI, DT, MaxRecurse);
584     // If the operation failed to simplify, or simplified to a different value
585     // to previously, then give up.
586     if (!V || (CommonValue && V != CommonValue))
587       return 0;
588     CommonValue = V;
589   }
590
591   return CommonValue;
592 }
593
594 /// SimplifyAddInst - Given operands for an Add, see if we can
595 /// fold the result.  If not, this returns null.
596 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
597                               const TargetData *TD,
598                               const TargetLibraryInfo *TLI,
599                               const DominatorTree *DT,
600                               unsigned MaxRecurse) {
601   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
602     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
603       Constant *Ops[] = { CLHS, CRHS };
604       return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
605                                       Ops, TD, TLI);
606     }
607
608     // Canonicalize the constant to the RHS.
609     std::swap(Op0, Op1);
610   }
611
612   // X + undef -> undef
613   if (match(Op1, m_Undef()))
614     return Op1;
615
616   // X + 0 -> X
617   if (match(Op1, m_Zero()))
618     return Op0;
619
620   // X + (Y - X) -> Y
621   // (Y - X) + X -> Y
622   // Eg: X + -X -> 0
623   Value *Y = 0;
624   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
625       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
626     return Y;
627
628   // X + ~X -> -1   since   ~X = -X-1
629   if (match(Op0, m_Not(m_Specific(Op1))) ||
630       match(Op1, m_Not(m_Specific(Op0))))
631     return Constant::getAllOnesValue(Op0->getType());
632
633   /// i1 add -> xor.
634   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
635     if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
636       return V;
637
638   // Try some generic simplifications for associative operations.
639   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, TLI, DT,
640                                           MaxRecurse))
641     return V;
642
643   // Mul distributes over Add.  Try some generic simplifications based on this.
644   if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
645                                 TD, TLI, DT, MaxRecurse))
646     return V;
647
648   // Threading Add over selects and phi nodes is pointless, so don't bother.
649   // Threading over the select in "A + select(cond, B, C)" means evaluating
650   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
651   // only if B and C are equal.  If B and C are equal then (since we assume
652   // that operands have already been simplified) "select(cond, B, C)" should
653   // have been simplified to the common value of B and C already.  Analysing
654   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
655   // for threading over phi nodes.
656
657   return 0;
658 }
659
660 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
661                              const TargetData *TD, const TargetLibraryInfo *TLI,
662                              const DominatorTree *DT) {
663   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
664 }
665
666 /// SimplifySubInst - Given operands for a Sub, see if we can
667 /// fold the result.  If not, this returns null.
668 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
669                               const TargetData *TD,
670                               const TargetLibraryInfo *TLI,
671                               const DominatorTree *DT,
672                               unsigned MaxRecurse) {
673   if (Constant *CLHS = dyn_cast<Constant>(Op0))
674     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
675       Constant *Ops[] = { CLHS, CRHS };
676       return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
677                                       Ops, TD, TLI);
678     }
679
680   // X - undef -> undef
681   // undef - X -> undef
682   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
683     return UndefValue::get(Op0->getType());
684
685   // X - 0 -> X
686   if (match(Op1, m_Zero()))
687     return Op0;
688
689   // X - X -> 0
690   if (Op0 == Op1)
691     return Constant::getNullValue(Op0->getType());
692
693   // (X*2) - X -> X
694   // (X<<1) - X -> X
695   Value *X = 0;
696   if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
697       match(Op0, m_Shl(m_Specific(Op1), m_One())))
698     return Op1;
699
700   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
701   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
702   Value *Y = 0, *Z = Op1;
703   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
704     // See if "V === Y - Z" simplifies.
705     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, TLI, DT, MaxRecurse-1))
706       // It does!  Now see if "X + V" simplifies.
707       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, TLI, DT,
708                                    MaxRecurse-1)) {
709         // It does, we successfully reassociated!
710         ++NumReassoc;
711         return W;
712       }
713     // See if "V === X - Z" simplifies.
714     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
715       // It does!  Now see if "Y + V" simplifies.
716       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, TLI, DT,
717                                    MaxRecurse-1)) {
718         // It does, we successfully reassociated!
719         ++NumReassoc;
720         return W;
721       }
722   }
723
724   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
725   // For example, X - (X + 1) -> -1
726   X = Op0;
727   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
728     // See if "V === X - Y" simplifies.
729     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, TLI, DT, MaxRecurse-1))
730       // It does!  Now see if "V - Z" simplifies.
731       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, TLI, DT,
732                                    MaxRecurse-1)) {
733         // It does, we successfully reassociated!
734         ++NumReassoc;
735         return W;
736       }
737     // See if "V === X - Z" simplifies.
738     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
739       // It does!  Now see if "V - Y" simplifies.
740       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, TLI, DT,
741                                    MaxRecurse-1)) {
742         // It does, we successfully reassociated!
743         ++NumReassoc;
744         return W;
745       }
746   }
747
748   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
749   // For example, X - (X - Y) -> Y.
750   Z = Op0;
751   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
752     // See if "V === Z - X" simplifies.
753     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, TLI, DT, MaxRecurse-1))
754       // It does!  Now see if "V + Y" simplifies.
755       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, TLI, DT,
756                                    MaxRecurse-1)) {
757         // It does, we successfully reassociated!
758         ++NumReassoc;
759         return W;
760       }
761
762   // Mul distributes over Sub.  Try some generic simplifications based on this.
763   if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
764                                 TD, TLI, DT, MaxRecurse))
765     return V;
766
767   // i1 sub -> xor.
768   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
769     if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
770       return V;
771
772   // Threading Sub over selects and phi nodes is pointless, so don't bother.
773   // Threading over the select in "A - select(cond, B, C)" means evaluating
774   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
775   // only if B and C are equal.  If B and C are equal then (since we assume
776   // that operands have already been simplified) "select(cond, B, C)" should
777   // have been simplified to the common value of B and C already.  Analysing
778   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
779   // for threading over phi nodes.
780
781   return 0;
782 }
783
784 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
785                              const TargetData *TD,
786                              const TargetLibraryInfo *TLI,
787                              const DominatorTree *DT) {
788   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
789 }
790
791 /// SimplifyMulInst - Given operands for a Mul, see if we can
792 /// fold the result.  If not, this returns null.
793 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
794                               const TargetLibraryInfo *TLI,
795                               const DominatorTree *DT, unsigned MaxRecurse) {
796   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
797     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
798       Constant *Ops[] = { CLHS, CRHS };
799       return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
800                                       Ops, TD, TLI);
801     }
802
803     // Canonicalize the constant to the RHS.
804     std::swap(Op0, Op1);
805   }
806
807   // X * undef -> 0
808   if (match(Op1, m_Undef()))
809     return Constant::getNullValue(Op0->getType());
810
811   // X * 0 -> 0
812   if (match(Op1, m_Zero()))
813     return Op1;
814
815   // X * 1 -> X
816   if (match(Op1, m_One()))
817     return Op0;
818
819   // (X / Y) * Y -> X if the division is exact.
820   Value *X = 0;
821   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
822       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
823     return X;
824
825   // i1 mul -> and.
826   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
827     if (Value *V = SimplifyAndInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
828       return V;
829
830   // Try some generic simplifications for associative operations.
831   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, TLI, DT,
832                                           MaxRecurse))
833     return V;
834
835   // Mul distributes over Add.  Try some generic simplifications based on this.
836   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
837                              TD, TLI, DT, MaxRecurse))
838     return V;
839
840   // If the operation is with the result of a select instruction, check whether
841   // operating on either branch of the select always yields the same value.
842   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
843     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, TLI, DT,
844                                          MaxRecurse))
845       return V;
846
847   // If the operation is with the result of a phi instruction, check whether
848   // operating on all incoming values of the phi always yields the same value.
849   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
850     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, TLI, DT,
851                                       MaxRecurse))
852       return V;
853
854   return 0;
855 }
856
857 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
858                              const TargetLibraryInfo *TLI,
859                              const DominatorTree *DT) {
860   return ::SimplifyMulInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
861 }
862
863 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
864 /// fold the result.  If not, this returns null.
865 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
866                           const TargetData *TD, const TargetLibraryInfo *TLI,
867                           const DominatorTree *DT, unsigned MaxRecurse) {
868   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
869     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
870       Constant *Ops[] = { C0, C1 };
871       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
872     }
873   }
874
875   bool isSigned = Opcode == Instruction::SDiv;
876
877   // X / undef -> undef
878   if (match(Op1, m_Undef()))
879     return Op1;
880
881   // undef / X -> 0
882   if (match(Op0, m_Undef()))
883     return Constant::getNullValue(Op0->getType());
884
885   // 0 / X -> 0, we don't need to preserve faults!
886   if (match(Op0, m_Zero()))
887     return Op0;
888
889   // X / 1 -> X
890   if (match(Op1, m_One()))
891     return Op0;
892
893   if (Op0->getType()->isIntegerTy(1))
894     // It can't be division by zero, hence it must be division by one.
895     return Op0;
896
897   // X / X -> 1
898   if (Op0 == Op1)
899     return ConstantInt::get(Op0->getType(), 1);
900
901   // (X * Y) / Y -> X if the multiplication does not overflow.
902   Value *X = 0, *Y = 0;
903   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
904     if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
905     OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
906     // If the Mul knows it does not overflow, then we are good to go.
907     if ((isSigned && Mul->hasNoSignedWrap()) ||
908         (!isSigned && Mul->hasNoUnsignedWrap()))
909       return X;
910     // If X has the form X = A / Y then X * Y cannot overflow.
911     if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
912       if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
913         return X;
914   }
915
916   // (X rem Y) / Y -> 0
917   if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
918       (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
919     return Constant::getNullValue(Op0->getType());
920
921   // If the operation is with the result of a select instruction, check whether
922   // operating on either branch of the select always yields the same value.
923   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
924     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT,
925                                          MaxRecurse))
926       return V;
927
928   // If the operation is with the result of a phi instruction, check whether
929   // operating on all incoming values of the phi always yields the same value.
930   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
931     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT,
932                                       MaxRecurse))
933       return V;
934
935   return 0;
936 }
937
938 /// SimplifySDivInst - Given operands for an SDiv, see if we can
939 /// fold the result.  If not, this returns null.
940 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
941                                const TargetLibraryInfo *TLI,
942                                const DominatorTree *DT, unsigned MaxRecurse) {
943   if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, TLI, DT,
944                              MaxRecurse))
945     return V;
946
947   return 0;
948 }
949
950 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
951                               const TargetLibraryInfo *TLI,
952                               const DominatorTree *DT) {
953   return ::SimplifySDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
954 }
955
956 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
957 /// fold the result.  If not, this returns null.
958 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
959                                const TargetLibraryInfo *TLI,
960                                const DominatorTree *DT, unsigned MaxRecurse) {
961   if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, TLI, DT,
962                              MaxRecurse))
963     return V;
964
965   return 0;
966 }
967
968 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
969                               const TargetLibraryInfo *TLI,
970                               const DominatorTree *DT) {
971   return ::SimplifyUDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
972 }
973
974 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
975                                const TargetLibraryInfo *,
976                                const DominatorTree *, unsigned) {
977   // undef / X -> undef    (the undef could be a snan).
978   if (match(Op0, m_Undef()))
979     return Op0;
980
981   // X / undef -> undef
982   if (match(Op1, m_Undef()))
983     return Op1;
984
985   return 0;
986 }
987
988 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
989                               const TargetLibraryInfo *TLI,
990                               const DominatorTree *DT) {
991   return ::SimplifyFDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
992 }
993
994 /// SimplifyRem - Given operands for an SRem or URem, see if we can
995 /// fold the result.  If not, this returns null.
996 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
997                           const TargetData *TD, const TargetLibraryInfo *TLI,
998                           const DominatorTree *DT, unsigned MaxRecurse) {
999   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1000     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1001       Constant *Ops[] = { C0, C1 };
1002       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
1003     }
1004   }
1005
1006   // X % undef -> undef
1007   if (match(Op1, m_Undef()))
1008     return Op1;
1009
1010   // undef % X -> 0
1011   if (match(Op0, m_Undef()))
1012     return Constant::getNullValue(Op0->getType());
1013
1014   // 0 % X -> 0, we don't need to preserve faults!
1015   if (match(Op0, m_Zero()))
1016     return Op0;
1017
1018   // X % 0 -> undef, we don't need to preserve faults!
1019   if (match(Op1, m_Zero()))
1020     return UndefValue::get(Op0->getType());
1021
1022   // X % 1 -> 0
1023   if (match(Op1, m_One()))
1024     return Constant::getNullValue(Op0->getType());
1025
1026   if (Op0->getType()->isIntegerTy(1))
1027     // It can't be remainder by zero, hence it must be remainder by one.
1028     return Constant::getNullValue(Op0->getType());
1029
1030   // X % X -> 0
1031   if (Op0 == Op1)
1032     return Constant::getNullValue(Op0->getType());
1033
1034   // If the operation is with the result of a select instruction, check whether
1035   // operating on either branch of the select always yields the same value.
1036   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1037     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1038       return V;
1039
1040   // If the operation is with the result of a phi instruction, check whether
1041   // operating on all incoming values of the phi always yields the same value.
1042   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1043     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1044       return V;
1045
1046   return 0;
1047 }
1048
1049 /// SimplifySRemInst - Given operands for an SRem, see if we can
1050 /// fold the result.  If not, this returns null.
1051 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1052                                const TargetLibraryInfo *TLI,
1053                                const DominatorTree *DT,
1054                                unsigned MaxRecurse) {                               
1055   if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, TLI, DT, MaxRecurse))
1056     return V;
1057
1058   return 0;
1059 }
1060
1061 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1062                               const TargetLibraryInfo *TLI,
1063                               const DominatorTree *DT) {
1064   return ::SimplifySRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1065 }
1066
1067 /// SimplifyURemInst - Given operands for a URem, see if we can
1068 /// fold the result.  If not, this returns null.
1069 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1070                                const TargetLibraryInfo *TLI,
1071                                const DominatorTree *DT,
1072                                unsigned MaxRecurse) {
1073   if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, TLI, DT, MaxRecurse))
1074     return V;
1075
1076   return 0;
1077 }
1078
1079 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1080                               const TargetLibraryInfo *TLI,
1081                               const DominatorTree *DT) {
1082   return ::SimplifyURemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1083 }
1084
1085 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
1086                                const TargetLibraryInfo *,
1087                                const DominatorTree *,
1088                                unsigned) {
1089   // undef % X -> undef    (the undef could be a snan).
1090   if (match(Op0, m_Undef()))
1091     return Op0;
1092
1093   // X % undef -> undef
1094   if (match(Op1, m_Undef()))
1095     return Op1;
1096
1097   return 0;
1098 }
1099
1100 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1101                               const TargetLibraryInfo *TLI,
1102                               const DominatorTree *DT) {
1103   return ::SimplifyFRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1104 }
1105
1106 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1107 /// fold the result.  If not, this returns null.
1108 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1109                             const TargetData *TD, const TargetLibraryInfo *TLI,
1110                             const DominatorTree *DT, unsigned MaxRecurse) {
1111   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1112     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1113       Constant *Ops[] = { C0, C1 };
1114       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
1115     }
1116   }
1117
1118   // 0 shift by X -> 0
1119   if (match(Op0, m_Zero()))
1120     return Op0;
1121
1122   // X shift by 0 -> X
1123   if (match(Op1, m_Zero()))
1124     return Op0;
1125
1126   // X shift by undef -> undef because it may shift by the bitwidth.
1127   if (match(Op1, m_Undef()))
1128     return Op1;
1129
1130   // Shifting by the bitwidth or more is undefined.
1131   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1132     if (CI->getValue().getLimitedValue() >=
1133         Op0->getType()->getScalarSizeInBits())
1134       return UndefValue::get(Op0->getType());
1135
1136   // If the operation is with the result of a select instruction, check whether
1137   // operating on either branch of the select always yields the same value.
1138   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1139     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1140       return V;
1141
1142   // If the operation is with the result of a phi instruction, check whether
1143   // operating on all incoming values of the phi always yields the same value.
1144   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1145     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1146       return V;
1147
1148   return 0;
1149 }
1150
1151 /// SimplifyShlInst - Given operands for an Shl, see if we can
1152 /// fold the result.  If not, this returns null.
1153 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1154                               const TargetData *TD,
1155                               const TargetLibraryInfo *TLI,
1156                               const DominatorTree *DT, unsigned MaxRecurse) {
1157   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, TLI, DT, MaxRecurse))
1158     return V;
1159
1160   // undef << X -> 0
1161   if (match(Op0, m_Undef()))
1162     return Constant::getNullValue(Op0->getType());
1163
1164   // (X >> A) << A -> X
1165   Value *X;
1166   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1167     return X;
1168   return 0;
1169 }
1170
1171 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1172                              const TargetData *TD, const TargetLibraryInfo *TLI,
1173                              const DominatorTree *DT) {
1174   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
1175 }
1176
1177 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1178 /// fold the result.  If not, this returns null.
1179 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1180                                const TargetData *TD,
1181                                const TargetLibraryInfo *TLI,
1182                                const DominatorTree *DT,
1183                                unsigned MaxRecurse) {
1184   if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
1185     return V;
1186
1187   // undef >>l X -> 0
1188   if (match(Op0, m_Undef()))
1189     return Constant::getNullValue(Op0->getType());
1190
1191   // (X << A) >> A -> X
1192   Value *X;
1193   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1194       cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1195     return X;
1196
1197   return 0;
1198 }
1199
1200 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1201                               const TargetData *TD,
1202                               const TargetLibraryInfo *TLI,
1203                               const DominatorTree *DT) {
1204   return ::SimplifyLShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
1205 }
1206
1207 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1208 /// fold the result.  If not, this returns null.
1209 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1210                                const TargetData *TD,
1211                                const TargetLibraryInfo *TLI,
1212                                const DominatorTree *DT,
1213                                unsigned MaxRecurse) {
1214   if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
1215     return V;
1216
1217   // all ones >>a X -> all ones
1218   if (match(Op0, m_AllOnes()))
1219     return Op0;
1220
1221   // undef >>a X -> all ones
1222   if (match(Op0, m_Undef()))
1223     return Constant::getAllOnesValue(Op0->getType());
1224
1225   // (X << A) >> A -> X
1226   Value *X;
1227   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1228       cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1229     return X;
1230
1231   return 0;
1232 }
1233
1234 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1235                               const TargetData *TD,
1236                               const TargetLibraryInfo *TLI,
1237                               const DominatorTree *DT) {
1238   return ::SimplifyAShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
1239 }
1240
1241 /// SimplifyAndInst - Given operands for an And, see if we can
1242 /// fold the result.  If not, this returns null.
1243 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD, 
1244                               const TargetLibraryInfo *TLI,
1245                               const DominatorTree *DT,
1246                               unsigned MaxRecurse) {
1247   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1248     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1249       Constant *Ops[] = { CLHS, CRHS };
1250       return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1251                                       Ops, TD, TLI);
1252     }
1253
1254     // Canonicalize the constant to the RHS.
1255     std::swap(Op0, Op1);
1256   }
1257
1258   // X & undef -> 0
1259   if (match(Op1, m_Undef()))
1260     return Constant::getNullValue(Op0->getType());
1261
1262   // X & X = X
1263   if (Op0 == Op1)
1264     return Op0;
1265
1266   // X & 0 = 0
1267   if (match(Op1, m_Zero()))
1268     return Op1;
1269
1270   // X & -1 = X
1271   if (match(Op1, m_AllOnes()))
1272     return Op0;
1273
1274   // A & ~A  =  ~A & A  =  0
1275   if (match(Op0, m_Not(m_Specific(Op1))) ||
1276       match(Op1, m_Not(m_Specific(Op0))))
1277     return Constant::getNullValue(Op0->getType());
1278
1279   // (A | ?) & A = A
1280   Value *A = 0, *B = 0;
1281   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1282       (A == Op1 || B == Op1))
1283     return Op1;
1284
1285   // A & (A | ?) = A
1286   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1287       (A == Op0 || B == Op0))
1288     return Op0;
1289
1290   // A & (-A) = A if A is a power of two or zero.
1291   if (match(Op0, m_Neg(m_Specific(Op1))) ||
1292       match(Op1, m_Neg(m_Specific(Op0)))) {
1293     if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1294       return Op0;
1295     if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1296       return Op1;
1297   }
1298
1299   // Try some generic simplifications for associative operations.
1300   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, TLI,
1301                                           DT, MaxRecurse))
1302     return V;
1303
1304   // And distributes over Or.  Try some generic simplifications based on this.
1305   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1306                              TD, TLI, DT, MaxRecurse))
1307     return V;
1308
1309   // And distributes over Xor.  Try some generic simplifications based on this.
1310   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1311                              TD, TLI, DT, MaxRecurse))
1312     return V;
1313
1314   // Or distributes over And.  Try some generic simplifications based on this.
1315   if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1316                                 TD, TLI, DT, MaxRecurse))
1317     return V;
1318
1319   // If the operation is with the result of a select instruction, check whether
1320   // operating on either branch of the select always yields the same value.
1321   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1322     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, TLI,
1323                                          DT, MaxRecurse))
1324       return V;
1325
1326   // If the operation is with the result of a phi instruction, check whether
1327   // operating on all incoming values of the phi always yields the same value.
1328   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1329     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, TLI, DT,
1330                                       MaxRecurse))
1331       return V;
1332
1333   return 0;
1334 }
1335
1336 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1337                              const TargetLibraryInfo *TLI,
1338                              const DominatorTree *DT) {
1339   return ::SimplifyAndInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1340 }
1341
1342 /// SimplifyOrInst - Given operands for an Or, see if we can
1343 /// fold the result.  If not, this returns null.
1344 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD, 
1345                              const TargetLibraryInfo *TLI,
1346                              const DominatorTree *DT, unsigned MaxRecurse) {
1347   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1348     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1349       Constant *Ops[] = { CLHS, CRHS };
1350       return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1351                                       Ops, TD, TLI);
1352     }
1353
1354     // Canonicalize the constant to the RHS.
1355     std::swap(Op0, Op1);
1356   }
1357
1358   // X | undef -> -1
1359   if (match(Op1, m_Undef()))
1360     return Constant::getAllOnesValue(Op0->getType());
1361
1362   // X | X = X
1363   if (Op0 == Op1)
1364     return Op0;
1365
1366   // X | 0 = X
1367   if (match(Op1, m_Zero()))
1368     return Op0;
1369
1370   // X | -1 = -1
1371   if (match(Op1, m_AllOnes()))
1372     return Op1;
1373
1374   // A | ~A  =  ~A | A  =  -1
1375   if (match(Op0, m_Not(m_Specific(Op1))) ||
1376       match(Op1, m_Not(m_Specific(Op0))))
1377     return Constant::getAllOnesValue(Op0->getType());
1378
1379   // (A & ?) | A = A
1380   Value *A = 0, *B = 0;
1381   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1382       (A == Op1 || B == Op1))
1383     return Op1;
1384
1385   // A | (A & ?) = A
1386   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1387       (A == Op0 || B == Op0))
1388     return Op0;
1389
1390   // ~(A & ?) | A = -1
1391   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1392       (A == Op1 || B == Op1))
1393     return Constant::getAllOnesValue(Op1->getType());
1394
1395   // A | ~(A & ?) = -1
1396   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1397       (A == Op0 || B == Op0))
1398     return Constant::getAllOnesValue(Op0->getType());
1399
1400   // Try some generic simplifications for associative operations.
1401   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, TLI,
1402                                           DT, MaxRecurse))
1403     return V;
1404
1405   // Or distributes over And.  Try some generic simplifications based on this.
1406   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, TD,
1407                              TLI, DT, MaxRecurse))
1408     return V;
1409
1410   // And distributes over Or.  Try some generic simplifications based on this.
1411   if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1412                                 TD, TLI, DT, MaxRecurse))
1413     return V;
1414
1415   // If the operation is with the result of a select instruction, check whether
1416   // operating on either branch of the select always yields the same value.
1417   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1418     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, TLI, DT,
1419                                          MaxRecurse))
1420       return V;
1421
1422   // If the operation is with the result of a phi instruction, check whether
1423   // operating on all incoming values of the phi always yields the same value.
1424   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1425     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, TLI, DT,
1426                                       MaxRecurse))
1427       return V;
1428
1429   return 0;
1430 }
1431
1432 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1433                             const TargetLibraryInfo *TLI,
1434                             const DominatorTree *DT) {
1435   return ::SimplifyOrInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1436 }
1437
1438 /// SimplifyXorInst - Given operands for a Xor, see if we can
1439 /// fold the result.  If not, this returns null.
1440 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1441                               const TargetLibraryInfo *TLI,
1442                               const DominatorTree *DT, unsigned MaxRecurse) {
1443   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1444     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1445       Constant *Ops[] = { CLHS, CRHS };
1446       return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1447                                       Ops, TD, TLI);
1448     }
1449
1450     // Canonicalize the constant to the RHS.
1451     std::swap(Op0, Op1);
1452   }
1453
1454   // A ^ undef -> undef
1455   if (match(Op1, m_Undef()))
1456     return Op1;
1457
1458   // A ^ 0 = A
1459   if (match(Op1, m_Zero()))
1460     return Op0;
1461
1462   // A ^ A = 0
1463   if (Op0 == Op1)
1464     return Constant::getNullValue(Op0->getType());
1465
1466   // A ^ ~A  =  ~A ^ A  =  -1
1467   if (match(Op0, m_Not(m_Specific(Op1))) ||
1468       match(Op1, m_Not(m_Specific(Op0))))
1469     return Constant::getAllOnesValue(Op0->getType());
1470
1471   // Try some generic simplifications for associative operations.
1472   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, TLI,
1473                                           DT, MaxRecurse))
1474     return V;
1475
1476   // And distributes over Xor.  Try some generic simplifications based on this.
1477   if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1478                                 TD, TLI, DT, MaxRecurse))
1479     return V;
1480
1481   // Threading Xor over selects and phi nodes is pointless, so don't bother.
1482   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1483   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1484   // only if B and C are equal.  If B and C are equal then (since we assume
1485   // that operands have already been simplified) "select(cond, B, C)" should
1486   // have been simplified to the common value of B and C already.  Analysing
1487   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1488   // for threading over phi nodes.
1489
1490   return 0;
1491 }
1492
1493 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1494                              const TargetLibraryInfo *TLI,
1495                              const DominatorTree *DT) {
1496   return ::SimplifyXorInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1497 }
1498
1499 static Type *GetCompareTy(Value *Op) {
1500   return CmpInst::makeCmpResultType(Op->getType());
1501 }
1502
1503 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1504 /// equivalent to the comparison "LHS Pred RHS".  Return such a value if found,
1505 /// otherwise return null.  Helper function for analyzing max/min idioms.
1506 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1507                                          Value *LHS, Value *RHS) {
1508   SelectInst *SI = dyn_cast<SelectInst>(V);
1509   if (!SI)
1510     return 0;
1511   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1512   if (!Cmp)
1513     return 0;
1514   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1515   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1516     return Cmp;
1517   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1518       LHS == CmpRHS && RHS == CmpLHS)
1519     return Cmp;
1520   return 0;
1521 }
1522
1523 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1524 /// fold the result.  If not, this returns null.
1525 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1526                                const TargetData *TD,
1527                                const TargetLibraryInfo *TLI,
1528                                const DominatorTree *DT,
1529                                unsigned MaxRecurse) {
1530   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1531   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1532
1533   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1534     if (Constant *CRHS = dyn_cast<Constant>(RHS))
1535       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
1536
1537     // If we have a constant, make sure it is on the RHS.
1538     std::swap(LHS, RHS);
1539     Pred = CmpInst::getSwappedPredicate(Pred);
1540   }
1541
1542   Type *ITy = GetCompareTy(LHS); // The return type.
1543   Type *OpTy = LHS->getType();   // The operand type.
1544
1545   // icmp X, X -> true/false
1546   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
1547   // because X could be 0.
1548   if (LHS == RHS || isa<UndefValue>(RHS))
1549     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1550
1551   // Special case logic when the operands have i1 type.
1552   if (OpTy->getScalarType()->isIntegerTy(1)) {
1553     switch (Pred) {
1554     default: break;
1555     case ICmpInst::ICMP_EQ:
1556       // X == 1 -> X
1557       if (match(RHS, m_One()))
1558         return LHS;
1559       break;
1560     case ICmpInst::ICMP_NE:
1561       // X != 0 -> X
1562       if (match(RHS, m_Zero()))
1563         return LHS;
1564       break;
1565     case ICmpInst::ICMP_UGT:
1566       // X >u 0 -> X
1567       if (match(RHS, m_Zero()))
1568         return LHS;
1569       break;
1570     case ICmpInst::ICMP_UGE:
1571       // X >=u 1 -> X
1572       if (match(RHS, m_One()))
1573         return LHS;
1574       break;
1575     case ICmpInst::ICMP_SLT:
1576       // X <s 0 -> X
1577       if (match(RHS, m_Zero()))
1578         return LHS;
1579       break;
1580     case ICmpInst::ICMP_SLE:
1581       // X <=s -1 -> X
1582       if (match(RHS, m_One()))
1583         return LHS;
1584       break;
1585     }
1586   }
1587
1588   // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1589   // different addresses, and what's more the address of a stack variable is
1590   // never null or equal to the address of a global.  Note that generalizing
1591   // to the case where LHS is a global variable address or null is pointless,
1592   // since if both LHS and RHS are constants then we already constant folded
1593   // the compare, and if only one of them is then we moved it to RHS already.
1594   Value *LHSPtr = LHS->stripPointerCasts();
1595   Value *RHSPtr = RHS->stripPointerCasts();
1596   if (LHSPtr == RHSPtr)
1597     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1598   if (isa<AllocaInst>(LHSPtr) && (isa<GlobalValue>(RHSPtr) ||
1599                                   isa<AllocaInst>(RHSPtr)  ||
1600                                   isa<ConstantPointerNull>(RHSPtr)))
1601     return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1602
1603   // If we are comparing with zero then try hard since this is a common case.
1604   if (match(RHS, m_Zero())) {
1605     bool LHSKnownNonNegative, LHSKnownNegative;
1606     switch (Pred) {
1607     default: llvm_unreachable("Unknown ICmp predicate!");
1608     case ICmpInst::ICMP_ULT:
1609       return getFalse(ITy);
1610     case ICmpInst::ICMP_UGE:
1611       return getTrue(ITy);
1612     case ICmpInst::ICMP_EQ:
1613     case ICmpInst::ICMP_ULE:
1614       if (isKnownNonZero(LHS, TD))
1615         return getFalse(ITy);
1616       break;
1617     case ICmpInst::ICMP_NE:
1618     case ICmpInst::ICMP_UGT:
1619       if (isKnownNonZero(LHS, TD))
1620         return getTrue(ITy);
1621       break;
1622     case ICmpInst::ICMP_SLT:
1623       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1624       if (LHSKnownNegative)
1625         return getTrue(ITy);
1626       if (LHSKnownNonNegative)
1627         return getFalse(ITy);
1628       break;
1629     case ICmpInst::ICMP_SLE:
1630       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1631       if (LHSKnownNegative)
1632         return getTrue(ITy);
1633       if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1634         return getFalse(ITy);
1635       break;
1636     case ICmpInst::ICMP_SGE:
1637       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1638       if (LHSKnownNegative)
1639         return getFalse(ITy);
1640       if (LHSKnownNonNegative)
1641         return getTrue(ITy);
1642       break;
1643     case ICmpInst::ICMP_SGT:
1644       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1645       if (LHSKnownNegative)
1646         return getFalse(ITy);
1647       if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1648         return getTrue(ITy);
1649       break;
1650     }
1651   }
1652
1653   // See if we are doing a comparison with a constant integer.
1654   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1655     // Rule out tautological comparisons (eg., ult 0 or uge 0).
1656     ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1657     if (RHS_CR.isEmptySet())
1658       return ConstantInt::getFalse(CI->getContext());
1659     if (RHS_CR.isFullSet())
1660       return ConstantInt::getTrue(CI->getContext());
1661
1662     // Many binary operators with constant RHS have easy to compute constant
1663     // range.  Use them to check whether the comparison is a tautology.
1664     uint32_t Width = CI->getBitWidth();
1665     APInt Lower = APInt(Width, 0);
1666     APInt Upper = APInt(Width, 0);
1667     ConstantInt *CI2;
1668     if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1669       // 'urem x, CI2' produces [0, CI2).
1670       Upper = CI2->getValue();
1671     } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1672       // 'srem x, CI2' produces (-|CI2|, |CI2|).
1673       Upper = CI2->getValue().abs();
1674       Lower = (-Upper) + 1;
1675     } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1676       // 'udiv CI2, x' produces [0, CI2].
1677       Upper = CI2->getValue() + 1;
1678     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1679       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1680       APInt NegOne = APInt::getAllOnesValue(Width);
1681       if (!CI2->isZero())
1682         Upper = NegOne.udiv(CI2->getValue()) + 1;
1683     } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1684       // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1685       APInt IntMin = APInt::getSignedMinValue(Width);
1686       APInt IntMax = APInt::getSignedMaxValue(Width);
1687       APInt Val = CI2->getValue().abs();
1688       if (!Val.isMinValue()) {
1689         Lower = IntMin.sdiv(Val);
1690         Upper = IntMax.sdiv(Val) + 1;
1691       }
1692     } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1693       // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1694       APInt NegOne = APInt::getAllOnesValue(Width);
1695       if (CI2->getValue().ult(Width))
1696         Upper = NegOne.lshr(CI2->getValue()) + 1;
1697     } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1698       // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1699       APInt IntMin = APInt::getSignedMinValue(Width);
1700       APInt IntMax = APInt::getSignedMaxValue(Width);
1701       if (CI2->getValue().ult(Width)) {
1702         Lower = IntMin.ashr(CI2->getValue());
1703         Upper = IntMax.ashr(CI2->getValue()) + 1;
1704       }
1705     } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1706       // 'or x, CI2' produces [CI2, UINT_MAX].
1707       Lower = CI2->getValue();
1708     } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1709       // 'and x, CI2' produces [0, CI2].
1710       Upper = CI2->getValue() + 1;
1711     }
1712     if (Lower != Upper) {
1713       ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1714       if (RHS_CR.contains(LHS_CR))
1715         return ConstantInt::getTrue(RHS->getContext());
1716       if (RHS_CR.inverse().contains(LHS_CR))
1717         return ConstantInt::getFalse(RHS->getContext());
1718     }
1719   }
1720
1721   // Compare of cast, for example (zext X) != 0 -> X != 0
1722   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1723     Instruction *LI = cast<CastInst>(LHS);
1724     Value *SrcOp = LI->getOperand(0);
1725     Type *SrcTy = SrcOp->getType();
1726     Type *DstTy = LI->getType();
1727
1728     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1729     // if the integer type is the same size as the pointer type.
1730     if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1731         TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1732       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1733         // Transfer the cast to the constant.
1734         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1735                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
1736                                         TD, TLI, DT, MaxRecurse-1))
1737           return V;
1738       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1739         if (RI->getOperand(0)->getType() == SrcTy)
1740           // Compare without the cast.
1741           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1742                                           TD, TLI, DT, MaxRecurse-1))
1743             return V;
1744       }
1745     }
1746
1747     if (isa<ZExtInst>(LHS)) {
1748       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1749       // same type.
1750       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1751         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1752           // Compare X and Y.  Note that signed predicates become unsigned.
1753           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1754                                           SrcOp, RI->getOperand(0), TD, TLI, DT,
1755                                           MaxRecurse-1))
1756             return V;
1757       }
1758       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1759       // too.  If not, then try to deduce the result of the comparison.
1760       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1761         // Compute the constant that would happen if we truncated to SrcTy then
1762         // reextended to DstTy.
1763         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1764         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1765
1766         // If the re-extended constant didn't change then this is effectively
1767         // also a case of comparing two zero-extended values.
1768         if (RExt == CI && MaxRecurse)
1769           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1770                                         SrcOp, Trunc, TD, TLI, DT, MaxRecurse-1))
1771             return V;
1772
1773         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1774         // there.  Use this to work out the result of the comparison.
1775         if (RExt != CI) {
1776           switch (Pred) {
1777           default: llvm_unreachable("Unknown ICmp predicate!");
1778           // LHS <u RHS.
1779           case ICmpInst::ICMP_EQ:
1780           case ICmpInst::ICMP_UGT:
1781           case ICmpInst::ICMP_UGE:
1782             return ConstantInt::getFalse(CI->getContext());
1783
1784           case ICmpInst::ICMP_NE:
1785           case ICmpInst::ICMP_ULT:
1786           case ICmpInst::ICMP_ULE:
1787             return ConstantInt::getTrue(CI->getContext());
1788
1789           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
1790           // is non-negative then LHS <s RHS.
1791           case ICmpInst::ICMP_SGT:
1792           case ICmpInst::ICMP_SGE:
1793             return CI->getValue().isNegative() ?
1794               ConstantInt::getTrue(CI->getContext()) :
1795               ConstantInt::getFalse(CI->getContext());
1796
1797           case ICmpInst::ICMP_SLT:
1798           case ICmpInst::ICMP_SLE:
1799             return CI->getValue().isNegative() ?
1800               ConstantInt::getFalse(CI->getContext()) :
1801               ConstantInt::getTrue(CI->getContext());
1802           }
1803         }
1804       }
1805     }
1806
1807     if (isa<SExtInst>(LHS)) {
1808       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1809       // same type.
1810       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1811         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1812           // Compare X and Y.  Note that the predicate does not change.
1813           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1814                                           TD, TLI, DT, MaxRecurse-1))
1815             return V;
1816       }
1817       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1818       // too.  If not, then try to deduce the result of the comparison.
1819       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1820         // Compute the constant that would happen if we truncated to SrcTy then
1821         // reextended to DstTy.
1822         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1823         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1824
1825         // If the re-extended constant didn't change then this is effectively
1826         // also a case of comparing two sign-extended values.
1827         if (RExt == CI && MaxRecurse)
1828           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, TLI, DT,
1829                                           MaxRecurse-1))
1830             return V;
1831
1832         // Otherwise the upper bits of LHS are all equal, while RHS has varying
1833         // bits there.  Use this to work out the result of the comparison.
1834         if (RExt != CI) {
1835           switch (Pred) {
1836           default: llvm_unreachable("Unknown ICmp predicate!");
1837           case ICmpInst::ICMP_EQ:
1838             return ConstantInt::getFalse(CI->getContext());
1839           case ICmpInst::ICMP_NE:
1840             return ConstantInt::getTrue(CI->getContext());
1841
1842           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
1843           // LHS >s RHS.
1844           case ICmpInst::ICMP_SGT:
1845           case ICmpInst::ICMP_SGE:
1846             return CI->getValue().isNegative() ?
1847               ConstantInt::getTrue(CI->getContext()) :
1848               ConstantInt::getFalse(CI->getContext());
1849           case ICmpInst::ICMP_SLT:
1850           case ICmpInst::ICMP_SLE:
1851             return CI->getValue().isNegative() ?
1852               ConstantInt::getFalse(CI->getContext()) :
1853               ConstantInt::getTrue(CI->getContext());
1854
1855           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
1856           // LHS >u RHS.
1857           case ICmpInst::ICMP_UGT:
1858           case ICmpInst::ICMP_UGE:
1859             // Comparison is true iff the LHS <s 0.
1860             if (MaxRecurse)
1861               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1862                                               Constant::getNullValue(SrcTy),
1863                                               TD, TLI, DT, MaxRecurse-1))
1864                 return V;
1865             break;
1866           case ICmpInst::ICMP_ULT:
1867           case ICmpInst::ICMP_ULE:
1868             // Comparison is true iff the LHS >=s 0.
1869             if (MaxRecurse)
1870               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1871                                               Constant::getNullValue(SrcTy),
1872                                               TD, TLI, DT, MaxRecurse-1))
1873                 return V;
1874             break;
1875           }
1876         }
1877       }
1878     }
1879   }
1880
1881   // Special logic for binary operators.
1882   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1883   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1884   if (MaxRecurse && (LBO || RBO)) {
1885     // Analyze the case when either LHS or RHS is an add instruction.
1886     Value *A = 0, *B = 0, *C = 0, *D = 0;
1887     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1888     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1889     if (LBO && LBO->getOpcode() == Instruction::Add) {
1890       A = LBO->getOperand(0); B = LBO->getOperand(1);
1891       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1892         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1893         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1894     }
1895     if (RBO && RBO->getOpcode() == Instruction::Add) {
1896       C = RBO->getOperand(0); D = RBO->getOperand(1);
1897       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1898         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1899         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1900     }
1901
1902     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1903     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1904       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1905                                       Constant::getNullValue(RHS->getType()),
1906                                       TD, TLI, DT, MaxRecurse-1))
1907         return V;
1908
1909     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1910     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1911       if (Value *V = SimplifyICmpInst(Pred,
1912                                       Constant::getNullValue(LHS->getType()),
1913                                       C == LHS ? D : C, TD, TLI, DT, MaxRecurse-1))
1914         return V;
1915
1916     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1917     if (A && C && (A == C || A == D || B == C || B == D) &&
1918         NoLHSWrapProblem && NoRHSWrapProblem) {
1919       // Determine Y and Z in the form icmp (X+Y), (X+Z).
1920       Value *Y = (A == C || A == D) ? B : A;
1921       Value *Z = (C == A || C == B) ? D : C;
1922       if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, TLI, DT, MaxRecurse-1))
1923         return V;
1924     }
1925   }
1926
1927   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
1928     bool KnownNonNegative, KnownNegative;
1929     switch (Pred) {
1930     default:
1931       break;
1932     case ICmpInst::ICMP_SGT:
1933     case ICmpInst::ICMP_SGE:
1934       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1935       if (!KnownNonNegative)
1936         break;
1937       // fall-through
1938     case ICmpInst::ICMP_EQ:
1939     case ICmpInst::ICMP_UGT:
1940     case ICmpInst::ICMP_UGE:
1941       return getFalse(ITy);
1942     case ICmpInst::ICMP_SLT:
1943     case ICmpInst::ICMP_SLE:
1944       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1945       if (!KnownNonNegative)
1946         break;
1947       // fall-through
1948     case ICmpInst::ICMP_NE:
1949     case ICmpInst::ICMP_ULT:
1950     case ICmpInst::ICMP_ULE:
1951       return getTrue(ITy);
1952     }
1953   }
1954   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1955     bool KnownNonNegative, KnownNegative;
1956     switch (Pred) {
1957     default:
1958       break;
1959     case ICmpInst::ICMP_SGT:
1960     case ICmpInst::ICMP_SGE:
1961       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1962       if (!KnownNonNegative)
1963         break;
1964       // fall-through
1965     case ICmpInst::ICMP_NE:
1966     case ICmpInst::ICMP_UGT:
1967     case ICmpInst::ICMP_UGE:
1968       return getTrue(ITy);
1969     case ICmpInst::ICMP_SLT:
1970     case ICmpInst::ICMP_SLE:
1971       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1972       if (!KnownNonNegative)
1973         break;
1974       // fall-through
1975     case ICmpInst::ICMP_EQ:
1976     case ICmpInst::ICMP_ULT:
1977     case ICmpInst::ICMP_ULE:
1978       return getFalse(ITy);
1979     }
1980   }
1981
1982   // x udiv y <=u x.
1983   if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
1984     // icmp pred (X /u Y), X
1985     if (Pred == ICmpInst::ICMP_UGT)
1986       return getFalse(ITy);
1987     if (Pred == ICmpInst::ICMP_ULE)
1988       return getTrue(ITy);
1989   }
1990
1991   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
1992       LBO->getOperand(1) == RBO->getOperand(1)) {
1993     switch (LBO->getOpcode()) {
1994     default: break;
1995     case Instruction::UDiv:
1996     case Instruction::LShr:
1997       if (ICmpInst::isSigned(Pred))
1998         break;
1999       // fall-through
2000     case Instruction::SDiv:
2001     case Instruction::AShr:
2002       if (!LBO->isExact() || !RBO->isExact())
2003         break;
2004       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2005                                       RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
2006         return V;
2007       break;
2008     case Instruction::Shl: {
2009       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2010       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2011       if (!NUW && !NSW)
2012         break;
2013       if (!NSW && ICmpInst::isSigned(Pred))
2014         break;
2015       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2016                                       RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
2017         return V;
2018       break;
2019     }
2020     }
2021   }
2022
2023   // Simplify comparisons involving max/min.
2024   Value *A, *B;
2025   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2026   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2027
2028   // Signed variants on "max(a,b)>=a -> true".
2029   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2030     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2031     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2032     // We analyze this as smax(A, B) pred A.
2033     P = Pred;
2034   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2035              (A == LHS || B == LHS)) {
2036     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2037     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2038     // We analyze this as smax(A, B) swapped-pred A.
2039     P = CmpInst::getSwappedPredicate(Pred);
2040   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2041              (A == RHS || B == RHS)) {
2042     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2043     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2044     // We analyze this as smax(-A, -B) swapped-pred -A.
2045     // Note that we do not need to actually form -A or -B thanks to EqP.
2046     P = CmpInst::getSwappedPredicate(Pred);
2047   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2048              (A == LHS || B == LHS)) {
2049     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2050     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2051     // We analyze this as smax(-A, -B) pred -A.
2052     // Note that we do not need to actually form -A or -B thanks to EqP.
2053     P = Pred;
2054   }
2055   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2056     // Cases correspond to "max(A, B) p A".
2057     switch (P) {
2058     default:
2059       break;
2060     case CmpInst::ICMP_EQ:
2061     case CmpInst::ICMP_SLE:
2062       // Equivalent to "A EqP B".  This may be the same as the condition tested
2063       // in the max/min; if so, we can just return that.
2064       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2065         return V;
2066       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2067         return V;
2068       // Otherwise, see if "A EqP B" simplifies.
2069       if (MaxRecurse)
2070         if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
2071           return V;
2072       break;
2073     case CmpInst::ICMP_NE:
2074     case CmpInst::ICMP_SGT: {
2075       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2076       // Equivalent to "A InvEqP B".  This may be the same as the condition
2077       // tested in the max/min; if so, we can just return that.
2078       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2079         return V;
2080       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2081         return V;
2082       // Otherwise, see if "A InvEqP B" simplifies.
2083       if (MaxRecurse)
2084         if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
2085           return V;
2086       break;
2087     }
2088     case CmpInst::ICMP_SGE:
2089       // Always true.
2090       return getTrue(ITy);
2091     case CmpInst::ICMP_SLT:
2092       // Always false.
2093       return getFalse(ITy);
2094     }
2095   }
2096
2097   // Unsigned variants on "max(a,b)>=a -> true".
2098   P = CmpInst::BAD_ICMP_PREDICATE;
2099   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2100     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2101     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2102     // We analyze this as umax(A, B) pred A.
2103     P = Pred;
2104   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2105              (A == LHS || B == LHS)) {
2106     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2107     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2108     // We analyze this as umax(A, B) swapped-pred A.
2109     P = CmpInst::getSwappedPredicate(Pred);
2110   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2111              (A == RHS || B == RHS)) {
2112     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2113     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2114     // We analyze this as umax(-A, -B) swapped-pred -A.
2115     // Note that we do not need to actually form -A or -B thanks to EqP.
2116     P = CmpInst::getSwappedPredicate(Pred);
2117   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2118              (A == LHS || B == LHS)) {
2119     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2120     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2121     // We analyze this as umax(-A, -B) pred -A.
2122     // Note that we do not need to actually form -A or -B thanks to EqP.
2123     P = Pred;
2124   }
2125   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2126     // Cases correspond to "max(A, B) p A".
2127     switch (P) {
2128     default:
2129       break;
2130     case CmpInst::ICMP_EQ:
2131     case CmpInst::ICMP_ULE:
2132       // Equivalent to "A EqP B".  This may be the same as the condition tested
2133       // in the max/min; if so, we can just return that.
2134       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2135         return V;
2136       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2137         return V;
2138       // Otherwise, see if "A EqP B" simplifies.
2139       if (MaxRecurse)
2140         if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
2141           return V;
2142       break;
2143     case CmpInst::ICMP_NE:
2144     case CmpInst::ICMP_UGT: {
2145       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2146       // Equivalent to "A InvEqP B".  This may be the same as the condition
2147       // tested in the max/min; if so, we can just return that.
2148       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2149         return V;
2150       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2151         return V;
2152       // Otherwise, see if "A InvEqP B" simplifies.
2153       if (MaxRecurse)
2154         if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
2155           return V;
2156       break;
2157     }
2158     case CmpInst::ICMP_UGE:
2159       // Always true.
2160       return getTrue(ITy);
2161     case CmpInst::ICMP_ULT:
2162       // Always false.
2163       return getFalse(ITy);
2164     }
2165   }
2166
2167   // Variants on "max(x,y) >= min(x,z)".
2168   Value *C, *D;
2169   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2170       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2171       (A == C || A == D || B == C || B == D)) {
2172     // max(x, ?) pred min(x, ?).
2173     if (Pred == CmpInst::ICMP_SGE)
2174       // Always true.
2175       return getTrue(ITy);
2176     if (Pred == CmpInst::ICMP_SLT)
2177       // Always false.
2178       return getFalse(ITy);
2179   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2180              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2181              (A == C || A == D || B == C || B == D)) {
2182     // min(x, ?) pred max(x, ?).
2183     if (Pred == CmpInst::ICMP_SLE)
2184       // Always true.
2185       return getTrue(ITy);
2186     if (Pred == CmpInst::ICMP_SGT)
2187       // Always false.
2188       return getFalse(ITy);
2189   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2190              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2191              (A == C || A == D || B == C || B == D)) {
2192     // max(x, ?) pred min(x, ?).
2193     if (Pred == CmpInst::ICMP_UGE)
2194       // Always true.
2195       return getTrue(ITy);
2196     if (Pred == CmpInst::ICMP_ULT)
2197       // Always false.
2198       return getFalse(ITy);
2199   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2200              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2201              (A == C || A == D || B == C || B == D)) {
2202     // min(x, ?) pred max(x, ?).
2203     if (Pred == CmpInst::ICMP_ULE)
2204       // Always true.
2205       return getTrue(ITy);
2206     if (Pred == CmpInst::ICMP_UGT)
2207       // Always false.
2208       return getFalse(ITy);
2209   }
2210
2211   // If the comparison is with the result of a select instruction, check whether
2212   // comparing with either branch of the select always yields the same value.
2213   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2214     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2215       return V;
2216
2217   // If the comparison is with the result of a phi instruction, check whether
2218   // doing the compare with each incoming phi value yields a common result.
2219   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2220     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2221       return V;
2222
2223   return 0;
2224 }
2225
2226 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2227                               const TargetData *TD,
2228                               const TargetLibraryInfo *TLI,
2229                               const DominatorTree *DT) {
2230   return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2231 }
2232
2233 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2234 /// fold the result.  If not, this returns null.
2235 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2236                                const TargetData *TD,
2237                                const TargetLibraryInfo *TLI,
2238                                const DominatorTree *DT,
2239                                unsigned MaxRecurse) {
2240   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2241   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2242
2243   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2244     if (Constant *CRHS = dyn_cast<Constant>(RHS))
2245       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
2246
2247     // If we have a constant, make sure it is on the RHS.
2248     std::swap(LHS, RHS);
2249     Pred = CmpInst::getSwappedPredicate(Pred);
2250   }
2251
2252   // Fold trivial predicates.
2253   if (Pred == FCmpInst::FCMP_FALSE)
2254     return ConstantInt::get(GetCompareTy(LHS), 0);
2255   if (Pred == FCmpInst::FCMP_TRUE)
2256     return ConstantInt::get(GetCompareTy(LHS), 1);
2257
2258   if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
2259     return UndefValue::get(GetCompareTy(LHS));
2260
2261   // fcmp x,x -> true/false.  Not all compares are foldable.
2262   if (LHS == RHS) {
2263     if (CmpInst::isTrueWhenEqual(Pred))
2264       return ConstantInt::get(GetCompareTy(LHS), 1);
2265     if (CmpInst::isFalseWhenEqual(Pred))
2266       return ConstantInt::get(GetCompareTy(LHS), 0);
2267   }
2268
2269   // Handle fcmp with constant RHS
2270   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2271     // If the constant is a nan, see if we can fold the comparison based on it.
2272     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2273       if (CFP->getValueAPF().isNaN()) {
2274         if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
2275           return ConstantInt::getFalse(CFP->getContext());
2276         assert(FCmpInst::isUnordered(Pred) &&
2277                "Comparison must be either ordered or unordered!");
2278         // True if unordered.
2279         return ConstantInt::getTrue(CFP->getContext());
2280       }
2281       // Check whether the constant is an infinity.
2282       if (CFP->getValueAPF().isInfinity()) {
2283         if (CFP->getValueAPF().isNegative()) {
2284           switch (Pred) {
2285           case FCmpInst::FCMP_OLT:
2286             // No value is ordered and less than negative infinity.
2287             return ConstantInt::getFalse(CFP->getContext());
2288           case FCmpInst::FCMP_UGE:
2289             // All values are unordered with or at least negative infinity.
2290             return ConstantInt::getTrue(CFP->getContext());
2291           default:
2292             break;
2293           }
2294         } else {
2295           switch (Pred) {
2296           case FCmpInst::FCMP_OGT:
2297             // No value is ordered and greater than infinity.
2298             return ConstantInt::getFalse(CFP->getContext());
2299           case FCmpInst::FCMP_ULE:
2300             // All values are unordered with and at most infinity.
2301             return ConstantInt::getTrue(CFP->getContext());
2302           default:
2303             break;
2304           }
2305         }
2306       }
2307     }
2308   }
2309
2310   // If the comparison is with the result of a select instruction, check whether
2311   // comparing with either branch of the select always yields the same value.
2312   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2313     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2314       return V;
2315
2316   // If the comparison is with the result of a phi instruction, check whether
2317   // doing the compare with each incoming phi value yields a common result.
2318   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2319     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2320       return V;
2321
2322   return 0;
2323 }
2324
2325 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2326                               const TargetData *TD,
2327                               const TargetLibraryInfo *TLI,
2328                               const DominatorTree *DT) {
2329   return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2330 }
2331
2332 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2333 /// the result.  If not, this returns null.
2334 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2335                                 const TargetData *TD, const DominatorTree *) {
2336   // select true, X, Y  -> X
2337   // select false, X, Y -> Y
2338   if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2339     return CB->getZExtValue() ? TrueVal : FalseVal;
2340
2341   // select C, X, X -> X
2342   if (TrueVal == FalseVal)
2343     return TrueVal;
2344
2345   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
2346     if (isa<Constant>(TrueVal))
2347       return TrueVal;
2348     return FalseVal;
2349   }
2350   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
2351     return FalseVal;
2352   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
2353     return TrueVal;
2354
2355   return 0;
2356 }
2357
2358 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2359 /// fold the result.  If not, this returns null.
2360 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
2361                              const DominatorTree *) {
2362   // The type of the GEP pointer operand.
2363   PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2364   // The GEP pointer operand is not a pointer, it's a vector of pointers.
2365   if (!PtrTy)
2366     return 0;
2367
2368   // getelementptr P -> P.
2369   if (Ops.size() == 1)
2370     return Ops[0];
2371
2372   if (isa<UndefValue>(Ops[0])) {
2373     // Compute the (pointer) type returned by the GEP instruction.
2374     Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2375     Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2376     return UndefValue::get(GEPTy);
2377   }
2378
2379   if (Ops.size() == 2) {
2380     // getelementptr P, 0 -> P.
2381     if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2382       if (C->isZero())
2383         return Ops[0];
2384     // getelementptr P, N -> P if P points to a type of zero size.
2385     if (TD) {
2386       Type *Ty = PtrTy->getElementType();
2387       if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
2388         return Ops[0];
2389     }
2390   }
2391
2392   // Check to see if this is constant foldable.
2393   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2394     if (!isa<Constant>(Ops[i]))
2395       return 0;
2396
2397   return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2398 }
2399
2400 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2401 /// can fold the result.  If not, this returns null.
2402 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2403                                      ArrayRef<unsigned> Idxs,
2404                                      const TargetData *,
2405                                      const DominatorTree *) {
2406   if (Constant *CAgg = dyn_cast<Constant>(Agg))
2407     if (Constant *CVal = dyn_cast<Constant>(Val))
2408       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2409
2410   // insertvalue x, undef, n -> x
2411   if (match(Val, m_Undef()))
2412     return Agg;
2413
2414   // insertvalue x, (extractvalue y, n), n
2415   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2416     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2417         EV->getIndices() == Idxs) {
2418       // insertvalue undef, (extractvalue y, n), n -> y
2419       if (match(Agg, m_Undef()))
2420         return EV->getAggregateOperand();
2421
2422       // insertvalue y, (extractvalue y, n), n -> y
2423       if (Agg == EV->getAggregateOperand())
2424         return Agg;
2425     }
2426
2427   return 0;
2428 }
2429
2430 /// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
2431 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2432   // If all of the PHI's incoming values are the same then replace the PHI node
2433   // with the common value.
2434   Value *CommonValue = 0;
2435   bool HasUndefInput = false;
2436   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2437     Value *Incoming = PN->getIncomingValue(i);
2438     // If the incoming value is the phi node itself, it can safely be skipped.
2439     if (Incoming == PN) continue;
2440     if (isa<UndefValue>(Incoming)) {
2441       // Remember that we saw an undef value, but otherwise ignore them.
2442       HasUndefInput = true;
2443       continue;
2444     }
2445     if (CommonValue && Incoming != CommonValue)
2446       return 0;  // Not the same, bail out.
2447     CommonValue = Incoming;
2448   }
2449
2450   // If CommonValue is null then all of the incoming values were either undef or
2451   // equal to the phi node itself.
2452   if (!CommonValue)
2453     return UndefValue::get(PN->getType());
2454
2455   // If we have a PHI node like phi(X, undef, X), where X is defined by some
2456   // instruction, we cannot return X as the result of the PHI node unless it
2457   // dominates the PHI block.
2458   if (HasUndefInput)
2459     return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2460
2461   return CommonValue;
2462 }
2463
2464 //=== Helper functions for higher up the class hierarchy.
2465
2466 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2467 /// fold the result.  If not, this returns null.
2468 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2469                             const TargetData *TD, 
2470                             const TargetLibraryInfo *TLI,
2471                             const DominatorTree *DT,
2472                             unsigned MaxRecurse) {
2473   switch (Opcode) {
2474   case Instruction::Add:
2475     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2476                            TD, TLI, DT, MaxRecurse);
2477   case Instruction::Sub:
2478     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2479                            TD, TLI, DT, MaxRecurse);
2480   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, TD, TLI, DT,
2481                                                   MaxRecurse);
2482   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, TLI, DT,
2483                                                   MaxRecurse);
2484   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, TLI, DT,
2485                                                   MaxRecurse);
2486   case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, TLI, DT,
2487                                                   MaxRecurse);
2488   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, TLI, DT,
2489                                                   MaxRecurse);
2490   case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, TLI, DT,
2491                                                   MaxRecurse);
2492   case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, TLI, DT,
2493                                                   MaxRecurse);
2494   case Instruction::Shl:
2495     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2496                            TD, TLI, DT, MaxRecurse);
2497   case Instruction::LShr:
2498     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2499                             MaxRecurse);
2500   case Instruction::AShr:
2501     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2502                             MaxRecurse);
2503   case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, TLI, DT,
2504                                                 MaxRecurse);
2505   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, TD, TLI, DT,
2506                                                 MaxRecurse);
2507   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, TLI, DT,
2508                                                 MaxRecurse);
2509   default:
2510     if (Constant *CLHS = dyn_cast<Constant>(LHS))
2511       if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2512         Constant *COps[] = {CLHS, CRHS};
2513         return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD, TLI);
2514       }
2515
2516     // If the operation is associative, try some generic simplifications.
2517     if (Instruction::isAssociative(Opcode))
2518       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, TLI, DT,
2519                                               MaxRecurse))
2520         return V;
2521
2522     // If the operation is with the result of a select instruction, check whether
2523     // operating on either branch of the select always yields the same value.
2524     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2525       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, TLI, DT,
2526                                            MaxRecurse))
2527         return V;
2528
2529     // If the operation is with the result of a phi instruction, check whether
2530     // operating on all incoming values of the phi always yields the same value.
2531     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2532       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, TLI, DT,
2533                                         MaxRecurse))
2534         return V;
2535
2536     return 0;
2537   }
2538 }
2539
2540 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2541                            const TargetData *TD, const TargetLibraryInfo *TLI,
2542                            const DominatorTree *DT) {
2543   return ::SimplifyBinOp(Opcode, LHS, RHS, TD, TLI, DT, RecursionLimit);
2544 }
2545
2546 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2547 /// fold the result.
2548 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2549                               const TargetData *TD,
2550                               const TargetLibraryInfo *TLI,
2551                               const DominatorTree *DT,
2552                               unsigned MaxRecurse) {
2553   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2554     return SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2555   return SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2556 }
2557
2558 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2559                              const TargetData *TD, const TargetLibraryInfo *TLI,
2560                              const DominatorTree *DT) {
2561   return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2562 }
2563
2564 static Value *SimplifyCallInst(CallInst *CI) {
2565   // call undef -> undef
2566   if (isa<UndefValue>(CI->getCalledValue()))
2567     return UndefValue::get(CI->getType());
2568
2569   return 0;
2570 }
2571
2572 /// SimplifyInstruction - See if we can compute a simplified version of this
2573 /// instruction.  If not, this returns null.
2574 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2575                                  const TargetLibraryInfo *TLI,
2576                                  const DominatorTree *DT) {
2577   Value *Result;
2578
2579   switch (I->getOpcode()) {
2580   default:
2581     Result = ConstantFoldInstruction(I, TD, TLI);
2582     break;
2583   case Instruction::Add:
2584     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2585                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
2586                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2587                              TD, TLI, DT);
2588     break;
2589   case Instruction::Sub:
2590     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2591                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
2592                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2593                              TD, TLI, DT);
2594     break;
2595   case Instruction::Mul:
2596     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2597     break;
2598   case Instruction::SDiv:
2599     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2600     break;
2601   case Instruction::UDiv:
2602     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2603     break;
2604   case Instruction::FDiv:
2605     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2606     break;
2607   case Instruction::SRem:
2608     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2609     break;
2610   case Instruction::URem:
2611     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2612     break;
2613   case Instruction::FRem:
2614     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2615     break;
2616   case Instruction::Shl:
2617     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2618                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
2619                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2620                              TD, TLI, DT);
2621     break;
2622   case Instruction::LShr:
2623     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2624                               cast<BinaryOperator>(I)->isExact(),
2625                               TD, TLI, DT);
2626     break;
2627   case Instruction::AShr:
2628     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2629                               cast<BinaryOperator>(I)->isExact(),
2630                               TD, TLI, DT);
2631     break;
2632   case Instruction::And:
2633     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2634     break;
2635   case Instruction::Or:
2636     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2637     break;
2638   case Instruction::Xor:
2639     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2640     break;
2641   case Instruction::ICmp:
2642     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2643                               I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2644     break;
2645   case Instruction::FCmp:
2646     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2647                               I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2648     break;
2649   case Instruction::Select:
2650     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2651                                 I->getOperand(2), TD, DT);
2652     break;
2653   case Instruction::GetElementPtr: {
2654     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2655     Result = SimplifyGEPInst(Ops, TD, DT);
2656     break;
2657   }
2658   case Instruction::InsertValue: {
2659     InsertValueInst *IV = cast<InsertValueInst>(I);
2660     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2661                                      IV->getInsertedValueOperand(),
2662                                      IV->getIndices(), TD, DT);
2663     break;
2664   }
2665   case Instruction::PHI:
2666     Result = SimplifyPHINode(cast<PHINode>(I), DT);
2667     break;
2668   case Instruction::Call:
2669     Result = SimplifyCallInst(cast<CallInst>(I));
2670     break;
2671   }
2672
2673   /// If called on unreachable code, the above logic may report that the
2674   /// instruction simplified to itself.  Make life easier for users by
2675   /// detecting that case here, returning a safe value instead.
2676   return Result == I ? UndefValue::get(I->getType()) : Result;
2677 }
2678
2679 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2680 /// delete the From instruction.  In addition to a basic RAUW, this does a
2681 /// recursive simplification of the newly formed instructions.  This catches
2682 /// things where one simplification exposes other opportunities.  This only
2683 /// simplifies and deletes scalar operations, it does not change the CFG.
2684 ///
2685 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
2686                                      const TargetData *TD,
2687                                      const TargetLibraryInfo *TLI,
2688                                      const DominatorTree *DT) {
2689   assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
2690
2691   // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2692   // we can know if it gets deleted out from under us or replaced in a
2693   // recursive simplification.
2694   WeakVH FromHandle(From);
2695   WeakVH ToHandle(To);
2696
2697   while (!From->use_empty()) {
2698     // Update the instruction to use the new value.
2699     Use &TheUse = From->use_begin().getUse();
2700     Instruction *User = cast<Instruction>(TheUse.getUser());
2701     TheUse = To;
2702
2703     // Check to see if the instruction can be folded due to the operand
2704     // replacement.  For example changing (or X, Y) into (or X, -1) can replace
2705     // the 'or' with -1.
2706     Value *SimplifiedVal;
2707     {
2708       // Sanity check to make sure 'User' doesn't dangle across
2709       // SimplifyInstruction.
2710       AssertingVH<> UserHandle(User);
2711
2712       SimplifiedVal = SimplifyInstruction(User, TD, TLI, DT);
2713       if (SimplifiedVal == 0) continue;
2714     }
2715
2716     // Recursively simplify this user to the new value.
2717     ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, TLI, DT);
2718     From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2719     To = ToHandle;
2720
2721     assert(ToHandle && "To value deleted by recursive simplification?");
2722
2723     // If the recursive simplification ended up revisiting and deleting
2724     // 'From' then we're done.
2725     if (From == 0)
2726       return;
2727   }
2728
2729   // If 'From' has value handles referring to it, do a real RAUW to update them.
2730   From->replaceAllUsesWith(To);
2731
2732   From->eraseFromParent();
2733 }