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