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