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