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