Use the new range metadata in computeMaskedBits and add a new optimization to
[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/Target/TargetData.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 TargetData *TD;
46   const TargetLibraryInfo *TLI;
47   const DominatorTree *DT;
48
49   Query(const TargetData *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 TargetData *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 TargetData &TD, GEPOperator *GEP,
668                                 APInt &Offset) {
669   unsigned IntPtrWidth = TD.getPointerSizeInBits();
670   assert(IntPtrWidth == Offset.getBitWidth());
671
672   gep_type_iterator GTI = gep_type_begin(GEP);
673   for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end(); I != E;
674        ++I, ++GTI) {
675     ConstantInt *OpC = dyn_cast<ConstantInt>(*I);
676     if (!OpC) return false;
677     if (OpC->isZero()) continue;
678
679     // Handle a struct index, which adds its field offset to the pointer.
680     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
681       unsigned ElementIdx = OpC->getZExtValue();
682       const StructLayout *SL = TD.getStructLayout(STy);
683       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
684       continue;
685     }
686
687     APInt TypeSize(IntPtrWidth, TD.getTypeAllocSize(GTI.getIndexedType()));
688     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
689   }
690   return true;
691 }
692
693 /// \brief Compute the base pointer and cumulative constant offsets for V.
694 ///
695 /// This strips all constant offsets off of V, leaving it the base pointer, and
696 /// accumulates the total constant offset applied in the returned constant. It
697 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
698 /// no constant offsets applied.
699 static Constant *stripAndComputeConstantOffsets(const TargetData &TD,
700                                                 Value *&V) {
701   if (!V->getType()->isPointerTy())
702     return 0;
703
704   unsigned IntPtrWidth = TD.getPointerSizeInBits();
705   APInt Offset = APInt::getNullValue(IntPtrWidth);
706
707   // Even though we don't look through PHI nodes, we could be called on an
708   // instruction in an unreachable block, which may be on a cycle.
709   SmallPtrSet<Value *, 4> Visited;
710   Visited.insert(V);
711   do {
712     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
713       if (!GEP->isInBounds() || !accumulateGEPOffset(TD, GEP, Offset))
714         break;
715       V = GEP->getPointerOperand();
716     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
717       V = cast<Operator>(V)->getOperand(0);
718     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
719       if (GA->mayBeOverridden())
720         break;
721       V = GA->getAliasee();
722     } else {
723       break;
724     }
725     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
726   } while (Visited.insert(V));
727
728   Type *IntPtrTy = TD.getIntPtrType(V->getContext());
729   return ConstantInt::get(IntPtrTy, Offset);
730 }
731
732 /// \brief Compute the constant difference between two pointer values.
733 /// If the difference is not a constant, returns zero.
734 static Constant *computePointerDifference(const TargetData &TD,
735                                           Value *LHS, Value *RHS) {
736   Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
737   if (!LHSOffset)
738     return 0;
739   Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
740   if (!RHSOffset)
741     return 0;
742
743   // If LHS and RHS are not related via constant offsets to the same base
744   // value, there is nothing we can do here.
745   if (LHS != RHS)
746     return 0;
747
748   // Otherwise, the difference of LHS - RHS can be computed as:
749   //    LHS - RHS
750   //  = (LHSOffset + Base) - (RHSOffset + Base)
751   //  = LHSOffset - RHSOffset
752   return ConstantExpr::getSub(LHSOffset, RHSOffset);
753 }
754
755 /// SimplifySubInst - Given operands for a Sub, see if we can
756 /// fold the result.  If not, this returns null.
757 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
758                               const Query &Q, unsigned MaxRecurse) {
759   if (Constant *CLHS = dyn_cast<Constant>(Op0))
760     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
761       Constant *Ops[] = { CLHS, CRHS };
762       return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
763                                       Ops, Q.TD, Q.TLI);
764     }
765
766   // X - undef -> undef
767   // undef - X -> undef
768   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
769     return UndefValue::get(Op0->getType());
770
771   // X - 0 -> X
772   if (match(Op1, m_Zero()))
773     return Op0;
774
775   // X - X -> 0
776   if (Op0 == Op1)
777     return Constant::getNullValue(Op0->getType());
778
779   // (X*2) - X -> X
780   // (X<<1) - X -> X
781   Value *X = 0;
782   if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
783       match(Op0, m_Shl(m_Specific(Op1), m_One())))
784     return Op1;
785
786   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
787   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
788   Value *Y = 0, *Z = Op1;
789   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
790     // See if "V === Y - Z" simplifies.
791     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
792       // It does!  Now see if "X + V" simplifies.
793       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
794         // It does, we successfully reassociated!
795         ++NumReassoc;
796         return W;
797       }
798     // See if "V === X - Z" simplifies.
799     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
800       // It does!  Now see if "Y + V" simplifies.
801       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
802         // It does, we successfully reassociated!
803         ++NumReassoc;
804         return W;
805       }
806   }
807
808   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
809   // For example, X - (X + 1) -> -1
810   X = Op0;
811   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
812     // See if "V === X - Y" simplifies.
813     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
814       // It does!  Now see if "V - Z" simplifies.
815       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
816         // It does, we successfully reassociated!
817         ++NumReassoc;
818         return W;
819       }
820     // See if "V === X - Z" simplifies.
821     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
822       // It does!  Now see if "V - Y" simplifies.
823       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
824         // It does, we successfully reassociated!
825         ++NumReassoc;
826         return W;
827       }
828   }
829
830   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
831   // For example, X - (X - Y) -> Y.
832   Z = Op0;
833   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
834     // See if "V === Z - X" simplifies.
835     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
836       // It does!  Now see if "V + Y" simplifies.
837       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
838         // It does, we successfully reassociated!
839         ++NumReassoc;
840         return W;
841       }
842
843   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
844   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
845       match(Op1, m_Trunc(m_Value(Y))))
846     if (X->getType() == Y->getType())
847       // See if "V === X - Y" simplifies.
848       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
849         // It does!  Now see if "trunc V" simplifies.
850         if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
851           // It does, return the simplified "trunc V".
852           return W;
853
854   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
855   if (Q.TD && match(Op0, m_PtrToInt(m_Value(X))) &&
856       match(Op1, m_PtrToInt(m_Value(Y))))
857     if (Constant *Result = computePointerDifference(*Q.TD, X, Y))
858       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
859
860   // Mul distributes over Sub.  Try some generic simplifications based on this.
861   if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
862                                 Q, MaxRecurse))
863     return V;
864
865   // i1 sub -> xor.
866   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
867     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
868       return V;
869
870   // Threading Sub over selects and phi nodes is pointless, so don't bother.
871   // Threading over the select in "A - select(cond, B, C)" means evaluating
872   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
873   // only if B and C are equal.  If B and C are equal then (since we assume
874   // that operands have already been simplified) "select(cond, B, C)" should
875   // have been simplified to the common value of B and C already.  Analysing
876   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
877   // for threading over phi nodes.
878
879   return 0;
880 }
881
882 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
883                              const TargetData *TD, const TargetLibraryInfo *TLI,
884                              const DominatorTree *DT) {
885   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
886                            RecursionLimit);
887 }
888
889 /// SimplifyMulInst - Given operands for a Mul, see if we can
890 /// fold the result.  If not, this returns null.
891 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
892                               unsigned MaxRecurse) {
893   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
894     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
895       Constant *Ops[] = { CLHS, CRHS };
896       return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
897                                       Ops, Q.TD, Q.TLI);
898     }
899
900     // Canonicalize the constant to the RHS.
901     std::swap(Op0, Op1);
902   }
903
904   // X * undef -> 0
905   if (match(Op1, m_Undef()))
906     return Constant::getNullValue(Op0->getType());
907
908   // X * 0 -> 0
909   if (match(Op1, m_Zero()))
910     return Op1;
911
912   // X * 1 -> X
913   if (match(Op1, m_One()))
914     return Op0;
915
916   // (X / Y) * Y -> X if the division is exact.
917   Value *X = 0;
918   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
919       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
920     return X;
921
922   // i1 mul -> and.
923   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
924     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
925       return V;
926
927   // Try some generic simplifications for associative operations.
928   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
929                                           MaxRecurse))
930     return V;
931
932   // Mul distributes over Add.  Try some generic simplifications based on this.
933   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
934                              Q, MaxRecurse))
935     return V;
936
937   // If the operation is with the result of a select instruction, check whether
938   // operating on either branch of the select always yields the same value.
939   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
940     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
941                                          MaxRecurse))
942       return V;
943
944   // If the operation is with the result of a phi instruction, check whether
945   // operating on all incoming values of the phi always yields the same value.
946   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
947     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
948                                       MaxRecurse))
949       return V;
950
951   return 0;
952 }
953
954 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
955                              const TargetLibraryInfo *TLI,
956                              const DominatorTree *DT) {
957   return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
958 }
959
960 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
961 /// fold the result.  If not, this returns null.
962 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
963                           const Query &Q, unsigned MaxRecurse) {
964   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
965     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
966       Constant *Ops[] = { C0, C1 };
967       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
968     }
969   }
970
971   bool isSigned = Opcode == Instruction::SDiv;
972
973   // X / undef -> undef
974   if (match(Op1, m_Undef()))
975     return Op1;
976
977   // undef / X -> 0
978   if (match(Op0, m_Undef()))
979     return Constant::getNullValue(Op0->getType());
980
981   // 0 / X -> 0, we don't need to preserve faults!
982   if (match(Op0, m_Zero()))
983     return Op0;
984
985   // X / 1 -> X
986   if (match(Op1, m_One()))
987     return Op0;
988
989   if (Op0->getType()->isIntegerTy(1))
990     // It can't be division by zero, hence it must be division by one.
991     return Op0;
992
993   // X / X -> 1
994   if (Op0 == Op1)
995     return ConstantInt::get(Op0->getType(), 1);
996
997   // (X * Y) / Y -> X if the multiplication does not overflow.
998   Value *X = 0, *Y = 0;
999   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1000     if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1001     OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1002     // If the Mul knows it does not overflow, then we are good to go.
1003     if ((isSigned && Mul->hasNoSignedWrap()) ||
1004         (!isSigned && Mul->hasNoUnsignedWrap()))
1005       return X;
1006     // If X has the form X = A / Y then X * Y cannot overflow.
1007     if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1008       if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1009         return X;
1010   }
1011
1012   // (X rem Y) / Y -> 0
1013   if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1014       (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1015     return Constant::getNullValue(Op0->getType());
1016
1017   // If the operation is with the result of a select instruction, check whether
1018   // operating on either branch of the select always yields the same value.
1019   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1020     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1021       return V;
1022
1023   // If the operation is with the result of a phi instruction, check whether
1024   // operating on all incoming values of the phi always yields the same value.
1025   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1026     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1027       return V;
1028
1029   return 0;
1030 }
1031
1032 /// SimplifySDivInst - Given operands for an SDiv, see if we can
1033 /// fold the result.  If not, this returns null.
1034 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1035                                unsigned MaxRecurse) {
1036   if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1037     return V;
1038
1039   return 0;
1040 }
1041
1042 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1043                               const TargetLibraryInfo *TLI,
1044                               const DominatorTree *DT) {
1045   return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1046 }
1047
1048 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
1049 /// fold the result.  If not, this returns null.
1050 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1051                                unsigned MaxRecurse) {
1052   if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1053     return V;
1054
1055   return 0;
1056 }
1057
1058 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1059                               const TargetLibraryInfo *TLI,
1060                               const DominatorTree *DT) {
1061   return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1062 }
1063
1064 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1065                                unsigned) {
1066   // undef / X -> undef    (the undef could be a snan).
1067   if (match(Op0, m_Undef()))
1068     return Op0;
1069
1070   // X / undef -> undef
1071   if (match(Op1, m_Undef()))
1072     return Op1;
1073
1074   return 0;
1075 }
1076
1077 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1078                               const TargetLibraryInfo *TLI,
1079                               const DominatorTree *DT) {
1080   return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1081 }
1082
1083 /// SimplifyRem - Given operands for an SRem or URem, see if we can
1084 /// fold the result.  If not, this returns null.
1085 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1086                           const Query &Q, unsigned MaxRecurse) {
1087   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1088     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1089       Constant *Ops[] = { C0, C1 };
1090       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
1091     }
1092   }
1093
1094   // X % undef -> undef
1095   if (match(Op1, m_Undef()))
1096     return Op1;
1097
1098   // undef % X -> 0
1099   if (match(Op0, m_Undef()))
1100     return Constant::getNullValue(Op0->getType());
1101
1102   // 0 % X -> 0, we don't need to preserve faults!
1103   if (match(Op0, m_Zero()))
1104     return Op0;
1105
1106   // X % 0 -> undef, we don't need to preserve faults!
1107   if (match(Op1, m_Zero()))
1108     return UndefValue::get(Op0->getType());
1109
1110   // X % 1 -> 0
1111   if (match(Op1, m_One()))
1112     return Constant::getNullValue(Op0->getType());
1113
1114   if (Op0->getType()->isIntegerTy(1))
1115     // It can't be remainder by zero, hence it must be remainder by one.
1116     return Constant::getNullValue(Op0->getType());
1117
1118   // X % X -> 0
1119   if (Op0 == Op1)
1120     return Constant::getNullValue(Op0->getType());
1121
1122   // If the operation is with the result of a select instruction, check whether
1123   // operating on either branch of the select always yields the same value.
1124   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1125     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1126       return V;
1127
1128   // If the operation is with the result of a phi instruction, check whether
1129   // operating on all incoming values of the phi always yields the same value.
1130   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1131     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1132       return V;
1133
1134   return 0;
1135 }
1136
1137 /// SimplifySRemInst - Given operands for an SRem, see if we can
1138 /// fold the result.  If not, this returns null.
1139 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1140                                unsigned MaxRecurse) {
1141   if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1142     return V;
1143
1144   return 0;
1145 }
1146
1147 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1148                               const TargetLibraryInfo *TLI,
1149                               const DominatorTree *DT) {
1150   return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1151 }
1152
1153 /// SimplifyURemInst - Given operands for a URem, see if we can
1154 /// fold the result.  If not, this returns null.
1155 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1156                                unsigned MaxRecurse) {
1157   if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1158     return V;
1159
1160   return 0;
1161 }
1162
1163 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1164                               const TargetLibraryInfo *TLI,
1165                               const DominatorTree *DT) {
1166   return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1167 }
1168
1169 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
1170                                unsigned) {
1171   // undef % X -> undef    (the undef could be a snan).
1172   if (match(Op0, m_Undef()))
1173     return Op0;
1174
1175   // X % undef -> undef
1176   if (match(Op1, m_Undef()))
1177     return Op1;
1178
1179   return 0;
1180 }
1181
1182 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1183                               const TargetLibraryInfo *TLI,
1184                               const DominatorTree *DT) {
1185   return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1186 }
1187
1188 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1189 /// fold the result.  If not, this returns null.
1190 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1191                             const Query &Q, unsigned MaxRecurse) {
1192   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1193     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1194       Constant *Ops[] = { C0, C1 };
1195       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
1196     }
1197   }
1198
1199   // 0 shift by X -> 0
1200   if (match(Op0, m_Zero()))
1201     return Op0;
1202
1203   // X shift by 0 -> X
1204   if (match(Op1, m_Zero()))
1205     return Op0;
1206
1207   // X shift by undef -> undef because it may shift by the bitwidth.
1208   if (match(Op1, m_Undef()))
1209     return Op1;
1210
1211   // Shifting by the bitwidth or more is undefined.
1212   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1213     if (CI->getValue().getLimitedValue() >=
1214         Op0->getType()->getScalarSizeInBits())
1215       return UndefValue::get(Op0->getType());
1216
1217   // If the operation is with the result of a select instruction, check whether
1218   // operating on either branch of the select always yields the same value.
1219   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1220     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1221       return V;
1222
1223   // If the operation is with the result of a phi instruction, check whether
1224   // operating on all incoming values of the phi always yields the same value.
1225   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1226     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1227       return V;
1228
1229   return 0;
1230 }
1231
1232 /// SimplifyShlInst - Given operands for an Shl, see if we can
1233 /// fold the result.  If not, this returns null.
1234 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1235                               const Query &Q, unsigned MaxRecurse) {
1236   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1237     return V;
1238
1239   // undef << X -> 0
1240   if (match(Op0, m_Undef()))
1241     return Constant::getNullValue(Op0->getType());
1242
1243   // (X >> A) << A -> X
1244   Value *X;
1245   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1246     return X;
1247   return 0;
1248 }
1249
1250 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1251                              const TargetData *TD, const TargetLibraryInfo *TLI,
1252                              const DominatorTree *DT) {
1253   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
1254                            RecursionLimit);
1255 }
1256
1257 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1258 /// fold the result.  If not, this returns null.
1259 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1260                                const Query &Q, unsigned MaxRecurse) {
1261   if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
1262     return V;
1263
1264   // undef >>l X -> 0
1265   if (match(Op0, m_Undef()))
1266     return Constant::getNullValue(Op0->getType());
1267
1268   // (X << A) >> A -> X
1269   Value *X;
1270   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1271       cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1272     return X;
1273
1274   return 0;
1275 }
1276
1277 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1278                               const TargetData *TD,
1279                               const TargetLibraryInfo *TLI,
1280                               const DominatorTree *DT) {
1281   return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1282                             RecursionLimit);
1283 }
1284
1285 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1286 /// fold the result.  If not, this returns null.
1287 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1288                                const Query &Q, unsigned MaxRecurse) {
1289   if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
1290     return V;
1291
1292   // all ones >>a X -> all ones
1293   if (match(Op0, m_AllOnes()))
1294     return Op0;
1295
1296   // undef >>a X -> all ones
1297   if (match(Op0, m_Undef()))
1298     return Constant::getAllOnesValue(Op0->getType());
1299
1300   // (X << A) >> A -> X
1301   Value *X;
1302   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1303       cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1304     return X;
1305
1306   return 0;
1307 }
1308
1309 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1310                               const TargetData *TD,
1311                               const TargetLibraryInfo *TLI,
1312                               const DominatorTree *DT) {
1313   return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1314                             RecursionLimit);
1315 }
1316
1317 /// SimplifyAndInst - Given operands for an And, see if we can
1318 /// fold the result.  If not, this returns null.
1319 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1320                               unsigned MaxRecurse) {
1321   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1322     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1323       Constant *Ops[] = { CLHS, CRHS };
1324       return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1325                                       Ops, Q.TD, Q.TLI);
1326     }
1327
1328     // Canonicalize the constant to the RHS.
1329     std::swap(Op0, Op1);
1330   }
1331
1332   // X & undef -> 0
1333   if (match(Op1, m_Undef()))
1334     return Constant::getNullValue(Op0->getType());
1335
1336   // X & X = X
1337   if (Op0 == Op1)
1338     return Op0;
1339
1340   // X & 0 = 0
1341   if (match(Op1, m_Zero()))
1342     return Op1;
1343
1344   // X & -1 = X
1345   if (match(Op1, m_AllOnes()))
1346     return Op0;
1347
1348   // A & ~A  =  ~A & A  =  0
1349   if (match(Op0, m_Not(m_Specific(Op1))) ||
1350       match(Op1, m_Not(m_Specific(Op0))))
1351     return Constant::getNullValue(Op0->getType());
1352
1353   // (A | ?) & A = A
1354   Value *A = 0, *B = 0;
1355   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1356       (A == Op1 || B == Op1))
1357     return Op1;
1358
1359   // A & (A | ?) = A
1360   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1361       (A == Op0 || B == Op0))
1362     return Op0;
1363
1364   // A & (-A) = A if A is a power of two or zero.
1365   if (match(Op0, m_Neg(m_Specific(Op1))) ||
1366       match(Op1, m_Neg(m_Specific(Op0)))) {
1367     if (isPowerOfTwo(Op0, Q.TD, /*OrZero*/true))
1368       return Op0;
1369     if (isPowerOfTwo(Op1, Q.TD, /*OrZero*/true))
1370       return Op1;
1371   }
1372
1373   unsigned Bitwidth = Op1->getType()->getScalarSizeInBits();
1374   APInt DemandedMask = APInt::getAllOnesValue(Bitwidth);
1375   APInt KnownZero0 = APInt::getNullValue(Bitwidth);
1376   APInt KnownOne0 = APInt::getNullValue(Bitwidth);
1377   ComputeMaskedBits(Op0, DemandedMask, KnownZero0, KnownOne0);
1378   APInt KnownZero1 = APInt::getNullValue(Bitwidth);
1379   APInt KnownOne1 = APInt::getNullValue(Bitwidth);
1380   ComputeMaskedBits(Op1, DemandedMask, KnownZero1, KnownOne1);
1381
1382   if ((KnownZero0 | KnownOne1).isAllOnesValue())
1383     return Op0;
1384
1385   if ((KnownZero1 | KnownOne0).isAllOnesValue())
1386     return Op1;
1387
1388   // Try some generic simplifications for associative operations.
1389   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1390                                           MaxRecurse))
1391     return V;
1392
1393   // And distributes over Or.  Try some generic simplifications based on this.
1394   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1395                              Q, MaxRecurse))
1396     return V;
1397
1398   // And distributes over Xor.  Try some generic simplifications based on this.
1399   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1400                              Q, MaxRecurse))
1401     return V;
1402
1403   // Or distributes over And.  Try some generic simplifications based on this.
1404   if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1405                                 Q, MaxRecurse))
1406     return V;
1407
1408   // If the operation is with the result of a select instruction, check whether
1409   // operating on either branch of the select always yields the same value.
1410   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1411     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1412                                          MaxRecurse))
1413       return V;
1414
1415   // If the operation is with the result of a phi instruction, check whether
1416   // operating on all incoming values of the phi always yields the same value.
1417   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1418     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1419                                       MaxRecurse))
1420       return V;
1421
1422   return 0;
1423 }
1424
1425 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1426                              const TargetLibraryInfo *TLI,
1427                              const DominatorTree *DT) {
1428   return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1429 }
1430
1431 /// SimplifyOrInst - Given operands for an Or, see if we can
1432 /// fold the result.  If not, this returns null.
1433 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1434                              unsigned MaxRecurse) {
1435   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1436     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1437       Constant *Ops[] = { CLHS, CRHS };
1438       return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1439                                       Ops, Q.TD, Q.TLI);
1440     }
1441
1442     // Canonicalize the constant to the RHS.
1443     std::swap(Op0, Op1);
1444   }
1445
1446   // X | undef -> -1
1447   if (match(Op1, m_Undef()))
1448     return Constant::getAllOnesValue(Op0->getType());
1449
1450   // X | X = X
1451   if (Op0 == Op1)
1452     return Op0;
1453
1454   // X | 0 = X
1455   if (match(Op1, m_Zero()))
1456     return Op0;
1457
1458   // X | -1 = -1
1459   if (match(Op1, m_AllOnes()))
1460     return Op1;
1461
1462   // A | ~A  =  ~A | A  =  -1
1463   if (match(Op0, m_Not(m_Specific(Op1))) ||
1464       match(Op1, m_Not(m_Specific(Op0))))
1465     return Constant::getAllOnesValue(Op0->getType());
1466
1467   // (A & ?) | A = A
1468   Value *A = 0, *B = 0;
1469   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1470       (A == Op1 || B == Op1))
1471     return Op1;
1472
1473   // A | (A & ?) = A
1474   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1475       (A == Op0 || B == Op0))
1476     return Op0;
1477
1478   // ~(A & ?) | A = -1
1479   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1480       (A == Op1 || B == Op1))
1481     return Constant::getAllOnesValue(Op1->getType());
1482
1483   // A | ~(A & ?) = -1
1484   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1485       (A == Op0 || B == Op0))
1486     return Constant::getAllOnesValue(Op0->getType());
1487
1488   // Try some generic simplifications for associative operations.
1489   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1490                                           MaxRecurse))
1491     return V;
1492
1493   // Or distributes over And.  Try some generic simplifications based on this.
1494   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1495                              MaxRecurse))
1496     return V;
1497
1498   // And distributes over Or.  Try some generic simplifications based on this.
1499   if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1500                                 Q, MaxRecurse))
1501     return V;
1502
1503   // If the operation is with the result of a select instruction, check whether
1504   // operating on either branch of the select always yields the same value.
1505   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1506     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1507                                          MaxRecurse))
1508       return V;
1509
1510   // If the operation is with the result of a phi instruction, check whether
1511   // operating on all incoming values of the phi always yields the same value.
1512   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1513     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1514       return V;
1515
1516   return 0;
1517 }
1518
1519 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1520                             const TargetLibraryInfo *TLI,
1521                             const DominatorTree *DT) {
1522   return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1523 }
1524
1525 /// SimplifyXorInst - Given operands for a Xor, see if we can
1526 /// fold the result.  If not, this returns null.
1527 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1528                               unsigned MaxRecurse) {
1529   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1530     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1531       Constant *Ops[] = { CLHS, CRHS };
1532       return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1533                                       Ops, Q.TD, Q.TLI);
1534     }
1535
1536     // Canonicalize the constant to the RHS.
1537     std::swap(Op0, Op1);
1538   }
1539
1540   // A ^ undef -> undef
1541   if (match(Op1, m_Undef()))
1542     return Op1;
1543
1544   // A ^ 0 = A
1545   if (match(Op1, m_Zero()))
1546     return Op0;
1547
1548   // A ^ A = 0
1549   if (Op0 == Op1)
1550     return Constant::getNullValue(Op0->getType());
1551
1552   // A ^ ~A  =  ~A ^ A  =  -1
1553   if (match(Op0, m_Not(m_Specific(Op1))) ||
1554       match(Op1, m_Not(m_Specific(Op0))))
1555     return Constant::getAllOnesValue(Op0->getType());
1556
1557   // Try some generic simplifications for associative operations.
1558   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1559                                           MaxRecurse))
1560     return V;
1561
1562   // And distributes over Xor.  Try some generic simplifications based on this.
1563   if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1564                                 Q, MaxRecurse))
1565     return V;
1566
1567   // Threading Xor over selects and phi nodes is pointless, so don't bother.
1568   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1569   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1570   // only if B and C are equal.  If B and C are equal then (since we assume
1571   // that operands have already been simplified) "select(cond, B, C)" should
1572   // have been simplified to the common value of B and C already.  Analysing
1573   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1574   // for threading over phi nodes.
1575
1576   return 0;
1577 }
1578
1579 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1580                              const TargetLibraryInfo *TLI,
1581                              const DominatorTree *DT) {
1582   return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1583 }
1584
1585 static Type *GetCompareTy(Value *Op) {
1586   return CmpInst::makeCmpResultType(Op->getType());
1587 }
1588
1589 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1590 /// equivalent to the comparison "LHS Pred RHS".  Return such a value if found,
1591 /// otherwise return null.  Helper function for analyzing max/min idioms.
1592 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1593                                          Value *LHS, Value *RHS) {
1594   SelectInst *SI = dyn_cast<SelectInst>(V);
1595   if (!SI)
1596     return 0;
1597   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1598   if (!Cmp)
1599     return 0;
1600   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1601   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1602     return Cmp;
1603   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1604       LHS == CmpRHS && RHS == CmpLHS)
1605     return Cmp;
1606   return 0;
1607 }
1608
1609 static Constant *computePointerICmp(const TargetData &TD,
1610                                     CmpInst::Predicate Pred,
1611                                     Value *LHS, Value *RHS) {
1612   // We can only fold certain predicates on pointer comparisons.
1613   switch (Pred) {
1614   default:
1615     return 0;
1616
1617     // Equality comaprisons are easy to fold.
1618   case CmpInst::ICMP_EQ:
1619   case CmpInst::ICMP_NE:
1620     break;
1621
1622     // We can only handle unsigned relational comparisons because 'inbounds' on
1623     // a GEP only protects against unsigned wrapping.
1624   case CmpInst::ICMP_UGT:
1625   case CmpInst::ICMP_UGE:
1626   case CmpInst::ICMP_ULT:
1627   case CmpInst::ICMP_ULE:
1628     // However, we have to switch them to their signed variants to handle
1629     // negative indices from the base pointer.
1630     Pred = ICmpInst::getSignedPredicate(Pred);
1631     break;
1632   }
1633
1634   Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
1635   if (!LHSOffset)
1636     return 0;
1637   Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
1638   if (!RHSOffset)
1639     return 0;
1640
1641   // If LHS and RHS are not related via constant offsets to the same base
1642   // value, there is nothing we can do here.
1643   if (LHS != RHS)
1644     return 0;
1645
1646   return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1647 }
1648
1649 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1650 /// fold the result.  If not, this returns null.
1651 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1652                                const Query &Q, unsigned MaxRecurse) {
1653   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1654   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1655
1656   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1657     if (Constant *CRHS = dyn_cast<Constant>(RHS))
1658       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
1659
1660     // If we have a constant, make sure it is on the RHS.
1661     std::swap(LHS, RHS);
1662     Pred = CmpInst::getSwappedPredicate(Pred);
1663   }
1664
1665   Type *ITy = GetCompareTy(LHS); // The return type.
1666   Type *OpTy = LHS->getType();   // The operand type.
1667
1668   // icmp X, X -> true/false
1669   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
1670   // because X could be 0.
1671   if (LHS == RHS || isa<UndefValue>(RHS))
1672     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1673
1674   // Special case logic when the operands have i1 type.
1675   if (OpTy->getScalarType()->isIntegerTy(1)) {
1676     switch (Pred) {
1677     default: break;
1678     case ICmpInst::ICMP_EQ:
1679       // X == 1 -> X
1680       if (match(RHS, m_One()))
1681         return LHS;
1682       break;
1683     case ICmpInst::ICMP_NE:
1684       // X != 0 -> X
1685       if (match(RHS, m_Zero()))
1686         return LHS;
1687       break;
1688     case ICmpInst::ICMP_UGT:
1689       // X >u 0 -> X
1690       if (match(RHS, m_Zero()))
1691         return LHS;
1692       break;
1693     case ICmpInst::ICMP_UGE:
1694       // X >=u 1 -> X
1695       if (match(RHS, m_One()))
1696         return LHS;
1697       break;
1698     case ICmpInst::ICMP_SLT:
1699       // X <s 0 -> X
1700       if (match(RHS, m_Zero()))
1701         return LHS;
1702       break;
1703     case ICmpInst::ICMP_SLE:
1704       // X <=s -1 -> X
1705       if (match(RHS, m_One()))
1706         return LHS;
1707       break;
1708     }
1709   }
1710
1711   // icmp <object*>, <object*/null> - Different identified objects have
1712   // different addresses (unless null), and what's more the address of an
1713   // identified local is never equal to another argument (again, barring null).
1714   // Note that generalizing to the case where LHS is a global variable address
1715   // or null is pointless, since if both LHS and RHS are constants then we
1716   // already constant folded the compare, and if only one of them is then we
1717   // moved it to RHS already.
1718   Value *LHSPtr = LHS->stripPointerCasts();
1719   Value *RHSPtr = RHS->stripPointerCasts();
1720   if (LHSPtr == RHSPtr)
1721     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1722
1723   // Be more aggressive about stripping pointer adjustments when checking a
1724   // comparison of an alloca address to another object.  We can rip off all
1725   // inbounds GEP operations, even if they are variable.
1726   LHSPtr = LHSPtr->stripInBoundsOffsets();
1727   if (llvm::isIdentifiedObject(LHSPtr)) {
1728     RHSPtr = RHSPtr->stripInBoundsOffsets();
1729     if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1730       // If both sides are different identified objects, they aren't equal
1731       // unless they're null.
1732       if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
1733           Pred == CmpInst::ICMP_EQ)
1734         return ConstantInt::get(ITy, false);
1735
1736       // A local identified object (alloca or noalias call) can't equal any
1737       // incoming argument, unless they're both null.
1738       if (isa<Instruction>(LHSPtr) && isa<Argument>(RHSPtr) &&
1739           Pred == CmpInst::ICMP_EQ)
1740         return ConstantInt::get(ITy, false);
1741     }
1742
1743     // Assume that the constant null is on the right.
1744     if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
1745       if (Pred == CmpInst::ICMP_EQ)
1746         return ConstantInt::get(ITy, false);
1747       else if (Pred == CmpInst::ICMP_NE)
1748         return ConstantInt::get(ITy, true);
1749     }
1750   } else if (isa<Argument>(LHSPtr)) {
1751     RHSPtr = RHSPtr->stripInBoundsOffsets();
1752     // An alloca can't be equal to an argument.
1753     if (isa<AllocaInst>(RHSPtr)) {
1754       if (Pred == CmpInst::ICMP_EQ)
1755         return ConstantInt::get(ITy, false);
1756       else if (Pred == CmpInst::ICMP_NE)
1757         return ConstantInt::get(ITy, true);
1758     }
1759   }
1760
1761   // If we are comparing with zero then try hard since this is a common case.
1762   if (match(RHS, m_Zero())) {
1763     bool LHSKnownNonNegative, LHSKnownNegative;
1764     switch (Pred) {
1765     default: llvm_unreachable("Unknown ICmp predicate!");
1766     case ICmpInst::ICMP_ULT:
1767       return getFalse(ITy);
1768     case ICmpInst::ICMP_UGE:
1769       return getTrue(ITy);
1770     case ICmpInst::ICMP_EQ:
1771     case ICmpInst::ICMP_ULE:
1772       if (isKnownNonZero(LHS, Q.TD))
1773         return getFalse(ITy);
1774       break;
1775     case ICmpInst::ICMP_NE:
1776     case ICmpInst::ICMP_UGT:
1777       if (isKnownNonZero(LHS, Q.TD))
1778         return getTrue(ITy);
1779       break;
1780     case ICmpInst::ICMP_SLT:
1781       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1782       if (LHSKnownNegative)
1783         return getTrue(ITy);
1784       if (LHSKnownNonNegative)
1785         return getFalse(ITy);
1786       break;
1787     case ICmpInst::ICMP_SLE:
1788       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1789       if (LHSKnownNegative)
1790         return getTrue(ITy);
1791       if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
1792         return getFalse(ITy);
1793       break;
1794     case ICmpInst::ICMP_SGE:
1795       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1796       if (LHSKnownNegative)
1797         return getFalse(ITy);
1798       if (LHSKnownNonNegative)
1799         return getTrue(ITy);
1800       break;
1801     case ICmpInst::ICMP_SGT:
1802       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1803       if (LHSKnownNegative)
1804         return getFalse(ITy);
1805       if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
1806         return getTrue(ITy);
1807       break;
1808     }
1809   }
1810
1811   // See if we are doing a comparison with a constant integer.
1812   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1813     // Rule out tautological comparisons (eg., ult 0 or uge 0).
1814     ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1815     if (RHS_CR.isEmptySet())
1816       return ConstantInt::getFalse(CI->getContext());
1817     if (RHS_CR.isFullSet())
1818       return ConstantInt::getTrue(CI->getContext());
1819
1820     // Many binary operators with constant RHS have easy to compute constant
1821     // range.  Use them to check whether the comparison is a tautology.
1822     uint32_t Width = CI->getBitWidth();
1823     APInt Lower = APInt(Width, 0);
1824     APInt Upper = APInt(Width, 0);
1825     ConstantInt *CI2;
1826     if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1827       // 'urem x, CI2' produces [0, CI2).
1828       Upper = CI2->getValue();
1829     } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1830       // 'srem x, CI2' produces (-|CI2|, |CI2|).
1831       Upper = CI2->getValue().abs();
1832       Lower = (-Upper) + 1;
1833     } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1834       // 'udiv CI2, x' produces [0, CI2].
1835       Upper = CI2->getValue() + 1;
1836     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1837       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1838       APInt NegOne = APInt::getAllOnesValue(Width);
1839       if (!CI2->isZero())
1840         Upper = NegOne.udiv(CI2->getValue()) + 1;
1841     } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1842       // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1843       APInt IntMin = APInt::getSignedMinValue(Width);
1844       APInt IntMax = APInt::getSignedMaxValue(Width);
1845       APInt Val = CI2->getValue().abs();
1846       if (!Val.isMinValue()) {
1847         Lower = IntMin.sdiv(Val);
1848         Upper = IntMax.sdiv(Val) + 1;
1849       }
1850     } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1851       // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1852       APInt NegOne = APInt::getAllOnesValue(Width);
1853       if (CI2->getValue().ult(Width))
1854         Upper = NegOne.lshr(CI2->getValue()) + 1;
1855     } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1856       // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1857       APInt IntMin = APInt::getSignedMinValue(Width);
1858       APInt IntMax = APInt::getSignedMaxValue(Width);
1859       if (CI2->getValue().ult(Width)) {
1860         Lower = IntMin.ashr(CI2->getValue());
1861         Upper = IntMax.ashr(CI2->getValue()) + 1;
1862       }
1863     } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1864       // 'or x, CI2' produces [CI2, UINT_MAX].
1865       Lower = CI2->getValue();
1866     } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1867       // 'and x, CI2' produces [0, CI2].
1868       Upper = CI2->getValue() + 1;
1869     }
1870     if (Lower != Upper) {
1871       ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1872       if (RHS_CR.contains(LHS_CR))
1873         return ConstantInt::getTrue(RHS->getContext());
1874       if (RHS_CR.inverse().contains(LHS_CR))
1875         return ConstantInt::getFalse(RHS->getContext());
1876     }
1877   }
1878
1879   // Compare of cast, for example (zext X) != 0 -> X != 0
1880   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1881     Instruction *LI = cast<CastInst>(LHS);
1882     Value *SrcOp = LI->getOperand(0);
1883     Type *SrcTy = SrcOp->getType();
1884     Type *DstTy = LI->getType();
1885
1886     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1887     // if the integer type is the same size as the pointer type.
1888     if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) &&
1889         Q.TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1890       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1891         // Transfer the cast to the constant.
1892         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1893                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
1894                                         Q, MaxRecurse-1))
1895           return V;
1896       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1897         if (RI->getOperand(0)->getType() == SrcTy)
1898           // Compare without the cast.
1899           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1900                                           Q, MaxRecurse-1))
1901             return V;
1902       }
1903     }
1904
1905     if (isa<ZExtInst>(LHS)) {
1906       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1907       // same type.
1908       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1909         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1910           // Compare X and Y.  Note that signed predicates become unsigned.
1911           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1912                                           SrcOp, RI->getOperand(0), Q,
1913                                           MaxRecurse-1))
1914             return V;
1915       }
1916       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1917       // too.  If not, then try to deduce the result of the comparison.
1918       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1919         // Compute the constant that would happen if we truncated to SrcTy then
1920         // reextended to DstTy.
1921         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1922         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1923
1924         // If the re-extended constant didn't change then this is effectively
1925         // also a case of comparing two zero-extended values.
1926         if (RExt == CI && MaxRecurse)
1927           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1928                                         SrcOp, Trunc, Q, MaxRecurse-1))
1929             return V;
1930
1931         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1932         // there.  Use this to work out the result of the comparison.
1933         if (RExt != CI) {
1934           switch (Pred) {
1935           default: llvm_unreachable("Unknown ICmp predicate!");
1936           // LHS <u RHS.
1937           case ICmpInst::ICMP_EQ:
1938           case ICmpInst::ICMP_UGT:
1939           case ICmpInst::ICMP_UGE:
1940             return ConstantInt::getFalse(CI->getContext());
1941
1942           case ICmpInst::ICMP_NE:
1943           case ICmpInst::ICMP_ULT:
1944           case ICmpInst::ICMP_ULE:
1945             return ConstantInt::getTrue(CI->getContext());
1946
1947           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
1948           // is non-negative then LHS <s RHS.
1949           case ICmpInst::ICMP_SGT:
1950           case ICmpInst::ICMP_SGE:
1951             return CI->getValue().isNegative() ?
1952               ConstantInt::getTrue(CI->getContext()) :
1953               ConstantInt::getFalse(CI->getContext());
1954
1955           case ICmpInst::ICMP_SLT:
1956           case ICmpInst::ICMP_SLE:
1957             return CI->getValue().isNegative() ?
1958               ConstantInt::getFalse(CI->getContext()) :
1959               ConstantInt::getTrue(CI->getContext());
1960           }
1961         }
1962       }
1963     }
1964
1965     if (isa<SExtInst>(LHS)) {
1966       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1967       // same type.
1968       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1969         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1970           // Compare X and Y.  Note that the predicate does not change.
1971           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1972                                           Q, MaxRecurse-1))
1973             return V;
1974       }
1975       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1976       // too.  If not, then try to deduce the result of the comparison.
1977       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1978         // Compute the constant that would happen if we truncated to SrcTy then
1979         // reextended to DstTy.
1980         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1981         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1982
1983         // If the re-extended constant didn't change then this is effectively
1984         // also a case of comparing two sign-extended values.
1985         if (RExt == CI && MaxRecurse)
1986           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
1987             return V;
1988
1989         // Otherwise the upper bits of LHS are all equal, while RHS has varying
1990         // bits there.  Use this to work out the result of the comparison.
1991         if (RExt != CI) {
1992           switch (Pred) {
1993           default: llvm_unreachable("Unknown ICmp predicate!");
1994           case ICmpInst::ICMP_EQ:
1995             return ConstantInt::getFalse(CI->getContext());
1996           case ICmpInst::ICMP_NE:
1997             return ConstantInt::getTrue(CI->getContext());
1998
1999           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
2000           // LHS >s RHS.
2001           case ICmpInst::ICMP_SGT:
2002           case ICmpInst::ICMP_SGE:
2003             return CI->getValue().isNegative() ?
2004               ConstantInt::getTrue(CI->getContext()) :
2005               ConstantInt::getFalse(CI->getContext());
2006           case ICmpInst::ICMP_SLT:
2007           case ICmpInst::ICMP_SLE:
2008             return CI->getValue().isNegative() ?
2009               ConstantInt::getFalse(CI->getContext()) :
2010               ConstantInt::getTrue(CI->getContext());
2011
2012           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
2013           // LHS >u RHS.
2014           case ICmpInst::ICMP_UGT:
2015           case ICmpInst::ICMP_UGE:
2016             // Comparison is true iff the LHS <s 0.
2017             if (MaxRecurse)
2018               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2019                                               Constant::getNullValue(SrcTy),
2020                                               Q, MaxRecurse-1))
2021                 return V;
2022             break;
2023           case ICmpInst::ICMP_ULT:
2024           case ICmpInst::ICMP_ULE:
2025             // Comparison is true iff the LHS >=s 0.
2026             if (MaxRecurse)
2027               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2028                                               Constant::getNullValue(SrcTy),
2029                                               Q, MaxRecurse-1))
2030                 return V;
2031             break;
2032           }
2033         }
2034       }
2035     }
2036   }
2037
2038   // Special logic for binary operators.
2039   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2040   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2041   if (MaxRecurse && (LBO || RBO)) {
2042     // Analyze the case when either LHS or RHS is an add instruction.
2043     Value *A = 0, *B = 0, *C = 0, *D = 0;
2044     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2045     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2046     if (LBO && LBO->getOpcode() == Instruction::Add) {
2047       A = LBO->getOperand(0); B = LBO->getOperand(1);
2048       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2049         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2050         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2051     }
2052     if (RBO && RBO->getOpcode() == Instruction::Add) {
2053       C = RBO->getOperand(0); D = RBO->getOperand(1);
2054       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2055         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2056         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2057     }
2058
2059     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2060     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2061       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2062                                       Constant::getNullValue(RHS->getType()),
2063                                       Q, MaxRecurse-1))
2064         return V;
2065
2066     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2067     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2068       if (Value *V = SimplifyICmpInst(Pred,
2069                                       Constant::getNullValue(LHS->getType()),
2070                                       C == LHS ? D : C, Q, MaxRecurse-1))
2071         return V;
2072
2073     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2074     if (A && C && (A == C || A == D || B == C || B == D) &&
2075         NoLHSWrapProblem && NoRHSWrapProblem) {
2076       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2077       Value *Y = (A == C || A == D) ? B : A;
2078       Value *Z = (C == A || C == B) ? D : C;
2079       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2080         return V;
2081     }
2082   }
2083
2084   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2085     bool KnownNonNegative, KnownNegative;
2086     switch (Pred) {
2087     default:
2088       break;
2089     case ICmpInst::ICMP_SGT:
2090     case ICmpInst::ICMP_SGE:
2091       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
2092       if (!KnownNonNegative)
2093         break;
2094       // fall-through
2095     case ICmpInst::ICMP_EQ:
2096     case ICmpInst::ICMP_UGT:
2097     case ICmpInst::ICMP_UGE:
2098       return getFalse(ITy);
2099     case ICmpInst::ICMP_SLT:
2100     case ICmpInst::ICMP_SLE:
2101       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
2102       if (!KnownNonNegative)
2103         break;
2104       // fall-through
2105     case ICmpInst::ICMP_NE:
2106     case ICmpInst::ICMP_ULT:
2107     case ICmpInst::ICMP_ULE:
2108       return getTrue(ITy);
2109     }
2110   }
2111   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2112     bool KnownNonNegative, KnownNegative;
2113     switch (Pred) {
2114     default:
2115       break;
2116     case ICmpInst::ICMP_SGT:
2117     case ICmpInst::ICMP_SGE:
2118       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
2119       if (!KnownNonNegative)
2120         break;
2121       // fall-through
2122     case ICmpInst::ICMP_NE:
2123     case ICmpInst::ICMP_UGT:
2124     case ICmpInst::ICMP_UGE:
2125       return getTrue(ITy);
2126     case ICmpInst::ICMP_SLT:
2127     case ICmpInst::ICMP_SLE:
2128       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
2129       if (!KnownNonNegative)
2130         break;
2131       // fall-through
2132     case ICmpInst::ICMP_EQ:
2133     case ICmpInst::ICMP_ULT:
2134     case ICmpInst::ICMP_ULE:
2135       return getFalse(ITy);
2136     }
2137   }
2138
2139   // x udiv y <=u x.
2140   if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2141     // icmp pred (X /u Y), X
2142     if (Pred == ICmpInst::ICMP_UGT)
2143       return getFalse(ITy);
2144     if (Pred == ICmpInst::ICMP_ULE)
2145       return getTrue(ITy);
2146   }
2147
2148   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2149       LBO->getOperand(1) == RBO->getOperand(1)) {
2150     switch (LBO->getOpcode()) {
2151     default: break;
2152     case Instruction::UDiv:
2153     case Instruction::LShr:
2154       if (ICmpInst::isSigned(Pred))
2155         break;
2156       // fall-through
2157     case Instruction::SDiv:
2158     case Instruction::AShr:
2159       if (!LBO->isExact() || !RBO->isExact())
2160         break;
2161       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2162                                       RBO->getOperand(0), Q, MaxRecurse-1))
2163         return V;
2164       break;
2165     case Instruction::Shl: {
2166       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2167       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2168       if (!NUW && !NSW)
2169         break;
2170       if (!NSW && ICmpInst::isSigned(Pred))
2171         break;
2172       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2173                                       RBO->getOperand(0), Q, MaxRecurse-1))
2174         return V;
2175       break;
2176     }
2177     }
2178   }
2179
2180   // Simplify comparisons involving max/min.
2181   Value *A, *B;
2182   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2183   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2184
2185   // Signed variants on "max(a,b)>=a -> true".
2186   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2187     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2188     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2189     // We analyze this as smax(A, B) pred A.
2190     P = Pred;
2191   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2192              (A == LHS || B == LHS)) {
2193     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2194     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2195     // We analyze this as smax(A, B) swapped-pred A.
2196     P = CmpInst::getSwappedPredicate(Pred);
2197   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2198              (A == RHS || B == RHS)) {
2199     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2200     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2201     // We analyze this as smax(-A, -B) swapped-pred -A.
2202     // Note that we do not need to actually form -A or -B thanks to EqP.
2203     P = CmpInst::getSwappedPredicate(Pred);
2204   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2205              (A == LHS || B == LHS)) {
2206     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2207     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2208     // We analyze this as smax(-A, -B) pred -A.
2209     // Note that we do not need to actually form -A or -B thanks to EqP.
2210     P = Pred;
2211   }
2212   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2213     // Cases correspond to "max(A, B) p A".
2214     switch (P) {
2215     default:
2216       break;
2217     case CmpInst::ICMP_EQ:
2218     case CmpInst::ICMP_SLE:
2219       // Equivalent to "A EqP B".  This may be the same as the condition tested
2220       // in the max/min; if so, we can just return that.
2221       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2222         return V;
2223       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2224         return V;
2225       // Otherwise, see if "A EqP B" simplifies.
2226       if (MaxRecurse)
2227         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2228           return V;
2229       break;
2230     case CmpInst::ICMP_NE:
2231     case CmpInst::ICMP_SGT: {
2232       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2233       // Equivalent to "A InvEqP B".  This may be the same as the condition
2234       // tested in the max/min; if so, we can just return that.
2235       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2236         return V;
2237       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2238         return V;
2239       // Otherwise, see if "A InvEqP B" simplifies.
2240       if (MaxRecurse)
2241         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2242           return V;
2243       break;
2244     }
2245     case CmpInst::ICMP_SGE:
2246       // Always true.
2247       return getTrue(ITy);
2248     case CmpInst::ICMP_SLT:
2249       // Always false.
2250       return getFalse(ITy);
2251     }
2252   }
2253
2254   // Unsigned variants on "max(a,b)>=a -> true".
2255   P = CmpInst::BAD_ICMP_PREDICATE;
2256   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2257     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2258     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2259     // We analyze this as umax(A, B) pred A.
2260     P = Pred;
2261   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2262              (A == LHS || B == LHS)) {
2263     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2264     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2265     // We analyze this as umax(A, B) swapped-pred A.
2266     P = CmpInst::getSwappedPredicate(Pred);
2267   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2268              (A == RHS || B == RHS)) {
2269     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2270     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2271     // We analyze this as umax(-A, -B) swapped-pred -A.
2272     // Note that we do not need to actually form -A or -B thanks to EqP.
2273     P = CmpInst::getSwappedPredicate(Pred);
2274   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2275              (A == LHS || B == LHS)) {
2276     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2277     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2278     // We analyze this as umax(-A, -B) pred -A.
2279     // Note that we do not need to actually form -A or -B thanks to EqP.
2280     P = Pred;
2281   }
2282   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2283     // Cases correspond to "max(A, B) p A".
2284     switch (P) {
2285     default:
2286       break;
2287     case CmpInst::ICMP_EQ:
2288     case CmpInst::ICMP_ULE:
2289       // Equivalent to "A EqP B".  This may be the same as the condition tested
2290       // in the max/min; if so, we can just return that.
2291       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2292         return V;
2293       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2294         return V;
2295       // Otherwise, see if "A EqP B" simplifies.
2296       if (MaxRecurse)
2297         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2298           return V;
2299       break;
2300     case CmpInst::ICMP_NE:
2301     case CmpInst::ICMP_UGT: {
2302       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2303       // Equivalent to "A InvEqP B".  This may be the same as the condition
2304       // tested in the max/min; if so, we can just return that.
2305       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2306         return V;
2307       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2308         return V;
2309       // Otherwise, see if "A InvEqP B" simplifies.
2310       if (MaxRecurse)
2311         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2312           return V;
2313       break;
2314     }
2315     case CmpInst::ICMP_UGE:
2316       // Always true.
2317       return getTrue(ITy);
2318     case CmpInst::ICMP_ULT:
2319       // Always false.
2320       return getFalse(ITy);
2321     }
2322   }
2323
2324   // Variants on "max(x,y) >= min(x,z)".
2325   Value *C, *D;
2326   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2327       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2328       (A == C || A == D || B == C || B == D)) {
2329     // max(x, ?) pred min(x, ?).
2330     if (Pred == CmpInst::ICMP_SGE)
2331       // Always true.
2332       return getTrue(ITy);
2333     if (Pred == CmpInst::ICMP_SLT)
2334       // Always false.
2335       return getFalse(ITy);
2336   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2337              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2338              (A == C || A == D || B == C || B == D)) {
2339     // min(x, ?) pred max(x, ?).
2340     if (Pred == CmpInst::ICMP_SLE)
2341       // Always true.
2342       return getTrue(ITy);
2343     if (Pred == CmpInst::ICMP_SGT)
2344       // Always false.
2345       return getFalse(ITy);
2346   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2347              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2348              (A == C || A == D || B == C || B == D)) {
2349     // max(x, ?) pred min(x, ?).
2350     if (Pred == CmpInst::ICMP_UGE)
2351       // Always true.
2352       return getTrue(ITy);
2353     if (Pred == CmpInst::ICMP_ULT)
2354       // Always false.
2355       return getFalse(ITy);
2356   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2357              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2358              (A == C || A == D || B == C || B == D)) {
2359     // min(x, ?) pred max(x, ?).
2360     if (Pred == CmpInst::ICMP_ULE)
2361       // Always true.
2362       return getTrue(ITy);
2363     if (Pred == CmpInst::ICMP_UGT)
2364       // Always false.
2365       return getFalse(ITy);
2366   }
2367
2368   // Simplify comparisons of related pointers using a powerful, recursive
2369   // GEP-walk when we have target data available..
2370   if (Q.TD && LHS->getType()->isPointerTy() && RHS->getType()->isPointerTy())
2371     if (Constant *C = computePointerICmp(*Q.TD, Pred, LHS, RHS))
2372       return C;
2373
2374   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2375     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2376       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2377           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2378           (ICmpInst::isEquality(Pred) ||
2379            (GLHS->isInBounds() && GRHS->isInBounds() &&
2380             Pred == ICmpInst::getSignedPredicate(Pred)))) {
2381         // The bases are equal and the indices are constant.  Build a constant
2382         // expression GEP with the same indices and a null base pointer to see
2383         // what constant folding can make out of it.
2384         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2385         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2386         Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2387
2388         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2389         Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2390         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2391       }
2392     }
2393   }
2394
2395   // If the comparison is with the result of a select instruction, check whether
2396   // comparing with either branch of the select always yields the same value.
2397   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2398     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2399       return V;
2400
2401   // If the comparison is with the result of a phi instruction, check whether
2402   // doing the compare with each incoming phi value yields a common result.
2403   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2404     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2405       return V;
2406
2407   return 0;
2408 }
2409
2410 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2411                               const TargetData *TD,
2412                               const TargetLibraryInfo *TLI,
2413                               const DominatorTree *DT) {
2414   return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2415                             RecursionLimit);
2416 }
2417
2418 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2419 /// fold the result.  If not, this returns null.
2420 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2421                                const Query &Q, unsigned MaxRecurse) {
2422   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2423   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2424
2425   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2426     if (Constant *CRHS = dyn_cast<Constant>(RHS))
2427       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
2428
2429     // If we have a constant, make sure it is on the RHS.
2430     std::swap(LHS, RHS);
2431     Pred = CmpInst::getSwappedPredicate(Pred);
2432   }
2433
2434   // Fold trivial predicates.
2435   if (Pred == FCmpInst::FCMP_FALSE)
2436     return ConstantInt::get(GetCompareTy(LHS), 0);
2437   if (Pred == FCmpInst::FCMP_TRUE)
2438     return ConstantInt::get(GetCompareTy(LHS), 1);
2439
2440   if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
2441     return UndefValue::get(GetCompareTy(LHS));
2442
2443   // fcmp x,x -> true/false.  Not all compares are foldable.
2444   if (LHS == RHS) {
2445     if (CmpInst::isTrueWhenEqual(Pred))
2446       return ConstantInt::get(GetCompareTy(LHS), 1);
2447     if (CmpInst::isFalseWhenEqual(Pred))
2448       return ConstantInt::get(GetCompareTy(LHS), 0);
2449   }
2450
2451   // Handle fcmp with constant RHS
2452   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2453     // If the constant is a nan, see if we can fold the comparison based on it.
2454     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2455       if (CFP->getValueAPF().isNaN()) {
2456         if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
2457           return ConstantInt::getFalse(CFP->getContext());
2458         assert(FCmpInst::isUnordered(Pred) &&
2459                "Comparison must be either ordered or unordered!");
2460         // True if unordered.
2461         return ConstantInt::getTrue(CFP->getContext());
2462       }
2463       // Check whether the constant is an infinity.
2464       if (CFP->getValueAPF().isInfinity()) {
2465         if (CFP->getValueAPF().isNegative()) {
2466           switch (Pred) {
2467           case FCmpInst::FCMP_OLT:
2468             // No value is ordered and less than negative infinity.
2469             return ConstantInt::getFalse(CFP->getContext());
2470           case FCmpInst::FCMP_UGE:
2471             // All values are unordered with or at least negative infinity.
2472             return ConstantInt::getTrue(CFP->getContext());
2473           default:
2474             break;
2475           }
2476         } else {
2477           switch (Pred) {
2478           case FCmpInst::FCMP_OGT:
2479             // No value is ordered and greater than infinity.
2480             return ConstantInt::getFalse(CFP->getContext());
2481           case FCmpInst::FCMP_ULE:
2482             // All values are unordered with and at most infinity.
2483             return ConstantInt::getTrue(CFP->getContext());
2484           default:
2485             break;
2486           }
2487         }
2488       }
2489     }
2490   }
2491
2492   // If the comparison is with the result of a select instruction, check whether
2493   // comparing with either branch of the select always yields the same value.
2494   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2495     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2496       return V;
2497
2498   // If the comparison is with the result of a phi instruction, check whether
2499   // doing the compare with each incoming phi value yields a common result.
2500   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2501     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2502       return V;
2503
2504   return 0;
2505 }
2506
2507 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2508                               const TargetData *TD,
2509                               const TargetLibraryInfo *TLI,
2510                               const DominatorTree *DT) {
2511   return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2512                             RecursionLimit);
2513 }
2514
2515 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2516 /// the result.  If not, this returns null.
2517 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2518                                  Value *FalseVal, const Query &Q,
2519                                  unsigned MaxRecurse) {
2520   // select true, X, Y  -> X
2521   // select false, X, Y -> Y
2522   if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2523     return CB->getZExtValue() ? TrueVal : FalseVal;
2524
2525   // select C, X, X -> X
2526   if (TrueVal == FalseVal)
2527     return TrueVal;
2528
2529   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
2530     if (isa<Constant>(TrueVal))
2531       return TrueVal;
2532     return FalseVal;
2533   }
2534   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
2535     return FalseVal;
2536   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
2537     return TrueVal;
2538
2539   return 0;
2540 }
2541
2542 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
2543                                 const TargetData *TD,
2544                                 const TargetLibraryInfo *TLI,
2545                                 const DominatorTree *DT) {
2546   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT),
2547                               RecursionLimit);
2548 }
2549
2550 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2551 /// fold the result.  If not, this returns null.
2552 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
2553   // The type of the GEP pointer operand.
2554   PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2555   // The GEP pointer operand is not a pointer, it's a vector of pointers.
2556   if (!PtrTy)
2557     return 0;
2558
2559   // getelementptr P -> P.
2560   if (Ops.size() == 1)
2561     return Ops[0];
2562
2563   if (isa<UndefValue>(Ops[0])) {
2564     // Compute the (pointer) type returned by the GEP instruction.
2565     Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2566     Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2567     return UndefValue::get(GEPTy);
2568   }
2569
2570   if (Ops.size() == 2) {
2571     // getelementptr P, 0 -> P.
2572     if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2573       if (C->isZero())
2574         return Ops[0];
2575     // getelementptr P, N -> P if P points to a type of zero size.
2576     if (Q.TD) {
2577       Type *Ty = PtrTy->getElementType();
2578       if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) == 0)
2579         return Ops[0];
2580     }
2581   }
2582
2583   // Check to see if this is constant foldable.
2584   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2585     if (!isa<Constant>(Ops[i]))
2586       return 0;
2587
2588   return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2589 }
2590
2591 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
2592                              const TargetLibraryInfo *TLI,
2593                              const DominatorTree *DT) {
2594   return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit);
2595 }
2596
2597 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2598 /// can fold the result.  If not, this returns null.
2599 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2600                                       ArrayRef<unsigned> Idxs, const Query &Q,
2601                                       unsigned) {
2602   if (Constant *CAgg = dyn_cast<Constant>(Agg))
2603     if (Constant *CVal = dyn_cast<Constant>(Val))
2604       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2605
2606   // insertvalue x, undef, n -> x
2607   if (match(Val, m_Undef()))
2608     return Agg;
2609
2610   // insertvalue x, (extractvalue y, n), n
2611   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2612     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2613         EV->getIndices() == Idxs) {
2614       // insertvalue undef, (extractvalue y, n), n -> y
2615       if (match(Agg, m_Undef()))
2616         return EV->getAggregateOperand();
2617
2618       // insertvalue y, (extractvalue y, n), n -> y
2619       if (Agg == EV->getAggregateOperand())
2620         return Agg;
2621     }
2622
2623   return 0;
2624 }
2625
2626 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2627                                      ArrayRef<unsigned> Idxs,
2628                                      const TargetData *TD,
2629                                      const TargetLibraryInfo *TLI,
2630                                      const DominatorTree *DT) {
2631   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT),
2632                                    RecursionLimit);
2633 }
2634
2635 /// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
2636 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
2637   // If all of the PHI's incoming values are the same then replace the PHI node
2638   // with the common value.
2639   Value *CommonValue = 0;
2640   bool HasUndefInput = false;
2641   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2642     Value *Incoming = PN->getIncomingValue(i);
2643     // If the incoming value is the phi node itself, it can safely be skipped.
2644     if (Incoming == PN) continue;
2645     if (isa<UndefValue>(Incoming)) {
2646       // Remember that we saw an undef value, but otherwise ignore them.
2647       HasUndefInput = true;
2648       continue;
2649     }
2650     if (CommonValue && Incoming != CommonValue)
2651       return 0;  // Not the same, bail out.
2652     CommonValue = Incoming;
2653   }
2654
2655   // If CommonValue is null then all of the incoming values were either undef or
2656   // equal to the phi node itself.
2657   if (!CommonValue)
2658     return UndefValue::get(PN->getType());
2659
2660   // If we have a PHI node like phi(X, undef, X), where X is defined by some
2661   // instruction, we cannot return X as the result of the PHI node unless it
2662   // dominates the PHI block.
2663   if (HasUndefInput)
2664     return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
2665
2666   return CommonValue;
2667 }
2668
2669 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2670   if (Constant *C = dyn_cast<Constant>(Op))
2671     return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI);
2672
2673   return 0;
2674 }
2675
2676 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const TargetData *TD,
2677                                const TargetLibraryInfo *TLI,
2678                                const DominatorTree *DT) {
2679   return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit);
2680 }
2681
2682 //=== Helper functions for higher up the class hierarchy.
2683
2684 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2685 /// fold the result.  If not, this returns null.
2686 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2687                             const Query &Q, unsigned MaxRecurse) {
2688   switch (Opcode) {
2689   case Instruction::Add:
2690     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2691                            Q, MaxRecurse);
2692   case Instruction::Sub:
2693     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2694                            Q, MaxRecurse);
2695   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
2696   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2697   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2698   case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2699   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2700   case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2701   case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
2702   case Instruction::Shl:
2703     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2704                            Q, MaxRecurse);
2705   case Instruction::LShr:
2706     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2707   case Instruction::AShr:
2708     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2709   case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2710   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2711   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
2712   default:
2713     if (Constant *CLHS = dyn_cast<Constant>(LHS))
2714       if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2715         Constant *COps[] = {CLHS, CRHS};
2716         return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD,
2717                                         Q.TLI);
2718       }
2719
2720     // If the operation is associative, try some generic simplifications.
2721     if (Instruction::isAssociative(Opcode))
2722       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
2723         return V;
2724
2725     // If the operation is with the result of a select instruction check whether
2726     // operating on either branch of the select always yields the same value.
2727     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2728       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
2729         return V;
2730
2731     // If the operation is with the result of a phi instruction, check whether
2732     // operating on all incoming values of the phi always yields the same value.
2733     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2734       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
2735         return V;
2736
2737     return 0;
2738   }
2739 }
2740
2741 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2742                            const TargetData *TD, const TargetLibraryInfo *TLI,
2743                            const DominatorTree *DT) {
2744   return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionLimit);
2745 }
2746
2747 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2748 /// fold the result.
2749 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2750                               const Query &Q, unsigned MaxRecurse) {
2751   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2752     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2753   return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2754 }
2755
2756 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2757                              const TargetData *TD, const TargetLibraryInfo *TLI,
2758                              const DominatorTree *DT) {
2759   return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2760                            RecursionLimit);
2761 }
2762
2763 static Value *SimplifyCallInst(CallInst *CI, const Query &) {
2764   // call undef -> undef
2765   if (isa<UndefValue>(CI->getCalledValue()))
2766     return UndefValue::get(CI->getType());
2767
2768   return 0;
2769 }
2770
2771 /// SimplifyInstruction - See if we can compute a simplified version of this
2772 /// instruction.  If not, this returns null.
2773 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2774                                  const TargetLibraryInfo *TLI,
2775                                  const DominatorTree *DT) {
2776   Value *Result;
2777
2778   switch (I->getOpcode()) {
2779   default:
2780     Result = ConstantFoldInstruction(I, TD, TLI);
2781     break;
2782   case Instruction::Add:
2783     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2784                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
2785                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2786                              TD, TLI, DT);
2787     break;
2788   case Instruction::Sub:
2789     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2790                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
2791                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2792                              TD, TLI, DT);
2793     break;
2794   case Instruction::Mul:
2795     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2796     break;
2797   case Instruction::SDiv:
2798     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2799     break;
2800   case Instruction::UDiv:
2801     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2802     break;
2803   case Instruction::FDiv:
2804     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2805     break;
2806   case Instruction::SRem:
2807     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2808     break;
2809   case Instruction::URem:
2810     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2811     break;
2812   case Instruction::FRem:
2813     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2814     break;
2815   case Instruction::Shl:
2816     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2817                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
2818                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2819                              TD, TLI, DT);
2820     break;
2821   case Instruction::LShr:
2822     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2823                               cast<BinaryOperator>(I)->isExact(),
2824                               TD, TLI, DT);
2825     break;
2826   case Instruction::AShr:
2827     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2828                               cast<BinaryOperator>(I)->isExact(),
2829                               TD, TLI, DT);
2830     break;
2831   case Instruction::And:
2832     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2833     break;
2834   case Instruction::Or:
2835     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2836     break;
2837   case Instruction::Xor:
2838     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2839     break;
2840   case Instruction::ICmp:
2841     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2842                               I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2843     break;
2844   case Instruction::FCmp:
2845     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2846                               I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2847     break;
2848   case Instruction::Select:
2849     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2850                                 I->getOperand(2), TD, TLI, DT);
2851     break;
2852   case Instruction::GetElementPtr: {
2853     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2854     Result = SimplifyGEPInst(Ops, TD, TLI, DT);
2855     break;
2856   }
2857   case Instruction::InsertValue: {
2858     InsertValueInst *IV = cast<InsertValueInst>(I);
2859     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2860                                      IV->getInsertedValueOperand(),
2861                                      IV->getIndices(), TD, TLI, DT);
2862     break;
2863   }
2864   case Instruction::PHI:
2865     Result = SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT));
2866     break;
2867   case Instruction::Call:
2868     Result = SimplifyCallInst(cast<CallInst>(I), Query (TD, TLI, DT));
2869     break;
2870   case Instruction::Trunc:
2871     Result = SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, DT);
2872     break;
2873   }
2874
2875   /// If called on unreachable code, the above logic may report that the
2876   /// instruction simplified to itself.  Make life easier for users by
2877   /// detecting that case here, returning a safe value instead.
2878   return Result == I ? UndefValue::get(I->getType()) : Result;
2879 }
2880
2881 /// \brief Implementation of recursive simplification through an instructions
2882 /// uses.
2883 ///
2884 /// This is the common implementation of the recursive simplification routines.
2885 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
2886 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
2887 /// instructions to process and attempt to simplify it using
2888 /// InstructionSimplify.
2889 ///
2890 /// This routine returns 'true' only when *it* simplifies something. The passed
2891 /// in simplified value does not count toward this.
2892 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
2893                                               const TargetData *TD,
2894                                               const TargetLibraryInfo *TLI,
2895                                               const DominatorTree *DT) {
2896   bool Simplified = false;
2897   SmallSetVector<Instruction *, 8> Worklist;
2898
2899   // If we have an explicit value to collapse to, do that round of the
2900   // simplification loop by hand initially.
2901   if (SimpleV) {
2902     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
2903          ++UI)
2904       if (*UI != I)
2905         Worklist.insert(cast<Instruction>(*UI));
2906
2907     // Replace the instruction with its simplified value.
2908     I->replaceAllUsesWith(SimpleV);
2909
2910     // Gracefully handle edge cases where the instruction is not wired into any
2911     // parent block.
2912     if (I->getParent())
2913       I->eraseFromParent();
2914   } else {
2915     Worklist.insert(I);
2916   }
2917
2918   // Note that we must test the size on each iteration, the worklist can grow.
2919   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
2920     I = Worklist[Idx];
2921
2922     // See if this instruction simplifies.
2923     SimpleV = SimplifyInstruction(I, TD, TLI, DT);
2924     if (!SimpleV)
2925       continue;
2926
2927     Simplified = true;
2928
2929     // Stash away all the uses of the old instruction so we can check them for
2930     // recursive simplifications after a RAUW. This is cheaper than checking all
2931     // uses of To on the recursive step in most cases.
2932     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
2933          ++UI)
2934       Worklist.insert(cast<Instruction>(*UI));
2935
2936     // Replace the instruction with its simplified value.
2937     I->replaceAllUsesWith(SimpleV);
2938
2939     // Gracefully handle edge cases where the instruction is not wired into any
2940     // parent block.
2941     if (I->getParent())
2942       I->eraseFromParent();
2943   }
2944   return Simplified;
2945 }
2946
2947 bool llvm::recursivelySimplifyInstruction(Instruction *I,
2948                                           const TargetData *TD,
2949                                           const TargetLibraryInfo *TLI,
2950                                           const DominatorTree *DT) {
2951   return replaceAndRecursivelySimplifyImpl(I, 0, TD, TLI, DT);
2952 }
2953
2954 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
2955                                          const TargetData *TD,
2956                                          const TargetLibraryInfo *TLI,
2957                                          const DominatorTree *DT) {
2958   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
2959   assert(SimpleV && "Must provide a simplified value.");
2960   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TD, TLI, DT);
2961 }