OSDN Git Service

[InstSimplify] shl nuw C, %x -> C iff signbit is set on C.
[android-x86/external-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/AliasAnalysis.h"
24 #include "llvm/Analysis/AssumptionCache.h"
25 #include "llvm/Analysis/CaptureTracking.h"
26 #include "llvm/Analysis/CmpInstAnalysis.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/Analysis/LoopAnalysisManager.h"
29 #include "llvm/Analysis/MemoryBuiltins.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Analysis/VectorUtils.h"
32 #include "llvm/IR/ConstantRange.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/GetElementPtrTypeIterator.h"
36 #include "llvm/IR/GlobalAlias.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/IR/PatternMatch.h"
39 #include "llvm/IR/ValueHandle.h"
40 #include "llvm/Support/KnownBits.h"
41 #include <algorithm>
42 using namespace llvm;
43 using namespace llvm::PatternMatch;
44
45 #define DEBUG_TYPE "instsimplify"
46
47 enum { RecursionLimit = 3 };
48
49 STATISTIC(NumExpand,  "Number of expansions");
50 STATISTIC(NumReassoc, "Number of reassociations");
51
52 static Value *SimplifyAndInst(Value *, Value *, const SimplifyQuery &, unsigned);
53 static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
54                             unsigned);
55 static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
56                               const SimplifyQuery &, unsigned);
57 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
58                               unsigned);
59 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
60                                const SimplifyQuery &Q, unsigned MaxRecurse);
61 static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
62 static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned);
63 static Value *SimplifyCastInst(unsigned, Value *, Type *,
64                                const SimplifyQuery &, unsigned);
65 static Value *SimplifyGEPInst(Type *, ArrayRef<Value *>, const SimplifyQuery &,
66                               unsigned);
67
68 /// For a boolean type or a vector of boolean type, return false or a vector
69 /// with every element false.
70 static Constant *getFalse(Type *Ty) {
71   return ConstantInt::getFalse(Ty);
72 }
73
74 /// For a boolean type or a vector of boolean type, return true or a vector
75 /// with every element true.
76 static Constant *getTrue(Type *Ty) {
77   return ConstantInt::getTrue(Ty);
78 }
79
80 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
81 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
82                           Value *RHS) {
83   CmpInst *Cmp = dyn_cast<CmpInst>(V);
84   if (!Cmp)
85     return false;
86   CmpInst::Predicate CPred = Cmp->getPredicate();
87   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
88   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
89     return true;
90   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
91     CRHS == LHS;
92 }
93
94 /// Does the given value dominate the specified phi node?
95 static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
96   Instruction *I = dyn_cast<Instruction>(V);
97   if (!I)
98     // Arguments and constants dominate all instructions.
99     return true;
100
101   // If we are processing instructions (and/or basic blocks) that have not been
102   // fully added to a function, the parent nodes may still be null. Simply
103   // return the conservative answer in these cases.
104   if (!I->getParent() || !P->getParent() || !I->getFunction())
105     return false;
106
107   // If we have a DominatorTree then do a precise test.
108   if (DT)
109     return DT->dominates(I, P);
110
111   // Otherwise, if the instruction is in the entry block and is not an invoke,
112   // then it obviously dominates all phi nodes.
113   if (I->getParent() == &I->getFunction()->getEntryBlock() &&
114       !isa<InvokeInst>(I))
115     return true;
116
117   return false;
118 }
119
120 /// Simplify "A op (B op' C)" by distributing op over op', turning it into
121 /// "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
122 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
123 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
124 /// Returns the simplified value, or null if no simplification was performed.
125 static Value *ExpandBinOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
126                           Instruction::BinaryOps OpcodeToExpand,
127                           const SimplifyQuery &Q, unsigned MaxRecurse) {
128   // Recursion is always used, so bail out at once if we already hit the limit.
129   if (!MaxRecurse--)
130     return nullptr;
131
132   // Check whether the expression has the form "(A op' B) op C".
133   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
134     if (Op0->getOpcode() == OpcodeToExpand) {
135       // It does!  Try turning it into "(A op C) op' (B op C)".
136       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
137       // Do "A op C" and "B op C" both simplify?
138       if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
139         if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
140           // They do! Return "L op' R" if it simplifies or is already available.
141           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
142           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
143                                      && L == B && R == A)) {
144             ++NumExpand;
145             return LHS;
146           }
147           // Otherwise return "L op' R" if it simplifies.
148           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
149             ++NumExpand;
150             return V;
151           }
152         }
153     }
154
155   // Check whether the expression has the form "A op (B op' C)".
156   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
157     if (Op1->getOpcode() == OpcodeToExpand) {
158       // It does!  Try turning it into "(A op B) op' (A op C)".
159       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
160       // Do "A op B" and "A op C" both simplify?
161       if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
162         if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
163           // They do! Return "L op' R" if it simplifies or is already available.
164           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
165           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
166                                      && L == C && R == B)) {
167             ++NumExpand;
168             return RHS;
169           }
170           // Otherwise return "L op' R" if it simplifies.
171           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
172             ++NumExpand;
173             return V;
174           }
175         }
176     }
177
178   return nullptr;
179 }
180
181 /// Generic simplifications for associative binary operations.
182 /// Returns the simpler value, or null if none was found.
183 static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
184                                        Value *LHS, Value *RHS,
185                                        const SimplifyQuery &Q,
186                                        unsigned MaxRecurse) {
187   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
188
189   // Recursion is always used, so bail out at once if we already hit the limit.
190   if (!MaxRecurse--)
191     return nullptr;
192
193   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
194   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
195
196   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
197   if (Op0 && Op0->getOpcode() == Opcode) {
198     Value *A = Op0->getOperand(0);
199     Value *B = Op0->getOperand(1);
200     Value *C = RHS;
201
202     // Does "B op C" simplify?
203     if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
204       // It does!  Return "A op V" if it simplifies or is already available.
205       // If V equals B then "A op V" is just the LHS.
206       if (V == B) return LHS;
207       // Otherwise return "A op V" if it simplifies.
208       if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
209         ++NumReassoc;
210         return W;
211       }
212     }
213   }
214
215   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
216   if (Op1 && Op1->getOpcode() == Opcode) {
217     Value *A = LHS;
218     Value *B = Op1->getOperand(0);
219     Value *C = Op1->getOperand(1);
220
221     // Does "A op B" simplify?
222     if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
223       // It does!  Return "V op C" if it simplifies or is already available.
224       // If V equals B then "V op C" is just the RHS.
225       if (V == B) return RHS;
226       // Otherwise return "V op C" if it simplifies.
227       if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
228         ++NumReassoc;
229         return W;
230       }
231     }
232   }
233
234   // The remaining transforms require commutativity as well as associativity.
235   if (!Instruction::isCommutative(Opcode))
236     return nullptr;
237
238   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
239   if (Op0 && Op0->getOpcode() == Opcode) {
240     Value *A = Op0->getOperand(0);
241     Value *B = Op0->getOperand(1);
242     Value *C = RHS;
243
244     // Does "C op A" simplify?
245     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
246       // It does!  Return "V op B" if it simplifies or is already available.
247       // If V equals A then "V op B" is just the LHS.
248       if (V == A) return LHS;
249       // Otherwise return "V op B" if it simplifies.
250       if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
251         ++NumReassoc;
252         return W;
253       }
254     }
255   }
256
257   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
258   if (Op1 && Op1->getOpcode() == Opcode) {
259     Value *A = LHS;
260     Value *B = Op1->getOperand(0);
261     Value *C = Op1->getOperand(1);
262
263     // Does "C op A" simplify?
264     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
265       // It does!  Return "B op V" if it simplifies or is already available.
266       // If V equals C then "B op V" is just the RHS.
267       if (V == C) return RHS;
268       // Otherwise return "B op V" if it simplifies.
269       if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
270         ++NumReassoc;
271         return W;
272       }
273     }
274   }
275
276   return nullptr;
277 }
278
279 /// In the case of a binary operation with a select instruction as an operand,
280 /// try to simplify the binop by seeing whether evaluating it on both branches
281 /// of the select results in the same value. Returns the common value if so,
282 /// otherwise returns null.
283 static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
284                                     Value *RHS, const SimplifyQuery &Q,
285                                     unsigned MaxRecurse) {
286   // Recursion is always used, so bail out at once if we already hit the limit.
287   if (!MaxRecurse--)
288     return nullptr;
289
290   SelectInst *SI;
291   if (isa<SelectInst>(LHS)) {
292     SI = cast<SelectInst>(LHS);
293   } else {
294     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
295     SI = cast<SelectInst>(RHS);
296   }
297
298   // Evaluate the BinOp on the true and false branches of the select.
299   Value *TV;
300   Value *FV;
301   if (SI == LHS) {
302     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
303     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
304   } else {
305     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
306     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
307   }
308
309   // If they simplified to the same value, then return the common value.
310   // If they both failed to simplify then return null.
311   if (TV == FV)
312     return TV;
313
314   // If one branch simplified to undef, return the other one.
315   if (TV && isa<UndefValue>(TV))
316     return FV;
317   if (FV && isa<UndefValue>(FV))
318     return TV;
319
320   // If applying the operation did not change the true and false select values,
321   // then the result of the binop is the select itself.
322   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
323     return SI;
324
325   // If one branch simplified and the other did not, and the simplified
326   // value is equal to the unsimplified one, return the simplified value.
327   // For example, select (cond, X, X & Z) & Z -> X & Z.
328   if ((FV && !TV) || (TV && !FV)) {
329     // Check that the simplified value has the form "X op Y" where "op" is the
330     // same as the original operation.
331     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
332     if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
333       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
334       // We already know that "op" is the same as for the simplified value.  See
335       // if the operands match too.  If so, return the simplified value.
336       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
337       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
338       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
339       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
340           Simplified->getOperand(1) == UnsimplifiedRHS)
341         return Simplified;
342       if (Simplified->isCommutative() &&
343           Simplified->getOperand(1) == UnsimplifiedLHS &&
344           Simplified->getOperand(0) == UnsimplifiedRHS)
345         return Simplified;
346     }
347   }
348
349   return nullptr;
350 }
351
352 /// In the case of a comparison with a select instruction, try to simplify the
353 /// comparison by seeing whether both branches of the select result in the same
354 /// value. Returns the common value if so, otherwise returns null.
355 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
356                                   Value *RHS, const SimplifyQuery &Q,
357                                   unsigned MaxRecurse) {
358   // Recursion is always used, so bail out at once if we already hit the limit.
359   if (!MaxRecurse--)
360     return nullptr;
361
362   // Make sure the select is on the LHS.
363   if (!isa<SelectInst>(LHS)) {
364     std::swap(LHS, RHS);
365     Pred = CmpInst::getSwappedPredicate(Pred);
366   }
367   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
368   SelectInst *SI = cast<SelectInst>(LHS);
369   Value *Cond = SI->getCondition();
370   Value *TV = SI->getTrueValue();
371   Value *FV = SI->getFalseValue();
372
373   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
374   // Does "cmp TV, RHS" simplify?
375   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
376   if (TCmp == Cond) {
377     // It not only simplified, it simplified to the select condition.  Replace
378     // it with 'true'.
379     TCmp = getTrue(Cond->getType());
380   } else if (!TCmp) {
381     // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
382     // condition then we can replace it with 'true'.  Otherwise give up.
383     if (!isSameCompare(Cond, Pred, TV, RHS))
384       return nullptr;
385     TCmp = getTrue(Cond->getType());
386   }
387
388   // Does "cmp FV, RHS" simplify?
389   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
390   if (FCmp == Cond) {
391     // It not only simplified, it simplified to the select condition.  Replace
392     // it with 'false'.
393     FCmp = getFalse(Cond->getType());
394   } else if (!FCmp) {
395     // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
396     // condition then we can replace it with 'false'.  Otherwise give up.
397     if (!isSameCompare(Cond, Pred, FV, RHS))
398       return nullptr;
399     FCmp = getFalse(Cond->getType());
400   }
401
402   // If both sides simplified to the same value, then use it as the result of
403   // the original comparison.
404   if (TCmp == FCmp)
405     return TCmp;
406
407   // The remaining cases only make sense if the select condition has the same
408   // type as the result of the comparison, so bail out if this is not so.
409   if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
410     return nullptr;
411   // If the false value simplified to false, then the result of the compare
412   // is equal to "Cond && TCmp".  This also catches the case when the false
413   // value simplified to false and the true value to true, returning "Cond".
414   if (match(FCmp, m_Zero()))
415     if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
416       return V;
417   // If the true value simplified to true, then the result of the compare
418   // is equal to "Cond || FCmp".
419   if (match(TCmp, m_One()))
420     if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
421       return V;
422   // Finally, if the false value simplified to true and the true value to
423   // false, then the result of the compare is equal to "!Cond".
424   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
425     if (Value *V =
426         SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
427                         Q, MaxRecurse))
428       return V;
429
430   return nullptr;
431 }
432
433 /// In the case of a binary operation with an operand that is a PHI instruction,
434 /// try to simplify the binop by seeing whether evaluating it on the incoming
435 /// phi values yields the same result for every value. If so returns the common
436 /// value, otherwise returns null.
437 static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
438                                  Value *RHS, const SimplifyQuery &Q,
439                                  unsigned MaxRecurse) {
440   // Recursion is always used, so bail out at once if we already hit the limit.
441   if (!MaxRecurse--)
442     return nullptr;
443
444   PHINode *PI;
445   if (isa<PHINode>(LHS)) {
446     PI = cast<PHINode>(LHS);
447     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
448     if (!valueDominatesPHI(RHS, PI, Q.DT))
449       return nullptr;
450   } else {
451     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
452     PI = cast<PHINode>(RHS);
453     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
454     if (!valueDominatesPHI(LHS, PI, Q.DT))
455       return nullptr;
456   }
457
458   // Evaluate the BinOp on the incoming phi values.
459   Value *CommonValue = nullptr;
460   for (Value *Incoming : PI->incoming_values()) {
461     // If the incoming value is the phi node itself, it can safely be skipped.
462     if (Incoming == PI) continue;
463     Value *V = PI == LHS ?
464       SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
465       SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
466     // If the operation failed to simplify, or simplified to a different value
467     // to previously, then give up.
468     if (!V || (CommonValue && V != CommonValue))
469       return nullptr;
470     CommonValue = V;
471   }
472
473   return CommonValue;
474 }
475
476 /// In the case of a comparison with a PHI instruction, try to simplify the
477 /// comparison by seeing whether comparing with all of the incoming phi values
478 /// yields the same result every time. If so returns the common result,
479 /// otherwise returns null.
480 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
481                                const SimplifyQuery &Q, unsigned MaxRecurse) {
482   // Recursion is always used, so bail out at once if we already hit the limit.
483   if (!MaxRecurse--)
484     return nullptr;
485
486   // Make sure the phi is on the LHS.
487   if (!isa<PHINode>(LHS)) {
488     std::swap(LHS, RHS);
489     Pred = CmpInst::getSwappedPredicate(Pred);
490   }
491   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
492   PHINode *PI = cast<PHINode>(LHS);
493
494   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
495   if (!valueDominatesPHI(RHS, PI, Q.DT))
496     return nullptr;
497
498   // Evaluate the BinOp on the incoming phi values.
499   Value *CommonValue = nullptr;
500   for (Value *Incoming : PI->incoming_values()) {
501     // If the incoming value is the phi node itself, it can safely be skipped.
502     if (Incoming == PI) continue;
503     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
504     // If the operation failed to simplify, or simplified to a different value
505     // to previously, then give up.
506     if (!V || (CommonValue && V != CommonValue))
507       return nullptr;
508     CommonValue = V;
509   }
510
511   return CommonValue;
512 }
513
514 static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
515                                        Value *&Op0, Value *&Op1,
516                                        const SimplifyQuery &Q) {
517   if (auto *CLHS = dyn_cast<Constant>(Op0)) {
518     if (auto *CRHS = dyn_cast<Constant>(Op1))
519       return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
520
521     // Canonicalize the constant to the RHS if this is a commutative operation.
522     if (Instruction::isCommutative(Opcode))
523       std::swap(Op0, Op1);
524   }
525   return nullptr;
526 }
527
528 /// Given operands for an Add, see if we can fold the result.
529 /// If not, this returns null.
530 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
531                               const SimplifyQuery &Q, unsigned MaxRecurse) {
532   if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
533     return C;
534
535   // X + undef -> undef
536   if (match(Op1, m_Undef()))
537     return Op1;
538
539   // X + 0 -> X
540   if (match(Op1, m_Zero()))
541     return Op0;
542
543   // X + (Y - X) -> Y
544   // (Y - X) + X -> Y
545   // Eg: X + -X -> 0
546   Value *Y = nullptr;
547   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
548       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
549     return Y;
550
551   // X + ~X -> -1   since   ~X = -X-1
552   Type *Ty = Op0->getType();
553   if (match(Op0, m_Not(m_Specific(Op1))) ||
554       match(Op1, m_Not(m_Specific(Op0))))
555     return Constant::getAllOnesValue(Ty);
556
557   // add nsw/nuw (xor Y, signmask), signmask --> Y
558   // The no-wrapping add guarantees that the top bit will be set by the add.
559   // Therefore, the xor must be clearing the already set sign bit of Y.
560   if ((isNSW || isNUW) && match(Op1, m_SignMask()) &&
561       match(Op0, m_Xor(m_Value(Y), m_SignMask())))
562     return Y;
563
564   /// i1 add -> xor.
565   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
566     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
567       return V;
568
569   // Try some generic simplifications for associative operations.
570   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
571                                           MaxRecurse))
572     return V;
573
574   // Threading Add over selects and phi nodes is pointless, so don't bother.
575   // Threading over the select in "A + select(cond, B, C)" means evaluating
576   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
577   // only if B and C are equal.  If B and C are equal then (since we assume
578   // that operands have already been simplified) "select(cond, B, C)" should
579   // have been simplified to the common value of B and C already.  Analysing
580   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
581   // for threading over phi nodes.
582
583   return nullptr;
584 }
585
586 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
587                              const SimplifyQuery &Query) {
588   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query, RecursionLimit);
589 }
590
591 /// Compute the base pointer and cumulative constant offsets for V.
592 ///
593 /// This strips all constant offsets off of V, leaving it the base pointer, and
594 /// accumulates the total constant offset applied in the returned constant. It
595 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
596 /// no constant offsets applied.
597 ///
598 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
599 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
600 /// folding.
601 static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
602                                                 bool AllowNonInbounds = false) {
603   assert(V->getType()->isPtrOrPtrVectorTy());
604
605   Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
606   APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
607
608   // Even though we don't look through PHI nodes, we could be called on an
609   // instruction in an unreachable block, which may be on a cycle.
610   SmallPtrSet<Value *, 4> Visited;
611   Visited.insert(V);
612   do {
613     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
614       if ((!AllowNonInbounds && !GEP->isInBounds()) ||
615           !GEP->accumulateConstantOffset(DL, Offset))
616         break;
617       V = GEP->getPointerOperand();
618     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
619       V = cast<Operator>(V)->getOperand(0);
620     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
621       if (GA->isInterposable())
622         break;
623       V = GA->getAliasee();
624     } else {
625       if (auto CS = CallSite(V))
626         if (Value *RV = CS.getReturnedArgOperand()) {
627           V = RV;
628           continue;
629         }
630       break;
631     }
632     assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
633   } while (Visited.insert(V).second);
634
635   Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
636   if (V->getType()->isVectorTy())
637     return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
638                                     OffsetIntPtr);
639   return OffsetIntPtr;
640 }
641
642 /// Compute the constant difference between two pointer values.
643 /// If the difference is not a constant, returns zero.
644 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
645                                           Value *RHS) {
646   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
647   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
648
649   // If LHS and RHS are not related via constant offsets to the same base
650   // value, there is nothing we can do here.
651   if (LHS != RHS)
652     return nullptr;
653
654   // Otherwise, the difference of LHS - RHS can be computed as:
655   //    LHS - RHS
656   //  = (LHSOffset + Base) - (RHSOffset + Base)
657   //  = LHSOffset - RHSOffset
658   return ConstantExpr::getSub(LHSOffset, RHSOffset);
659 }
660
661 /// Given operands for a Sub, see if we can fold the result.
662 /// If not, this returns null.
663 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
664                               const SimplifyQuery &Q, unsigned MaxRecurse) {
665   if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
666     return C;
667
668   // X - undef -> undef
669   // undef - X -> undef
670   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
671     return UndefValue::get(Op0->getType());
672
673   // X - 0 -> X
674   if (match(Op1, m_Zero()))
675     return Op0;
676
677   // X - X -> 0
678   if (Op0 == Op1)
679     return Constant::getNullValue(Op0->getType());
680
681   // Is this a negation?
682   if (match(Op0, m_Zero())) {
683     // 0 - X -> 0 if the sub is NUW.
684     if (isNUW)
685       return Constant::getNullValue(Op0->getType());
686
687     KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
688     if (Known.Zero.isMaxSignedValue()) {
689       // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
690       // Op1 must be 0 because negating the minimum signed value is undefined.
691       if (isNSW)
692         return Constant::getNullValue(Op0->getType());
693
694       // 0 - X -> X if X is 0 or the minimum signed value.
695       return Op1;
696     }
697   }
698
699   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
700   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
701   Value *X = nullptr, *Y = nullptr, *Z = Op1;
702   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
703     // See if "V === Y - Z" simplifies.
704     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
705       // It does!  Now see if "X + V" simplifies.
706       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
707         // It does, we successfully reassociated!
708         ++NumReassoc;
709         return W;
710       }
711     // See if "V === X - Z" simplifies.
712     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
713       // It does!  Now see if "Y + V" simplifies.
714       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
715         // It does, we successfully reassociated!
716         ++NumReassoc;
717         return W;
718       }
719   }
720
721   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
722   // For example, X - (X + 1) -> -1
723   X = Op0;
724   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
725     // See if "V === X - Y" simplifies.
726     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
727       // It does!  Now see if "V - Z" simplifies.
728       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
729         // It does, we successfully reassociated!
730         ++NumReassoc;
731         return W;
732       }
733     // See if "V === X - Z" simplifies.
734     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
735       // It does!  Now see if "V - Y" simplifies.
736       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
737         // It does, we successfully reassociated!
738         ++NumReassoc;
739         return W;
740       }
741   }
742
743   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
744   // For example, X - (X - Y) -> Y.
745   Z = Op0;
746   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
747     // See if "V === Z - X" simplifies.
748     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
749       // It does!  Now see if "V + Y" simplifies.
750       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
751         // It does, we successfully reassociated!
752         ++NumReassoc;
753         return W;
754       }
755
756   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
757   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
758       match(Op1, m_Trunc(m_Value(Y))))
759     if (X->getType() == Y->getType())
760       // See if "V === X - Y" simplifies.
761       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
762         // It does!  Now see if "trunc V" simplifies.
763         if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
764                                         Q, MaxRecurse - 1))
765           // It does, return the simplified "trunc V".
766           return W;
767
768   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
769   if (match(Op0, m_PtrToInt(m_Value(X))) &&
770       match(Op1, m_PtrToInt(m_Value(Y))))
771     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
772       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
773
774   // i1 sub -> xor.
775   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
776     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
777       return V;
778
779   // Threading Sub over selects and phi nodes is pointless, so don't bother.
780   // Threading over the select in "A - select(cond, B, C)" means evaluating
781   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
782   // only if B and C are equal.  If B and C are equal then (since we assume
783   // that operands have already been simplified) "select(cond, B, C)" should
784   // have been simplified to the common value of B and C already.  Analysing
785   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
786   // for threading over phi nodes.
787
788   return nullptr;
789 }
790
791 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
792                              const SimplifyQuery &Q) {
793   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
794 }
795
796 /// Given operands for a Mul, see if we can fold the result.
797 /// If not, this returns null.
798 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
799                               unsigned MaxRecurse) {
800   if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
801     return C;
802
803   // X * undef -> 0
804   // X * 0 -> 0
805   if (match(Op1, m_CombineOr(m_Undef(), m_Zero())))
806     return Constant::getNullValue(Op0->getType());
807
808   // X * 1 -> X
809   if (match(Op1, m_One()))
810     return Op0;
811
812   // (X / Y) * Y -> X if the division is exact.
813   Value *X = nullptr;
814   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
815       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
816     return X;
817
818   // i1 mul -> and.
819   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
820     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
821       return V;
822
823   // Try some generic simplifications for associative operations.
824   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
825                                           MaxRecurse))
826     return V;
827
828   // Mul distributes over Add. Try some generic simplifications based on this.
829   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
830                              Q, MaxRecurse))
831     return V;
832
833   // If the operation is with the result of a select instruction, check whether
834   // operating on either branch of the select always yields the same value.
835   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
836     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
837                                          MaxRecurse))
838       return V;
839
840   // If the operation is with the result of a phi instruction, check whether
841   // operating on all incoming values of the phi always yields the same value.
842   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
843     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
844                                       MaxRecurse))
845       return V;
846
847   return nullptr;
848 }
849
850 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
851   return ::SimplifyMulInst(Op0, Op1, Q, RecursionLimit);
852 }
853
854 /// Check for common or similar folds of integer division or integer remainder.
855 /// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
856 static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) {
857   Type *Ty = Op0->getType();
858
859   // X / undef -> undef
860   // X % undef -> undef
861   if (match(Op1, m_Undef()))
862     return Op1;
863
864   // X / 0 -> undef
865   // X % 0 -> undef
866   // We don't need to preserve faults!
867   if (match(Op1, m_Zero()))
868     return UndefValue::get(Ty);
869
870   // If any element of a constant divisor vector is zero or undef, the whole op
871   // is undef.
872   auto *Op1C = dyn_cast<Constant>(Op1);
873   if (Op1C && Ty->isVectorTy()) {
874     unsigned NumElts = Ty->getVectorNumElements();
875     for (unsigned i = 0; i != NumElts; ++i) {
876       Constant *Elt = Op1C->getAggregateElement(i);
877       if (Elt && (Elt->isNullValue() || isa<UndefValue>(Elt)))
878         return UndefValue::get(Ty);
879     }
880   }
881
882   // undef / X -> 0
883   // undef % X -> 0
884   if (match(Op0, m_Undef()))
885     return Constant::getNullValue(Ty);
886
887   // 0 / X -> 0
888   // 0 % X -> 0
889   if (match(Op0, m_Zero()))
890     return Constant::getNullValue(Op0->getType());
891
892   // X / X -> 1
893   // X % X -> 0
894   if (Op0 == Op1)
895     return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
896
897   // X / 1 -> X
898   // X % 1 -> 0
899   // If this is a boolean op (single-bit element type), we can't have
900   // division-by-zero or remainder-by-zero, so assume the divisor is 1.
901   if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1))
902     return IsDiv ? Op0 : Constant::getNullValue(Ty);
903
904   return nullptr;
905 }
906
907 /// Given a predicate and two operands, return true if the comparison is true.
908 /// This is a helper for div/rem simplification where we return some other value
909 /// when we can prove a relationship between the operands.
910 static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
911                        const SimplifyQuery &Q, unsigned MaxRecurse) {
912   Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
913   Constant *C = dyn_cast_or_null<Constant>(V);
914   return (C && C->isAllOnesValue());
915 }
916
917 /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
918 /// to simplify X % Y to X.
919 static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
920                       unsigned MaxRecurse, bool IsSigned) {
921   // Recursion is always used, so bail out at once if we already hit the limit.
922   if (!MaxRecurse--)
923     return false;
924
925   if (IsSigned) {
926     // |X| / |Y| --> 0
927     //
928     // We require that 1 operand is a simple constant. That could be extended to
929     // 2 variables if we computed the sign bit for each.
930     //
931     // Make sure that a constant is not the minimum signed value because taking
932     // the abs() of that is undefined.
933     Type *Ty = X->getType();
934     const APInt *C;
935     if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
936       // Is the variable divisor magnitude always greater than the constant
937       // dividend magnitude?
938       // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
939       Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
940       Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
941       if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
942           isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
943         return true;
944     }
945     if (match(Y, m_APInt(C))) {
946       // Special-case: we can't take the abs() of a minimum signed value. If
947       // that's the divisor, then all we have to do is prove that the dividend
948       // is also not the minimum signed value.
949       if (C->isMinSignedValue())
950         return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
951
952       // Is the variable dividend magnitude always less than the constant
953       // divisor magnitude?
954       // |X| < |C| --> X > -abs(C) and X < abs(C)
955       Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
956       Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
957       if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
958           isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
959         return true;
960     }
961     return false;
962   }
963
964   // IsSigned == false.
965   // Is the dividend unsigned less than the divisor?
966   return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
967 }
968
969 /// These are simplifications common to SDiv and UDiv.
970 static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
971                           const SimplifyQuery &Q, unsigned MaxRecurse) {
972   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
973     return C;
974
975   if (Value *V = simplifyDivRem(Op0, Op1, true))
976     return V;
977
978   bool IsSigned = Opcode == Instruction::SDiv;
979
980   // (X * Y) / Y -> X if the multiplication does not overflow.
981   Value *X;
982   if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
983     auto *Mul = cast<OverflowingBinaryOperator>(Op0);
984     // If the Mul does not overflow, then we are good to go.
985     if ((IsSigned && Mul->hasNoSignedWrap()) ||
986         (!IsSigned && Mul->hasNoUnsignedWrap()))
987       return X;
988     // If X has the form X = A / Y, then X * Y cannot overflow.
989     if ((IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
990         (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1)))))
991       return X;
992   }
993
994   // (X rem Y) / Y -> 0
995   if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
996       (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
997     return Constant::getNullValue(Op0->getType());
998
999   // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1000   ConstantInt *C1, *C2;
1001   if (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1002       match(Op1, m_ConstantInt(C2))) {
1003     bool Overflow;
1004     (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
1005     if (Overflow)
1006       return Constant::getNullValue(Op0->getType());
1007   }
1008
1009   // If the operation is with the result of a select instruction, check whether
1010   // operating on either branch of the select always yields the same value.
1011   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1012     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1013       return V;
1014
1015   // If the operation is with the result of a phi instruction, check whether
1016   // operating on all incoming values of the phi always yields the same value.
1017   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1018     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1019       return V;
1020
1021   if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1022     return Constant::getNullValue(Op0->getType());
1023
1024   return nullptr;
1025 }
1026
1027 /// These are simplifications common to SRem and URem.
1028 static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1029                           const SimplifyQuery &Q, unsigned MaxRecurse) {
1030   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1031     return C;
1032
1033   if (Value *V = simplifyDivRem(Op0, Op1, false))
1034     return V;
1035
1036   // (X % Y) % Y -> X % Y
1037   if ((Opcode == Instruction::SRem &&
1038        match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1039       (Opcode == Instruction::URem &&
1040        match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1041     return Op0;
1042
1043   // (X << Y) % X -> 0
1044   if ((Opcode == Instruction::SRem &&
1045        match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1046       (Opcode == Instruction::URem &&
1047        match(Op0, m_NUWShl(m_Specific(Op1), m_Value()))))
1048     return Constant::getNullValue(Op0->getType());
1049
1050   // If the operation is with the result of a select instruction, check whether
1051   // operating on either branch of the select always yields the same value.
1052   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1053     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1054       return V;
1055
1056   // If the operation is with the result of a phi instruction, check whether
1057   // operating on all incoming values of the phi always yields the same value.
1058   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1059     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1060       return V;
1061
1062   // If X / Y == 0, then X % Y == X.
1063   if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
1064     return Op0;
1065
1066   return nullptr;
1067 }
1068
1069 /// Given operands for an SDiv, see if we can fold the result.
1070 /// If not, this returns null.
1071 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1072                                unsigned MaxRecurse) {
1073   return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse);
1074 }
1075
1076 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1077   return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit);
1078 }
1079
1080 /// Given operands for a UDiv, see if we can fold the result.
1081 /// If not, this returns null.
1082 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1083                                unsigned MaxRecurse) {
1084   return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse);
1085 }
1086
1087 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1088   return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit);
1089 }
1090
1091 /// Given operands for an SRem, see if we can fold the result.
1092 /// If not, this returns null.
1093 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1094                                unsigned MaxRecurse) {
1095   return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
1096 }
1097
1098 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1099   return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit);
1100 }
1101
1102 /// Given operands for a URem, see if we can fold the result.
1103 /// If not, this returns null.
1104 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1105                                unsigned MaxRecurse) {
1106   return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
1107 }
1108
1109 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1110   return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit);
1111 }
1112
1113 /// Returns true if a shift by \c Amount always yields undef.
1114 static bool isUndefShift(Value *Amount) {
1115   Constant *C = dyn_cast<Constant>(Amount);
1116   if (!C)
1117     return false;
1118
1119   // X shift by undef -> undef because it may shift by the bitwidth.
1120   if (isa<UndefValue>(C))
1121     return true;
1122
1123   // Shifting by the bitwidth or more is undefined.
1124   if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1125     if (CI->getValue().getLimitedValue() >=
1126         CI->getType()->getScalarSizeInBits())
1127       return true;
1128
1129   // If all lanes of a vector shift are undefined the whole shift is.
1130   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1131     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1132       if (!isUndefShift(C->getAggregateElement(I)))
1133         return false;
1134     return true;
1135   }
1136
1137   return false;
1138 }
1139
1140 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1141 /// If not, this returns null.
1142 static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
1143                             Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse) {
1144   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1145     return C;
1146
1147   // 0 shift by X -> 0
1148   if (match(Op0, m_Zero()))
1149     return Constant::getNullValue(Op0->getType());
1150
1151   // X shift by 0 -> X
1152   if (match(Op1, m_Zero()))
1153     return Op0;
1154
1155   // Fold undefined shifts.
1156   if (isUndefShift(Op1))
1157     return UndefValue::get(Op0->getType());
1158
1159   // If the operation is with the result of a select instruction, check whether
1160   // operating on either branch of the select always yields the same value.
1161   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1162     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1163       return V;
1164
1165   // If the operation is with the result of a phi instruction, check whether
1166   // operating on all incoming values of the phi always yields the same value.
1167   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1168     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1169       return V;
1170
1171   // If any bits in the shift amount make that value greater than or equal to
1172   // the number of bits in the type, the shift is undefined.
1173   KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1174   if (Known.One.getLimitedValue() >= Known.getBitWidth())
1175     return UndefValue::get(Op0->getType());
1176
1177   // If all valid bits in the shift amount are known zero, the first operand is
1178   // unchanged.
1179   unsigned NumValidShiftBits = Log2_32_Ceil(Known.getBitWidth());
1180   if (Known.countMinTrailingZeros() >= NumValidShiftBits)
1181     return Op0;
1182
1183   return nullptr;
1184 }
1185
1186 /// Given operands for an Shl, LShr or AShr, see if we can
1187 /// fold the result.  If not, this returns null.
1188 static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
1189                                  Value *Op1, bool isExact, const SimplifyQuery &Q,
1190                                  unsigned MaxRecurse) {
1191   if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1192     return V;
1193
1194   // X >> X -> 0
1195   if (Op0 == Op1)
1196     return Constant::getNullValue(Op0->getType());
1197
1198   // undef >> X -> 0
1199   // undef >> X -> undef (if it's exact)
1200   if (match(Op0, m_Undef()))
1201     return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1202
1203   // The low bit cannot be shifted out of an exact shift if it is set.
1204   if (isExact) {
1205     KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
1206     if (Op0Known.One[0])
1207       return Op0;
1208   }
1209
1210   return nullptr;
1211 }
1212
1213 /// Given operands for an Shl, see if we can fold the result.
1214 /// If not, this returns null.
1215 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1216                               const SimplifyQuery &Q, unsigned MaxRecurse) {
1217   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1218     return V;
1219
1220   // undef << X -> 0
1221   // undef << X -> undef if (if it's NSW/NUW)
1222   if (match(Op0, m_Undef()))
1223     return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1224
1225   // (X >> A) << A -> X
1226   Value *X;
1227   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1228     return X;
1229
1230   // shl nuw i8 C, %x  ->  C  iff C has sign bit set.
1231   if (isNUW && match(Op0, m_Negative()))
1232     return Op0;
1233   // NOTE: could use computeKnownBits() / LazyValueInfo,
1234   // but the cost-benefit analysis suggests it isn't worth it.
1235
1236   return nullptr;
1237 }
1238
1239 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1240                              const SimplifyQuery &Q) {
1241   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
1242 }
1243
1244 /// Given operands for an LShr, see if we can fold the result.
1245 /// If not, this returns null.
1246 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1247                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1248   if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1249                                     MaxRecurse))
1250       return V;
1251
1252   // (X << A) >> A -> X
1253   Value *X;
1254   if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1255     return X;
1256
1257   return nullptr;
1258 }
1259
1260 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1261                               const SimplifyQuery &Q) {
1262   return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1263 }
1264
1265 /// Given operands for an AShr, see if we can fold the result.
1266 /// If not, this returns null.
1267 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1268                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1269   if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1270                                     MaxRecurse))
1271     return V;
1272
1273   // all ones >>a X -> -1
1274   // Do not return Op0 because it may contain undef elements if it's a vector.
1275   if (match(Op0, m_AllOnes()))
1276     return Constant::getAllOnesValue(Op0->getType());
1277
1278   // (X << A) >> A -> X
1279   Value *X;
1280   if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1281     return X;
1282
1283   // Arithmetic shifting an all-sign-bit value is a no-op.
1284   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1285   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1286     return Op0;
1287
1288   return nullptr;
1289 }
1290
1291 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1292                               const SimplifyQuery &Q) {
1293   return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1294 }
1295
1296 /// Commuted variants are assumed to be handled by calling this function again
1297 /// with the parameters swapped.
1298 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1299                                          ICmpInst *UnsignedICmp, bool IsAnd) {
1300   Value *X, *Y;
1301
1302   ICmpInst::Predicate EqPred;
1303   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1304       !ICmpInst::isEquality(EqPred))
1305     return nullptr;
1306
1307   ICmpInst::Predicate UnsignedPred;
1308   if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1309       ICmpInst::isUnsigned(UnsignedPred))
1310     ;
1311   else if (match(UnsignedICmp,
1312                  m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1313            ICmpInst::isUnsigned(UnsignedPred))
1314     UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1315   else
1316     return nullptr;
1317
1318   // X < Y && Y != 0  -->  X < Y
1319   // X < Y || Y != 0  -->  Y != 0
1320   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1321     return IsAnd ? UnsignedICmp : ZeroICmp;
1322
1323   // X >= Y || Y != 0  -->  true
1324   // X >= Y || Y == 0  -->  X >= Y
1325   if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1326     if (EqPred == ICmpInst::ICMP_NE)
1327       return getTrue(UnsignedICmp->getType());
1328     return UnsignedICmp;
1329   }
1330
1331   // X < Y && Y == 0  -->  false
1332   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1333       IsAnd)
1334     return getFalse(UnsignedICmp->getType());
1335
1336   return nullptr;
1337 }
1338
1339 /// Commuted variants are assumed to be handled by calling this function again
1340 /// with the parameters swapped.
1341 static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1342   ICmpInst::Predicate Pred0, Pred1;
1343   Value *A ,*B;
1344   if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1345       !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1346     return nullptr;
1347
1348   // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1349   // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1350   // can eliminate Op1 from this 'and'.
1351   if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1352     return Op0;
1353
1354   // Check for any combination of predicates that are guaranteed to be disjoint.
1355   if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1356       (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1357       (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1358       (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1359     return getFalse(Op0->getType());
1360
1361   return nullptr;
1362 }
1363
1364 /// Commuted variants are assumed to be handled by calling this function again
1365 /// with the parameters swapped.
1366 static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1367   ICmpInst::Predicate Pred0, Pred1;
1368   Value *A ,*B;
1369   if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1370       !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1371     return nullptr;
1372
1373   // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1374   // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1375   // can eliminate Op0 from this 'or'.
1376   if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1377     return Op1;
1378
1379   // Check for any combination of predicates that cover the entire range of
1380   // possibilities.
1381   if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1382       (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1383       (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1384       (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1385     return getTrue(Op0->getType());
1386
1387   return nullptr;
1388 }
1389
1390 /// Test if a pair of compares with a shared operand and 2 constants has an
1391 /// empty set intersection, full set union, or if one compare is a superset of
1392 /// the other.
1393 static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
1394                                                 bool IsAnd) {
1395   // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1396   if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1397     return nullptr;
1398
1399   const APInt *C0, *C1;
1400   if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1401       !match(Cmp1->getOperand(1), m_APInt(C1)))
1402     return nullptr;
1403
1404   auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1405   auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1406
1407   // For and-of-compares, check if the intersection is empty:
1408   // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1409   if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1410     return getFalse(Cmp0->getType());
1411
1412   // For or-of-compares, check if the union is full:
1413   // (icmp X, C0) || (icmp X, C1) --> full set --> true
1414   if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1415     return getTrue(Cmp0->getType());
1416
1417   // Is one range a superset of the other?
1418   // If this is and-of-compares, take the smaller set:
1419   // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1420   // If this is or-of-compares, take the larger set:
1421   // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1422   if (Range0.contains(Range1))
1423     return IsAnd ? Cmp1 : Cmp0;
1424   if (Range1.contains(Range0))
1425     return IsAnd ? Cmp0 : Cmp1;
1426
1427   return nullptr;
1428 }
1429
1430 static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
1431                                            bool IsAnd) {
1432   ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
1433   if (!match(Cmp0->getOperand(1), m_Zero()) ||
1434       !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
1435     return nullptr;
1436
1437   if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
1438     return nullptr;
1439
1440   // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
1441   Value *X = Cmp0->getOperand(0);
1442   Value *Y = Cmp1->getOperand(0);
1443
1444   // If one of the compares is a masked version of a (not) null check, then
1445   // that compare implies the other, so we eliminate the other. Optionally, look
1446   // through a pointer-to-int cast to match a null check of a pointer type.
1447
1448   // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
1449   // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
1450   // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
1451   // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
1452   if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
1453       match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
1454     return Cmp1;
1455
1456   // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
1457   // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
1458   // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
1459   // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
1460   if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
1461       match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
1462     return Cmp0;
1463
1464   return nullptr;
1465 }
1466
1467 static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1) {
1468   // (icmp (add V, C0), C1) & (icmp V, C0)
1469   ICmpInst::Predicate Pred0, Pred1;
1470   const APInt *C0, *C1;
1471   Value *V;
1472   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1473     return nullptr;
1474
1475   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1476     return nullptr;
1477
1478   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1479   if (AddInst->getOperand(1) != Op1->getOperand(1))
1480     return nullptr;
1481
1482   Type *ITy = Op0->getType();
1483   bool isNSW = AddInst->hasNoSignedWrap();
1484   bool isNUW = AddInst->hasNoUnsignedWrap();
1485
1486   const APInt Delta = *C1 - *C0;
1487   if (C0->isStrictlyPositive()) {
1488     if (Delta == 2) {
1489       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1490         return getFalse(ITy);
1491       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1492         return getFalse(ITy);
1493     }
1494     if (Delta == 1) {
1495       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1496         return getFalse(ITy);
1497       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1498         return getFalse(ITy);
1499     }
1500   }
1501   if (C0->getBoolValue() && isNUW) {
1502     if (Delta == 2)
1503       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1504         return getFalse(ITy);
1505     if (Delta == 1)
1506       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1507         return getFalse(ITy);
1508   }
1509
1510   return nullptr;
1511 }
1512
1513 static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1514   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1515     return X;
1516   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true))
1517     return X;
1518
1519   if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1520     return X;
1521   if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0))
1522     return X;
1523
1524   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
1525     return X;
1526
1527   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
1528     return X;
1529
1530   if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1))
1531     return X;
1532   if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0))
1533     return X;
1534
1535   return nullptr;
1536 }
1537
1538 static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1) {
1539   // (icmp (add V, C0), C1) | (icmp V, C0)
1540   ICmpInst::Predicate Pred0, Pred1;
1541   const APInt *C0, *C1;
1542   Value *V;
1543   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1544     return nullptr;
1545
1546   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1547     return nullptr;
1548
1549   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1550   if (AddInst->getOperand(1) != Op1->getOperand(1))
1551     return nullptr;
1552
1553   Type *ITy = Op0->getType();
1554   bool isNSW = AddInst->hasNoSignedWrap();
1555   bool isNUW = AddInst->hasNoUnsignedWrap();
1556
1557   const APInt Delta = *C1 - *C0;
1558   if (C0->isStrictlyPositive()) {
1559     if (Delta == 2) {
1560       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1561         return getTrue(ITy);
1562       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1563         return getTrue(ITy);
1564     }
1565     if (Delta == 1) {
1566       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1567         return getTrue(ITy);
1568       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1569         return getTrue(ITy);
1570     }
1571   }
1572   if (C0->getBoolValue() && isNUW) {
1573     if (Delta == 2)
1574       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1575         return getTrue(ITy);
1576     if (Delta == 1)
1577       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1578         return getTrue(ITy);
1579   }
1580
1581   return nullptr;
1582 }
1583
1584 static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1585   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1586     return X;
1587   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false))
1588     return X;
1589
1590   if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1591     return X;
1592   if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0))
1593     return X;
1594
1595   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1596     return X;
1597
1598   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
1599     return X;
1600
1601   if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1))
1602     return X;
1603   if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0))
1604     return X;
1605
1606   return nullptr;
1607 }
1608
1609 static Value *simplifyAndOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) {
1610   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1611   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1612   if (LHS0->getType() != RHS0->getType())
1613     return nullptr;
1614
1615   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1616   if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1617       (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1618     // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
1619     // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
1620     // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
1621     // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
1622     // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
1623     // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
1624     // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
1625     // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
1626     if ((isKnownNeverNaN(LHS0) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
1627         (isKnownNeverNaN(LHS1) && (LHS0 == RHS0 || LHS0 == RHS1)))
1628       return RHS;
1629
1630     // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
1631     // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
1632     // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
1633     // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
1634     // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
1635     // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
1636     // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
1637     // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
1638     if ((isKnownNeverNaN(RHS0) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
1639         (isKnownNeverNaN(RHS1) && (RHS0 == LHS0 || RHS0 == LHS1)))
1640       return LHS;
1641   }
1642
1643   return nullptr;
1644 }
1645
1646 static Value *simplifyAndOrOfCmps(Value *Op0, Value *Op1, bool IsAnd) {
1647   // Look through casts of the 'and' operands to find compares.
1648   auto *Cast0 = dyn_cast<CastInst>(Op0);
1649   auto *Cast1 = dyn_cast<CastInst>(Op1);
1650   if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1651       Cast0->getSrcTy() == Cast1->getSrcTy()) {
1652     Op0 = Cast0->getOperand(0);
1653     Op1 = Cast1->getOperand(0);
1654   }
1655
1656   Value *V = nullptr;
1657   auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1658   auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1659   if (ICmp0 && ICmp1)
1660     V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1) :
1661                 simplifyOrOfICmps(ICmp0, ICmp1);
1662
1663   auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
1664   auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
1665   if (FCmp0 && FCmp1)
1666     V = simplifyAndOrOfFCmps(FCmp0, FCmp1, IsAnd);
1667
1668   if (!V)
1669     return nullptr;
1670   if (!Cast0)
1671     return V;
1672
1673   // If we looked through casts, we can only handle a constant simplification
1674   // because we are not allowed to create a cast instruction here.
1675   if (auto *C = dyn_cast<Constant>(V))
1676     return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
1677
1678   return nullptr;
1679 }
1680
1681 /// Given operands for an And, see if we can fold the result.
1682 /// If not, this returns null.
1683 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1684                               unsigned MaxRecurse) {
1685   if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
1686     return C;
1687
1688   // X & undef -> 0
1689   if (match(Op1, m_Undef()))
1690     return Constant::getNullValue(Op0->getType());
1691
1692   // X & X = X
1693   if (Op0 == Op1)
1694     return Op0;
1695
1696   // X & 0 = 0
1697   if (match(Op1, m_Zero()))
1698     return Constant::getNullValue(Op0->getType());
1699
1700   // X & -1 = X
1701   if (match(Op1, m_AllOnes()))
1702     return Op0;
1703
1704   // A & ~A  =  ~A & A  =  0
1705   if (match(Op0, m_Not(m_Specific(Op1))) ||
1706       match(Op1, m_Not(m_Specific(Op0))))
1707     return Constant::getNullValue(Op0->getType());
1708
1709   // (A | ?) & A = A
1710   if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
1711     return Op1;
1712
1713   // A & (A | ?) = A
1714   if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
1715     return Op0;
1716
1717   // A mask that only clears known zeros of a shifted value is a no-op.
1718   Value *X;
1719   const APInt *Mask;
1720   const APInt *ShAmt;
1721   if (match(Op1, m_APInt(Mask))) {
1722     // If all bits in the inverted and shifted mask are clear:
1723     // and (shl X, ShAmt), Mask --> shl X, ShAmt
1724     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
1725         (~(*Mask)).lshr(*ShAmt).isNullValue())
1726       return Op0;
1727
1728     // If all bits in the inverted and shifted mask are clear:
1729     // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
1730     if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
1731         (~(*Mask)).shl(*ShAmt).isNullValue())
1732       return Op0;
1733   }
1734
1735   // A & (-A) = A if A is a power of two or zero.
1736   if (match(Op0, m_Neg(m_Specific(Op1))) ||
1737       match(Op1, m_Neg(m_Specific(Op0)))) {
1738     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1739                                Q.DT))
1740       return Op0;
1741     if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1742                                Q.DT))
1743       return Op1;
1744   }
1745
1746   if (Value *V = simplifyAndOrOfCmps(Op0, Op1, true))
1747     return V;
1748
1749   // Try some generic simplifications for associative operations.
1750   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1751                                           MaxRecurse))
1752     return V;
1753
1754   // And distributes over Or.  Try some generic simplifications based on this.
1755   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1756                              Q, MaxRecurse))
1757     return V;
1758
1759   // And distributes over Xor.  Try some generic simplifications based on this.
1760   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1761                              Q, MaxRecurse))
1762     return V;
1763
1764   // If the operation is with the result of a select instruction, check whether
1765   // operating on either branch of the select always yields the same value.
1766   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1767     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1768                                          MaxRecurse))
1769       return V;
1770
1771   // If the operation is with the result of a phi instruction, check whether
1772   // operating on all incoming values of the phi always yields the same value.
1773   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1774     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1775                                       MaxRecurse))
1776       return V;
1777
1778   return nullptr;
1779 }
1780
1781 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1782   return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit);
1783 }
1784
1785 /// Given operands for an Or, see if we can fold the result.
1786 /// If not, this returns null.
1787 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1788                              unsigned MaxRecurse) {
1789   if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
1790     return C;
1791
1792   // X | undef -> -1
1793   // X | -1 = -1
1794   // Do not return Op1 because it may contain undef elements if it's a vector.
1795   if (match(Op1, m_Undef()) || match(Op1, m_AllOnes()))
1796     return Constant::getAllOnesValue(Op0->getType());
1797
1798   // X | X = X
1799   // X | 0 = X
1800   if (Op0 == Op1 || match(Op1, m_Zero()))
1801     return Op0;
1802
1803   // A | ~A  =  ~A | A  =  -1
1804   if (match(Op0, m_Not(m_Specific(Op1))) ||
1805       match(Op1, m_Not(m_Specific(Op0))))
1806     return Constant::getAllOnesValue(Op0->getType());
1807
1808   // (A & ?) | A = A
1809   if (match(Op0, m_c_And(m_Specific(Op1), m_Value())))
1810     return Op1;
1811
1812   // A | (A & ?) = A
1813   if (match(Op1, m_c_And(m_Specific(Op0), m_Value())))
1814     return Op0;
1815
1816   // ~(A & ?) | A = -1
1817   if (match(Op0, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
1818     return Constant::getAllOnesValue(Op1->getType());
1819
1820   // A | ~(A & ?) = -1
1821   if (match(Op1, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
1822     return Constant::getAllOnesValue(Op0->getType());
1823
1824   Value *A, *B;
1825   // (A & ~B) | (A ^ B) -> (A ^ B)
1826   // (~B & A) | (A ^ B) -> (A ^ B)
1827   // (A & ~B) | (B ^ A) -> (B ^ A)
1828   // (~B & A) | (B ^ A) -> (B ^ A)
1829   if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1830       (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1831        match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
1832     return Op1;
1833
1834   // Commute the 'or' operands.
1835   // (A ^ B) | (A & ~B) -> (A ^ B)
1836   // (A ^ B) | (~B & A) -> (A ^ B)
1837   // (B ^ A) | (A & ~B) -> (B ^ A)
1838   // (B ^ A) | (~B & A) -> (B ^ A)
1839   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1840       (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1841        match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
1842     return Op0;
1843
1844   // (A & B) | (~A ^ B) -> (~A ^ B)
1845   // (B & A) | (~A ^ B) -> (~A ^ B)
1846   // (A & B) | (B ^ ~A) -> (B ^ ~A)
1847   // (B & A) | (B ^ ~A) -> (B ^ ~A)
1848   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1849       (match(Op1, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
1850        match(Op1, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
1851     return Op1;
1852
1853   // (~A ^ B) | (A & B) -> (~A ^ B)
1854   // (~A ^ B) | (B & A) -> (~A ^ B)
1855   // (B ^ ~A) | (A & B) -> (B ^ ~A)
1856   // (B ^ ~A) | (B & A) -> (B ^ ~A)
1857   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1858       (match(Op0, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
1859        match(Op0, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
1860     return Op0;
1861
1862   if (Value *V = simplifyAndOrOfCmps(Op0, Op1, false))
1863     return V;
1864
1865   // Try some generic simplifications for associative operations.
1866   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1867                                           MaxRecurse))
1868     return V;
1869
1870   // Or distributes over And.  Try some generic simplifications based on this.
1871   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1872                              MaxRecurse))
1873     return V;
1874
1875   // If the operation is with the result of a select instruction, check whether
1876   // operating on either branch of the select always yields the same value.
1877   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1878     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1879                                          MaxRecurse))
1880       return V;
1881
1882   // (A & C1)|(B & C2)
1883   const APInt *C1, *C2;
1884   if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
1885       match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
1886     if (*C1 == ~*C2) {
1887       // (A & C1)|(B & C2)
1888       // If we have: ((V + N) & C1) | (V & C2)
1889       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1890       // replace with V+N.
1891       Value *N;
1892       if (C2->isMask() && // C2 == 0+1+
1893           match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
1894         // Add commutes, try both ways.
1895         if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1896           return A;
1897       }
1898       // Or commutes, try both ways.
1899       if (C1->isMask() &&
1900           match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
1901         // Add commutes, try both ways.
1902         if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1903           return B;
1904       }
1905     }
1906   }
1907
1908   // If the operation is with the result of a phi instruction, check whether
1909   // operating on all incoming values of the phi always yields the same value.
1910   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1911     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1912       return V;
1913
1914   return nullptr;
1915 }
1916
1917 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1918   return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit);
1919 }
1920
1921 /// Given operands for a Xor, see if we can fold the result.
1922 /// If not, this returns null.
1923 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1924                               unsigned MaxRecurse) {
1925   if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
1926     return C;
1927
1928   // A ^ undef -> undef
1929   if (match(Op1, m_Undef()))
1930     return Op1;
1931
1932   // A ^ 0 = A
1933   if (match(Op1, m_Zero()))
1934     return Op0;
1935
1936   // A ^ A = 0
1937   if (Op0 == Op1)
1938     return Constant::getNullValue(Op0->getType());
1939
1940   // A ^ ~A  =  ~A ^ A  =  -1
1941   if (match(Op0, m_Not(m_Specific(Op1))) ||
1942       match(Op1, m_Not(m_Specific(Op0))))
1943     return Constant::getAllOnesValue(Op0->getType());
1944
1945   // Try some generic simplifications for associative operations.
1946   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1947                                           MaxRecurse))
1948     return V;
1949
1950   // Threading Xor over selects and phi nodes is pointless, so don't bother.
1951   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1952   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1953   // only if B and C are equal.  If B and C are equal then (since we assume
1954   // that operands have already been simplified) "select(cond, B, C)" should
1955   // have been simplified to the common value of B and C already.  Analysing
1956   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1957   // for threading over phi nodes.
1958
1959   return nullptr;
1960 }
1961
1962 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1963   return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit);
1964 }
1965
1966
1967 static Type *GetCompareTy(Value *Op) {
1968   return CmpInst::makeCmpResultType(Op->getType());
1969 }
1970
1971 /// Rummage around inside V looking for something equivalent to the comparison
1972 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
1973 /// Helper function for analyzing max/min idioms.
1974 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1975                                          Value *LHS, Value *RHS) {
1976   SelectInst *SI = dyn_cast<SelectInst>(V);
1977   if (!SI)
1978     return nullptr;
1979   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1980   if (!Cmp)
1981     return nullptr;
1982   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1983   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1984     return Cmp;
1985   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1986       LHS == CmpRHS && RHS == CmpLHS)
1987     return Cmp;
1988   return nullptr;
1989 }
1990
1991 // A significant optimization not implemented here is assuming that alloca
1992 // addresses are not equal to incoming argument values. They don't *alias*,
1993 // as we say, but that doesn't mean they aren't equal, so we take a
1994 // conservative approach.
1995 //
1996 // This is inspired in part by C++11 5.10p1:
1997 //   "Two pointers of the same type compare equal if and only if they are both
1998 //    null, both point to the same function, or both represent the same
1999 //    address."
2000 //
2001 // This is pretty permissive.
2002 //
2003 // It's also partly due to C11 6.5.9p6:
2004 //   "Two pointers compare equal if and only if both are null pointers, both are
2005 //    pointers to the same object (including a pointer to an object and a
2006 //    subobject at its beginning) or function, both are pointers to one past the
2007 //    last element of the same array object, or one is a pointer to one past the
2008 //    end of one array object and the other is a pointer to the start of a
2009 //    different array object that happens to immediately follow the first array
2010 //    object in the address space.)
2011 //
2012 // C11's version is more restrictive, however there's no reason why an argument
2013 // couldn't be a one-past-the-end value for a stack object in the caller and be
2014 // equal to the beginning of a stack object in the callee.
2015 //
2016 // If the C and C++ standards are ever made sufficiently restrictive in this
2017 // area, it may be possible to update LLVM's semantics accordingly and reinstate
2018 // this optimization.
2019 static Constant *
2020 computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2021                    const DominatorTree *DT, CmpInst::Predicate Pred,
2022                    AssumptionCache *AC, const Instruction *CxtI,
2023                    Value *LHS, Value *RHS) {
2024   // First, skip past any trivial no-ops.
2025   LHS = LHS->stripPointerCasts();
2026   RHS = RHS->stripPointerCasts();
2027
2028   // A non-null pointer is not equal to a null pointer.
2029   if (llvm::isKnownNonZero(LHS, DL) && isa<ConstantPointerNull>(RHS) &&
2030       (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2031     return ConstantInt::get(GetCompareTy(LHS),
2032                             !CmpInst::isTrueWhenEqual(Pred));
2033
2034   // We can only fold certain predicates on pointer comparisons.
2035   switch (Pred) {
2036   default:
2037     return nullptr;
2038
2039     // Equality comaprisons are easy to fold.
2040   case CmpInst::ICMP_EQ:
2041   case CmpInst::ICMP_NE:
2042     break;
2043
2044     // We can only handle unsigned relational comparisons because 'inbounds' on
2045     // a GEP only protects against unsigned wrapping.
2046   case CmpInst::ICMP_UGT:
2047   case CmpInst::ICMP_UGE:
2048   case CmpInst::ICMP_ULT:
2049   case CmpInst::ICMP_ULE:
2050     // However, we have to switch them to their signed variants to handle
2051     // negative indices from the base pointer.
2052     Pred = ICmpInst::getSignedPredicate(Pred);
2053     break;
2054   }
2055
2056   // Strip off any constant offsets so that we can reason about them.
2057   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2058   // here and compare base addresses like AliasAnalysis does, however there are
2059   // numerous hazards. AliasAnalysis and its utilities rely on special rules
2060   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2061   // doesn't need to guarantee pointer inequality when it says NoAlias.
2062   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2063   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
2064
2065   // If LHS and RHS are related via constant offsets to the same base
2066   // value, we can replace it with an icmp which just compares the offsets.
2067   if (LHS == RHS)
2068     return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
2069
2070   // Various optimizations for (in)equality comparisons.
2071   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2072     // Different non-empty allocations that exist at the same time have
2073     // different addresses (if the program can tell). Global variables always
2074     // exist, so they always exist during the lifetime of each other and all
2075     // allocas. Two different allocas usually have different addresses...
2076     //
2077     // However, if there's an @llvm.stackrestore dynamically in between two
2078     // allocas, they may have the same address. It's tempting to reduce the
2079     // scope of the problem by only looking at *static* allocas here. That would
2080     // cover the majority of allocas while significantly reducing the likelihood
2081     // of having an @llvm.stackrestore pop up in the middle. However, it's not
2082     // actually impossible for an @llvm.stackrestore to pop up in the middle of
2083     // an entry block. Also, if we have a block that's not attached to a
2084     // function, we can't tell if it's "static" under the current definition.
2085     // Theoretically, this problem could be fixed by creating a new kind of
2086     // instruction kind specifically for static allocas. Such a new instruction
2087     // could be required to be at the top of the entry block, thus preventing it
2088     // from being subject to a @llvm.stackrestore. Instcombine could even
2089     // convert regular allocas into these special allocas. It'd be nifty.
2090     // However, until then, this problem remains open.
2091     //
2092     // So, we'll assume that two non-empty allocas have different addresses
2093     // for now.
2094     //
2095     // With all that, if the offsets are within the bounds of their allocations
2096     // (and not one-past-the-end! so we can't use inbounds!), and their
2097     // allocations aren't the same, the pointers are not equal.
2098     //
2099     // Note that it's not necessary to check for LHS being a global variable
2100     // address, due to canonicalization and constant folding.
2101     if (isa<AllocaInst>(LHS) &&
2102         (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
2103       ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2104       ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
2105       uint64_t LHSSize, RHSSize;
2106       if (LHSOffsetCI && RHSOffsetCI &&
2107           getObjectSize(LHS, LHSSize, DL, TLI) &&
2108           getObjectSize(RHS, RHSSize, DL, TLI)) {
2109         const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2110         const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
2111         if (!LHSOffsetValue.isNegative() &&
2112             !RHSOffsetValue.isNegative() &&
2113             LHSOffsetValue.ult(LHSSize) &&
2114             RHSOffsetValue.ult(RHSSize)) {
2115           return ConstantInt::get(GetCompareTy(LHS),
2116                                   !CmpInst::isTrueWhenEqual(Pred));
2117         }
2118       }
2119
2120       // Repeat the above check but this time without depending on DataLayout
2121       // or being able to compute a precise size.
2122       if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2123           !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2124           LHSOffset->isNullValue() &&
2125           RHSOffset->isNullValue())
2126         return ConstantInt::get(GetCompareTy(LHS),
2127                                 !CmpInst::isTrueWhenEqual(Pred));
2128     }
2129
2130     // Even if an non-inbounds GEP occurs along the path we can still optimize
2131     // equality comparisons concerning the result. We avoid walking the whole
2132     // chain again by starting where the last calls to
2133     // stripAndComputeConstantOffsets left off and accumulate the offsets.
2134     Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2135     Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
2136     if (LHS == RHS)
2137       return ConstantExpr::getICmp(Pred,
2138                                    ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2139                                    ConstantExpr::getAdd(RHSOffset, RHSNoBound));
2140
2141     // If one side of the equality comparison must come from a noalias call
2142     // (meaning a system memory allocation function), and the other side must
2143     // come from a pointer that cannot overlap with dynamically-allocated
2144     // memory within the lifetime of the current function (allocas, byval
2145     // arguments, globals), then determine the comparison result here.
2146     SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2147     GetUnderlyingObjects(LHS, LHSUObjs, DL);
2148     GetUnderlyingObjects(RHS, RHSUObjs, DL);
2149
2150     // Is the set of underlying objects all noalias calls?
2151     auto IsNAC = [](ArrayRef<Value *> Objects) {
2152       return all_of(Objects, isNoAliasCall);
2153     };
2154
2155     // Is the set of underlying objects all things which must be disjoint from
2156     // noalias calls. For allocas, we consider only static ones (dynamic
2157     // allocas might be transformed into calls to malloc not simultaneously
2158     // live with the compared-to allocation). For globals, we exclude symbols
2159     // that might be resolve lazily to symbols in another dynamically-loaded
2160     // library (and, thus, could be malloc'ed by the implementation).
2161     auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2162       return all_of(Objects, [](Value *V) {
2163         if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2164           return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2165         if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2166           return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2167                   GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2168                  !GV->isThreadLocal();
2169         if (const Argument *A = dyn_cast<Argument>(V))
2170           return A->hasByValAttr();
2171         return false;
2172       });
2173     };
2174
2175     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2176         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2177         return ConstantInt::get(GetCompareTy(LHS),
2178                                 !CmpInst::isTrueWhenEqual(Pred));
2179
2180     // Fold comparisons for non-escaping pointer even if the allocation call
2181     // cannot be elided. We cannot fold malloc comparison to null. Also, the
2182     // dynamic allocation call could be either of the operands.
2183     Value *MI = nullptr;
2184     if (isAllocLikeFn(LHS, TLI) &&
2185         llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
2186       MI = LHS;
2187     else if (isAllocLikeFn(RHS, TLI) &&
2188              llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
2189       MI = RHS;
2190     // FIXME: We should also fold the compare when the pointer escapes, but the
2191     // compare dominates the pointer escape
2192     if (MI && !PointerMayBeCaptured(MI, true, true))
2193       return ConstantInt::get(GetCompareTy(LHS),
2194                               CmpInst::isFalseWhenEqual(Pred));
2195   }
2196
2197   // Otherwise, fail.
2198   return nullptr;
2199 }
2200
2201 /// Fold an icmp when its operands have i1 scalar type.
2202 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2203                                   Value *RHS, const SimplifyQuery &Q) {
2204   Type *ITy = GetCompareTy(LHS); // The return type.
2205   Type *OpTy = LHS->getType();   // The operand type.
2206   if (!OpTy->isIntOrIntVectorTy(1))
2207     return nullptr;
2208
2209   // A boolean compared to true/false can be simplified in 14 out of the 20
2210   // (10 predicates * 2 constants) possible combinations. Cases not handled here
2211   // require a 'not' of the LHS, so those must be transformed in InstCombine.
2212   if (match(RHS, m_Zero())) {
2213     switch (Pred) {
2214     case CmpInst::ICMP_NE:  // X !=  0 -> X
2215     case CmpInst::ICMP_UGT: // X >u  0 -> X
2216     case CmpInst::ICMP_SLT: // X <s  0 -> X
2217       return LHS;
2218
2219     case CmpInst::ICMP_ULT: // X <u  0 -> false
2220     case CmpInst::ICMP_SGT: // X >s  0 -> false
2221       return getFalse(ITy);
2222
2223     case CmpInst::ICMP_UGE: // X >=u 0 -> true
2224     case CmpInst::ICMP_SLE: // X <=s 0 -> true
2225       return getTrue(ITy);
2226
2227     default: break;
2228     }
2229   } else if (match(RHS, m_One())) {
2230     switch (Pred) {
2231     case CmpInst::ICMP_EQ:  // X ==   1 -> X
2232     case CmpInst::ICMP_UGE: // X >=u  1 -> X
2233     case CmpInst::ICMP_SLE: // X <=s -1 -> X
2234       return LHS;
2235
2236     case CmpInst::ICMP_UGT: // X >u   1 -> false
2237     case CmpInst::ICMP_SLT: // X <s  -1 -> false
2238       return getFalse(ITy);
2239
2240     case CmpInst::ICMP_ULE: // X <=u  1 -> true
2241     case CmpInst::ICMP_SGE: // X >=s -1 -> true
2242       return getTrue(ITy);
2243
2244     default: break;
2245     }
2246   }
2247
2248   switch (Pred) {
2249   default:
2250     break;
2251   case ICmpInst::ICMP_UGE:
2252     if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2253       return getTrue(ITy);
2254     break;
2255   case ICmpInst::ICMP_SGE:
2256     /// For signed comparison, the values for an i1 are 0 and -1
2257     /// respectively. This maps into a truth table of:
2258     /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
2259     ///  0  |  0  |  1 (0 >= 0)   |  1
2260     ///  0  |  1  |  1 (0 >= -1)  |  1
2261     ///  1  |  0  |  0 (-1 >= 0)  |  0
2262     ///  1  |  1  |  1 (-1 >= -1) |  1
2263     if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2264       return getTrue(ITy);
2265     break;
2266   case ICmpInst::ICMP_ULE:
2267     if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2268       return getTrue(ITy);
2269     break;
2270   }
2271
2272   return nullptr;
2273 }
2274
2275 /// Try hard to fold icmp with zero RHS because this is a common case.
2276 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2277                                    Value *RHS, const SimplifyQuery &Q) {
2278   if (!match(RHS, m_Zero()))
2279     return nullptr;
2280
2281   Type *ITy = GetCompareTy(LHS); // The return type.
2282   switch (Pred) {
2283   default:
2284     llvm_unreachable("Unknown ICmp predicate!");
2285   case ICmpInst::ICMP_ULT:
2286     return getFalse(ITy);
2287   case ICmpInst::ICMP_UGE:
2288     return getTrue(ITy);
2289   case ICmpInst::ICMP_EQ:
2290   case ICmpInst::ICMP_ULE:
2291     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2292       return getFalse(ITy);
2293     break;
2294   case ICmpInst::ICMP_NE:
2295   case ICmpInst::ICMP_UGT:
2296     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2297       return getTrue(ITy);
2298     break;
2299   case ICmpInst::ICMP_SLT: {
2300     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2301     if (LHSKnown.isNegative())
2302       return getTrue(ITy);
2303     if (LHSKnown.isNonNegative())
2304       return getFalse(ITy);
2305     break;
2306   }
2307   case ICmpInst::ICMP_SLE: {
2308     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2309     if (LHSKnown.isNegative())
2310       return getTrue(ITy);
2311     if (LHSKnown.isNonNegative() &&
2312         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2313       return getFalse(ITy);
2314     break;
2315   }
2316   case ICmpInst::ICMP_SGE: {
2317     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2318     if (LHSKnown.isNegative())
2319       return getFalse(ITy);
2320     if (LHSKnown.isNonNegative())
2321       return getTrue(ITy);
2322     break;
2323   }
2324   case ICmpInst::ICMP_SGT: {
2325     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2326     if (LHSKnown.isNegative())
2327       return getFalse(ITy);
2328     if (LHSKnown.isNonNegative() &&
2329         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2330       return getTrue(ITy);
2331     break;
2332   }
2333   }
2334
2335   return nullptr;
2336 }
2337
2338 /// Many binary operators with a constant operand have an easy-to-compute
2339 /// range of outputs. This can be used to fold a comparison to always true or
2340 /// always false.
2341 static void setLimitsForBinOp(BinaryOperator &BO, APInt &Lower, APInt &Upper) {
2342   unsigned Width = Lower.getBitWidth();
2343   const APInt *C;
2344   switch (BO.getOpcode()) {
2345   case Instruction::Add:
2346     if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
2347       // FIXME: If we have both nuw and nsw, we should reduce the range further.
2348       if (BO.hasNoUnsignedWrap()) {
2349         // 'add nuw x, C' produces [C, UINT_MAX].
2350         Lower = *C;
2351       } else if (BO.hasNoSignedWrap()) {
2352         if (C->isNegative()) {
2353           // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
2354           Lower = APInt::getSignedMinValue(Width);
2355           Upper = APInt::getSignedMaxValue(Width) + *C + 1;
2356         } else {
2357           // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
2358           Lower = APInt::getSignedMinValue(Width) + *C;
2359           Upper = APInt::getSignedMaxValue(Width) + 1;
2360         }
2361       }
2362     }
2363     break;
2364
2365   case Instruction::And:
2366     if (match(BO.getOperand(1), m_APInt(C)))
2367       // 'and x, C' produces [0, C].
2368       Upper = *C + 1;
2369     break;
2370
2371   case Instruction::Or:
2372     if (match(BO.getOperand(1), m_APInt(C)))
2373       // 'or x, C' produces [C, UINT_MAX].
2374       Lower = *C;
2375     break;
2376
2377   case Instruction::AShr:
2378     if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2379       // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
2380       Lower = APInt::getSignedMinValue(Width).ashr(*C);
2381       Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
2382     } else if (match(BO.getOperand(0), m_APInt(C))) {
2383       unsigned ShiftAmount = Width - 1;
2384       if (!C->isNullValue() && BO.isExact())
2385         ShiftAmount = C->countTrailingZeros();
2386       if (C->isNegative()) {
2387         // 'ashr C, x' produces [C, C >> (Width-1)]
2388         Lower = *C;
2389         Upper = C->ashr(ShiftAmount) + 1;
2390       } else {
2391         // 'ashr C, x' produces [C >> (Width-1), C]
2392         Lower = C->ashr(ShiftAmount);
2393         Upper = *C + 1;
2394       }
2395     }
2396     break;
2397
2398   case Instruction::LShr:
2399     if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2400       // 'lshr x, C' produces [0, UINT_MAX >> C].
2401       Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
2402     } else if (match(BO.getOperand(0), m_APInt(C))) {
2403       // 'lshr C, x' produces [C >> (Width-1), C].
2404       unsigned ShiftAmount = Width - 1;
2405       if (!C->isNullValue() && BO.isExact())
2406         ShiftAmount = C->countTrailingZeros();
2407       Lower = C->lshr(ShiftAmount);
2408       Upper = *C + 1;
2409     }
2410     break;
2411
2412   case Instruction::Shl:
2413     if (match(BO.getOperand(0), m_APInt(C))) {
2414       if (BO.hasNoUnsignedWrap()) {
2415         // 'shl nuw C, x' produces [C, C << CLZ(C)]
2416         Lower = *C;
2417         Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2418       } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
2419         if (C->isNegative()) {
2420           // 'shl nsw C, x' produces [C << CLO(C)-1, C]
2421           unsigned ShiftAmount = C->countLeadingOnes() - 1;
2422           Lower = C->shl(ShiftAmount);
2423           Upper = *C + 1;
2424         } else {
2425           // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
2426           unsigned ShiftAmount = C->countLeadingZeros() - 1;
2427           Lower = *C;
2428           Upper = C->shl(ShiftAmount) + 1;
2429         }
2430       }
2431     }
2432     break;
2433
2434   case Instruction::SDiv:
2435     if (match(BO.getOperand(1), m_APInt(C))) {
2436       APInt IntMin = APInt::getSignedMinValue(Width);
2437       APInt IntMax = APInt::getSignedMaxValue(Width);
2438       if (C->isAllOnesValue()) {
2439         // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2440         //    where C != -1 and C != 0 and C != 1
2441         Lower = IntMin + 1;
2442         Upper = IntMax + 1;
2443       } else if (C->countLeadingZeros() < Width - 1) {
2444         // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
2445         //    where C != -1 and C != 0 and C != 1
2446         Lower = IntMin.sdiv(*C);
2447         Upper = IntMax.sdiv(*C);
2448         if (Lower.sgt(Upper))
2449           std::swap(Lower, Upper);
2450         Upper = Upper + 1;
2451         assert(Upper != Lower && "Upper part of range has wrapped!");
2452       }
2453     } else if (match(BO.getOperand(0), m_APInt(C))) {
2454       if (C->isMinSignedValue()) {
2455         // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2456         Lower = *C;
2457         Upper = Lower.lshr(1) + 1;
2458       } else {
2459         // 'sdiv C, x' produces [-|C|, |C|].
2460         Upper = C->abs() + 1;
2461         Lower = (-Upper) + 1;
2462       }
2463     }
2464     break;
2465
2466   case Instruction::UDiv:
2467     if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
2468       // 'udiv x, C' produces [0, UINT_MAX / C].
2469       Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
2470     } else if (match(BO.getOperand(0), m_APInt(C))) {
2471       // 'udiv C, x' produces [0, C].
2472       Upper = *C + 1;
2473     }
2474     break;
2475
2476   case Instruction::SRem:
2477     if (match(BO.getOperand(1), m_APInt(C))) {
2478       // 'srem x, C' produces (-|C|, |C|).
2479       Upper = C->abs();
2480       Lower = (-Upper) + 1;
2481     }
2482     break;
2483
2484   case Instruction::URem:
2485     if (match(BO.getOperand(1), m_APInt(C)))
2486       // 'urem x, C' produces [0, C).
2487       Upper = *C;
2488     break;
2489
2490   default:
2491     break;
2492   }
2493 }
2494
2495 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2496                                        Value *RHS) {
2497   Type *ITy = GetCompareTy(RHS); // The return type.
2498
2499   Value *X;
2500   // Sign-bit checks can be optimized to true/false after unsigned
2501   // floating-point casts:
2502   // icmp slt (bitcast (uitofp X)),  0 --> false
2503   // icmp sgt (bitcast (uitofp X)), -1 --> true
2504   if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
2505     if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
2506       return ConstantInt::getFalse(ITy);
2507     if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
2508       return ConstantInt::getTrue(ITy);
2509   }
2510
2511   const APInt *C;
2512   if (!match(RHS, m_APInt(C)))
2513     return nullptr;
2514
2515   // Rule out tautological comparisons (eg., ult 0 or uge 0).
2516   ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
2517   if (RHS_CR.isEmptySet())
2518     return ConstantInt::getFalse(ITy);
2519   if (RHS_CR.isFullSet())
2520     return ConstantInt::getTrue(ITy);
2521
2522   // Find the range of possible values for binary operators.
2523   unsigned Width = C->getBitWidth();
2524   APInt Lower = APInt(Width, 0);
2525   APInt Upper = APInt(Width, 0);
2526   if (auto *BO = dyn_cast<BinaryOperator>(LHS))
2527     setLimitsForBinOp(*BO, Lower, Upper);
2528
2529   ConstantRange LHS_CR =
2530       Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2531
2532   if (auto *I = dyn_cast<Instruction>(LHS))
2533     if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2534       LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2535
2536   if (!LHS_CR.isFullSet()) {
2537     if (RHS_CR.contains(LHS_CR))
2538       return ConstantInt::getTrue(ITy);
2539     if (RHS_CR.inverse().contains(LHS_CR))
2540       return ConstantInt::getFalse(ITy);
2541   }
2542
2543   return nullptr;
2544 }
2545
2546 /// TODO: A large part of this logic is duplicated in InstCombine's
2547 /// foldICmpBinOp(). We should be able to share that and avoid the code
2548 /// duplication.
2549 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2550                                     Value *RHS, const SimplifyQuery &Q,
2551                                     unsigned MaxRecurse) {
2552   Type *ITy = GetCompareTy(LHS); // The return type.
2553
2554   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2555   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2556   if (MaxRecurse && (LBO || RBO)) {
2557     // Analyze the case when either LHS or RHS is an add instruction.
2558     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2559     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2560     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2561     if (LBO && LBO->getOpcode() == Instruction::Add) {
2562       A = LBO->getOperand(0);
2563       B = LBO->getOperand(1);
2564       NoLHSWrapProblem =
2565           ICmpInst::isEquality(Pred) ||
2566           (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2567           (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2568     }
2569     if (RBO && RBO->getOpcode() == Instruction::Add) {
2570       C = RBO->getOperand(0);
2571       D = RBO->getOperand(1);
2572       NoRHSWrapProblem =
2573           ICmpInst::isEquality(Pred) ||
2574           (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2575           (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2576     }
2577
2578     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2579     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2580       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2581                                       Constant::getNullValue(RHS->getType()), Q,
2582                                       MaxRecurse - 1))
2583         return V;
2584
2585     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2586     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2587       if (Value *V =
2588               SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2589                                C == LHS ? D : C, Q, MaxRecurse - 1))
2590         return V;
2591
2592     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2593     if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2594         NoRHSWrapProblem) {
2595       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2596       Value *Y, *Z;
2597       if (A == C) {
2598         // C + B == C + D  ->  B == D
2599         Y = B;
2600         Z = D;
2601       } else if (A == D) {
2602         // D + B == C + D  ->  B == C
2603         Y = B;
2604         Z = C;
2605       } else if (B == C) {
2606         // A + C == C + D  ->  A == D
2607         Y = A;
2608         Z = D;
2609       } else {
2610         assert(B == D);
2611         // A + D == C + D  ->  A == C
2612         Y = A;
2613         Z = C;
2614       }
2615       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2616         return V;
2617     }
2618   }
2619
2620   {
2621     Value *Y = nullptr;
2622     // icmp pred (or X, Y), X
2623     if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2624       if (Pred == ICmpInst::ICMP_ULT)
2625         return getFalse(ITy);
2626       if (Pred == ICmpInst::ICMP_UGE)
2627         return getTrue(ITy);
2628
2629       if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2630         KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2631         KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2632         if (RHSKnown.isNonNegative() && YKnown.isNegative())
2633           return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2634         if (RHSKnown.isNegative() || YKnown.isNonNegative())
2635           return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2636       }
2637     }
2638     // icmp pred X, (or X, Y)
2639     if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2640       if (Pred == ICmpInst::ICMP_ULE)
2641         return getTrue(ITy);
2642       if (Pred == ICmpInst::ICMP_UGT)
2643         return getFalse(ITy);
2644
2645       if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2646         KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2647         KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2648         if (LHSKnown.isNonNegative() && YKnown.isNegative())
2649           return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2650         if (LHSKnown.isNegative() || YKnown.isNonNegative())
2651           return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2652       }
2653     }
2654   }
2655
2656   // icmp pred (and X, Y), X
2657   if (LBO && match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
2658     if (Pred == ICmpInst::ICMP_UGT)
2659       return getFalse(ITy);
2660     if (Pred == ICmpInst::ICMP_ULE)
2661       return getTrue(ITy);
2662   }
2663   // icmp pred X, (and X, Y)
2664   if (RBO && match(RBO, m_c_And(m_Value(), m_Specific(LHS)))) {
2665     if (Pred == ICmpInst::ICMP_UGE)
2666       return getTrue(ITy);
2667     if (Pred == ICmpInst::ICMP_ULT)
2668       return getFalse(ITy);
2669   }
2670
2671   // 0 - (zext X) pred C
2672   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2673     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2674       if (RHSC->getValue().isStrictlyPositive()) {
2675         if (Pred == ICmpInst::ICMP_SLT)
2676           return ConstantInt::getTrue(RHSC->getContext());
2677         if (Pred == ICmpInst::ICMP_SGE)
2678           return ConstantInt::getFalse(RHSC->getContext());
2679         if (Pred == ICmpInst::ICMP_EQ)
2680           return ConstantInt::getFalse(RHSC->getContext());
2681         if (Pred == ICmpInst::ICMP_NE)
2682           return ConstantInt::getTrue(RHSC->getContext());
2683       }
2684       if (RHSC->getValue().isNonNegative()) {
2685         if (Pred == ICmpInst::ICMP_SLE)
2686           return ConstantInt::getTrue(RHSC->getContext());
2687         if (Pred == ICmpInst::ICMP_SGT)
2688           return ConstantInt::getFalse(RHSC->getContext());
2689       }
2690     }
2691   }
2692
2693   // icmp pred (urem X, Y), Y
2694   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2695     switch (Pred) {
2696     default:
2697       break;
2698     case ICmpInst::ICMP_SGT:
2699     case ICmpInst::ICMP_SGE: {
2700       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2701       if (!Known.isNonNegative())
2702         break;
2703       LLVM_FALLTHROUGH;
2704     }
2705     case ICmpInst::ICMP_EQ:
2706     case ICmpInst::ICMP_UGT:
2707     case ICmpInst::ICMP_UGE:
2708       return getFalse(ITy);
2709     case ICmpInst::ICMP_SLT:
2710     case ICmpInst::ICMP_SLE: {
2711       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2712       if (!Known.isNonNegative())
2713         break;
2714       LLVM_FALLTHROUGH;
2715     }
2716     case ICmpInst::ICMP_NE:
2717     case ICmpInst::ICMP_ULT:
2718     case ICmpInst::ICMP_ULE:
2719       return getTrue(ITy);
2720     }
2721   }
2722
2723   // icmp pred X, (urem Y, X)
2724   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2725     switch (Pred) {
2726     default:
2727       break;
2728     case ICmpInst::ICMP_SGT:
2729     case ICmpInst::ICMP_SGE: {
2730       KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2731       if (!Known.isNonNegative())
2732         break;
2733       LLVM_FALLTHROUGH;
2734     }
2735     case ICmpInst::ICMP_NE:
2736     case ICmpInst::ICMP_UGT:
2737     case ICmpInst::ICMP_UGE:
2738       return getTrue(ITy);
2739     case ICmpInst::ICMP_SLT:
2740     case ICmpInst::ICMP_SLE: {
2741       KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2742       if (!Known.isNonNegative())
2743         break;
2744       LLVM_FALLTHROUGH;
2745     }
2746     case ICmpInst::ICMP_EQ:
2747     case ICmpInst::ICMP_ULT:
2748     case ICmpInst::ICMP_ULE:
2749       return getFalse(ITy);
2750     }
2751   }
2752
2753   // x >> y <=u x
2754   // x udiv y <=u x.
2755   if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2756               match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2757     // icmp pred (X op Y), X
2758     if (Pred == ICmpInst::ICMP_UGT)
2759       return getFalse(ITy);
2760     if (Pred == ICmpInst::ICMP_ULE)
2761       return getTrue(ITy);
2762   }
2763
2764   // x >=u x >> y
2765   // x >=u x udiv y.
2766   if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2767               match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2768     // icmp pred X, (X op Y)
2769     if (Pred == ICmpInst::ICMP_ULT)
2770       return getFalse(ITy);
2771     if (Pred == ICmpInst::ICMP_UGE)
2772       return getTrue(ITy);
2773   }
2774
2775   // handle:
2776   //   CI2 << X == CI
2777   //   CI2 << X != CI
2778   //
2779   //   where CI2 is a power of 2 and CI isn't
2780   if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2781     const APInt *CI2Val, *CIVal = &CI->getValue();
2782     if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2783         CI2Val->isPowerOf2()) {
2784       if (!CIVal->isPowerOf2()) {
2785         // CI2 << X can equal zero in some circumstances,
2786         // this simplification is unsafe if CI is zero.
2787         //
2788         // We know it is safe if:
2789         // - The shift is nsw, we can't shift out the one bit.
2790         // - The shift is nuw, we can't shift out the one bit.
2791         // - CI2 is one
2792         // - CI isn't zero
2793         if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2794             CI2Val->isOneValue() || !CI->isZero()) {
2795           if (Pred == ICmpInst::ICMP_EQ)
2796             return ConstantInt::getFalse(RHS->getContext());
2797           if (Pred == ICmpInst::ICMP_NE)
2798             return ConstantInt::getTrue(RHS->getContext());
2799         }
2800       }
2801       if (CIVal->isSignMask() && CI2Val->isOneValue()) {
2802         if (Pred == ICmpInst::ICMP_UGT)
2803           return ConstantInt::getFalse(RHS->getContext());
2804         if (Pred == ICmpInst::ICMP_ULE)
2805           return ConstantInt::getTrue(RHS->getContext());
2806       }
2807     }
2808   }
2809
2810   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2811       LBO->getOperand(1) == RBO->getOperand(1)) {
2812     switch (LBO->getOpcode()) {
2813     default:
2814       break;
2815     case Instruction::UDiv:
2816     case Instruction::LShr:
2817       if (ICmpInst::isSigned(Pred) || !LBO->isExact() || !RBO->isExact())
2818         break;
2819       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2820                                       RBO->getOperand(0), Q, MaxRecurse - 1))
2821           return V;
2822       break;
2823     case Instruction::SDiv:
2824       if (!ICmpInst::isEquality(Pred) || !LBO->isExact() || !RBO->isExact())
2825         break;
2826       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2827                                       RBO->getOperand(0), Q, MaxRecurse - 1))
2828         return V;
2829       break;
2830     case Instruction::AShr:
2831       if (!LBO->isExact() || !RBO->isExact())
2832         break;
2833       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2834                                       RBO->getOperand(0), Q, MaxRecurse - 1))
2835         return V;
2836       break;
2837     case Instruction::Shl: {
2838       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2839       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2840       if (!NUW && !NSW)
2841         break;
2842       if (!NSW && ICmpInst::isSigned(Pred))
2843         break;
2844       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2845                                       RBO->getOperand(0), Q, MaxRecurse - 1))
2846         return V;
2847       break;
2848     }
2849     }
2850   }
2851   return nullptr;
2852 }
2853
2854 /// Simplify integer comparisons where at least one operand of the compare
2855 /// matches an integer min/max idiom.
2856 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
2857                                      Value *RHS, const SimplifyQuery &Q,
2858                                      unsigned MaxRecurse) {
2859   Type *ITy = GetCompareTy(LHS); // The return type.
2860   Value *A, *B;
2861   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2862   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2863
2864   // Signed variants on "max(a,b)>=a -> true".
2865   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2866     if (A != RHS)
2867       std::swap(A, B);       // smax(A, B) pred A.
2868     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2869     // We analyze this as smax(A, B) pred A.
2870     P = Pred;
2871   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2872              (A == LHS || B == LHS)) {
2873     if (A != LHS)
2874       std::swap(A, B);       // A pred smax(A, B).
2875     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2876     // We analyze this as smax(A, B) swapped-pred A.
2877     P = CmpInst::getSwappedPredicate(Pred);
2878   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2879              (A == RHS || B == RHS)) {
2880     if (A != RHS)
2881       std::swap(A, B);       // smin(A, B) pred A.
2882     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2883     // We analyze this as smax(-A, -B) swapped-pred -A.
2884     // Note that we do not need to actually form -A or -B thanks to EqP.
2885     P = CmpInst::getSwappedPredicate(Pred);
2886   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2887              (A == LHS || B == LHS)) {
2888     if (A != LHS)
2889       std::swap(A, B);       // A pred smin(A, B).
2890     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2891     // We analyze this as smax(-A, -B) pred -A.
2892     // Note that we do not need to actually form -A or -B thanks to EqP.
2893     P = Pred;
2894   }
2895   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2896     // Cases correspond to "max(A, B) p A".
2897     switch (P) {
2898     default:
2899       break;
2900     case CmpInst::ICMP_EQ:
2901     case CmpInst::ICMP_SLE:
2902       // Equivalent to "A EqP B".  This may be the same as the condition tested
2903       // in the max/min; if so, we can just return that.
2904       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2905         return V;
2906       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2907         return V;
2908       // Otherwise, see if "A EqP B" simplifies.
2909       if (MaxRecurse)
2910         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2911           return V;
2912       break;
2913     case CmpInst::ICMP_NE:
2914     case CmpInst::ICMP_SGT: {
2915       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2916       // Equivalent to "A InvEqP B".  This may be the same as the condition
2917       // tested in the max/min; if so, we can just return that.
2918       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2919         return V;
2920       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2921         return V;
2922       // Otherwise, see if "A InvEqP B" simplifies.
2923       if (MaxRecurse)
2924         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2925           return V;
2926       break;
2927     }
2928     case CmpInst::ICMP_SGE:
2929       // Always true.
2930       return getTrue(ITy);
2931     case CmpInst::ICMP_SLT:
2932       // Always false.
2933       return getFalse(ITy);
2934     }
2935   }
2936
2937   // Unsigned variants on "max(a,b)>=a -> true".
2938   P = CmpInst::BAD_ICMP_PREDICATE;
2939   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2940     if (A != RHS)
2941       std::swap(A, B);       // umax(A, B) pred A.
2942     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2943     // We analyze this as umax(A, B) pred A.
2944     P = Pred;
2945   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2946              (A == LHS || B == LHS)) {
2947     if (A != LHS)
2948       std::swap(A, B);       // A pred umax(A, B).
2949     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2950     // We analyze this as umax(A, B) swapped-pred A.
2951     P = CmpInst::getSwappedPredicate(Pred);
2952   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2953              (A == RHS || B == RHS)) {
2954     if (A != RHS)
2955       std::swap(A, B);       // umin(A, B) pred A.
2956     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2957     // We analyze this as umax(-A, -B) swapped-pred -A.
2958     // Note that we do not need to actually form -A or -B thanks to EqP.
2959     P = CmpInst::getSwappedPredicate(Pred);
2960   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2961              (A == LHS || B == LHS)) {
2962     if (A != LHS)
2963       std::swap(A, B);       // A pred umin(A, B).
2964     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2965     // We analyze this as umax(-A, -B) pred -A.
2966     // Note that we do not need to actually form -A or -B thanks to EqP.
2967     P = Pred;
2968   }
2969   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2970     // Cases correspond to "max(A, B) p A".
2971     switch (P) {
2972     default:
2973       break;
2974     case CmpInst::ICMP_EQ:
2975     case CmpInst::ICMP_ULE:
2976       // Equivalent to "A EqP B".  This may be the same as the condition tested
2977       // in the max/min; if so, we can just return that.
2978       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2979         return V;
2980       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2981         return V;
2982       // Otherwise, see if "A EqP B" simplifies.
2983       if (MaxRecurse)
2984         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2985           return V;
2986       break;
2987     case CmpInst::ICMP_NE:
2988     case CmpInst::ICMP_UGT: {
2989       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2990       // Equivalent to "A InvEqP B".  This may be the same as the condition
2991       // tested in the max/min; if so, we can just return that.
2992       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2993         return V;
2994       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2995         return V;
2996       // Otherwise, see if "A InvEqP B" simplifies.
2997       if (MaxRecurse)
2998         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2999           return V;
3000       break;
3001     }
3002     case CmpInst::ICMP_UGE:
3003       // Always true.
3004       return getTrue(ITy);
3005     case CmpInst::ICMP_ULT:
3006       // Always false.
3007       return getFalse(ITy);
3008     }
3009   }
3010
3011   // Variants on "max(x,y) >= min(x,z)".
3012   Value *C, *D;
3013   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3014       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3015       (A == C || A == D || B == C || B == D)) {
3016     // max(x, ?) pred min(x, ?).
3017     if (Pred == CmpInst::ICMP_SGE)
3018       // Always true.
3019       return getTrue(ITy);
3020     if (Pred == CmpInst::ICMP_SLT)
3021       // Always false.
3022       return getFalse(ITy);
3023   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3024              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3025              (A == C || A == D || B == C || B == D)) {
3026     // min(x, ?) pred max(x, ?).
3027     if (Pred == CmpInst::ICMP_SLE)
3028       // Always true.
3029       return getTrue(ITy);
3030     if (Pred == CmpInst::ICMP_SGT)
3031       // Always false.
3032       return getFalse(ITy);
3033   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3034              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3035              (A == C || A == D || B == C || B == D)) {
3036     // max(x, ?) pred min(x, ?).
3037     if (Pred == CmpInst::ICMP_UGE)
3038       // Always true.
3039       return getTrue(ITy);
3040     if (Pred == CmpInst::ICMP_ULT)
3041       // Always false.
3042       return getFalse(ITy);
3043   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3044              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3045              (A == C || A == D || B == C || B == D)) {
3046     // min(x, ?) pred max(x, ?).
3047     if (Pred == CmpInst::ICMP_ULE)
3048       // Always true.
3049       return getTrue(ITy);
3050     if (Pred == CmpInst::ICMP_UGT)
3051       // Always false.
3052       return getFalse(ITy);
3053   }
3054
3055   return nullptr;
3056 }
3057
3058 /// Given operands for an ICmpInst, see if we can fold the result.
3059 /// If not, this returns null.
3060 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3061                                const SimplifyQuery &Q, unsigned MaxRecurse) {
3062   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3063   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3064
3065   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3066     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3067       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3068
3069     // If we have a constant, make sure it is on the RHS.
3070     std::swap(LHS, RHS);
3071     Pred = CmpInst::getSwappedPredicate(Pred);
3072   }
3073
3074   Type *ITy = GetCompareTy(LHS); // The return type.
3075
3076   // icmp X, X -> true/false
3077   // icmp X, undef -> true/false because undef could be X.
3078   if (LHS == RHS || isa<UndefValue>(RHS))
3079     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3080
3081   if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3082     return V;
3083
3084   if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3085     return V;
3086
3087   if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
3088     return V;
3089
3090   // If both operands have range metadata, use the metadata
3091   // to simplify the comparison.
3092   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3093     auto RHS_Instr = cast<Instruction>(RHS);
3094     auto LHS_Instr = cast<Instruction>(LHS);
3095
3096     if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
3097         LHS_Instr->getMetadata(LLVMContext::MD_range)) {
3098       auto RHS_CR = getConstantRangeFromMetadata(
3099           *RHS_Instr->getMetadata(LLVMContext::MD_range));
3100       auto LHS_CR = getConstantRangeFromMetadata(
3101           *LHS_Instr->getMetadata(LLVMContext::MD_range));
3102
3103       auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3104       if (Satisfied_CR.contains(LHS_CR))
3105         return ConstantInt::getTrue(RHS->getContext());
3106
3107       auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3108                 CmpInst::getInversePredicate(Pred), RHS_CR);
3109       if (InversedSatisfied_CR.contains(LHS_CR))
3110         return ConstantInt::getFalse(RHS->getContext());
3111     }
3112   }
3113
3114   // Compare of cast, for example (zext X) != 0 -> X != 0
3115   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3116     Instruction *LI = cast<CastInst>(LHS);
3117     Value *SrcOp = LI->getOperand(0);
3118     Type *SrcTy = SrcOp->getType();
3119     Type *DstTy = LI->getType();
3120
3121     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3122     // if the integer type is the same size as the pointer type.
3123     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3124         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3125       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3126         // Transfer the cast to the constant.
3127         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3128                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
3129                                         Q, MaxRecurse-1))
3130           return V;
3131       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3132         if (RI->getOperand(0)->getType() == SrcTy)
3133           // Compare without the cast.
3134           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3135                                           Q, MaxRecurse-1))
3136             return V;
3137       }
3138     }
3139
3140     if (isa<ZExtInst>(LHS)) {
3141       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3142       // same type.
3143       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3144         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3145           // Compare X and Y.  Note that signed predicates become unsigned.
3146           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3147                                           SrcOp, RI->getOperand(0), Q,
3148                                           MaxRecurse-1))
3149             return V;
3150       }
3151       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3152       // too.  If not, then try to deduce the result of the comparison.
3153       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3154         // Compute the constant that would happen if we truncated to SrcTy then
3155         // reextended to DstTy.
3156         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3157         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3158
3159         // If the re-extended constant didn't change then this is effectively
3160         // also a case of comparing two zero-extended values.
3161         if (RExt == CI && MaxRecurse)
3162           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3163                                         SrcOp, Trunc, Q, MaxRecurse-1))
3164             return V;
3165
3166         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3167         // there.  Use this to work out the result of the comparison.
3168         if (RExt != CI) {
3169           switch (Pred) {
3170           default: llvm_unreachable("Unknown ICmp predicate!");
3171           // LHS <u RHS.
3172           case ICmpInst::ICMP_EQ:
3173           case ICmpInst::ICMP_UGT:
3174           case ICmpInst::ICMP_UGE:
3175             return ConstantInt::getFalse(CI->getContext());
3176
3177           case ICmpInst::ICMP_NE:
3178           case ICmpInst::ICMP_ULT:
3179           case ICmpInst::ICMP_ULE:
3180             return ConstantInt::getTrue(CI->getContext());
3181
3182           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
3183           // is non-negative then LHS <s RHS.
3184           case ICmpInst::ICMP_SGT:
3185           case ICmpInst::ICMP_SGE:
3186             return CI->getValue().isNegative() ?
3187               ConstantInt::getTrue(CI->getContext()) :
3188               ConstantInt::getFalse(CI->getContext());
3189
3190           case ICmpInst::ICMP_SLT:
3191           case ICmpInst::ICMP_SLE:
3192             return CI->getValue().isNegative() ?
3193               ConstantInt::getFalse(CI->getContext()) :
3194               ConstantInt::getTrue(CI->getContext());
3195           }
3196         }
3197       }
3198     }
3199
3200     if (isa<SExtInst>(LHS)) {
3201       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3202       // same type.
3203       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3204         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3205           // Compare X and Y.  Note that the predicate does not change.
3206           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3207                                           Q, MaxRecurse-1))
3208             return V;
3209       }
3210       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3211       // too.  If not, then try to deduce the result of the comparison.
3212       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3213         // Compute the constant that would happen if we truncated to SrcTy then
3214         // reextended to DstTy.
3215         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3216         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3217
3218         // If the re-extended constant didn't change then this is effectively
3219         // also a case of comparing two sign-extended values.
3220         if (RExt == CI && MaxRecurse)
3221           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
3222             return V;
3223
3224         // Otherwise the upper bits of LHS are all equal, while RHS has varying
3225         // bits there.  Use this to work out the result of the comparison.
3226         if (RExt != CI) {
3227           switch (Pred) {
3228           default: llvm_unreachable("Unknown ICmp predicate!");
3229           case ICmpInst::ICMP_EQ:
3230             return ConstantInt::getFalse(CI->getContext());
3231           case ICmpInst::ICMP_NE:
3232             return ConstantInt::getTrue(CI->getContext());
3233
3234           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
3235           // LHS >s RHS.
3236           case ICmpInst::ICMP_SGT:
3237           case ICmpInst::ICMP_SGE:
3238             return CI->getValue().isNegative() ?
3239               ConstantInt::getTrue(CI->getContext()) :
3240               ConstantInt::getFalse(CI->getContext());
3241           case ICmpInst::ICMP_SLT:
3242           case ICmpInst::ICMP_SLE:
3243             return CI->getValue().isNegative() ?
3244               ConstantInt::getFalse(CI->getContext()) :
3245               ConstantInt::getTrue(CI->getContext());
3246
3247           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
3248           // LHS >u RHS.
3249           case ICmpInst::ICMP_UGT:
3250           case ICmpInst::ICMP_UGE:
3251             // Comparison is true iff the LHS <s 0.
3252             if (MaxRecurse)
3253               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3254                                               Constant::getNullValue(SrcTy),
3255                                               Q, MaxRecurse-1))
3256                 return V;
3257             break;
3258           case ICmpInst::ICMP_ULT:
3259           case ICmpInst::ICMP_ULE:
3260             // Comparison is true iff the LHS >=s 0.
3261             if (MaxRecurse)
3262               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3263                                               Constant::getNullValue(SrcTy),
3264                                               Q, MaxRecurse-1))
3265                 return V;
3266             break;
3267           }
3268         }
3269       }
3270     }
3271   }
3272
3273   // icmp eq|ne X, Y -> false|true if X != Y
3274   if (ICmpInst::isEquality(Pred) &&
3275       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
3276     return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
3277   }
3278
3279   if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3280     return V;
3281
3282   if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
3283     return V;
3284
3285   // Simplify comparisons of related pointers using a powerful, recursive
3286   // GEP-walk when we have target data available..
3287   if (LHS->getType()->isPointerTy())
3288     if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI, LHS,
3289                                      RHS))
3290       return C;
3291   if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3292     if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3293       if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3294               Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3295           Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3296               Q.DL.getTypeSizeInBits(CRHS->getType()))
3297         if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3298                                          CLHS->getPointerOperand(),
3299                                          CRHS->getPointerOperand()))
3300           return C;
3301
3302   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3303     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3304       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3305           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3306           (ICmpInst::isEquality(Pred) ||
3307            (GLHS->isInBounds() && GRHS->isInBounds() &&
3308             Pred == ICmpInst::getSignedPredicate(Pred)))) {
3309         // The bases are equal and the indices are constant.  Build a constant
3310         // expression GEP with the same indices and a null base pointer to see
3311         // what constant folding can make out of it.
3312         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3313         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
3314         Constant *NewLHS = ConstantExpr::getGetElementPtr(
3315             GLHS->getSourceElementType(), Null, IndicesLHS);
3316
3317         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3318         Constant *NewRHS = ConstantExpr::getGetElementPtr(
3319             GLHS->getSourceElementType(), Null, IndicesRHS);
3320         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3321       }
3322     }
3323   }
3324
3325   // If the comparison is with the result of a select instruction, check whether
3326   // comparing with either branch of the select always yields the same value.
3327   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3328     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3329       return V;
3330
3331   // If the comparison is with the result of a phi instruction, check whether
3332   // doing the compare with each incoming phi value yields a common result.
3333   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3334     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3335       return V;
3336
3337   return nullptr;
3338 }
3339
3340 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3341                               const SimplifyQuery &Q) {
3342   return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3343 }
3344
3345 /// Given operands for an FCmpInst, see if we can fold the result.
3346 /// If not, this returns null.
3347 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3348                                FastMathFlags FMF, const SimplifyQuery &Q,
3349                                unsigned MaxRecurse) {
3350   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3351   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3352
3353   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3354     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3355       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3356
3357     // If we have a constant, make sure it is on the RHS.
3358     std::swap(LHS, RHS);
3359     Pred = CmpInst::getSwappedPredicate(Pred);
3360   }
3361
3362   // Fold trivial predicates.
3363   Type *RetTy = GetCompareTy(LHS);
3364   if (Pred == FCmpInst::FCMP_FALSE)
3365     return getFalse(RetTy);
3366   if (Pred == FCmpInst::FCMP_TRUE)
3367     return getTrue(RetTy);
3368
3369   // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3370   if (FMF.noNaNs()) {
3371     if (Pred == FCmpInst::FCMP_UNO)
3372       return getFalse(RetTy);
3373     if (Pred == FCmpInst::FCMP_ORD)
3374       return getTrue(RetTy);
3375   }
3376
3377   // NaN is unordered; NaN is not ordered.
3378   assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3379          "Comparison must be either ordered or unordered");
3380   if (match(RHS, m_NaN()))
3381     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3382
3383   // fcmp pred x, undef  and  fcmp pred undef, x
3384   // fold to true if unordered, false if ordered
3385   if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3386     // Choosing NaN for the undef will always make unordered comparison succeed
3387     // and ordered comparison fail.
3388     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3389   }
3390
3391   // fcmp x,x -> true/false.  Not all compares are foldable.
3392   if (LHS == RHS) {
3393     if (CmpInst::isTrueWhenEqual(Pred))
3394       return getTrue(RetTy);
3395     if (CmpInst::isFalseWhenEqual(Pred))
3396       return getFalse(RetTy);
3397   }
3398
3399   // Handle fcmp with constant RHS.
3400   const APFloat *C;
3401   if (match(RHS, m_APFloat(C))) {
3402     // Check whether the constant is an infinity.
3403     if (C->isInfinity()) {
3404       if (C->isNegative()) {
3405         switch (Pred) {
3406         case FCmpInst::FCMP_OLT:
3407           // No value is ordered and less than negative infinity.
3408           return getFalse(RetTy);
3409         case FCmpInst::FCMP_UGE:
3410           // All values are unordered with or at least negative infinity.
3411           return getTrue(RetTy);
3412         default:
3413           break;
3414         }
3415       } else {
3416         switch (Pred) {
3417         case FCmpInst::FCMP_OGT:
3418           // No value is ordered and greater than infinity.
3419           return getFalse(RetTy);
3420         case FCmpInst::FCMP_ULE:
3421           // All values are unordered with and at most infinity.
3422           return getTrue(RetTy);
3423         default:
3424           break;
3425         }
3426       }
3427     }
3428     if (C->isZero()) {
3429       switch (Pred) {
3430       case FCmpInst::FCMP_UGE:
3431         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3432           return getTrue(RetTy);
3433         break;
3434       case FCmpInst::FCMP_OLT:
3435         // X < 0
3436         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3437           return getFalse(RetTy);
3438         break;
3439       default:
3440         break;
3441       }
3442     } else if (C->isNegative()) {
3443       assert(!C->isNaN() && "Unexpected NaN constant!");
3444       // TODO: We can catch more cases by using a range check rather than
3445       //       relying on CannotBeOrderedLessThanZero.
3446       switch (Pred) {
3447       case FCmpInst::FCMP_UGE:
3448       case FCmpInst::FCMP_UGT:
3449       case FCmpInst::FCMP_UNE:
3450         // (X >= 0) implies (X > C) when (C < 0)
3451         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3452           return getTrue(RetTy);
3453         break;
3454       case FCmpInst::FCMP_OEQ:
3455       case FCmpInst::FCMP_OLE:
3456       case FCmpInst::FCMP_OLT:
3457         // (X >= 0) implies !(X < C) when (C < 0)
3458         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3459           return getFalse(RetTy);
3460         break;
3461       default:
3462         break;
3463       }
3464     }
3465   }
3466
3467   // If the comparison is with the result of a select instruction, check whether
3468   // comparing with either branch of the select always yields the same value.
3469   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3470     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3471       return V;
3472
3473   // If the comparison is with the result of a phi instruction, check whether
3474   // doing the compare with each incoming phi value yields a common result.
3475   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3476     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3477       return V;
3478
3479   return nullptr;
3480 }
3481
3482 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3483                               FastMathFlags FMF, const SimplifyQuery &Q) {
3484   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
3485 }
3486
3487 /// See if V simplifies when its operand Op is replaced with RepOp.
3488 static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3489                                            const SimplifyQuery &Q,
3490                                            unsigned MaxRecurse) {
3491   // Trivial replacement.
3492   if (V == Op)
3493     return RepOp;
3494
3495   // We cannot replace a constant, and shouldn't even try.
3496   if (isa<Constant>(Op))
3497     return nullptr;
3498
3499   auto *I = dyn_cast<Instruction>(V);
3500   if (!I)
3501     return nullptr;
3502
3503   // If this is a binary operator, try to simplify it with the replaced op.
3504   if (auto *B = dyn_cast<BinaryOperator>(I)) {
3505     // Consider:
3506     //   %cmp = icmp eq i32 %x, 2147483647
3507     //   %add = add nsw i32 %x, 1
3508     //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
3509     //
3510     // We can't replace %sel with %add unless we strip away the flags.
3511     if (isa<OverflowingBinaryOperator>(B))
3512       if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3513         return nullptr;
3514     if (isa<PossiblyExactOperator>(B))
3515       if (B->isExact())
3516         return nullptr;
3517
3518     if (MaxRecurse) {
3519       if (B->getOperand(0) == Op)
3520         return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3521                              MaxRecurse - 1);
3522       if (B->getOperand(1) == Op)
3523         return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3524                              MaxRecurse - 1);
3525     }
3526   }
3527
3528   // Same for CmpInsts.
3529   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3530     if (MaxRecurse) {
3531       if (C->getOperand(0) == Op)
3532         return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3533                                MaxRecurse - 1);
3534       if (C->getOperand(1) == Op)
3535         return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3536                                MaxRecurse - 1);
3537     }
3538   }
3539
3540   // Same for GEPs.
3541   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3542     if (MaxRecurse) {
3543       SmallVector<Value *, 8> NewOps(GEP->getNumOperands());
3544       transform(GEP->operands(), NewOps.begin(),
3545                 [&](Value *V) { return V == Op ? RepOp : V; });
3546       return SimplifyGEPInst(GEP->getSourceElementType(), NewOps, Q,
3547                              MaxRecurse - 1);
3548     }
3549   }
3550
3551   // TODO: We could hand off more cases to instsimplify here.
3552
3553   // If all operands are constant after substituting Op for RepOp then we can
3554   // constant fold the instruction.
3555   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3556     // Build a list of all constant operands.
3557     SmallVector<Constant *, 8> ConstOps;
3558     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3559       if (I->getOperand(i) == Op)
3560         ConstOps.push_back(CRepOp);
3561       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3562         ConstOps.push_back(COp);
3563       else
3564         break;
3565     }
3566
3567     // All operands were constants, fold it.
3568     if (ConstOps.size() == I->getNumOperands()) {
3569       if (CmpInst *C = dyn_cast<CmpInst>(I))
3570         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3571                                                ConstOps[1], Q.DL, Q.TLI);
3572
3573       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3574         if (!LI->isVolatile())
3575           return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
3576
3577       return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
3578     }
3579   }
3580
3581   return nullptr;
3582 }
3583
3584 /// Try to simplify a select instruction when its condition operand is an
3585 /// integer comparison where one operand of the compare is a constant.
3586 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3587                                     const APInt *Y, bool TrueWhenUnset) {
3588   const APInt *C;
3589
3590   // (X & Y) == 0 ? X & ~Y : X  --> X
3591   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
3592   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3593       *Y == ~*C)
3594     return TrueWhenUnset ? FalseVal : TrueVal;
3595
3596   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
3597   // (X & Y) != 0 ? X : X & ~Y  --> X
3598   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3599       *Y == ~*C)
3600     return TrueWhenUnset ? FalseVal : TrueVal;
3601
3602   if (Y->isPowerOf2()) {
3603     // (X & Y) == 0 ? X | Y : X  --> X | Y
3604     // (X & Y) != 0 ? X | Y : X  --> X
3605     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3606         *Y == *C)
3607       return TrueWhenUnset ? TrueVal : FalseVal;
3608
3609     // (X & Y) == 0 ? X : X | Y  --> X
3610     // (X & Y) != 0 ? X : X | Y  --> X | Y
3611     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3612         *Y == *C)
3613       return TrueWhenUnset ? TrueVal : FalseVal;
3614   }
3615
3616   return nullptr;
3617 }
3618
3619 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
3620 /// eq/ne.
3621 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
3622                                            ICmpInst::Predicate Pred,
3623                                            Value *TrueVal, Value *FalseVal) {
3624   Value *X;
3625   APInt Mask;
3626   if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
3627     return nullptr;
3628
3629   return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
3630                                Pred == ICmpInst::ICMP_EQ);
3631 }
3632
3633 /// Try to simplify a select instruction when its condition operand is an
3634 /// integer comparison.
3635 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3636                                          Value *FalseVal, const SimplifyQuery &Q,
3637                                          unsigned MaxRecurse) {
3638   ICmpInst::Predicate Pred;
3639   Value *CmpLHS, *CmpRHS;
3640   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3641     return nullptr;
3642
3643   if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3644     Value *X;
3645     const APInt *Y;
3646     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3647       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3648                                            Pred == ICmpInst::ICMP_EQ))
3649         return V;
3650   }
3651
3652   // Check for other compares that behave like bit test.
3653   if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
3654                                               TrueVal, FalseVal))
3655     return V;
3656
3657   // If we have an equality comparison, then we know the value in one of the
3658   // arms of the select. See if substituting this value into the arm and
3659   // simplifying the result yields the same value as the other arm.
3660   if (Pred == ICmpInst::ICMP_EQ) {
3661     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3662             TrueVal ||
3663         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3664             TrueVal)
3665       return FalseVal;
3666     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3667             FalseVal ||
3668         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3669             FalseVal)
3670       return FalseVal;
3671   } else if (Pred == ICmpInst::ICMP_NE) {
3672     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3673             FalseVal ||
3674         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3675             FalseVal)
3676       return TrueVal;
3677     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3678             TrueVal ||
3679         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3680             TrueVal)
3681       return TrueVal;
3682   }
3683
3684   return nullptr;
3685 }
3686
3687 /// Given operands for a SelectInst, see if we can fold the result.
3688 /// If not, this returns null.
3689 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3690                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
3691   if (auto *CondC = dyn_cast<Constant>(Cond)) {
3692     if (auto *TrueC = dyn_cast<Constant>(TrueVal))
3693       if (auto *FalseC = dyn_cast<Constant>(FalseVal))
3694         return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
3695
3696     // select undef, X, Y -> X or Y
3697     if (isa<UndefValue>(CondC))
3698       return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
3699
3700     // TODO: Vector constants with undef elements don't simplify.
3701
3702     // select true, X, Y  -> X
3703     if (CondC->isAllOnesValue())
3704       return TrueVal;
3705     // select false, X, Y -> Y
3706     if (CondC->isNullValue())
3707       return FalseVal;
3708   }
3709
3710   // select ?, X, X -> X
3711   if (TrueVal == FalseVal)
3712     return TrueVal;
3713
3714   if (isa<UndefValue>(TrueVal))   // select ?, undef, X -> X
3715     return FalseVal;
3716   if (isa<UndefValue>(FalseVal))   // select ?, X, undef -> X
3717     return TrueVal;
3718
3719   if (Value *V =
3720           simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
3721     return V;
3722
3723   return nullptr;
3724 }
3725
3726 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3727                                 const SimplifyQuery &Q) {
3728   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
3729 }
3730
3731 /// Given operands for an GetElementPtrInst, see if we can fold the result.
3732 /// If not, this returns null.
3733 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3734                               const SimplifyQuery &Q, unsigned) {
3735   // The type of the GEP pointer operand.
3736   unsigned AS =
3737       cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
3738
3739   // getelementptr P -> P.
3740   if (Ops.size() == 1)
3741     return Ops[0];
3742
3743   // Compute the (pointer) type returned by the GEP instruction.
3744   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
3745   Type *GEPTy = PointerType::get(LastType, AS);
3746   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3747     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3748   else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
3749     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3750
3751   if (isa<UndefValue>(Ops[0]))
3752     return UndefValue::get(GEPTy);
3753
3754   if (Ops.size() == 2) {
3755     // getelementptr P, 0 -> P.
3756     if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy)
3757       return Ops[0];
3758
3759     Type *Ty = SrcTy;
3760     if (Ty->isSized()) {
3761       Value *P;
3762       uint64_t C;
3763       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
3764       // getelementptr P, N -> P if P points to a type of zero size.
3765       if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy)
3766         return Ops[0];
3767
3768       // The following transforms are only safe if the ptrtoint cast
3769       // doesn't truncate the pointers.
3770       if (Ops[1]->getType()->getScalarSizeInBits() ==
3771           Q.DL.getIndexSizeInBits(AS)) {
3772         auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3773           if (match(P, m_Zero()))
3774             return Constant::getNullValue(GEPTy);
3775           Value *Temp;
3776           if (match(P, m_PtrToInt(m_Value(Temp))))
3777             if (Temp->getType() == GEPTy)
3778               return Temp;
3779           return nullptr;
3780         };
3781
3782         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3783         if (TyAllocSize == 1 &&
3784             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3785           if (Value *R = PtrToIntOrZero(P))
3786             return R;
3787
3788         // getelementptr V, (ashr (sub P, V), C) -> Q
3789         // if P points to a type of size 1 << C.
3790         if (match(Ops[1],
3791                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3792                          m_ConstantInt(C))) &&
3793             TyAllocSize == 1ULL << C)
3794           if (Value *R = PtrToIntOrZero(P))
3795             return R;
3796
3797         // getelementptr V, (sdiv (sub P, V), C) -> Q
3798         // if P points to a type of size C.
3799         if (match(Ops[1],
3800                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3801                          m_SpecificInt(TyAllocSize))))
3802           if (Value *R = PtrToIntOrZero(P))
3803             return R;
3804       }
3805     }
3806   }
3807
3808   if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3809       all_of(Ops.slice(1).drop_back(1),
3810              [](Value *Idx) { return match(Idx, m_Zero()); })) {
3811     unsigned IdxWidth =
3812         Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3813     if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) {
3814       APInt BasePtrOffset(IdxWidth, 0);
3815       Value *StrippedBasePtr =
3816           Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3817                                                             BasePtrOffset);
3818
3819       // gep (gep V, C), (sub 0, V) -> C
3820       if (match(Ops.back(),
3821                 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3822         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3823         return ConstantExpr::getIntToPtr(CI, GEPTy);
3824       }
3825       // gep (gep V, C), (xor V, -1) -> C-1
3826       if (match(Ops.back(),
3827                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3828         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3829         return ConstantExpr::getIntToPtr(CI, GEPTy);
3830       }
3831     }
3832   }
3833
3834   // Check to see if this is constant foldable.
3835   if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); }))
3836     return nullptr;
3837
3838   auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3839                                             Ops.slice(1));
3840   if (auto *CEFolded = ConstantFoldConstant(CE, Q.DL))
3841     return CEFolded;
3842   return CE;
3843 }
3844
3845 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3846                              const SimplifyQuery &Q) {
3847   return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
3848 }
3849
3850 /// Given operands for an InsertValueInst, see if we can fold the result.
3851 /// If not, this returns null.
3852 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3853                                       ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
3854                                       unsigned) {
3855   if (Constant *CAgg = dyn_cast<Constant>(Agg))
3856     if (Constant *CVal = dyn_cast<Constant>(Val))
3857       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3858
3859   // insertvalue x, undef, n -> x
3860   if (match(Val, m_Undef()))
3861     return Agg;
3862
3863   // insertvalue x, (extractvalue y, n), n
3864   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
3865     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3866         EV->getIndices() == Idxs) {
3867       // insertvalue undef, (extractvalue y, n), n -> y
3868       if (match(Agg, m_Undef()))
3869         return EV->getAggregateOperand();
3870
3871       // insertvalue y, (extractvalue y, n), n -> y
3872       if (Agg == EV->getAggregateOperand())
3873         return Agg;
3874     }
3875
3876   return nullptr;
3877 }
3878
3879 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
3880                                      ArrayRef<unsigned> Idxs,
3881                                      const SimplifyQuery &Q) {
3882   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
3883 }
3884
3885 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
3886                                        const SimplifyQuery &Q) {
3887   // Try to constant fold.
3888   auto *VecC = dyn_cast<Constant>(Vec);
3889   auto *ValC = dyn_cast<Constant>(Val);
3890   auto *IdxC = dyn_cast<Constant>(Idx);
3891   if (VecC && ValC && IdxC)
3892     return ConstantFoldInsertElementInstruction(VecC, ValC, IdxC);
3893
3894   // Fold into undef if index is out of bounds.
3895   if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
3896     uint64_t NumElements = cast<VectorType>(Vec->getType())->getNumElements();
3897     if (CI->uge(NumElements))
3898       return UndefValue::get(Vec->getType());
3899   }
3900
3901   // If index is undef, it might be out of bounds (see above case)
3902   if (isa<UndefValue>(Idx))
3903     return UndefValue::get(Vec->getType());
3904
3905   return nullptr;
3906 }
3907
3908 /// Given operands for an ExtractValueInst, see if we can fold the result.
3909 /// If not, this returns null.
3910 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3911                                        const SimplifyQuery &, unsigned) {
3912   if (auto *CAgg = dyn_cast<Constant>(Agg))
3913     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3914
3915   // extractvalue x, (insertvalue y, elt, n), n -> elt
3916   unsigned NumIdxs = Idxs.size();
3917   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3918        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3919     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3920     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3921     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3922     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3923         Idxs.slice(0, NumCommonIdxs)) {
3924       if (NumIdxs == NumInsertValueIdxs)
3925         return IVI->getInsertedValueOperand();
3926       break;
3927     }
3928   }
3929
3930   return nullptr;
3931 }
3932
3933 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3934                                       const SimplifyQuery &Q) {
3935   return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
3936 }
3937
3938 /// Given operands for an ExtractElementInst, see if we can fold the result.
3939 /// If not, this returns null.
3940 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &,
3941                                          unsigned) {
3942   if (auto *CVec = dyn_cast<Constant>(Vec)) {
3943     if (auto *CIdx = dyn_cast<Constant>(Idx))
3944       return ConstantFoldExtractElementInstruction(CVec, CIdx);
3945
3946     // The index is not relevant if our vector is a splat.
3947     if (auto *Splat = CVec->getSplatValue())
3948       return Splat;
3949
3950     if (isa<UndefValue>(Vec))
3951       return UndefValue::get(Vec->getType()->getVectorElementType());
3952   }
3953
3954   // If extracting a specified index from the vector, see if we can recursively
3955   // find a previously computed scalar that was inserted into the vector.
3956   if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
3957     if (IdxC->getValue().uge(Vec->getType()->getVectorNumElements()))
3958       // definitely out of bounds, thus undefined result
3959       return UndefValue::get(Vec->getType()->getVectorElementType());
3960     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
3961       return Elt;
3962   }
3963
3964   // An undef extract index can be arbitrarily chosen to be an out-of-range
3965   // index value, which would result in the instruction being undef.
3966   if (isa<UndefValue>(Idx))
3967     return UndefValue::get(Vec->getType()->getVectorElementType());
3968
3969   return nullptr;
3970 }
3971
3972 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
3973                                         const SimplifyQuery &Q) {
3974   return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
3975 }
3976
3977 /// See if we can fold the given phi. If not, returns null.
3978 static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
3979   // If all of the PHI's incoming values are the same then replace the PHI node
3980   // with the common value.
3981   Value *CommonValue = nullptr;
3982   bool HasUndefInput = false;
3983   for (Value *Incoming : PN->incoming_values()) {
3984     // If the incoming value is the phi node itself, it can safely be skipped.
3985     if (Incoming == PN) continue;
3986     if (isa<UndefValue>(Incoming)) {
3987       // Remember that we saw an undef value, but otherwise ignore them.
3988       HasUndefInput = true;
3989       continue;
3990     }
3991     if (CommonValue && Incoming != CommonValue)
3992       return nullptr;  // Not the same, bail out.
3993     CommonValue = Incoming;
3994   }
3995
3996   // If CommonValue is null then all of the incoming values were either undef or
3997   // equal to the phi node itself.
3998   if (!CommonValue)
3999     return UndefValue::get(PN->getType());
4000
4001   // If we have a PHI node like phi(X, undef, X), where X is defined by some
4002   // instruction, we cannot return X as the result of the PHI node unless it
4003   // dominates the PHI block.
4004   if (HasUndefInput)
4005     return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
4006
4007   return CommonValue;
4008 }
4009
4010 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4011                                Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
4012   if (auto *C = dyn_cast<Constant>(Op))
4013     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
4014
4015   if (auto *CI = dyn_cast<CastInst>(Op)) {
4016     auto *Src = CI->getOperand(0);
4017     Type *SrcTy = Src->getType();
4018     Type *MidTy = CI->getType();
4019     Type *DstTy = Ty;
4020     if (Src->getType() == Ty) {
4021       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4022       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4023       Type *SrcIntPtrTy =
4024           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4025       Type *MidIntPtrTy =
4026           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4027       Type *DstIntPtrTy =
4028           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4029       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4030                                          SrcIntPtrTy, MidIntPtrTy,
4031                                          DstIntPtrTy) == Instruction::BitCast)
4032         return Src;
4033     }
4034   }
4035
4036   // bitcast x -> x
4037   if (CastOpc == Instruction::BitCast)
4038     if (Op->getType() == Ty)
4039       return Op;
4040
4041   return nullptr;
4042 }
4043
4044 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4045                               const SimplifyQuery &Q) {
4046   return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4047 }
4048
4049 /// For the given destination element of a shuffle, peek through shuffles to
4050 /// match a root vector source operand that contains that element in the same
4051 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4052 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4053                                    int MaskVal, Value *RootVec,
4054                                    unsigned MaxRecurse) {
4055   if (!MaxRecurse--)
4056     return nullptr;
4057
4058   // Bail out if any mask value is undefined. That kind of shuffle may be
4059   // simplified further based on demanded bits or other folds.
4060   if (MaskVal == -1)
4061     return nullptr;
4062
4063   // The mask value chooses which source operand we need to look at next.
4064   int InVecNumElts = Op0->getType()->getVectorNumElements();
4065   int RootElt = MaskVal;
4066   Value *SourceOp = Op0;
4067   if (MaskVal >= InVecNumElts) {
4068     RootElt = MaskVal - InVecNumElts;
4069     SourceOp = Op1;
4070   }
4071
4072   // If the source operand is a shuffle itself, look through it to find the
4073   // matching root vector.
4074   if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4075     return foldIdentityShuffles(
4076         DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4077         SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
4078   }
4079
4080   // TODO: Look through bitcasts? What if the bitcast changes the vector element
4081   // size?
4082
4083   // The source operand is not a shuffle. Initialize the root vector value for
4084   // this shuffle if that has not been done yet.
4085   if (!RootVec)
4086     RootVec = SourceOp;
4087
4088   // Give up as soon as a source operand does not match the existing root value.
4089   if (RootVec != SourceOp)
4090     return nullptr;
4091
4092   // The element must be coming from the same lane in the source vector
4093   // (although it may have crossed lanes in intermediate shuffles).
4094   if (RootElt != DestElt)
4095     return nullptr;
4096
4097   return RootVec;
4098 }
4099
4100 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4101                                         Type *RetTy, const SimplifyQuery &Q,
4102                                         unsigned MaxRecurse) {
4103   if (isa<UndefValue>(Mask))
4104     return UndefValue::get(RetTy);
4105
4106   Type *InVecTy = Op0->getType();
4107   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
4108   unsigned InVecNumElts = InVecTy->getVectorNumElements();
4109
4110   SmallVector<int, 32> Indices;
4111   ShuffleVectorInst::getShuffleMask(Mask, Indices);
4112   assert(MaskNumElts == Indices.size() &&
4113          "Size of Indices not same as number of mask elements?");
4114
4115   // Canonicalization: If mask does not select elements from an input vector,
4116   // replace that input vector with undef.
4117   bool MaskSelects0 = false, MaskSelects1 = false;
4118   for (unsigned i = 0; i != MaskNumElts; ++i) {
4119     if (Indices[i] == -1)
4120       continue;
4121     if ((unsigned)Indices[i] < InVecNumElts)
4122       MaskSelects0 = true;
4123     else
4124       MaskSelects1 = true;
4125   }
4126   if (!MaskSelects0)
4127     Op0 = UndefValue::get(InVecTy);
4128   if (!MaskSelects1)
4129     Op1 = UndefValue::get(InVecTy);
4130
4131   auto *Op0Const = dyn_cast<Constant>(Op0);
4132   auto *Op1Const = dyn_cast<Constant>(Op1);
4133
4134   // If all operands are constant, constant fold the shuffle.
4135   if (Op0Const && Op1Const)
4136     return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
4137
4138   // Canonicalization: if only one input vector is constant, it shall be the
4139   // second one.
4140   if (Op0Const && !Op1Const) {
4141     std::swap(Op0, Op1);
4142     ShuffleVectorInst::commuteShuffleMask(Indices, InVecNumElts);
4143   }
4144
4145   // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4146   // value type is same as the input vectors' type.
4147   if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
4148     if (isa<UndefValue>(Op1) && RetTy == InVecTy &&
4149         OpShuf->getMask()->getSplatValue())
4150       return Op0;
4151
4152   // Don't fold a shuffle with undef mask elements. This may get folded in a
4153   // better way using demanded bits or other analysis.
4154   // TODO: Should we allow this?
4155   if (find(Indices, -1) != Indices.end())
4156     return nullptr;
4157
4158   // Check if every element of this shuffle can be mapped back to the
4159   // corresponding element of a single root vector. If so, we don't need this
4160   // shuffle. This handles simple identity shuffles as well as chains of
4161   // shuffles that may widen/narrow and/or move elements across lanes and back.
4162   Value *RootVec = nullptr;
4163   for (unsigned i = 0; i != MaskNumElts; ++i) {
4164     // Note that recursion is limited for each vector element, so if any element
4165     // exceeds the limit, this will fail to simplify.
4166     RootVec =
4167         foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
4168
4169     // We can't replace a widening/narrowing shuffle with one of its operands.
4170     if (!RootVec || RootVec->getType() != RetTy)
4171       return nullptr;
4172   }
4173   return RootVec;
4174 }
4175
4176 /// Given operands for a ShuffleVectorInst, fold the result or return null.
4177 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4178                                        Type *RetTy, const SimplifyQuery &Q) {
4179   return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
4180 }
4181
4182 static Constant *propagateNaN(Constant *In) {
4183   // If the input is a vector with undef elements, just return a default NaN.
4184   if (!In->isNaN())
4185     return ConstantFP::getNaN(In->getType());
4186
4187   // Propagate the existing NaN constant when possible.
4188   // TODO: Should we quiet a signaling NaN?
4189   return In;
4190 }
4191
4192 static Constant *simplifyFPBinop(Value *Op0, Value *Op1) {
4193   if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4194     return ConstantFP::getNaN(Op0->getType());
4195
4196   if (match(Op0, m_NaN()))
4197     return propagateNaN(cast<Constant>(Op0));
4198   if (match(Op1, m_NaN()))
4199     return propagateNaN(cast<Constant>(Op1));
4200
4201   return nullptr;
4202 }
4203
4204 /// Given operands for an FAdd, see if we can fold the result.  If not, this
4205 /// returns null.
4206 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4207                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4208   if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
4209     return C;
4210
4211   if (Constant *C = simplifyFPBinop(Op0, Op1))
4212     return C;
4213
4214   // fadd X, -0 ==> X
4215   if (match(Op1, m_NegZeroFP()))
4216     return Op0;
4217
4218   // fadd X, 0 ==> X, when we know X is not -0
4219   if (match(Op1, m_PosZeroFP()) &&
4220       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4221     return Op0;
4222
4223   // With nnan: (+/-0.0 - X) + X --> 0.0 (and commuted variant)
4224   // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
4225   // Negative zeros are allowed because we always end up with positive zero:
4226   // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4227   // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4228   // X =  0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
4229   // X =  0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
4230   if (FMF.noNaNs() && (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
4231                        match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0)))))
4232     return ConstantFP::getNullValue(Op0->getType());
4233
4234   return nullptr;
4235 }
4236
4237 /// Given operands for an FSub, see if we can fold the result.  If not, this
4238 /// returns null.
4239 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4240                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4241   if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
4242     return C;
4243
4244   if (Constant *C = simplifyFPBinop(Op0, Op1))
4245     return C;
4246
4247   // fsub X, +0 ==> X
4248   if (match(Op1, m_PosZeroFP()))
4249     return Op0;
4250
4251   // fsub X, -0 ==> X, when we know X is not -0
4252   if (match(Op1, m_NegZeroFP()) &&
4253       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4254     return Op0;
4255
4256   // fsub -0.0, (fsub -0.0, X) ==> X
4257   Value *X;
4258   if (match(Op0, m_NegZeroFP()) &&
4259       match(Op1, m_FSub(m_NegZeroFP(), m_Value(X))))
4260     return X;
4261
4262   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
4263   if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
4264       match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))))
4265     return X;
4266
4267   // fsub nnan x, x ==> 0.0
4268   if (FMF.noNaNs() && Op0 == Op1)
4269     return Constant::getNullValue(Op0->getType());
4270
4271   return nullptr;
4272 }
4273
4274 /// Given the operands for an FMul, see if we can fold the result
4275 static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4276                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4277   if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
4278     return C;
4279
4280   if (Constant *C = simplifyFPBinop(Op0, Op1))
4281     return C;
4282
4283   // fmul X, 1.0 ==> X
4284   if (match(Op1, m_FPOne()))
4285     return Op0;
4286
4287   // fmul nnan nsz X, 0 ==> 0
4288   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
4289     return ConstantFP::getNullValue(Op0->getType());
4290
4291   // sqrt(X) * sqrt(X) --> X, if we can:
4292   // 1. Remove the intermediate rounding (reassociate).
4293   // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
4294   // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
4295   Value *X;
4296   if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
4297       FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
4298     return X;
4299
4300   return nullptr;
4301 }
4302
4303 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4304                               const SimplifyQuery &Q) {
4305   return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
4306 }
4307
4308
4309 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4310                               const SimplifyQuery &Q) {
4311   return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
4312 }
4313
4314 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4315                               const SimplifyQuery &Q) {
4316   return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
4317 }
4318
4319 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4320                                const SimplifyQuery &Q, unsigned) {
4321   if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
4322     return C;
4323
4324   if (Constant *C = simplifyFPBinop(Op0, Op1))
4325     return C;
4326
4327   // X / 1.0 -> X
4328   if (match(Op1, m_FPOne()))
4329     return Op0;
4330
4331   // 0 / X -> 0
4332   // Requires that NaNs are off (X could be zero) and signed zeroes are
4333   // ignored (X could be positive or negative, so the output sign is unknown).
4334   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
4335     return ConstantFP::getNullValue(Op0->getType());
4336
4337   if (FMF.noNaNs()) {
4338     // X / X -> 1.0 is legal when NaNs are ignored.
4339     // We can ignore infinities because INF/INF is NaN.
4340     if (Op0 == Op1)
4341       return ConstantFP::get(Op0->getType(), 1.0);
4342
4343     // (X * Y) / Y --> X if we can reassociate to the above form.
4344     Value *X;
4345     if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
4346       return X;
4347
4348     // -X /  X -> -1.0 and
4349     //  X / -X -> -1.0 are legal when NaNs are ignored.
4350     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
4351     if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
4352          BinaryOperator::getFNegArgument(Op0) == Op1) ||
4353         (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
4354          BinaryOperator::getFNegArgument(Op1) == Op0))
4355       return ConstantFP::get(Op0->getType(), -1.0);
4356   }
4357
4358   return nullptr;
4359 }
4360
4361 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4362                               const SimplifyQuery &Q) {
4363   return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
4364 }
4365
4366 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4367                                const SimplifyQuery &Q, unsigned) {
4368   if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
4369     return C;
4370
4371   if (Constant *C = simplifyFPBinop(Op0, Op1))
4372     return C;
4373
4374   // Unlike fdiv, the result of frem always matches the sign of the dividend.
4375   // The constant match may include undef elements in a vector, so return a full
4376   // zero constant as the result.
4377   if (FMF.noNaNs()) {
4378     // +0 % X -> 0
4379     if (match(Op0, m_PosZeroFP()))
4380       return ConstantFP::getNullValue(Op0->getType());
4381     // -0 % X -> -0
4382     if (match(Op0, m_NegZeroFP()))
4383       return ConstantFP::getNegativeZero(Op0->getType());
4384   }
4385
4386   return nullptr;
4387 }
4388
4389 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4390                               const SimplifyQuery &Q) {
4391   return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
4392 }
4393
4394 //=== Helper functions for higher up the class hierarchy.
4395
4396 /// Given operands for a BinaryOperator, see if we can fold the result.
4397 /// If not, this returns null.
4398 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4399                             const SimplifyQuery &Q, unsigned MaxRecurse) {
4400   switch (Opcode) {
4401   case Instruction::Add:
4402     return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
4403   case Instruction::Sub:
4404     return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
4405   case Instruction::Mul:
4406     return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
4407   case Instruction::SDiv:
4408     return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4409   case Instruction::UDiv:
4410     return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
4411   case Instruction::SRem:
4412     return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4413   case Instruction::URem:
4414     return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
4415   case Instruction::Shl:
4416     return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
4417   case Instruction::LShr:
4418     return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
4419   case Instruction::AShr:
4420     return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4421   case Instruction::And:
4422     return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4423   case Instruction::Or:
4424     return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4425   case Instruction::Xor:
4426     return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
4427   case Instruction::FAdd:
4428     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4429   case Instruction::FSub:
4430     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4431   case Instruction::FMul:
4432     return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4433   case Instruction::FDiv:
4434     return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4435   case Instruction::FRem:
4436     return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4437   default:
4438     llvm_unreachable("Unexpected opcode");
4439   }
4440 }
4441
4442 /// Given operands for a BinaryOperator, see if we can fold the result.
4443 /// If not, this returns null.
4444 /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4445 /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4446 static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4447                               const FastMathFlags &FMF, const SimplifyQuery &Q,
4448                               unsigned MaxRecurse) {
4449   switch (Opcode) {
4450   case Instruction::FAdd:
4451     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4452   case Instruction::FSub:
4453     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4454   case Instruction::FMul:
4455     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
4456   case Instruction::FDiv:
4457     return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
4458   default:
4459     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4460   }
4461 }
4462
4463 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4464                            const SimplifyQuery &Q) {
4465   return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
4466 }
4467
4468 Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4469                              FastMathFlags FMF, const SimplifyQuery &Q) {
4470   return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
4471 }
4472
4473 /// Given operands for a CmpInst, see if we can fold the result.
4474 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4475                               const SimplifyQuery &Q, unsigned MaxRecurse) {
4476   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
4477     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
4478   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4479 }
4480
4481 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4482                              const SimplifyQuery &Q) {
4483   return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
4484 }
4485
4486 static bool IsIdempotent(Intrinsic::ID ID) {
4487   switch (ID) {
4488   default: return false;
4489
4490   // Unary idempotent: f(f(x)) = f(x)
4491   case Intrinsic::fabs:
4492   case Intrinsic::floor:
4493   case Intrinsic::ceil:
4494   case Intrinsic::trunc:
4495   case Intrinsic::rint:
4496   case Intrinsic::nearbyint:
4497   case Intrinsic::round:
4498   case Intrinsic::canonicalize:
4499     return true;
4500   }
4501 }
4502
4503 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4504                                    const DataLayout &DL) {
4505   GlobalValue *PtrSym;
4506   APInt PtrOffset;
4507   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4508     return nullptr;
4509
4510   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4511   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4512   Type *Int32PtrTy = Int32Ty->getPointerTo();
4513   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4514
4515   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4516   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4517     return nullptr;
4518
4519   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4520   if (OffsetInt % 4 != 0)
4521     return nullptr;
4522
4523   Constant *C = ConstantExpr::getGetElementPtr(
4524       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4525       ConstantInt::get(Int64Ty, OffsetInt / 4));
4526   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4527   if (!Loaded)
4528     return nullptr;
4529
4530   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4531   if (!LoadedCE)
4532     return nullptr;
4533
4534   if (LoadedCE->getOpcode() == Instruction::Trunc) {
4535     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4536     if (!LoadedCE)
4537       return nullptr;
4538   }
4539
4540   if (LoadedCE->getOpcode() != Instruction::Sub)
4541     return nullptr;
4542
4543   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4544   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4545     return nullptr;
4546   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4547
4548   Constant *LoadedRHS = LoadedCE->getOperand(1);
4549   GlobalValue *LoadedRHSSym;
4550   APInt LoadedRHSOffset;
4551   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4552                                   DL) ||
4553       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4554     return nullptr;
4555
4556   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4557 }
4558
4559 static bool maskIsAllZeroOrUndef(Value *Mask) {
4560   auto *ConstMask = dyn_cast<Constant>(Mask);
4561   if (!ConstMask)
4562     return false;
4563   if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4564     return true;
4565   for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4566        ++I) {
4567     if (auto *MaskElt = ConstMask->getAggregateElement(I))
4568       if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4569         continue;
4570     return false;
4571   }
4572   return true;
4573 }
4574
4575 template <typename IterTy>
4576 static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
4577                                 const SimplifyQuery &Q, unsigned MaxRecurse) {
4578   Intrinsic::ID IID = F->getIntrinsicID();
4579   unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
4580
4581   // Unary Ops
4582   if (NumOperands == 1) {
4583     // Perform idempotent optimizations
4584     if (IsIdempotent(IID)) {
4585       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) {
4586         if (II->getIntrinsicID() == IID)
4587           return II;
4588       }
4589     }
4590
4591     Value *IIOperand = *ArgBegin;
4592     Value *X;
4593     switch (IID) {
4594     case Intrinsic::fabs: {
4595       if (SignBitMustBeZero(IIOperand, Q.TLI))
4596         return IIOperand;
4597       return nullptr;
4598     }
4599     case Intrinsic::bswap: {
4600       // bswap(bswap(x)) -> x
4601       if (match(IIOperand, m_BSwap(m_Value(X))))
4602         return X;
4603       return nullptr;
4604     }
4605     case Intrinsic::bitreverse: {
4606       // bitreverse(bitreverse(x)) -> x
4607       if (match(IIOperand, m_BitReverse(m_Value(X))))
4608         return X;
4609       return nullptr;
4610     }
4611     case Intrinsic::exp: {
4612       // exp(log(x)) -> x
4613       if (Q.CxtI->hasAllowReassoc() &&
4614           match(IIOperand, m_Intrinsic<Intrinsic::log>(m_Value(X))))
4615         return X;
4616       return nullptr;
4617     }
4618     case Intrinsic::exp2: {
4619       // exp2(log2(x)) -> x
4620       if (Q.CxtI->hasAllowReassoc() &&
4621           match(IIOperand, m_Intrinsic<Intrinsic::log2>(m_Value(X))))
4622         return X;
4623       return nullptr;
4624     }
4625     case Intrinsic::log: {
4626       // log(exp(x)) -> x
4627       if (Q.CxtI->hasAllowReassoc() &&
4628           match(IIOperand, m_Intrinsic<Intrinsic::exp>(m_Value(X))))
4629         return X;
4630       return nullptr;
4631     }
4632     case Intrinsic::log2: {
4633       // log2(exp2(x)) -> x
4634       if (Q.CxtI->hasAllowReassoc() &&
4635           match(IIOperand, m_Intrinsic<Intrinsic::exp2>(m_Value(X)))) {
4636         return X;
4637       }
4638       return nullptr;
4639     }
4640     default:
4641       return nullptr;
4642     }
4643   }
4644
4645   // Binary Ops
4646   if (NumOperands == 2) {
4647     Value *LHS = *ArgBegin;
4648     Value *RHS = *(ArgBegin + 1);
4649     Type *ReturnType = F->getReturnType();
4650
4651     switch (IID) {
4652     case Intrinsic::usub_with_overflow:
4653     case Intrinsic::ssub_with_overflow: {
4654       // X - X -> { 0, false }
4655       if (LHS == RHS)
4656         return Constant::getNullValue(ReturnType);
4657
4658       // X - undef -> undef
4659       // undef - X -> undef
4660       if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4661         return UndefValue::get(ReturnType);
4662
4663       return nullptr;
4664     }
4665     case Intrinsic::uadd_with_overflow:
4666     case Intrinsic::sadd_with_overflow: {
4667       // X + undef -> undef
4668       if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4669         return UndefValue::get(ReturnType);
4670
4671       return nullptr;
4672     }
4673     case Intrinsic::umul_with_overflow:
4674     case Intrinsic::smul_with_overflow: {
4675       // 0 * X -> { 0, false }
4676       // X * 0 -> { 0, false }
4677       if (match(LHS, m_Zero()) || match(RHS, m_Zero()))
4678         return Constant::getNullValue(ReturnType);
4679
4680       // undef * X -> { 0, false }
4681       // X * undef -> { 0, false }
4682       if (match(LHS, m_Undef()) || match(RHS, m_Undef()))
4683         return Constant::getNullValue(ReturnType);
4684
4685       return nullptr;
4686     }
4687     case Intrinsic::load_relative: {
4688       Constant *C0 = dyn_cast<Constant>(LHS);
4689       Constant *C1 = dyn_cast<Constant>(RHS);
4690       if (C0 && C1)
4691         return SimplifyRelativeLoad(C0, C1, Q.DL);
4692       return nullptr;
4693     }
4694     case Intrinsic::powi:
4695       if (ConstantInt *Power = dyn_cast<ConstantInt>(RHS)) {
4696         // powi(x, 0) -> 1.0
4697         if (Power->isZero())
4698           return ConstantFP::get(LHS->getType(), 1.0);
4699         // powi(x, 1) -> x
4700         if (Power->isOne())
4701           return LHS;
4702       }
4703       return nullptr;
4704     default:
4705       return nullptr;
4706     }
4707   }
4708
4709   // Simplify calls to llvm.masked.load.*
4710   switch (IID) {
4711   case Intrinsic::masked_load: {
4712     Value *MaskArg = ArgBegin[2];
4713     Value *PassthruArg = ArgBegin[3];
4714     // If the mask is all zeros or undef, the "passthru" argument is the result.
4715     if (maskIsAllZeroOrUndef(MaskArg))
4716       return PassthruArg;
4717     return nullptr;
4718   }
4719   default:
4720     return nullptr;
4721   }
4722 }
4723
4724 template <typename IterTy>
4725 static Value *SimplifyCall(ImmutableCallSite CS, Value *V, IterTy ArgBegin,
4726                            IterTy ArgEnd, const SimplifyQuery &Q,
4727                            unsigned MaxRecurse) {
4728   Type *Ty = V->getType();
4729   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4730     Ty = PTy->getElementType();
4731   FunctionType *FTy = cast<FunctionType>(Ty);
4732
4733   // call undef -> undef
4734   // call null -> undef
4735   if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
4736     return UndefValue::get(FTy->getReturnType());
4737
4738   Function *F = dyn_cast<Function>(V);
4739   if (!F)
4740     return nullptr;
4741
4742   if (F->isIntrinsic())
4743     if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
4744       return Ret;
4745
4746   if (!canConstantFoldCallTo(CS, F))
4747     return nullptr;
4748
4749   SmallVector<Constant *, 4> ConstantArgs;
4750   ConstantArgs.reserve(ArgEnd - ArgBegin);
4751   for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4752     Constant *C = dyn_cast<Constant>(*I);
4753     if (!C)
4754       return nullptr;
4755     ConstantArgs.push_back(C);
4756   }
4757
4758   return ConstantFoldCall(CS, F, ConstantArgs, Q.TLI);
4759 }
4760
4761 Value *llvm::SimplifyCall(ImmutableCallSite CS, Value *V,
4762                           User::op_iterator ArgBegin, User::op_iterator ArgEnd,
4763                           const SimplifyQuery &Q) {
4764   return ::SimplifyCall(CS, V, ArgBegin, ArgEnd, Q, RecursionLimit);
4765 }
4766
4767 Value *llvm::SimplifyCall(ImmutableCallSite CS, Value *V,
4768                           ArrayRef<Value *> Args, const SimplifyQuery &Q) {
4769   return ::SimplifyCall(CS, V, Args.begin(), Args.end(), Q, RecursionLimit);
4770 }
4771
4772 Value *llvm::SimplifyCall(ImmutableCallSite ICS, const SimplifyQuery &Q) {
4773   CallSite CS(const_cast<Instruction*>(ICS.getInstruction()));
4774   return ::SimplifyCall(CS, CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
4775                         Q, RecursionLimit);
4776 }
4777
4778 /// See if we can compute a simplified version of this instruction.
4779 /// If not, this returns null.
4780
4781 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
4782                                  OptimizationRemarkEmitter *ORE) {
4783   const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
4784   Value *Result;
4785
4786   switch (I->getOpcode()) {
4787   default:
4788     Result = ConstantFoldInstruction(I, Q.DL, Q.TLI);
4789     break;
4790   case Instruction::FAdd:
4791     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
4792                               I->getFastMathFlags(), Q);
4793     break;
4794   case Instruction::Add:
4795     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4796                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4797                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q);
4798     break;
4799   case Instruction::FSub:
4800     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
4801                               I->getFastMathFlags(), Q);
4802     break;
4803   case Instruction::Sub:
4804     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4805                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4806                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q);
4807     break;
4808   case Instruction::FMul:
4809     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
4810                               I->getFastMathFlags(), Q);
4811     break;
4812   case Instruction::Mul:
4813     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q);
4814     break;
4815   case Instruction::SDiv:
4816     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q);
4817     break;
4818   case Instruction::UDiv:
4819     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q);
4820     break;
4821   case Instruction::FDiv:
4822     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
4823                               I->getFastMathFlags(), Q);
4824     break;
4825   case Instruction::SRem:
4826     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q);
4827     break;
4828   case Instruction::URem:
4829     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q);
4830     break;
4831   case Instruction::FRem:
4832     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
4833                               I->getFastMathFlags(), Q);
4834     break;
4835   case Instruction::Shl:
4836     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4837                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4838                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q);
4839     break;
4840   case Instruction::LShr:
4841     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
4842                               cast<BinaryOperator>(I)->isExact(), Q);
4843     break;
4844   case Instruction::AShr:
4845     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
4846                               cast<BinaryOperator>(I)->isExact(), Q);
4847     break;
4848   case Instruction::And:
4849     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q);
4850     break;
4851   case Instruction::Or:
4852     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q);
4853     break;
4854   case Instruction::Xor:
4855     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q);
4856     break;
4857   case Instruction::ICmp:
4858     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
4859                               I->getOperand(0), I->getOperand(1), Q);
4860     break;
4861   case Instruction::FCmp:
4862     Result =
4863         SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
4864                          I->getOperand(1), I->getFastMathFlags(), Q);
4865     break;
4866   case Instruction::Select:
4867     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
4868                                 I->getOperand(2), Q);
4869     break;
4870   case Instruction::GetElementPtr: {
4871     SmallVector<Value *, 8> Ops(I->op_begin(), I->op_end());
4872     Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
4873                              Ops, Q);
4874     break;
4875   }
4876   case Instruction::InsertValue: {
4877     InsertValueInst *IV = cast<InsertValueInst>(I);
4878     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4879                                      IV->getInsertedValueOperand(),
4880                                      IV->getIndices(), Q);
4881     break;
4882   }
4883   case Instruction::InsertElement: {
4884     auto *IE = cast<InsertElementInst>(I);
4885     Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1),
4886                                        IE->getOperand(2), Q);
4887     break;
4888   }
4889   case Instruction::ExtractValue: {
4890     auto *EVI = cast<ExtractValueInst>(I);
4891     Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
4892                                       EVI->getIndices(), Q);
4893     break;
4894   }
4895   case Instruction::ExtractElement: {
4896     auto *EEI = cast<ExtractElementInst>(I);
4897     Result = SimplifyExtractElementInst(EEI->getVectorOperand(),
4898                                         EEI->getIndexOperand(), Q);
4899     break;
4900   }
4901   case Instruction::ShuffleVector: {
4902     auto *SVI = cast<ShuffleVectorInst>(I);
4903     Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4904                                        SVI->getMask(), SVI->getType(), Q);
4905     break;
4906   }
4907   case Instruction::PHI:
4908     Result = SimplifyPHINode(cast<PHINode>(I), Q);
4909     break;
4910   case Instruction::Call: {
4911     CallSite CS(cast<CallInst>(I));
4912     Result = SimplifyCall(CS, Q);
4913     break;
4914   }
4915 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4916 #include "llvm/IR/Instruction.def"
4917 #undef HANDLE_CAST_INST
4918     Result =
4919         SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q);
4920     break;
4921   case Instruction::Alloca:
4922     // No simplifications for Alloca and it can't be constant folded.
4923     Result = nullptr;
4924     break;
4925   }
4926
4927   // In general, it is possible for computeKnownBits to determine all bits in a
4928   // value even when the operands are not all constants.
4929   if (!Result && I->getType()->isIntOrIntVectorTy()) {
4930     KnownBits Known = computeKnownBits(I, Q.DL, /*Depth*/ 0, Q.AC, I, Q.DT, ORE);
4931     if (Known.isConstant())
4932       Result = ConstantInt::get(I->getType(), Known.getConstant());
4933   }
4934
4935   /// If called on unreachable code, the above logic may report that the
4936   /// instruction simplified to itself.  Make life easier for users by
4937   /// detecting that case here, returning a safe value instead.
4938   return Result == I ? UndefValue::get(I->getType()) : Result;
4939 }
4940
4941 /// Implementation of recursive simplification through an instruction's
4942 /// uses.
4943 ///
4944 /// This is the common implementation of the recursive simplification routines.
4945 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4946 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4947 /// instructions to process and attempt to simplify it using
4948 /// InstructionSimplify.
4949 ///
4950 /// This routine returns 'true' only when *it* simplifies something. The passed
4951 /// in simplified value does not count toward this.
4952 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
4953                                               const TargetLibraryInfo *TLI,
4954                                               const DominatorTree *DT,
4955                                               AssumptionCache *AC) {
4956   bool Simplified = false;
4957   SmallSetVector<Instruction *, 8> Worklist;
4958   const DataLayout &DL = I->getModule()->getDataLayout();
4959
4960   // If we have an explicit value to collapse to, do that round of the
4961   // simplification loop by hand initially.
4962   if (SimpleV) {
4963     for (User *U : I->users())
4964       if (U != I)
4965         Worklist.insert(cast<Instruction>(U));
4966
4967     // Replace the instruction with its simplified value.
4968     I->replaceAllUsesWith(SimpleV);
4969
4970     // Gracefully handle edge cases where the instruction is not wired into any
4971     // parent block.
4972     if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4973         !I->mayHaveSideEffects())
4974       I->eraseFromParent();
4975   } else {
4976     Worklist.insert(I);
4977   }
4978
4979   // Note that we must test the size on each iteration, the worklist can grow.
4980   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4981     I = Worklist[Idx];
4982
4983     // See if this instruction simplifies.
4984     SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
4985     if (!SimpleV)
4986       continue;
4987
4988     Simplified = true;
4989
4990     // Stash away all the uses of the old instruction so we can check them for
4991     // recursive simplifications after a RAUW. This is cheaper than checking all
4992     // uses of To on the recursive step in most cases.
4993     for (User *U : I->users())
4994       Worklist.insert(cast<Instruction>(U));
4995
4996     // Replace the instruction with its simplified value.
4997     I->replaceAllUsesWith(SimpleV);
4998
4999     // Gracefully handle edge cases where the instruction is not wired into any
5000     // parent block.
5001     if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
5002         !I->mayHaveSideEffects())
5003       I->eraseFromParent();
5004   }
5005   return Simplified;
5006 }
5007
5008 bool llvm::recursivelySimplifyInstruction(Instruction *I,
5009                                           const TargetLibraryInfo *TLI,
5010                                           const DominatorTree *DT,
5011                                           AssumptionCache *AC) {
5012   return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
5013 }
5014
5015 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
5016                                          const TargetLibraryInfo *TLI,
5017                                          const DominatorTree *DT,
5018                                          AssumptionCache *AC) {
5019   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
5020   assert(SimpleV && "Must provide a simplified value.");
5021   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
5022 }
5023
5024 namespace llvm {
5025 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
5026   auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
5027   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
5028   auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5029   auto *TLI = TLIWP ? &TLIWP->getTLI() : nullptr;
5030   auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
5031   auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
5032   return {F.getParent()->getDataLayout(), TLI, DT, AC};
5033 }
5034
5035 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
5036                                          const DataLayout &DL) {
5037   return {DL, &AR.TLI, &AR.DT, &AR.AC};
5038 }
5039
5040 template <class T, class... TArgs>
5041 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
5042                                          Function &F) {
5043   auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
5044   auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
5045   auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
5046   return {F.getParent()->getDataLayout(), TLI, DT, AC};
5047 }
5048 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
5049                                                   Function &);
5050 }