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