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