xref: /llvm-project/llvm/lib/Analysis/InstructionSimplify.cpp (revision 6f619c98aea164f46b5e086d445d62d697ab3b39)
1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements routines for folding instructions into simpler forms
10 // that do not require creating new instructions.  This does constant folding
11 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
12 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
13 // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
14 // simplified: This is usually true and assuming it simplifies the logic (if
15 // they have not been simplified then results are correct but maybe suboptimal).
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Analysis/InstructionSimplify.h"
20 
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/AssumptionCache.h"
26 #include "llvm/Analysis/CaptureTracking.h"
27 #include "llvm/Analysis/CmpInstAnalysis.h"
28 #include "llvm/Analysis/ConstantFolding.h"
29 #include "llvm/Analysis/InstSimplifyFolder.h"
30 #include "llvm/Analysis/LoopAnalysisManager.h"
31 #include "llvm/Analysis/MemoryBuiltins.h"
32 #include "llvm/Analysis/OverflowInstAnalysis.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/Analysis/VectorUtils.h"
35 #include "llvm/IR/ConstantRange.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/InstrTypes.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/PatternMatch.h"
42 #include "llvm/IR/Statepoint.h"
43 #include "llvm/Support/KnownBits.h"
44 #include <algorithm>
45 #include <optional>
46 using namespace llvm;
47 using namespace llvm::PatternMatch;
48 
49 #define DEBUG_TYPE "instsimplify"
50 
51 enum { RecursionLimit = 3 };
52 
53 STATISTIC(NumExpand, "Number of expansions");
54 STATISTIC(NumReassoc, "Number of reassociations");
55 
56 static Value *simplifyAndInst(Value *, Value *, const SimplifyQuery &,
57                               unsigned);
58 static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
59 static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
60                              const SimplifyQuery &, unsigned);
61 static Value *simplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
62                             unsigned);
63 static Value *simplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &,
64                             const SimplifyQuery &, unsigned);
65 static Value *simplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
66                               unsigned);
67 static Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
68                                const SimplifyQuery &Q, unsigned MaxRecurse);
69 static Value *simplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
70 static Value *simplifyXorInst(Value *, Value *, const SimplifyQuery &,
71                               unsigned);
72 static Value *simplifyCastInst(unsigned, Value *, Type *, const SimplifyQuery &,
73                                unsigned);
74 static Value *simplifyGEPInst(Type *, Value *, ArrayRef<Value *>,
75                               GEPNoWrapFlags, const SimplifyQuery &, unsigned);
76 static Value *simplifySelectInst(Value *, Value *, Value *,
77                                  const SimplifyQuery &, unsigned);
78 static Value *simplifyInstructionWithOperands(Instruction *I,
79                                               ArrayRef<Value *> NewOps,
80                                               const SimplifyQuery &SQ,
81                                               unsigned MaxRecurse);
82 
83 static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal,
84                                      Value *FalseVal) {
85   BinaryOperator::BinaryOps BinOpCode;
86   if (auto *BO = dyn_cast<BinaryOperator>(Cond))
87     BinOpCode = BO->getOpcode();
88   else
89     return nullptr;
90 
91   CmpInst::Predicate ExpectedPred, Pred1, Pred2;
92   if (BinOpCode == BinaryOperator::Or) {
93     ExpectedPred = ICmpInst::ICMP_NE;
94   } else if (BinOpCode == BinaryOperator::And) {
95     ExpectedPred = ICmpInst::ICMP_EQ;
96   } else
97     return nullptr;
98 
99   // %A = icmp eq %TV, %FV
100   // %B = icmp eq %X, %Y (and one of these is a select operand)
101   // %C = and %A, %B
102   // %D = select %C, %TV, %FV
103   // -->
104   // %FV
105 
106   // %A = icmp ne %TV, %FV
107   // %B = icmp ne %X, %Y (and one of these is a select operand)
108   // %C = or %A, %B
109   // %D = select %C, %TV, %FV
110   // -->
111   // %TV
112   Value *X, *Y;
113   if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal),
114                                       m_Specific(FalseVal)),
115                              m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
116       Pred1 != Pred2 || Pred1 != ExpectedPred)
117     return nullptr;
118 
119   if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
120     return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
121 
122   return nullptr;
123 }
124 
125 /// For a boolean type or a vector of boolean type, return false or a vector
126 /// with every element false.
127 static Constant *getFalse(Type *Ty) { return ConstantInt::getFalse(Ty); }
128 
129 /// For a boolean type or a vector of boolean type, return true or a vector
130 /// with every element true.
131 static Constant *getTrue(Type *Ty) { return ConstantInt::getTrue(Ty); }
132 
133 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
134 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
135                           Value *RHS) {
136   CmpInst *Cmp = dyn_cast<CmpInst>(V);
137   if (!Cmp)
138     return false;
139   CmpInst::Predicate CPred = Cmp->getPredicate();
140   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
141   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
142     return true;
143   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
144          CRHS == LHS;
145 }
146 
147 /// Simplify comparison with true or false branch of select:
148 ///  %sel = select i1 %cond, i32 %tv, i32 %fv
149 ///  %cmp = icmp sle i32 %sel, %rhs
150 /// Compose new comparison by substituting %sel with either %tv or %fv
151 /// and see if it simplifies.
152 static Value *simplifyCmpSelCase(CmpInst::Predicate Pred, Value *LHS,
153                                  Value *RHS, Value *Cond,
154                                  const SimplifyQuery &Q, unsigned MaxRecurse,
155                                  Constant *TrueOrFalse) {
156   Value *SimplifiedCmp = simplifyCmpInst(Pred, LHS, RHS, Q, MaxRecurse);
157   if (SimplifiedCmp == Cond) {
158     // %cmp simplified to the select condition (%cond).
159     return TrueOrFalse;
160   } else if (!SimplifiedCmp && isSameCompare(Cond, Pred, LHS, RHS)) {
161     // It didn't simplify. However, if composed comparison is equivalent
162     // to the select condition (%cond) then we can replace it.
163     return TrueOrFalse;
164   }
165   return SimplifiedCmp;
166 }
167 
168 /// Simplify comparison with true branch of select
169 static Value *simplifyCmpSelTrueCase(CmpInst::Predicate Pred, Value *LHS,
170                                      Value *RHS, Value *Cond,
171                                      const SimplifyQuery &Q,
172                                      unsigned MaxRecurse) {
173   return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
174                             getTrue(Cond->getType()));
175 }
176 
177 /// Simplify comparison with false branch of select
178 static Value *simplifyCmpSelFalseCase(CmpInst::Predicate Pred, Value *LHS,
179                                       Value *RHS, Value *Cond,
180                                       const SimplifyQuery &Q,
181                                       unsigned MaxRecurse) {
182   return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
183                             getFalse(Cond->getType()));
184 }
185 
186 /// We know comparison with both branches of select can be simplified, but they
187 /// are not equal. This routine handles some logical simplifications.
188 static Value *handleOtherCmpSelSimplifications(Value *TCmp, Value *FCmp,
189                                                Value *Cond,
190                                                const SimplifyQuery &Q,
191                                                unsigned MaxRecurse) {
192   // If the false value simplified to false, then the result of the compare
193   // is equal to "Cond && TCmp".  This also catches the case when the false
194   // value simplified to false and the true value to true, returning "Cond".
195   // Folding select to and/or isn't poison-safe in general; impliesPoison
196   // checks whether folding it does not convert a well-defined value into
197   // poison.
198   if (match(FCmp, m_Zero()) && impliesPoison(TCmp, Cond))
199     if (Value *V = simplifyAndInst(Cond, TCmp, Q, MaxRecurse))
200       return V;
201   // If the true value simplified to true, then the result of the compare
202   // is equal to "Cond || FCmp".
203   if (match(TCmp, m_One()) && impliesPoison(FCmp, Cond))
204     if (Value *V = simplifyOrInst(Cond, FCmp, Q, MaxRecurse))
205       return V;
206   // Finally, if the false value simplified to true and the true value to
207   // false, then the result of the compare is equal to "!Cond".
208   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
209     if (Value *V = simplifyXorInst(
210             Cond, Constant::getAllOnesValue(Cond->getType()), Q, MaxRecurse))
211       return V;
212   return nullptr;
213 }
214 
215 /// Does the given value dominate the specified phi node?
216 static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
217   Instruction *I = dyn_cast<Instruction>(V);
218   if (!I)
219     // Arguments and constants dominate all instructions.
220     return true;
221 
222   // If we have a DominatorTree then do a precise test.
223   if (DT)
224     return DT->dominates(I, P);
225 
226   // Otherwise, if the instruction is in the entry block and is not an invoke,
227   // then it obviously dominates all phi nodes.
228   if (I->getParent()->isEntryBlock() && !isa<InvokeInst>(I) &&
229       !isa<CallBrInst>(I))
230     return true;
231 
232   return false;
233 }
234 
235 /// Try to simplify a binary operator of form "V op OtherOp" where V is
236 /// "(B0 opex B1)" by distributing 'op' across 'opex' as
237 /// "(B0 op OtherOp) opex (B1 op OtherOp)".
238 static Value *expandBinOp(Instruction::BinaryOps Opcode, Value *V,
239                           Value *OtherOp, Instruction::BinaryOps OpcodeToExpand,
240                           const SimplifyQuery &Q, unsigned MaxRecurse) {
241   auto *B = dyn_cast<BinaryOperator>(V);
242   if (!B || B->getOpcode() != OpcodeToExpand)
243     return nullptr;
244   Value *B0 = B->getOperand(0), *B1 = B->getOperand(1);
245   Value *L =
246       simplifyBinOp(Opcode, B0, OtherOp, Q.getWithoutUndef(), MaxRecurse);
247   if (!L)
248     return nullptr;
249   Value *R =
250       simplifyBinOp(Opcode, B1, OtherOp, Q.getWithoutUndef(), MaxRecurse);
251   if (!R)
252     return nullptr;
253 
254   // Does the expanded pair of binops simplify to the existing binop?
255   if ((L == B0 && R == B1) ||
256       (Instruction::isCommutative(OpcodeToExpand) && L == B1 && R == B0)) {
257     ++NumExpand;
258     return B;
259   }
260 
261   // Otherwise, return "L op' R" if it simplifies.
262   Value *S = simplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse);
263   if (!S)
264     return nullptr;
265 
266   ++NumExpand;
267   return S;
268 }
269 
270 /// Try to simplify binops of form "A op (B op' C)" or the commuted variant by
271 /// distributing op over op'.
272 static Value *expandCommutativeBinOp(Instruction::BinaryOps Opcode, Value *L,
273                                      Value *R,
274                                      Instruction::BinaryOps OpcodeToExpand,
275                                      const SimplifyQuery &Q,
276                                      unsigned MaxRecurse) {
277   // Recursion is always used, so bail out at once if we already hit the limit.
278   if (!MaxRecurse--)
279     return nullptr;
280 
281   if (Value *V = expandBinOp(Opcode, L, R, OpcodeToExpand, Q, MaxRecurse))
282     return V;
283   if (Value *V = expandBinOp(Opcode, R, L, OpcodeToExpand, Q, MaxRecurse))
284     return V;
285   return nullptr;
286 }
287 
288 /// Generic simplifications for associative binary operations.
289 /// Returns the simpler value, or null if none was found.
290 static Value *simplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
291                                        Value *LHS, Value *RHS,
292                                        const SimplifyQuery &Q,
293                                        unsigned MaxRecurse) {
294   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
295 
296   // Recursion is always used, so bail out at once if we already hit the limit.
297   if (!MaxRecurse--)
298     return nullptr;
299 
300   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
301   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
302 
303   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
304   if (Op0 && Op0->getOpcode() == Opcode) {
305     Value *A = Op0->getOperand(0);
306     Value *B = Op0->getOperand(1);
307     Value *C = RHS;
308 
309     // Does "B op C" simplify?
310     if (Value *V = simplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
311       // It does!  Return "A op V" if it simplifies or is already available.
312       // If V equals B then "A op V" is just the LHS.
313       if (V == B)
314         return LHS;
315       // Otherwise return "A op V" if it simplifies.
316       if (Value *W = simplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
317         ++NumReassoc;
318         return W;
319       }
320     }
321   }
322 
323   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
324   if (Op1 && Op1->getOpcode() == Opcode) {
325     Value *A = LHS;
326     Value *B = Op1->getOperand(0);
327     Value *C = Op1->getOperand(1);
328 
329     // Does "A op B" simplify?
330     if (Value *V = simplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
331       // It does!  Return "V op C" if it simplifies or is already available.
332       // If V equals B then "V op C" is just the RHS.
333       if (V == B)
334         return RHS;
335       // Otherwise return "V op C" if it simplifies.
336       if (Value *W = simplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
337         ++NumReassoc;
338         return W;
339       }
340     }
341   }
342 
343   // The remaining transforms require commutativity as well as associativity.
344   if (!Instruction::isCommutative(Opcode))
345     return nullptr;
346 
347   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
348   if (Op0 && Op0->getOpcode() == Opcode) {
349     Value *A = Op0->getOperand(0);
350     Value *B = Op0->getOperand(1);
351     Value *C = RHS;
352 
353     // Does "C op A" simplify?
354     if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
355       // It does!  Return "V op B" if it simplifies or is already available.
356       // If V equals A then "V op B" is just the LHS.
357       if (V == A)
358         return LHS;
359       // Otherwise return "V op B" if it simplifies.
360       if (Value *W = simplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
361         ++NumReassoc;
362         return W;
363       }
364     }
365   }
366 
367   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
368   if (Op1 && Op1->getOpcode() == Opcode) {
369     Value *A = LHS;
370     Value *B = Op1->getOperand(0);
371     Value *C = Op1->getOperand(1);
372 
373     // Does "C op A" simplify?
374     if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
375       // It does!  Return "B op V" if it simplifies or is already available.
376       // If V equals C then "B op V" is just the RHS.
377       if (V == C)
378         return RHS;
379       // Otherwise return "B op V" if it simplifies.
380       if (Value *W = simplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
381         ++NumReassoc;
382         return W;
383       }
384     }
385   }
386 
387   return nullptr;
388 }
389 
390 /// In the case of a binary operation with a select instruction as an operand,
391 /// try to simplify the binop by seeing whether evaluating it on both branches
392 /// of the select results in the same value. Returns the common value if so,
393 /// otherwise returns null.
394 static Value *threadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
395                                     Value *RHS, const SimplifyQuery &Q,
396                                     unsigned MaxRecurse) {
397   // Recursion is always used, so bail out at once if we already hit the limit.
398   if (!MaxRecurse--)
399     return nullptr;
400 
401   SelectInst *SI;
402   if (isa<SelectInst>(LHS)) {
403     SI = cast<SelectInst>(LHS);
404   } else {
405     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
406     SI = cast<SelectInst>(RHS);
407   }
408 
409   // Evaluate the BinOp on the true and false branches of the select.
410   Value *TV;
411   Value *FV;
412   if (SI == LHS) {
413     TV = simplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
414     FV = simplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
415   } else {
416     TV = simplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
417     FV = simplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
418   }
419 
420   // If they simplified to the same value, then return the common value.
421   // If they both failed to simplify then return null.
422   if (TV == FV)
423     return TV;
424 
425   // If one branch simplified to undef, return the other one.
426   if (TV && Q.isUndefValue(TV))
427     return FV;
428   if (FV && Q.isUndefValue(FV))
429     return TV;
430 
431   // If applying the operation did not change the true and false select values,
432   // then the result of the binop is the select itself.
433   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
434     return SI;
435 
436   // If one branch simplified and the other did not, and the simplified
437   // value is equal to the unsimplified one, return the simplified value.
438   // For example, select (cond, X, X & Z) & Z -> X & Z.
439   if ((FV && !TV) || (TV && !FV)) {
440     // Check that the simplified value has the form "X op Y" where "op" is the
441     // same as the original operation.
442     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
443     if (Simplified && Simplified->getOpcode() == unsigned(Opcode) &&
444         !Simplified->hasPoisonGeneratingFlags()) {
445       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
446       // We already know that "op" is the same as for the simplified value.  See
447       // if the operands match too.  If so, return the simplified value.
448       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
449       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
450       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
451       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
452           Simplified->getOperand(1) == UnsimplifiedRHS)
453         return Simplified;
454       if (Simplified->isCommutative() &&
455           Simplified->getOperand(1) == UnsimplifiedLHS &&
456           Simplified->getOperand(0) == UnsimplifiedRHS)
457         return Simplified;
458     }
459   }
460 
461   return nullptr;
462 }
463 
464 /// In the case of a comparison with a select instruction, try to simplify the
465 /// comparison by seeing whether both branches of the select result in the same
466 /// value. Returns the common value if so, otherwise returns null.
467 /// For example, if we have:
468 ///  %tmp = select i1 %cmp, i32 1, i32 2
469 ///  %cmp1 = icmp sle i32 %tmp, 3
470 /// We can simplify %cmp1 to true, because both branches of select are
471 /// less than 3. We compose new comparison by substituting %tmp with both
472 /// branches of select and see if it can be simplified.
473 static Value *threadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
474                                   Value *RHS, const SimplifyQuery &Q,
475                                   unsigned MaxRecurse) {
476   // Recursion is always used, so bail out at once if we already hit the limit.
477   if (!MaxRecurse--)
478     return nullptr;
479 
480   // Make sure the select is on the LHS.
481   if (!isa<SelectInst>(LHS)) {
482     std::swap(LHS, RHS);
483     Pred = CmpInst::getSwappedPredicate(Pred);
484   }
485   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
486   SelectInst *SI = cast<SelectInst>(LHS);
487   Value *Cond = SI->getCondition();
488   Value *TV = SI->getTrueValue();
489   Value *FV = SI->getFalseValue();
490 
491   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
492   // Does "cmp TV, RHS" simplify?
493   Value *TCmp = simplifyCmpSelTrueCase(Pred, TV, RHS, Cond, Q, MaxRecurse);
494   if (!TCmp)
495     return nullptr;
496 
497   // Does "cmp FV, RHS" simplify?
498   Value *FCmp = simplifyCmpSelFalseCase(Pred, FV, RHS, Cond, Q, MaxRecurse);
499   if (!FCmp)
500     return nullptr;
501 
502   // If both sides simplified to the same value, then use it as the result of
503   // the original comparison.
504   if (TCmp == FCmp)
505     return TCmp;
506 
507   // The remaining cases only make sense if the select condition has the same
508   // type as the result of the comparison, so bail out if this is not so.
509   if (Cond->getType()->isVectorTy() == RHS->getType()->isVectorTy())
510     return handleOtherCmpSelSimplifications(TCmp, FCmp, Cond, Q, MaxRecurse);
511 
512   return nullptr;
513 }
514 
515 /// In the case of a binary operation with an operand that is a PHI instruction,
516 /// try to simplify the binop by seeing whether evaluating it on the incoming
517 /// phi values yields the same result for every value. If so returns the common
518 /// value, otherwise returns null.
519 static Value *threadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
520                                  Value *RHS, const SimplifyQuery &Q,
521                                  unsigned MaxRecurse) {
522   // Recursion is always used, so bail out at once if we already hit the limit.
523   if (!MaxRecurse--)
524     return nullptr;
525 
526   PHINode *PI;
527   if (isa<PHINode>(LHS)) {
528     PI = cast<PHINode>(LHS);
529     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
530     if (!valueDominatesPHI(RHS, PI, Q.DT))
531       return nullptr;
532   } else {
533     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
534     PI = cast<PHINode>(RHS);
535     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
536     if (!valueDominatesPHI(LHS, PI, Q.DT))
537       return nullptr;
538   }
539 
540   // Evaluate the BinOp on the incoming phi values.
541   Value *CommonValue = nullptr;
542   for (Use &Incoming : PI->incoming_values()) {
543     // If the incoming value is the phi node itself, it can safely be skipped.
544     if (Incoming == PI)
545       continue;
546     Instruction *InTI = PI->getIncomingBlock(Incoming)->getTerminator();
547     Value *V = PI == LHS
548                    ? simplifyBinOp(Opcode, Incoming, RHS,
549                                    Q.getWithInstruction(InTI), MaxRecurse)
550                    : simplifyBinOp(Opcode, LHS, Incoming,
551                                    Q.getWithInstruction(InTI), MaxRecurse);
552     // If the operation failed to simplify, or simplified to a different value
553     // to previously, then give up.
554     if (!V || (CommonValue && V != CommonValue))
555       return nullptr;
556     CommonValue = V;
557   }
558 
559   return CommonValue;
560 }
561 
562 /// In the case of a comparison with a PHI instruction, try to simplify the
563 /// comparison by seeing whether comparing with all of the incoming phi values
564 /// yields the same result every time. If so returns the common result,
565 /// otherwise returns null.
566 static Value *threadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
567                                const SimplifyQuery &Q, unsigned MaxRecurse) {
568   // Recursion is always used, so bail out at once if we already hit the limit.
569   if (!MaxRecurse--)
570     return nullptr;
571 
572   // Make sure the phi is on the LHS.
573   if (!isa<PHINode>(LHS)) {
574     std::swap(LHS, RHS);
575     Pred = CmpInst::getSwappedPredicate(Pred);
576   }
577   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
578   PHINode *PI = cast<PHINode>(LHS);
579 
580   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
581   if (!valueDominatesPHI(RHS, PI, Q.DT))
582     return nullptr;
583 
584   // Evaluate the BinOp on the incoming phi values.
585   Value *CommonValue = nullptr;
586   for (unsigned u = 0, e = PI->getNumIncomingValues(); u < e; ++u) {
587     Value *Incoming = PI->getIncomingValue(u);
588     Instruction *InTI = PI->getIncomingBlock(u)->getTerminator();
589     // If the incoming value is the phi node itself, it can safely be skipped.
590     if (Incoming == PI)
591       continue;
592     // Change the context instruction to the "edge" that flows into the phi.
593     // This is important because that is where incoming is actually "evaluated"
594     // even though it is used later somewhere else.
595     Value *V = simplifyCmpInst(Pred, Incoming, RHS, Q.getWithInstruction(InTI),
596                                MaxRecurse);
597     // If the operation failed to simplify, or simplified to a different value
598     // to previously, then give up.
599     if (!V || (CommonValue && V != CommonValue))
600       return nullptr;
601     CommonValue = V;
602   }
603 
604   return CommonValue;
605 }
606 
607 static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
608                                        Value *&Op0, Value *&Op1,
609                                        const SimplifyQuery &Q) {
610   if (auto *CLHS = dyn_cast<Constant>(Op0)) {
611     if (auto *CRHS = dyn_cast<Constant>(Op1)) {
612       switch (Opcode) {
613       default:
614         break;
615       case Instruction::FAdd:
616       case Instruction::FSub:
617       case Instruction::FMul:
618       case Instruction::FDiv:
619       case Instruction::FRem:
620         if (Q.CxtI != nullptr)
621           return ConstantFoldFPInstOperands(Opcode, CLHS, CRHS, Q.DL, Q.CxtI);
622       }
623       return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
624     }
625 
626     // Canonicalize the constant to the RHS if this is a commutative operation.
627     if (Instruction::isCommutative(Opcode))
628       std::swap(Op0, Op1);
629   }
630   return nullptr;
631 }
632 
633 /// Given operands for an Add, see if we can fold the result.
634 /// If not, this returns null.
635 static Value *simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
636                               const SimplifyQuery &Q, unsigned MaxRecurse) {
637   if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
638     return C;
639 
640   // X + poison -> poison
641   if (isa<PoisonValue>(Op1))
642     return Op1;
643 
644   // X + undef -> undef
645   if (Q.isUndefValue(Op1))
646     return Op1;
647 
648   // X + 0 -> X
649   if (match(Op1, m_Zero()))
650     return Op0;
651 
652   // If two operands are negative, return 0.
653   if (isKnownNegation(Op0, Op1))
654     return Constant::getNullValue(Op0->getType());
655 
656   // X + (Y - X) -> Y
657   // (Y - X) + X -> Y
658   // Eg: X + -X -> 0
659   Value *Y = nullptr;
660   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
661       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
662     return Y;
663 
664   // X + ~X -> -1   since   ~X = -X-1
665   Type *Ty = Op0->getType();
666   if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
667     return Constant::getAllOnesValue(Ty);
668 
669   // add nsw/nuw (xor Y, signmask), signmask --> Y
670   // The no-wrapping add guarantees that the top bit will be set by the add.
671   // Therefore, the xor must be clearing the already set sign bit of Y.
672   if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
673       match(Op0, m_Xor(m_Value(Y), m_SignMask())))
674     return Y;
675 
676   // add nuw %x, -1  ->  -1, because %x can only be 0.
677   if (IsNUW && match(Op1, m_AllOnes()))
678     return Op1; // Which is -1.
679 
680   /// i1 add -> xor.
681   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
682     if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
683       return V;
684 
685   // Try some generic simplifications for associative operations.
686   if (Value *V =
687           simplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, MaxRecurse))
688     return V;
689 
690   // Threading Add over selects and phi nodes is pointless, so don't bother.
691   // Threading over the select in "A + select(cond, B, C)" means evaluating
692   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
693   // only if B and C are equal.  If B and C are equal then (since we assume
694   // that operands have already been simplified) "select(cond, B, C)" should
695   // have been simplified to the common value of B and C already.  Analysing
696   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
697   // for threading over phi nodes.
698 
699   return nullptr;
700 }
701 
702 Value *llvm::simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
703                              const SimplifyQuery &Query) {
704   return ::simplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
705 }
706 
707 /// Compute the base pointer and cumulative constant offsets for V.
708 ///
709 /// This strips all constant offsets off of V, leaving it the base pointer, and
710 /// accumulates the total constant offset applied in the returned constant.
711 /// It returns zero if there are no constant offsets applied.
712 ///
713 /// This is very similar to stripAndAccumulateConstantOffsets(), except it
714 /// normalizes the offset bitwidth to the stripped pointer type, not the
715 /// original pointer type.
716 static APInt stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
717                                             bool AllowNonInbounds = false) {
718   assert(V->getType()->isPtrOrPtrVectorTy());
719 
720   APInt Offset = APInt::getZero(DL.getIndexTypeSizeInBits(V->getType()));
721   V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds);
722   // As that strip may trace through `addrspacecast`, need to sext or trunc
723   // the offset calculated.
724   return Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(V->getType()));
725 }
726 
727 /// Compute the constant difference between two pointer values.
728 /// If the difference is not a constant, returns zero.
729 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
730                                           Value *RHS) {
731   APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
732   APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
733 
734   // If LHS and RHS are not related via constant offsets to the same base
735   // value, there is nothing we can do here.
736   if (LHS != RHS)
737     return nullptr;
738 
739   // Otherwise, the difference of LHS - RHS can be computed as:
740   //    LHS - RHS
741   //  = (LHSOffset + Base) - (RHSOffset + Base)
742   //  = LHSOffset - RHSOffset
743   Constant *Res = ConstantInt::get(LHS->getContext(), LHSOffset - RHSOffset);
744   if (auto *VecTy = dyn_cast<VectorType>(LHS->getType()))
745     Res = ConstantVector::getSplat(VecTy->getElementCount(), Res);
746   return Res;
747 }
748 
749 /// Test if there is a dominating equivalence condition for the
750 /// two operands. If there is, try to reduce the binary operation
751 /// between the two operands.
752 /// Example: Op0 - Op1 --> 0 when Op0 == Op1
753 static Value *simplifyByDomEq(unsigned Opcode, Value *Op0, Value *Op1,
754                               const SimplifyQuery &Q, unsigned MaxRecurse) {
755   // Recursive run it can not get any benefit
756   if (MaxRecurse != RecursionLimit)
757     return nullptr;
758 
759   std::optional<bool> Imp =
760       isImpliedByDomCondition(CmpInst::ICMP_EQ, Op0, Op1, Q.CxtI, Q.DL);
761   if (Imp && *Imp) {
762     Type *Ty = Op0->getType();
763     switch (Opcode) {
764     case Instruction::Sub:
765     case Instruction::Xor:
766     case Instruction::URem:
767     case Instruction::SRem:
768       return Constant::getNullValue(Ty);
769 
770     case Instruction::SDiv:
771     case Instruction::UDiv:
772       return ConstantInt::get(Ty, 1);
773 
774     case Instruction::And:
775     case Instruction::Or:
776       // Could be either one - choose Op1 since that's more likely a constant.
777       return Op1;
778     default:
779       break;
780     }
781   }
782   return nullptr;
783 }
784 
785 /// Given operands for a Sub, see if we can fold the result.
786 /// If not, this returns null.
787 static Value *simplifySubInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
788                               const SimplifyQuery &Q, unsigned MaxRecurse) {
789   if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
790     return C;
791 
792   // X - poison -> poison
793   // poison - X -> poison
794   if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1))
795     return PoisonValue::get(Op0->getType());
796 
797   // X - undef -> undef
798   // undef - X -> undef
799   if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
800     return UndefValue::get(Op0->getType());
801 
802   // X - 0 -> X
803   if (match(Op1, m_Zero()))
804     return Op0;
805 
806   // X - X -> 0
807   if (Op0 == Op1)
808     return Constant::getNullValue(Op0->getType());
809 
810   // Is this a negation?
811   if (match(Op0, m_Zero())) {
812     // 0 - X -> 0 if the sub is NUW.
813     if (IsNUW)
814       return Constant::getNullValue(Op0->getType());
815 
816     KnownBits Known = computeKnownBits(Op1, /* Depth */ 0, Q);
817     if (Known.Zero.isMaxSignedValue()) {
818       // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
819       // Op1 must be 0 because negating the minimum signed value is undefined.
820       if (IsNSW)
821         return Constant::getNullValue(Op0->getType());
822 
823       // 0 - X -> X if X is 0 or the minimum signed value.
824       return Op1;
825     }
826   }
827 
828   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
829   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
830   Value *X = nullptr, *Y = nullptr, *Z = Op1;
831   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
832     // See if "V === Y - Z" simplifies.
833     if (Value *V = simplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse - 1))
834       // It does!  Now see if "X + V" simplifies.
835       if (Value *W = simplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse - 1)) {
836         // It does, we successfully reassociated!
837         ++NumReassoc;
838         return W;
839       }
840     // See if "V === X - Z" simplifies.
841     if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
842       // It does!  Now see if "Y + V" simplifies.
843       if (Value *W = simplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse - 1)) {
844         // It does, we successfully reassociated!
845         ++NumReassoc;
846         return W;
847       }
848   }
849 
850   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
851   // For example, X - (X + 1) -> -1
852   X = Op0;
853   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
854     // See if "V === X - Y" simplifies.
855     if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
856       // It does!  Now see if "V - Z" simplifies.
857       if (Value *W = simplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse - 1)) {
858         // It does, we successfully reassociated!
859         ++NumReassoc;
860         return W;
861       }
862     // See if "V === X - Z" simplifies.
863     if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
864       // It does!  Now see if "V - Y" simplifies.
865       if (Value *W = simplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse - 1)) {
866         // It does, we successfully reassociated!
867         ++NumReassoc;
868         return W;
869       }
870   }
871 
872   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
873   // For example, X - (X - Y) -> Y.
874   Z = Op0;
875   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
876     // See if "V === Z - X" simplifies.
877     if (Value *V = simplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse - 1))
878       // It does!  Now see if "V + Y" simplifies.
879       if (Value *W = simplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse - 1)) {
880         // It does, we successfully reassociated!
881         ++NumReassoc;
882         return W;
883       }
884 
885   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
886   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
887       match(Op1, m_Trunc(m_Value(Y))))
888     if (X->getType() == Y->getType())
889       // See if "V === X - Y" simplifies.
890       if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
891         // It does!  Now see if "trunc V" simplifies.
892         if (Value *W = simplifyCastInst(Instruction::Trunc, V, Op0->getType(),
893                                         Q, MaxRecurse - 1))
894           // It does, return the simplified "trunc V".
895           return W;
896 
897   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
898   if (match(Op0, m_PtrToInt(m_Value(X))) && match(Op1, m_PtrToInt(m_Value(Y))))
899     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
900       return ConstantFoldIntegerCast(Result, Op0->getType(), /*IsSigned*/ true,
901                                      Q.DL);
902 
903   // i1 sub -> xor.
904   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
905     if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
906       return V;
907 
908   // Threading Sub over selects and phi nodes is pointless, so don't bother.
909   // Threading over the select in "A - select(cond, B, C)" means evaluating
910   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
911   // only if B and C are equal.  If B and C are equal then (since we assume
912   // that operands have already been simplified) "select(cond, B, C)" should
913   // have been simplified to the common value of B and C already.  Analysing
914   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
915   // for threading over phi nodes.
916 
917   if (Value *V = simplifyByDomEq(Instruction::Sub, Op0, Op1, Q, MaxRecurse))
918     return V;
919 
920   return nullptr;
921 }
922 
923 Value *llvm::simplifySubInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
924                              const SimplifyQuery &Q) {
925   return ::simplifySubInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
926 }
927 
928 /// Given operands for a Mul, see if we can fold the result.
929 /// If not, this returns null.
930 static Value *simplifyMulInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
931                               const SimplifyQuery &Q, unsigned MaxRecurse) {
932   if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
933     return C;
934 
935   // X * poison -> poison
936   if (isa<PoisonValue>(Op1))
937     return Op1;
938 
939   // X * undef -> 0
940   // X * 0 -> 0
941   if (Q.isUndefValue(Op1) || match(Op1, m_Zero()))
942     return Constant::getNullValue(Op0->getType());
943 
944   // X * 1 -> X
945   if (match(Op1, m_One()))
946     return Op0;
947 
948   // (X / Y) * Y -> X if the division is exact.
949   Value *X = nullptr;
950   if (Q.IIQ.UseInstrInfo &&
951       (match(Op0,
952              m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) ||     // (X / Y) * Y
953        match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
954     return X;
955 
956    if (Op0->getType()->isIntOrIntVectorTy(1)) {
957     // mul i1 nsw is a special-case because -1 * -1 is poison (+1 is not
958     // representable). All other cases reduce to 0, so just return 0.
959     if (IsNSW)
960       return ConstantInt::getNullValue(Op0->getType());
961 
962     // Treat "mul i1" as "and i1".
963     if (MaxRecurse)
964       if (Value *V = simplifyAndInst(Op0, Op1, Q, MaxRecurse - 1))
965         return V;
966   }
967 
968   // Try some generic simplifications for associative operations.
969   if (Value *V =
970           simplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
971     return V;
972 
973   // Mul distributes over Add. Try some generic simplifications based on this.
974   if (Value *V = expandCommutativeBinOp(Instruction::Mul, Op0, Op1,
975                                         Instruction::Add, Q, MaxRecurse))
976     return V;
977 
978   // If the operation is with the result of a select instruction, check whether
979   // operating on either branch of the select always yields the same value.
980   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
981     if (Value *V =
982             threadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
983       return V;
984 
985   // If the operation is with the result of a phi instruction, check whether
986   // operating on all incoming values of the phi always yields the same value.
987   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
988     if (Value *V =
989             threadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
990       return V;
991 
992   return nullptr;
993 }
994 
995 Value *llvm::simplifyMulInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
996                              const SimplifyQuery &Q) {
997   return ::simplifyMulInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
998 }
999 
1000 /// Given a predicate and two operands, return true if the comparison is true.
1001 /// This is a helper for div/rem simplification where we return some other value
1002 /// when we can prove a relationship between the operands.
1003 static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
1004                        const SimplifyQuery &Q, unsigned MaxRecurse) {
1005   Value *V = simplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
1006   Constant *C = dyn_cast_or_null<Constant>(V);
1007   return (C && C->isAllOnesValue());
1008 }
1009 
1010 /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
1011 /// to simplify X % Y to X.
1012 static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
1013                       unsigned MaxRecurse, bool IsSigned) {
1014   // Recursion is always used, so bail out at once if we already hit the limit.
1015   if (!MaxRecurse--)
1016     return false;
1017 
1018   if (IsSigned) {
1019     // (X srem Y) sdiv Y --> 0
1020     if (match(X, m_SRem(m_Value(), m_Specific(Y))))
1021       return true;
1022 
1023     // |X| / |Y| --> 0
1024     //
1025     // We require that 1 operand is a simple constant. That could be extended to
1026     // 2 variables if we computed the sign bit for each.
1027     //
1028     // Make sure that a constant is not the minimum signed value because taking
1029     // the abs() of that is undefined.
1030     Type *Ty = X->getType();
1031     const APInt *C;
1032     if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
1033       // Is the variable divisor magnitude always greater than the constant
1034       // dividend magnitude?
1035       // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
1036       Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
1037       Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
1038       if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
1039           isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
1040         return true;
1041     }
1042     if (match(Y, m_APInt(C))) {
1043       // Special-case: we can't take the abs() of a minimum signed value. If
1044       // that's the divisor, then all we have to do is prove that the dividend
1045       // is also not the minimum signed value.
1046       if (C->isMinSignedValue())
1047         return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
1048 
1049       // Is the variable dividend magnitude always less than the constant
1050       // divisor magnitude?
1051       // |X| < |C| --> X > -abs(C) and X < abs(C)
1052       Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
1053       Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
1054       if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
1055           isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
1056         return true;
1057     }
1058     return false;
1059   }
1060 
1061   // IsSigned == false.
1062 
1063   // Is the unsigned dividend known to be less than a constant divisor?
1064   // TODO: Convert this (and above) to range analysis
1065   //      ("computeConstantRangeIncludingKnownBits")?
1066   const APInt *C;
1067   if (match(Y, m_APInt(C)) &&
1068       computeKnownBits(X, /* Depth */ 0, Q).getMaxValue().ult(*C))
1069     return true;
1070 
1071   // Try again for any divisor:
1072   // Is the dividend unsigned less than the divisor?
1073   return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
1074 }
1075 
1076 /// Check for common or similar folds of integer division or integer remainder.
1077 /// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
1078 static Value *simplifyDivRem(Instruction::BinaryOps Opcode, Value *Op0,
1079                              Value *Op1, const SimplifyQuery &Q,
1080                              unsigned MaxRecurse) {
1081   bool IsDiv = (Opcode == Instruction::SDiv || Opcode == Instruction::UDiv);
1082   bool IsSigned = (Opcode == Instruction::SDiv || Opcode == Instruction::SRem);
1083 
1084   Type *Ty = Op0->getType();
1085 
1086   // X / undef -> poison
1087   // X % undef -> poison
1088   if (Q.isUndefValue(Op1) || isa<PoisonValue>(Op1))
1089     return PoisonValue::get(Ty);
1090 
1091   // X / 0 -> poison
1092   // X % 0 -> poison
1093   // We don't need to preserve faults!
1094   if (match(Op1, m_Zero()))
1095     return PoisonValue::get(Ty);
1096 
1097   // If any element of a constant divisor fixed width vector is zero or undef
1098   // the behavior is undefined and we can fold the whole op to poison.
1099   auto *Op1C = dyn_cast<Constant>(Op1);
1100   auto *VTy = dyn_cast<FixedVectorType>(Ty);
1101   if (Op1C && VTy) {
1102     unsigned NumElts = VTy->getNumElements();
1103     for (unsigned i = 0; i != NumElts; ++i) {
1104       Constant *Elt = Op1C->getAggregateElement(i);
1105       if (Elt && (Elt->isNullValue() || Q.isUndefValue(Elt)))
1106         return PoisonValue::get(Ty);
1107     }
1108   }
1109 
1110   // poison / X -> poison
1111   // poison % X -> poison
1112   if (isa<PoisonValue>(Op0))
1113     return Op0;
1114 
1115   // undef / X -> 0
1116   // undef % X -> 0
1117   if (Q.isUndefValue(Op0))
1118     return Constant::getNullValue(Ty);
1119 
1120   // 0 / X -> 0
1121   // 0 % X -> 0
1122   if (match(Op0, m_Zero()))
1123     return Constant::getNullValue(Op0->getType());
1124 
1125   // X / X -> 1
1126   // X % X -> 0
1127   if (Op0 == Op1)
1128     return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
1129 
1130   KnownBits Known = computeKnownBits(Op1, /* Depth */ 0, Q);
1131   // X / 0 -> poison
1132   // X % 0 -> poison
1133   // If the divisor is known to be zero, just return poison. This can happen in
1134   // some cases where its provable indirectly the denominator is zero but it's
1135   // not trivially simplifiable (i.e known zero through a phi node).
1136   if (Known.isZero())
1137     return PoisonValue::get(Ty);
1138 
1139   // X / 1 -> X
1140   // X % 1 -> 0
1141   // If the divisor can only be zero or one, we can't have division-by-zero
1142   // or remainder-by-zero, so assume the divisor is 1.
1143   //   e.g. 1, zext (i8 X), sdiv X (Y and 1)
1144   if (Known.countMinLeadingZeros() == Known.getBitWidth() - 1)
1145     return IsDiv ? Op0 : Constant::getNullValue(Ty);
1146 
1147   // If X * Y does not overflow, then:
1148   //   X * Y / Y -> X
1149   //   X * Y % Y -> 0
1150   Value *X;
1151   if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
1152     auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1153     // The multiplication can't overflow if it is defined not to, or if
1154     // X == A / Y for some A.
1155     if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
1156         (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)) ||
1157         (IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
1158         (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1))))) {
1159       return IsDiv ? X : Constant::getNullValue(Op0->getType());
1160     }
1161   }
1162 
1163   if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1164     return IsDiv ? Constant::getNullValue(Op0->getType()) : Op0;
1165 
1166   if (Value *V = simplifyByDomEq(Opcode, Op0, Op1, Q, MaxRecurse))
1167     return V;
1168 
1169   // If the operation is with the result of a select instruction, check whether
1170   // operating on either branch of the select always yields the same value.
1171   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1172     if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1173       return V;
1174 
1175   // If the operation is with the result of a phi instruction, check whether
1176   // operating on all incoming values of the phi always yields the same value.
1177   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1178     if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1179       return V;
1180 
1181   return nullptr;
1182 }
1183 
1184 /// These are simplifications common to SDiv and UDiv.
1185 static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1186                           bool IsExact, const SimplifyQuery &Q,
1187                           unsigned MaxRecurse) {
1188   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1189     return C;
1190 
1191   if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
1192     return V;
1193 
1194   const APInt *DivC;
1195   if (IsExact && match(Op1, m_APInt(DivC))) {
1196     // If this is an exact divide by a constant, then the dividend (Op0) must
1197     // have at least as many trailing zeros as the divisor to divide evenly. If
1198     // it has less trailing zeros, then the result must be poison.
1199     if (DivC->countr_zero()) {
1200       KnownBits KnownOp0 = computeKnownBits(Op0, /* Depth */ 0, Q);
1201       if (KnownOp0.countMaxTrailingZeros() < DivC->countr_zero())
1202         return PoisonValue::get(Op0->getType());
1203     }
1204 
1205     // udiv exact (mul nsw X, C), C --> X
1206     // sdiv exact (mul nuw X, C), C --> X
1207     // where C is not a power of 2.
1208     Value *X;
1209     if (!DivC->isPowerOf2() &&
1210         (Opcode == Instruction::UDiv
1211              ? match(Op0, m_NSWMul(m_Value(X), m_Specific(Op1)))
1212              : match(Op0, m_NUWMul(m_Value(X), m_Specific(Op1)))))
1213       return X;
1214   }
1215 
1216   return nullptr;
1217 }
1218 
1219 /// These are simplifications common to SRem and URem.
1220 static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1221                           const SimplifyQuery &Q, unsigned MaxRecurse) {
1222   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1223     return C;
1224 
1225   if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
1226     return V;
1227 
1228   // (X << Y) % X -> 0
1229   if (Q.IIQ.UseInstrInfo) {
1230     if ((Opcode == Instruction::SRem &&
1231          match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1232         (Opcode == Instruction::URem &&
1233          match(Op0, m_NUWShl(m_Specific(Op1), m_Value()))))
1234       return Constant::getNullValue(Op0->getType());
1235 
1236     const APInt *C0;
1237     if (match(Op1, m_APInt(C0))) {
1238       // (srem (mul nsw X, C1), C0) -> 0 if C1 s% C0 == 0
1239       // (urem (mul nuw X, C1), C0) -> 0 if C1 u% C0 == 0
1240       if (Opcode == Instruction::SRem
1241               ? match(Op0,
1242                       m_NSWMul(m_Value(), m_CheckedInt([C0](const APInt &C) {
1243                                  return C.srem(*C0).isZero();
1244                                })))
1245               : match(Op0,
1246                       m_NUWMul(m_Value(), m_CheckedInt([C0](const APInt &C) {
1247                                  return C.urem(*C0).isZero();
1248                                }))))
1249         return Constant::getNullValue(Op0->getType());
1250     }
1251   }
1252   return nullptr;
1253 }
1254 
1255 /// Given operands for an SDiv, see if we can fold the result.
1256 /// If not, this returns null.
1257 static Value *simplifySDivInst(Value *Op0, Value *Op1, bool IsExact,
1258                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1259   // If two operands are negated and no signed overflow, return -1.
1260   if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
1261     return Constant::getAllOnesValue(Op0->getType());
1262 
1263   return simplifyDiv(Instruction::SDiv, Op0, Op1, IsExact, Q, MaxRecurse);
1264 }
1265 
1266 Value *llvm::simplifySDivInst(Value *Op0, Value *Op1, bool IsExact,
1267                               const SimplifyQuery &Q) {
1268   return ::simplifySDivInst(Op0, Op1, IsExact, Q, RecursionLimit);
1269 }
1270 
1271 /// Given operands for a UDiv, see if we can fold the result.
1272 /// If not, this returns null.
1273 static Value *simplifyUDivInst(Value *Op0, Value *Op1, bool IsExact,
1274                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1275   return simplifyDiv(Instruction::UDiv, Op0, Op1, IsExact, Q, MaxRecurse);
1276 }
1277 
1278 Value *llvm::simplifyUDivInst(Value *Op0, Value *Op1, bool IsExact,
1279                               const SimplifyQuery &Q) {
1280   return ::simplifyUDivInst(Op0, Op1, IsExact, Q, RecursionLimit);
1281 }
1282 
1283 /// Given operands for an SRem, see if we can fold the result.
1284 /// If not, this returns null.
1285 static Value *simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1286                                unsigned MaxRecurse) {
1287   // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1288   // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1289   Value *X;
1290   if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1291     return ConstantInt::getNullValue(Op0->getType());
1292 
1293   // If the two operands are negated, return 0.
1294   if (isKnownNegation(Op0, Op1))
1295     return ConstantInt::getNullValue(Op0->getType());
1296 
1297   return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
1298 }
1299 
1300 Value *llvm::simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1301   return ::simplifySRemInst(Op0, Op1, Q, RecursionLimit);
1302 }
1303 
1304 /// Given operands for a URem, see if we can fold the result.
1305 /// If not, this returns null.
1306 static Value *simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1307                                unsigned MaxRecurse) {
1308   return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
1309 }
1310 
1311 Value *llvm::simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1312   return ::simplifyURemInst(Op0, Op1, Q, RecursionLimit);
1313 }
1314 
1315 /// Returns true if a shift by \c Amount always yields poison.
1316 static bool isPoisonShift(Value *Amount, const SimplifyQuery &Q) {
1317   Constant *C = dyn_cast<Constant>(Amount);
1318   if (!C)
1319     return false;
1320 
1321   // X shift by undef -> poison because it may shift by the bitwidth.
1322   if (Q.isUndefValue(C))
1323     return true;
1324 
1325   // Shifting by the bitwidth or more is poison. This covers scalars and
1326   // fixed/scalable vectors with splat constants.
1327   const APInt *AmountC;
1328   if (match(C, m_APInt(AmountC)) && AmountC->uge(AmountC->getBitWidth()))
1329     return true;
1330 
1331   // Try harder for fixed-length vectors:
1332   // If all lanes of a vector shift are poison, the whole shift is poison.
1333   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1334     for (unsigned I = 0,
1335                   E = cast<FixedVectorType>(C->getType())->getNumElements();
1336          I != E; ++I)
1337       if (!isPoisonShift(C->getAggregateElement(I), Q))
1338         return false;
1339     return true;
1340   }
1341 
1342   return false;
1343 }
1344 
1345 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1346 /// If not, this returns null.
1347 static Value *simplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
1348                             Value *Op1, bool IsNSW, const SimplifyQuery &Q,
1349                             unsigned MaxRecurse) {
1350   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1351     return C;
1352 
1353   // poison shift by X -> poison
1354   if (isa<PoisonValue>(Op0))
1355     return Op0;
1356 
1357   // 0 shift by X -> 0
1358   if (match(Op0, m_Zero()))
1359     return Constant::getNullValue(Op0->getType());
1360 
1361   // X shift by 0 -> X
1362   // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1363   // would be poison.
1364   Value *X;
1365   if (match(Op1, m_Zero()) ||
1366       (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1367     return Op0;
1368 
1369   // Fold undefined shifts.
1370   if (isPoisonShift(Op1, Q))
1371     return PoisonValue::get(Op0->getType());
1372 
1373   // If the operation is with the result of a select instruction, check whether
1374   // operating on either branch of the select always yields the same value.
1375   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1376     if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1377       return V;
1378 
1379   // If the operation is with the result of a phi instruction, check whether
1380   // operating on all incoming values of the phi always yields the same value.
1381   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1382     if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1383       return V;
1384 
1385   // If any bits in the shift amount make that value greater than or equal to
1386   // the number of bits in the type, the shift is undefined.
1387   KnownBits KnownAmt = computeKnownBits(Op1, /* Depth */ 0, Q);
1388   if (KnownAmt.getMinValue().uge(KnownAmt.getBitWidth()))
1389     return PoisonValue::get(Op0->getType());
1390 
1391   // If all valid bits in the shift amount are known zero, the first operand is
1392   // unchanged.
1393   unsigned NumValidShiftBits = Log2_32_Ceil(KnownAmt.getBitWidth());
1394   if (KnownAmt.countMinTrailingZeros() >= NumValidShiftBits)
1395     return Op0;
1396 
1397   // Check for nsw shl leading to a poison value.
1398   if (IsNSW) {
1399     assert(Opcode == Instruction::Shl && "Expected shl for nsw instruction");
1400     KnownBits KnownVal = computeKnownBits(Op0, /* Depth */ 0, Q);
1401     KnownBits KnownShl = KnownBits::shl(KnownVal, KnownAmt);
1402 
1403     if (KnownVal.Zero.isSignBitSet())
1404       KnownShl.Zero.setSignBit();
1405     if (KnownVal.One.isSignBitSet())
1406       KnownShl.One.setSignBit();
1407 
1408     if (KnownShl.hasConflict())
1409       return PoisonValue::get(Op0->getType());
1410   }
1411 
1412   return nullptr;
1413 }
1414 
1415 /// Given operands for an LShr or AShr, see if we can fold the result.  If not,
1416 /// this returns null.
1417 static Value *simplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
1418                                  Value *Op1, bool IsExact,
1419                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
1420   if (Value *V =
1421           simplifyShift(Opcode, Op0, Op1, /*IsNSW*/ false, Q, MaxRecurse))
1422     return V;
1423 
1424   // X >> X -> 0
1425   if (Op0 == Op1)
1426     return Constant::getNullValue(Op0->getType());
1427 
1428   // undef >> X -> 0
1429   // undef >> X -> undef (if it's exact)
1430   if (Q.isUndefValue(Op0))
1431     return IsExact ? Op0 : Constant::getNullValue(Op0->getType());
1432 
1433   // The low bit cannot be shifted out of an exact shift if it is set.
1434   // TODO: Generalize by counting trailing zeros (see fold for exact division).
1435   if (IsExact) {
1436     KnownBits Op0Known = computeKnownBits(Op0, /* Depth */ 0, Q);
1437     if (Op0Known.One[0])
1438       return Op0;
1439   }
1440 
1441   return nullptr;
1442 }
1443 
1444 /// Given operands for an Shl, see if we can fold the result.
1445 /// If not, this returns null.
1446 static Value *simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
1447                               const SimplifyQuery &Q, unsigned MaxRecurse) {
1448   if (Value *V =
1449           simplifyShift(Instruction::Shl, Op0, Op1, IsNSW, Q, MaxRecurse))
1450     return V;
1451 
1452   Type *Ty = Op0->getType();
1453   // undef << X -> 0
1454   // undef << X -> undef if (if it's NSW/NUW)
1455   if (Q.isUndefValue(Op0))
1456     return IsNSW || IsNUW ? Op0 : Constant::getNullValue(Ty);
1457 
1458   // (X >> A) << A -> X
1459   Value *X;
1460   if (Q.IIQ.UseInstrInfo &&
1461       match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1462     return X;
1463 
1464   // shl nuw i8 C, %x  ->  C  iff C has sign bit set.
1465   if (IsNUW && match(Op0, m_Negative()))
1466     return Op0;
1467   // NOTE: could use computeKnownBits() / LazyValueInfo,
1468   // but the cost-benefit analysis suggests it isn't worth it.
1469 
1470   // "nuw" guarantees that only zeros are shifted out, and "nsw" guarantees
1471   // that the sign-bit does not change, so the only input that does not
1472   // produce poison is 0, and "0 << (bitwidth-1) --> 0".
1473   if (IsNSW && IsNUW &&
1474       match(Op1, m_SpecificInt(Ty->getScalarSizeInBits() - 1)))
1475     return Constant::getNullValue(Ty);
1476 
1477   return nullptr;
1478 }
1479 
1480 Value *llvm::simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
1481                              const SimplifyQuery &Q) {
1482   return ::simplifyShlInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
1483 }
1484 
1485 /// Given operands for an LShr, see if we can fold the result.
1486 /// If not, this returns null.
1487 static Value *simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
1488                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1489   if (Value *V = simplifyRightShift(Instruction::LShr, Op0, Op1, IsExact, Q,
1490                                     MaxRecurse))
1491     return V;
1492 
1493   // (X << A) >> A -> X
1494   Value *X;
1495   if (Q.IIQ.UseInstrInfo && match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1496     return X;
1497 
1498   // ((X << A) | Y) >> A -> X  if effective width of Y is not larger than A.
1499   // We can return X as we do in the above case since OR alters no bits in X.
1500   // SimplifyDemandedBits in InstCombine can do more general optimization for
1501   // bit manipulation. This pattern aims to provide opportunities for other
1502   // optimizers by supporting a simple but common case in InstSimplify.
1503   Value *Y;
1504   const APInt *ShRAmt, *ShLAmt;
1505   if (Q.IIQ.UseInstrInfo && match(Op1, m_APInt(ShRAmt)) &&
1506       match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
1507       *ShRAmt == *ShLAmt) {
1508     const KnownBits YKnown = computeKnownBits(Y, /* Depth */ 0, Q);
1509     const unsigned EffWidthY = YKnown.countMaxActiveBits();
1510     if (ShRAmt->uge(EffWidthY))
1511       return X;
1512   }
1513 
1514   return nullptr;
1515 }
1516 
1517 Value *llvm::simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
1518                               const SimplifyQuery &Q) {
1519   return ::simplifyLShrInst(Op0, Op1, IsExact, Q, RecursionLimit);
1520 }
1521 
1522 /// Given operands for an AShr, see if we can fold the result.
1523 /// If not, this returns null.
1524 static Value *simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
1525                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1526   if (Value *V = simplifyRightShift(Instruction::AShr, Op0, Op1, IsExact, Q,
1527                                     MaxRecurse))
1528     return V;
1529 
1530   // -1 >>a X --> -1
1531   // (-1 << X) a>> X --> -1
1532   // We could return the original -1 constant to preserve poison elements.
1533   if (match(Op0, m_AllOnes()) ||
1534       match(Op0, m_Shl(m_AllOnes(), m_Specific(Op1))))
1535     return Constant::getAllOnesValue(Op0->getType());
1536 
1537   // (X << A) >> A -> X
1538   Value *X;
1539   if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1540     return X;
1541 
1542   // Arithmetic shifting an all-sign-bit value is a no-op.
1543   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1544   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1545     return Op0;
1546 
1547   return nullptr;
1548 }
1549 
1550 Value *llvm::simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
1551                               const SimplifyQuery &Q) {
1552   return ::simplifyAShrInst(Op0, Op1, IsExact, Q, RecursionLimit);
1553 }
1554 
1555 /// Commuted variants are assumed to be handled by calling this function again
1556 /// with the parameters swapped.
1557 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1558                                          ICmpInst *UnsignedICmp, bool IsAnd,
1559                                          const SimplifyQuery &Q) {
1560   Value *X, *Y;
1561 
1562   ICmpInst::Predicate EqPred;
1563   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1564       !ICmpInst::isEquality(EqPred))
1565     return nullptr;
1566 
1567   ICmpInst::Predicate UnsignedPred;
1568 
1569   Value *A, *B;
1570   // Y = (A - B);
1571   if (match(Y, m_Sub(m_Value(A), m_Value(B)))) {
1572     if (match(UnsignedICmp,
1573               m_c_ICmp(UnsignedPred, m_Specific(A), m_Specific(B))) &&
1574         ICmpInst::isUnsigned(UnsignedPred)) {
1575       // A >=/<= B || (A - B) != 0  <-->  true
1576       if ((UnsignedPred == ICmpInst::ICMP_UGE ||
1577            UnsignedPred == ICmpInst::ICMP_ULE) &&
1578           EqPred == ICmpInst::ICMP_NE && !IsAnd)
1579         return ConstantInt::getTrue(UnsignedICmp->getType());
1580       // A </> B && (A - B) == 0  <-->  false
1581       if ((UnsignedPred == ICmpInst::ICMP_ULT ||
1582            UnsignedPred == ICmpInst::ICMP_UGT) &&
1583           EqPred == ICmpInst::ICMP_EQ && IsAnd)
1584         return ConstantInt::getFalse(UnsignedICmp->getType());
1585 
1586       // A </> B && (A - B) != 0  <-->  A </> B
1587       // A </> B || (A - B) != 0  <-->  (A - B) != 0
1588       if (EqPred == ICmpInst::ICMP_NE && (UnsignedPred == ICmpInst::ICMP_ULT ||
1589                                           UnsignedPred == ICmpInst::ICMP_UGT))
1590         return IsAnd ? UnsignedICmp : ZeroICmp;
1591 
1592       // A <=/>= B && (A - B) == 0  <-->  (A - B) == 0
1593       // A <=/>= B || (A - B) == 0  <-->  A <=/>= B
1594       if (EqPred == ICmpInst::ICMP_EQ && (UnsignedPred == ICmpInst::ICMP_ULE ||
1595                                           UnsignedPred == ICmpInst::ICMP_UGE))
1596         return IsAnd ? ZeroICmp : UnsignedICmp;
1597     }
1598 
1599     // Given  Y = (A - B)
1600     //   Y >= A && Y != 0  --> Y >= A  iff B != 0
1601     //   Y <  A || Y == 0  --> Y <  A  iff B != 0
1602     if (match(UnsignedICmp,
1603               m_c_ICmp(UnsignedPred, m_Specific(Y), m_Specific(A)))) {
1604       if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd &&
1605           EqPred == ICmpInst::ICMP_NE && isKnownNonZero(B, Q))
1606         return UnsignedICmp;
1607       if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd &&
1608           EqPred == ICmpInst::ICMP_EQ && isKnownNonZero(B, Q))
1609         return UnsignedICmp;
1610     }
1611   }
1612 
1613   if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1614       ICmpInst::isUnsigned(UnsignedPred))
1615     ;
1616   else if (match(UnsignedICmp,
1617                  m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
1618            ICmpInst::isUnsigned(UnsignedPred))
1619     UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1620   else
1621     return nullptr;
1622 
1623   // X > Y && Y == 0  -->  Y == 0  iff X != 0
1624   // X > Y || Y == 0  -->  X > Y   iff X != 0
1625   if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1626       isKnownNonZero(X, Q))
1627     return IsAnd ? ZeroICmp : UnsignedICmp;
1628 
1629   // X <= Y && Y != 0  -->  X <= Y  iff X != 0
1630   // X <= Y || Y != 0  -->  Y != 0  iff X != 0
1631   if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1632       isKnownNonZero(X, Q))
1633     return IsAnd ? UnsignedICmp : ZeroICmp;
1634 
1635   // The transforms below here are expected to be handled more generally with
1636   // simplifyAndOrOfICmpsWithLimitConst() or in InstCombine's
1637   // foldAndOrOfICmpsWithConstEq(). If we are looking to trim optimizer overlap,
1638   // these are candidates for removal.
1639 
1640   // X < Y && Y != 0  -->  X < Y
1641   // X < Y || Y != 0  -->  Y != 0
1642   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1643     return IsAnd ? UnsignedICmp : ZeroICmp;
1644 
1645   // X >= Y && Y == 0  -->  Y == 0
1646   // X >= Y || Y == 0  -->  X >= Y
1647   if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ)
1648     return IsAnd ? ZeroICmp : UnsignedICmp;
1649 
1650   // X < Y && Y == 0  -->  false
1651   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1652       IsAnd)
1653     return getFalse(UnsignedICmp->getType());
1654 
1655   // X >= Y || Y != 0  -->  true
1656   if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_NE &&
1657       !IsAnd)
1658     return getTrue(UnsignedICmp->getType());
1659 
1660   return nullptr;
1661 }
1662 
1663 /// Test if a pair of compares with a shared operand and 2 constants has an
1664 /// empty set intersection, full set union, or if one compare is a superset of
1665 /// the other.
1666 static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
1667                                                 bool IsAnd) {
1668   // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1669   if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1670     return nullptr;
1671 
1672   const APInt *C0, *C1;
1673   if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1674       !match(Cmp1->getOperand(1), m_APInt(C1)))
1675     return nullptr;
1676 
1677   auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1678   auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1679 
1680   // For and-of-compares, check if the intersection is empty:
1681   // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1682   if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1683     return getFalse(Cmp0->getType());
1684 
1685   // For or-of-compares, check if the union is full:
1686   // (icmp X, C0) || (icmp X, C1) --> full set --> true
1687   if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1688     return getTrue(Cmp0->getType());
1689 
1690   // Is one range a superset of the other?
1691   // If this is and-of-compares, take the smaller set:
1692   // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1693   // If this is or-of-compares, take the larger set:
1694   // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1695   if (Range0.contains(Range1))
1696     return IsAnd ? Cmp1 : Cmp0;
1697   if (Range1.contains(Range0))
1698     return IsAnd ? Cmp0 : Cmp1;
1699 
1700   return nullptr;
1701 }
1702 
1703 static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1704                                         const InstrInfoQuery &IIQ) {
1705   // (icmp (add V, C0), C1) & (icmp V, C0)
1706   ICmpInst::Predicate Pred0, Pred1;
1707   const APInt *C0, *C1;
1708   Value *V;
1709   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1710     return nullptr;
1711 
1712   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1713     return nullptr;
1714 
1715   auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
1716   if (AddInst->getOperand(1) != Op1->getOperand(1))
1717     return nullptr;
1718 
1719   Type *ITy = Op0->getType();
1720   bool IsNSW = IIQ.hasNoSignedWrap(AddInst);
1721   bool IsNUW = IIQ.hasNoUnsignedWrap(AddInst);
1722 
1723   const APInt Delta = *C1 - *C0;
1724   if (C0->isStrictlyPositive()) {
1725     if (Delta == 2) {
1726       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1727         return getFalse(ITy);
1728       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && IsNSW)
1729         return getFalse(ITy);
1730     }
1731     if (Delta == 1) {
1732       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1733         return getFalse(ITy);
1734       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && IsNSW)
1735         return getFalse(ITy);
1736     }
1737   }
1738   if (C0->getBoolValue() && IsNUW) {
1739     if (Delta == 2)
1740       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1741         return getFalse(ITy);
1742     if (Delta == 1)
1743       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1744         return getFalse(ITy);
1745   }
1746 
1747   return nullptr;
1748 }
1749 
1750 /// Try to simplify and/or of icmp with ctpop intrinsic.
1751 static Value *simplifyAndOrOfICmpsWithCtpop(ICmpInst *Cmp0, ICmpInst *Cmp1,
1752                                             bool IsAnd) {
1753   ICmpInst::Predicate Pred0, Pred1;
1754   Value *X;
1755   const APInt *C;
1756   if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
1757                           m_APInt(C))) ||
1758       !match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())) || C->isZero())
1759     return nullptr;
1760 
1761   // (ctpop(X) == C) || (X != 0) --> X != 0 where C > 0
1762   if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_NE)
1763     return Cmp1;
1764   // (ctpop(X) != C) && (X == 0) --> X == 0 where C > 0
1765   if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_EQ)
1766     return Cmp1;
1767 
1768   return nullptr;
1769 }
1770 
1771 static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1772                                  const SimplifyQuery &Q) {
1773   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true, Q))
1774     return X;
1775   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true, Q))
1776     return X;
1777 
1778   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
1779     return X;
1780 
1781   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, true))
1782     return X;
1783   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, true))
1784     return X;
1785 
1786   if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1787     return X;
1788   if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1789     return X;
1790 
1791   return nullptr;
1792 }
1793 
1794 static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1795                                        const InstrInfoQuery &IIQ) {
1796   // (icmp (add V, C0), C1) | (icmp V, C0)
1797   ICmpInst::Predicate Pred0, Pred1;
1798   const APInt *C0, *C1;
1799   Value *V;
1800   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1801     return nullptr;
1802 
1803   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1804     return nullptr;
1805 
1806   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1807   if (AddInst->getOperand(1) != Op1->getOperand(1))
1808     return nullptr;
1809 
1810   Type *ITy = Op0->getType();
1811   bool IsNSW = IIQ.hasNoSignedWrap(AddInst);
1812   bool IsNUW = IIQ.hasNoUnsignedWrap(AddInst);
1813 
1814   const APInt Delta = *C1 - *C0;
1815   if (C0->isStrictlyPositive()) {
1816     if (Delta == 2) {
1817       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1818         return getTrue(ITy);
1819       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && IsNSW)
1820         return getTrue(ITy);
1821     }
1822     if (Delta == 1) {
1823       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1824         return getTrue(ITy);
1825       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && IsNSW)
1826         return getTrue(ITy);
1827     }
1828   }
1829   if (C0->getBoolValue() && IsNUW) {
1830     if (Delta == 2)
1831       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1832         return getTrue(ITy);
1833     if (Delta == 1)
1834       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1835         return getTrue(ITy);
1836   }
1837 
1838   return nullptr;
1839 }
1840 
1841 static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1842                                 const SimplifyQuery &Q) {
1843   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false, Q))
1844     return X;
1845   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false, Q))
1846     return X;
1847 
1848   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1849     return X;
1850 
1851   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, false))
1852     return X;
1853   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, false))
1854     return X;
1855 
1856   if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1857     return X;
1858   if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1859     return X;
1860 
1861   return nullptr;
1862 }
1863 
1864 static Value *simplifyAndOrOfFCmps(const SimplifyQuery &Q, FCmpInst *LHS,
1865                                    FCmpInst *RHS, bool IsAnd) {
1866   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1867   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1868   if (LHS0->getType() != RHS0->getType())
1869     return nullptr;
1870 
1871   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1872   if ((PredL == FCmpInst::FCMP_ORD || PredL == FCmpInst::FCMP_UNO) &&
1873       ((FCmpInst::isOrdered(PredR) && IsAnd) ||
1874        (FCmpInst::isUnordered(PredR) && !IsAnd))) {
1875     // (fcmp ord X, 0) & (fcmp o** X, Y) --> fcmp o** X, Y
1876     // (fcmp uno X, 0) & (fcmp o** X, Y) --> false
1877     // (fcmp uno X, 0) | (fcmp u** X, Y) --> fcmp u** X, Y
1878     // (fcmp ord X, 0) | (fcmp u** X, Y) --> true
1879     if ((LHS0 == RHS0 || LHS0 == RHS1) && match(LHS1, m_PosZeroFP()))
1880       return FCmpInst::isOrdered(PredL) == FCmpInst::isOrdered(PredR)
1881                  ? static_cast<Value *>(RHS)
1882                  : ConstantInt::getBool(LHS->getType(), !IsAnd);
1883   }
1884 
1885   if ((PredR == FCmpInst::FCMP_ORD || PredR == FCmpInst::FCMP_UNO) &&
1886       ((FCmpInst::isOrdered(PredL) && IsAnd) ||
1887        (FCmpInst::isUnordered(PredL) && !IsAnd))) {
1888     // (fcmp o** X, Y) & (fcmp ord X, 0) --> fcmp o** X, Y
1889     // (fcmp o** X, Y) & (fcmp uno X, 0) --> false
1890     // (fcmp u** X, Y) | (fcmp uno X, 0) --> fcmp u** X, Y
1891     // (fcmp u** X, Y) | (fcmp ord X, 0) --> true
1892     if ((RHS0 == LHS0 || RHS0 == LHS1) && match(RHS1, m_PosZeroFP()))
1893       return FCmpInst::isOrdered(PredL) == FCmpInst::isOrdered(PredR)
1894                  ? static_cast<Value *>(LHS)
1895                  : ConstantInt::getBool(LHS->getType(), !IsAnd);
1896   }
1897 
1898   return nullptr;
1899 }
1900 
1901 static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q, Value *Op0,
1902                                   Value *Op1, bool IsAnd) {
1903   // Look through casts of the 'and' operands to find compares.
1904   auto *Cast0 = dyn_cast<CastInst>(Op0);
1905   auto *Cast1 = dyn_cast<CastInst>(Op1);
1906   if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1907       Cast0->getSrcTy() == Cast1->getSrcTy()) {
1908     Op0 = Cast0->getOperand(0);
1909     Op1 = Cast1->getOperand(0);
1910   }
1911 
1912   Value *V = nullptr;
1913   auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1914   auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1915   if (ICmp0 && ICmp1)
1916     V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q)
1917               : simplifyOrOfICmps(ICmp0, ICmp1, Q);
1918 
1919   auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
1920   auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
1921   if (FCmp0 && FCmp1)
1922     V = simplifyAndOrOfFCmps(Q, FCmp0, FCmp1, IsAnd);
1923 
1924   if (!V)
1925     return nullptr;
1926   if (!Cast0)
1927     return V;
1928 
1929   // If we looked through casts, we can only handle a constant simplification
1930   // because we are not allowed to create a cast instruction here.
1931   if (auto *C = dyn_cast<Constant>(V))
1932     return ConstantFoldCastOperand(Cast0->getOpcode(), C, Cast0->getType(),
1933                                    Q.DL);
1934 
1935   return nullptr;
1936 }
1937 
1938 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
1939                                      const SimplifyQuery &Q,
1940                                      bool AllowRefinement,
1941                                      SmallVectorImpl<Instruction *> *DropFlags,
1942                                      unsigned MaxRecurse);
1943 
1944 static Value *simplifyAndOrWithICmpEq(unsigned Opcode, Value *Op0, Value *Op1,
1945                                       const SimplifyQuery &Q,
1946                                       unsigned MaxRecurse) {
1947   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1948          "Must be and/or");
1949   ICmpInst::Predicate Pred;
1950   Value *A, *B;
1951   if (!match(Op0, m_ICmp(Pred, m_Value(A), m_Value(B))) ||
1952       !ICmpInst::isEquality(Pred))
1953     return nullptr;
1954 
1955   auto Simplify = [&](Value *Res) -> Value * {
1956     Constant *Absorber = ConstantExpr::getBinOpAbsorber(Opcode, Res->getType());
1957 
1958     // and (icmp eq a, b), x implies (a==b) inside x.
1959     // or (icmp ne a, b), x implies (a==b) inside x.
1960     // If x simplifies to true/false, we can simplify the and/or.
1961     if (Pred ==
1962         (Opcode == Instruction::And ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
1963       if (Res == Absorber)
1964         return Absorber;
1965       if (Res == ConstantExpr::getBinOpIdentity(Opcode, Res->getType()))
1966         return Op0;
1967       return nullptr;
1968     }
1969 
1970     // If we have and (icmp ne a, b), x and for a==b we can simplify x to false,
1971     // then we can drop the icmp, as x will already be false in the case where
1972     // the icmp is false. Similar for or and true.
1973     if (Res == Absorber)
1974       return Op1;
1975     return nullptr;
1976   };
1977 
1978   if (Value *Res =
1979           simplifyWithOpReplaced(Op1, A, B, Q, /* AllowRefinement */ true,
1980                                  /* DropFlags */ nullptr, MaxRecurse))
1981     return Simplify(Res);
1982   if (Value *Res =
1983           simplifyWithOpReplaced(Op1, B, A, Q, /* AllowRefinement */ true,
1984                                  /* DropFlags */ nullptr, MaxRecurse))
1985     return Simplify(Res);
1986 
1987   return nullptr;
1988 }
1989 
1990 /// Given a bitwise logic op, check if the operands are add/sub with a common
1991 /// source value and inverted constant (identity: C - X -> ~(X + ~C)).
1992 static Value *simplifyLogicOfAddSub(Value *Op0, Value *Op1,
1993                                     Instruction::BinaryOps Opcode) {
1994   assert(Op0->getType() == Op1->getType() && "Mismatched binop types");
1995   assert(BinaryOperator::isBitwiseLogicOp(Opcode) && "Expected logic op");
1996   Value *X;
1997   Constant *C1, *C2;
1998   if ((match(Op0, m_Add(m_Value(X), m_Constant(C1))) &&
1999        match(Op1, m_Sub(m_Constant(C2), m_Specific(X)))) ||
2000       (match(Op1, m_Add(m_Value(X), m_Constant(C1))) &&
2001        match(Op0, m_Sub(m_Constant(C2), m_Specific(X))))) {
2002     if (ConstantExpr::getNot(C1) == C2) {
2003       // (X + C) & (~C - X) --> (X + C) & ~(X + C) --> 0
2004       // (X + C) | (~C - X) --> (X + C) | ~(X + C) --> -1
2005       // (X + C) ^ (~C - X) --> (X + C) ^ ~(X + C) --> -1
2006       Type *Ty = Op0->getType();
2007       return Opcode == Instruction::And ? ConstantInt::getNullValue(Ty)
2008                                         : ConstantInt::getAllOnesValue(Ty);
2009     }
2010   }
2011   return nullptr;
2012 }
2013 
2014 // Commutative patterns for and that will be tried with both operand orders.
2015 static Value *simplifyAndCommutative(Value *Op0, Value *Op1,
2016                                      const SimplifyQuery &Q,
2017                                      unsigned MaxRecurse) {
2018   // ~A & A =  0
2019   if (match(Op0, m_Not(m_Specific(Op1))))
2020     return Constant::getNullValue(Op0->getType());
2021 
2022   // (A | ?) & A = A
2023   if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
2024     return Op1;
2025 
2026   // (X | ~Y) & (X | Y) --> X
2027   Value *X, *Y;
2028   if (match(Op0, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2029       match(Op1, m_c_Or(m_Specific(X), m_Specific(Y))))
2030     return X;
2031 
2032   // If we have a multiplication overflow check that is being 'and'ed with a
2033   // check that one of the multipliers is not zero, we can omit the 'and', and
2034   // only keep the overflow check.
2035   if (isCheckForZeroAndMulWithOverflow(Op0, Op1, true))
2036     return Op1;
2037 
2038   // -A & A = A if A is a power of two or zero.
2039   if (match(Op0, m_Neg(m_Specific(Op1))) &&
2040       isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
2041     return Op1;
2042 
2043   // This is a similar pattern used for checking if a value is a power-of-2:
2044   // (A - 1) & A --> 0 (if A is a power-of-2 or 0)
2045   if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) &&
2046       isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
2047     return Constant::getNullValue(Op1->getType());
2048 
2049   // (x << N) & ((x << M) - 1) --> 0, where x is known to be a power of 2 and
2050   // M <= N.
2051   const APInt *Shift1, *Shift2;
2052   if (match(Op0, m_Shl(m_Value(X), m_APInt(Shift1))) &&
2053       match(Op1, m_Add(m_Shl(m_Specific(X), m_APInt(Shift2)), m_AllOnes())) &&
2054       isKnownToBeAPowerOfTwo(X, Q.DL, /*OrZero*/ true, /*Depth*/ 0, Q.AC,
2055                              Q.CxtI) &&
2056       Shift1->uge(*Shift2))
2057     return Constant::getNullValue(Op0->getType());
2058 
2059   if (Value *V =
2060           simplifyAndOrWithICmpEq(Instruction::And, Op0, Op1, Q, MaxRecurse))
2061     return V;
2062 
2063   return nullptr;
2064 }
2065 
2066 /// Given operands for an And, see if we can fold the result.
2067 /// If not, this returns null.
2068 static Value *simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2069                               unsigned MaxRecurse) {
2070   if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
2071     return C;
2072 
2073   // X & poison -> poison
2074   if (isa<PoisonValue>(Op1))
2075     return Op1;
2076 
2077   // X & undef -> 0
2078   if (Q.isUndefValue(Op1))
2079     return Constant::getNullValue(Op0->getType());
2080 
2081   // X & X = X
2082   if (Op0 == Op1)
2083     return Op0;
2084 
2085   // X & 0 = 0
2086   if (match(Op1, m_Zero()))
2087     return Constant::getNullValue(Op0->getType());
2088 
2089   // X & -1 = X
2090   if (match(Op1, m_AllOnes()))
2091     return Op0;
2092 
2093   if (Value *Res = simplifyAndCommutative(Op0, Op1, Q, MaxRecurse))
2094     return Res;
2095   if (Value *Res = simplifyAndCommutative(Op1, Op0, Q, MaxRecurse))
2096     return Res;
2097 
2098   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::And))
2099     return V;
2100 
2101   // A mask that only clears known zeros of a shifted value is a no-op.
2102   const APInt *Mask;
2103   const APInt *ShAmt;
2104   Value *X, *Y;
2105   if (match(Op1, m_APInt(Mask))) {
2106     // If all bits in the inverted and shifted mask are clear:
2107     // and (shl X, ShAmt), Mask --> shl X, ShAmt
2108     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
2109         (~(*Mask)).lshr(*ShAmt).isZero())
2110       return Op0;
2111 
2112     // If all bits in the inverted and shifted mask are clear:
2113     // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
2114     if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
2115         (~(*Mask)).shl(*ShAmt).isZero())
2116       return Op0;
2117   }
2118 
2119   // and 2^x-1, 2^C --> 0 where x <= C.
2120   const APInt *PowerC;
2121   Value *Shift;
2122   if (match(Op1, m_Power2(PowerC)) &&
2123       match(Op0, m_Add(m_Value(Shift), m_AllOnes())) &&
2124       isKnownToBeAPowerOfTwo(Shift, Q.DL, /*OrZero*/ false, 0, Q.AC, Q.CxtI,
2125                              Q.DT)) {
2126     KnownBits Known = computeKnownBits(Shift, /* Depth */ 0, Q);
2127     // Use getActiveBits() to make use of the additional power of two knowledge
2128     if (PowerC->getActiveBits() >= Known.getMaxValue().getActiveBits())
2129       return ConstantInt::getNullValue(Op1->getType());
2130   }
2131 
2132   if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
2133     return V;
2134 
2135   // Try some generic simplifications for associative operations.
2136   if (Value *V =
2137           simplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, MaxRecurse))
2138     return V;
2139 
2140   // And distributes over Or.  Try some generic simplifications based on this.
2141   if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2142                                         Instruction::Or, Q, MaxRecurse))
2143     return V;
2144 
2145   // And distributes over Xor.  Try some generic simplifications based on this.
2146   if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2147                                         Instruction::Xor, Q, MaxRecurse))
2148     return V;
2149 
2150   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2151     if (Op0->getType()->isIntOrIntVectorTy(1)) {
2152       // A & (A && B) -> A && B
2153       if (match(Op1, m_Select(m_Specific(Op0), m_Value(), m_Zero())))
2154         return Op1;
2155       else if (match(Op0, m_Select(m_Specific(Op1), m_Value(), m_Zero())))
2156         return Op0;
2157     }
2158     // If the operation is with the result of a select instruction, check
2159     // whether operating on either branch of the select always yields the same
2160     // value.
2161     if (Value *V =
2162             threadBinOpOverSelect(Instruction::And, Op0, Op1, Q, MaxRecurse))
2163       return V;
2164   }
2165 
2166   // If the operation is with the result of a phi instruction, check whether
2167   // operating on all incoming values of the phi always yields the same value.
2168   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2169     if (Value *V =
2170             threadBinOpOverPHI(Instruction::And, Op0, Op1, Q, MaxRecurse))
2171       return V;
2172 
2173   // Assuming the effective width of Y is not larger than A, i.e. all bits
2174   // from X and Y are disjoint in (X << A) | Y,
2175   // if the mask of this AND op covers all bits of X or Y, while it covers
2176   // no bits from the other, we can bypass this AND op. E.g.,
2177   // ((X << A) | Y) & Mask -> Y,
2178   //     if Mask = ((1 << effective_width_of(Y)) - 1)
2179   // ((X << A) | Y) & Mask -> X << A,
2180   //     if Mask = ((1 << effective_width_of(X)) - 1) << A
2181   // SimplifyDemandedBits in InstCombine can optimize the general case.
2182   // This pattern aims to help other passes for a common case.
2183   Value *XShifted;
2184   if (Q.IIQ.UseInstrInfo && match(Op1, m_APInt(Mask)) &&
2185       match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
2186                                      m_Value(XShifted)),
2187                         m_Value(Y)))) {
2188     const unsigned Width = Op0->getType()->getScalarSizeInBits();
2189     const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
2190     const KnownBits YKnown = computeKnownBits(Y, /* Depth */ 0, Q);
2191     const unsigned EffWidthY = YKnown.countMaxActiveBits();
2192     if (EffWidthY <= ShftCnt) {
2193       const KnownBits XKnown = computeKnownBits(X, /* Depth */ 0, Q);
2194       const unsigned EffWidthX = XKnown.countMaxActiveBits();
2195       const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
2196       const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
2197       // If the mask is extracting all bits from X or Y as is, we can skip
2198       // this AND op.
2199       if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
2200         return Y;
2201       if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
2202         return XShifted;
2203     }
2204   }
2205 
2206   // ((X | Y) ^ X ) & ((X | Y) ^ Y) --> 0
2207   // ((X | Y) ^ Y ) & ((X | Y) ^ X) --> 0
2208   BinaryOperator *Or;
2209   if (match(Op0, m_c_Xor(m_Value(X),
2210                          m_CombineAnd(m_BinOp(Or),
2211                                       m_c_Or(m_Deferred(X), m_Value(Y))))) &&
2212       match(Op1, m_c_Xor(m_Specific(Or), m_Specific(Y))))
2213     return Constant::getNullValue(Op0->getType());
2214 
2215   const APInt *C1;
2216   Value *A;
2217   // (A ^ C) & (A ^ ~C) -> 0
2218   if (match(Op0, m_Xor(m_Value(A), m_APInt(C1))) &&
2219       match(Op1, m_Xor(m_Specific(A), m_SpecificInt(~*C1))))
2220     return Constant::getNullValue(Op0->getType());
2221 
2222   if (Op0->getType()->isIntOrIntVectorTy(1)) {
2223     if (std::optional<bool> Implied = isImpliedCondition(Op0, Op1, Q.DL)) {
2224       // If Op0 is true implies Op1 is true, then Op0 is a subset of Op1.
2225       if (*Implied == true)
2226         return Op0;
2227       // If Op0 is true implies Op1 is false, then they are not true together.
2228       if (*Implied == false)
2229         return ConstantInt::getFalse(Op0->getType());
2230     }
2231     if (std::optional<bool> Implied = isImpliedCondition(Op1, Op0, Q.DL)) {
2232       // If Op1 is true implies Op0 is true, then Op1 is a subset of Op0.
2233       if (*Implied)
2234         return Op1;
2235       // If Op1 is true implies Op0 is false, then they are not true together.
2236       if (!*Implied)
2237         return ConstantInt::getFalse(Op1->getType());
2238     }
2239   }
2240 
2241   if (Value *V = simplifyByDomEq(Instruction::And, Op0, Op1, Q, MaxRecurse))
2242     return V;
2243 
2244   return nullptr;
2245 }
2246 
2247 Value *llvm::simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2248   return ::simplifyAndInst(Op0, Op1, Q, RecursionLimit);
2249 }
2250 
2251 // TODO: Many of these folds could use LogicalAnd/LogicalOr.
2252 static Value *simplifyOrLogic(Value *X, Value *Y) {
2253   assert(X->getType() == Y->getType() && "Expected same type for 'or' ops");
2254   Type *Ty = X->getType();
2255 
2256   // X | ~X --> -1
2257   if (match(Y, m_Not(m_Specific(X))))
2258     return ConstantInt::getAllOnesValue(Ty);
2259 
2260   // X | ~(X & ?) = -1
2261   if (match(Y, m_Not(m_c_And(m_Specific(X), m_Value()))))
2262     return ConstantInt::getAllOnesValue(Ty);
2263 
2264   // X | (X & ?) --> X
2265   if (match(Y, m_c_And(m_Specific(X), m_Value())))
2266     return X;
2267 
2268   Value *A, *B;
2269 
2270   // (A ^ B) | (A | B) --> A | B
2271   // (A ^ B) | (B | A) --> B | A
2272   if (match(X, m_Xor(m_Value(A), m_Value(B))) &&
2273       match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2274     return Y;
2275 
2276   // ~(A ^ B) | (A | B) --> -1
2277   // ~(A ^ B) | (B | A) --> -1
2278   if (match(X, m_Not(m_Xor(m_Value(A), m_Value(B)))) &&
2279       match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2280     return ConstantInt::getAllOnesValue(Ty);
2281 
2282   // (A & ~B) | (A ^ B) --> A ^ B
2283   // (~B & A) | (A ^ B) --> A ^ B
2284   // (A & ~B) | (B ^ A) --> B ^ A
2285   // (~B & A) | (B ^ A) --> B ^ A
2286   if (match(X, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2287       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2288     return Y;
2289 
2290   // (~A ^ B) | (A & B) --> ~A ^ B
2291   // (B ^ ~A) | (A & B) --> B ^ ~A
2292   // (~A ^ B) | (B & A) --> ~A ^ B
2293   // (B ^ ~A) | (B & A) --> B ^ ~A
2294   if (match(X, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2295       match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2296     return X;
2297 
2298   // (~A | B) | (A ^ B) --> -1
2299   // (~A | B) | (B ^ A) --> -1
2300   // (B | ~A) | (A ^ B) --> -1
2301   // (B | ~A) | (B ^ A) --> -1
2302   if (match(X, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2303       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2304     return ConstantInt::getAllOnesValue(Ty);
2305 
2306   // (~A & B) | ~(A | B) --> ~A
2307   // (~A & B) | ~(B | A) --> ~A
2308   // (B & ~A) | ~(A | B) --> ~A
2309   // (B & ~A) | ~(B | A) --> ~A
2310   Value *NotA;
2311   if (match(X, m_c_And(m_CombineAnd(m_Value(NotA), m_Not(m_Value(A))),
2312                        m_Value(B))) &&
2313       match(Y, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
2314     return NotA;
2315   // The same is true of Logical And
2316   // TODO: This could share the logic of the version above if there was a
2317   // version of LogicalAnd that allowed more than just i1 types.
2318   if (match(X, m_c_LogicalAnd(m_CombineAnd(m_Value(NotA), m_Not(m_Value(A))),
2319                               m_Value(B))) &&
2320       match(Y, m_Not(m_c_LogicalOr(m_Specific(A), m_Specific(B)))))
2321     return NotA;
2322 
2323   // ~(A ^ B) | (A & B) --> ~(A ^ B)
2324   // ~(A ^ B) | (B & A) --> ~(A ^ B)
2325   Value *NotAB;
2326   if (match(X, m_CombineAnd(m_Not(m_Xor(m_Value(A), m_Value(B))),
2327                             m_Value(NotAB))) &&
2328       match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2329     return NotAB;
2330 
2331   // ~(A & B) | (A ^ B) --> ~(A & B)
2332   // ~(A & B) | (B ^ A) --> ~(A & B)
2333   if (match(X, m_CombineAnd(m_Not(m_And(m_Value(A), m_Value(B))),
2334                             m_Value(NotAB))) &&
2335       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2336     return NotAB;
2337 
2338   return nullptr;
2339 }
2340 
2341 /// Given operands for an Or, see if we can fold the result.
2342 /// If not, this returns null.
2343 static Value *simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2344                              unsigned MaxRecurse) {
2345   if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
2346     return C;
2347 
2348   // X | poison -> poison
2349   if (isa<PoisonValue>(Op1))
2350     return Op1;
2351 
2352   // X | undef -> -1
2353   // X | -1 = -1
2354   // Do not return Op1 because it may contain undef elements if it's a vector.
2355   if (Q.isUndefValue(Op1) || match(Op1, m_AllOnes()))
2356     return Constant::getAllOnesValue(Op0->getType());
2357 
2358   // X | X = X
2359   // X | 0 = X
2360   if (Op0 == Op1 || match(Op1, m_Zero()))
2361     return Op0;
2362 
2363   if (Value *R = simplifyOrLogic(Op0, Op1))
2364     return R;
2365   if (Value *R = simplifyOrLogic(Op1, Op0))
2366     return R;
2367 
2368   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Or))
2369     return V;
2370 
2371   // Rotated -1 is still -1:
2372   // (-1 << X) | (-1 >> (C - X)) --> -1
2373   // (-1 >> X) | (-1 << (C - X)) --> -1
2374   // ...with C <= bitwidth (and commuted variants).
2375   Value *X, *Y;
2376   if ((match(Op0, m_Shl(m_AllOnes(), m_Value(X))) &&
2377        match(Op1, m_LShr(m_AllOnes(), m_Value(Y)))) ||
2378       (match(Op1, m_Shl(m_AllOnes(), m_Value(X))) &&
2379        match(Op0, m_LShr(m_AllOnes(), m_Value(Y))))) {
2380     const APInt *C;
2381     if ((match(X, m_Sub(m_APInt(C), m_Specific(Y))) ||
2382          match(Y, m_Sub(m_APInt(C), m_Specific(X)))) &&
2383         C->ule(X->getType()->getScalarSizeInBits())) {
2384       return ConstantInt::getAllOnesValue(X->getType());
2385     }
2386   }
2387 
2388   // A funnel shift (rotate) can be decomposed into simpler shifts. See if we
2389   // are mixing in another shift that is redundant with the funnel shift.
2390 
2391   // (fshl X, ?, Y) | (shl X, Y) --> fshl X, ?, Y
2392   // (shl X, Y) | (fshl X, ?, Y) --> fshl X, ?, Y
2393   if (match(Op0,
2394             m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
2395       match(Op1, m_Shl(m_Specific(X), m_Specific(Y))))
2396     return Op0;
2397   if (match(Op1,
2398             m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
2399       match(Op0, m_Shl(m_Specific(X), m_Specific(Y))))
2400     return Op1;
2401 
2402   // (fshr ?, X, Y) | (lshr X, Y) --> fshr ?, X, Y
2403   // (lshr X, Y) | (fshr ?, X, Y) --> fshr ?, X, Y
2404   if (match(Op0,
2405             m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
2406       match(Op1, m_LShr(m_Specific(X), m_Specific(Y))))
2407     return Op0;
2408   if (match(Op1,
2409             m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
2410       match(Op0, m_LShr(m_Specific(X), m_Specific(Y))))
2411     return Op1;
2412 
2413   if (Value *V =
2414           simplifyAndOrWithICmpEq(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2415     return V;
2416   if (Value *V =
2417           simplifyAndOrWithICmpEq(Instruction::Or, Op1, Op0, Q, MaxRecurse))
2418     return V;
2419 
2420   if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
2421     return V;
2422 
2423   // If we have a multiplication overflow check that is being 'and'ed with a
2424   // check that one of the multipliers is not zero, we can omit the 'and', and
2425   // only keep the overflow check.
2426   if (isCheckForZeroAndMulWithOverflow(Op0, Op1, false))
2427     return Op1;
2428   if (isCheckForZeroAndMulWithOverflow(Op1, Op0, false))
2429     return Op0;
2430 
2431   // Try some generic simplifications for associative operations.
2432   if (Value *V =
2433           simplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2434     return V;
2435 
2436   // Or distributes over And.  Try some generic simplifications based on this.
2437   if (Value *V = expandCommutativeBinOp(Instruction::Or, Op0, Op1,
2438                                         Instruction::And, Q, MaxRecurse))
2439     return V;
2440 
2441   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2442     if (Op0->getType()->isIntOrIntVectorTy(1)) {
2443       // A | (A || B) -> A || B
2444       if (match(Op1, m_Select(m_Specific(Op0), m_One(), m_Value())))
2445         return Op1;
2446       else if (match(Op0, m_Select(m_Specific(Op1), m_One(), m_Value())))
2447         return Op0;
2448     }
2449     // If the operation is with the result of a select instruction, check
2450     // whether operating on either branch of the select always yields the same
2451     // value.
2452     if (Value *V =
2453             threadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2454       return V;
2455   }
2456 
2457   // (A & C1)|(B & C2)
2458   Value *A, *B;
2459   const APInt *C1, *C2;
2460   if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
2461       match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
2462     if (*C1 == ~*C2) {
2463       // (A & C1)|(B & C2)
2464       // If we have: ((V + N) & C1) | (V & C2)
2465       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2466       // replace with V+N.
2467       Value *N;
2468       if (C2->isMask() && // C2 == 0+1+
2469           match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
2470         // Add commutes, try both ways.
2471         if (MaskedValueIsZero(N, *C2, Q))
2472           return A;
2473       }
2474       // Or commutes, try both ways.
2475       if (C1->isMask() && match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
2476         // Add commutes, try both ways.
2477         if (MaskedValueIsZero(N, *C1, Q))
2478           return B;
2479       }
2480     }
2481   }
2482 
2483   // If the operation is with the result of a phi instruction, check whether
2484   // operating on all incoming values of the phi always yields the same value.
2485   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2486     if (Value *V = threadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2487       return V;
2488 
2489   // (A ^ C) | (A ^ ~C) -> -1, i.e. all bits set to one.
2490   if (match(Op0, m_Xor(m_Value(A), m_APInt(C1))) &&
2491       match(Op1, m_Xor(m_Specific(A), m_SpecificInt(~*C1))))
2492     return Constant::getAllOnesValue(Op0->getType());
2493 
2494   if (Op0->getType()->isIntOrIntVectorTy(1)) {
2495     if (std::optional<bool> Implied =
2496             isImpliedCondition(Op0, Op1, Q.DL, false)) {
2497       // If Op0 is false implies Op1 is false, then Op1 is a subset of Op0.
2498       if (*Implied == false)
2499         return Op0;
2500       // If Op0 is false implies Op1 is true, then at least one is always true.
2501       if (*Implied == true)
2502         return ConstantInt::getTrue(Op0->getType());
2503     }
2504     if (std::optional<bool> Implied =
2505             isImpliedCondition(Op1, Op0, Q.DL, false)) {
2506       // If Op1 is false implies Op0 is false, then Op0 is a subset of Op1.
2507       if (*Implied == false)
2508         return Op1;
2509       // If Op1 is false implies Op0 is true, then at least one is always true.
2510       if (*Implied == true)
2511         return ConstantInt::getTrue(Op1->getType());
2512     }
2513   }
2514 
2515   if (Value *V = simplifyByDomEq(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2516     return V;
2517 
2518   return nullptr;
2519 }
2520 
2521 Value *llvm::simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2522   return ::simplifyOrInst(Op0, Op1, Q, RecursionLimit);
2523 }
2524 
2525 /// Given operands for a Xor, see if we can fold the result.
2526 /// If not, this returns null.
2527 static Value *simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2528                               unsigned MaxRecurse) {
2529   if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
2530     return C;
2531 
2532   // X ^ poison -> poison
2533   if (isa<PoisonValue>(Op1))
2534     return Op1;
2535 
2536   // A ^ undef -> undef
2537   if (Q.isUndefValue(Op1))
2538     return Op1;
2539 
2540   // A ^ 0 = A
2541   if (match(Op1, m_Zero()))
2542     return Op0;
2543 
2544   // A ^ A = 0
2545   if (Op0 == Op1)
2546     return Constant::getNullValue(Op0->getType());
2547 
2548   // A ^ ~A  =  ~A ^ A  =  -1
2549   if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
2550     return Constant::getAllOnesValue(Op0->getType());
2551 
2552   auto foldAndOrNot = [](Value *X, Value *Y) -> Value * {
2553     Value *A, *B;
2554     // (~A & B) ^ (A | B) --> A -- There are 8 commuted variants.
2555     if (match(X, m_c_And(m_Not(m_Value(A)), m_Value(B))) &&
2556         match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2557       return A;
2558 
2559     // (~A | B) ^ (A & B) --> ~A -- There are 8 commuted variants.
2560     // The 'not' op must contain a complete -1 operand (no undef elements for
2561     // vector) for the transform to be safe.
2562     Value *NotA;
2563     if (match(X, m_c_Or(m_CombineAnd(m_Not(m_Value(A)), m_Value(NotA)),
2564                         m_Value(B))) &&
2565         match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2566       return NotA;
2567 
2568     return nullptr;
2569   };
2570   if (Value *R = foldAndOrNot(Op0, Op1))
2571     return R;
2572   if (Value *R = foldAndOrNot(Op1, Op0))
2573     return R;
2574 
2575   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Xor))
2576     return V;
2577 
2578   // Try some generic simplifications for associative operations.
2579   if (Value *V =
2580           simplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
2581     return V;
2582 
2583   // Threading Xor over selects and phi nodes is pointless, so don't bother.
2584   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2585   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2586   // only if B and C are equal.  If B and C are equal then (since we assume
2587   // that operands have already been simplified) "select(cond, B, C)" should
2588   // have been simplified to the common value of B and C already.  Analysing
2589   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
2590   // for threading over phi nodes.
2591 
2592   if (Value *V = simplifyByDomEq(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
2593     return V;
2594 
2595   return nullptr;
2596 }
2597 
2598 Value *llvm::simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2599   return ::simplifyXorInst(Op0, Op1, Q, RecursionLimit);
2600 }
2601 
2602 static Type *getCompareTy(Value *Op) {
2603   return CmpInst::makeCmpResultType(Op->getType());
2604 }
2605 
2606 /// Rummage around inside V looking for something equivalent to the comparison
2607 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
2608 /// Helper function for analyzing max/min idioms.
2609 static Value *extractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2610                                          Value *LHS, Value *RHS) {
2611   SelectInst *SI = dyn_cast<SelectInst>(V);
2612   if (!SI)
2613     return nullptr;
2614   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2615   if (!Cmp)
2616     return nullptr;
2617   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2618   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2619     return Cmp;
2620   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2621       LHS == CmpRHS && RHS == CmpLHS)
2622     return Cmp;
2623   return nullptr;
2624 }
2625 
2626 /// Return true if the underlying object (storage) must be disjoint from
2627 /// storage returned by any noalias return call.
2628 static bool isAllocDisjoint(const Value *V) {
2629   // For allocas, we consider only static ones (dynamic
2630   // allocas might be transformed into calls to malloc not simultaneously
2631   // live with the compared-to allocation). For globals, we exclude symbols
2632   // that might be resolve lazily to symbols in another dynamically-loaded
2633   // library (and, thus, could be malloc'ed by the implementation).
2634   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2635     return AI->isStaticAlloca();
2636   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2637     return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2638             GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2639            !GV->isThreadLocal();
2640   if (const Argument *A = dyn_cast<Argument>(V))
2641     return A->hasByValAttr();
2642   return false;
2643 }
2644 
2645 /// Return true if V1 and V2 are each the base of some distict storage region
2646 /// [V, object_size(V)] which do not overlap.  Note that zero sized regions
2647 /// *are* possible, and that zero sized regions do not overlap with any other.
2648 static bool haveNonOverlappingStorage(const Value *V1, const Value *V2) {
2649   // Global variables always exist, so they always exist during the lifetime
2650   // of each other and all allocas.  Global variables themselves usually have
2651   // non-overlapping storage, but since their addresses are constants, the
2652   // case involving two globals does not reach here and is instead handled in
2653   // constant folding.
2654   //
2655   // Two different allocas usually have different addresses...
2656   //
2657   // However, if there's an @llvm.stackrestore dynamically in between two
2658   // allocas, they may have the same address. It's tempting to reduce the
2659   // scope of the problem by only looking at *static* allocas here. That would
2660   // cover the majority of allocas while significantly reducing the likelihood
2661   // of having an @llvm.stackrestore pop up in the middle. However, it's not
2662   // actually impossible for an @llvm.stackrestore to pop up in the middle of
2663   // an entry block. Also, if we have a block that's not attached to a
2664   // function, we can't tell if it's "static" under the current definition.
2665   // Theoretically, this problem could be fixed by creating a new kind of
2666   // instruction kind specifically for static allocas. Such a new instruction
2667   // could be required to be at the top of the entry block, thus preventing it
2668   // from being subject to a @llvm.stackrestore. Instcombine could even
2669   // convert regular allocas into these special allocas. It'd be nifty.
2670   // However, until then, this problem remains open.
2671   //
2672   // So, we'll assume that two non-empty allocas have different addresses
2673   // for now.
2674   auto isByValArg = [](const Value *V) {
2675     const Argument *A = dyn_cast<Argument>(V);
2676     return A && A->hasByValAttr();
2677   };
2678 
2679   // Byval args are backed by store which does not overlap with each other,
2680   // allocas, or globals.
2681   if (isByValArg(V1))
2682     return isa<AllocaInst>(V2) || isa<GlobalVariable>(V2) || isByValArg(V2);
2683   if (isByValArg(V2))
2684     return isa<AllocaInst>(V1) || isa<GlobalVariable>(V1) || isByValArg(V1);
2685 
2686   return isa<AllocaInst>(V1) &&
2687          (isa<AllocaInst>(V2) || isa<GlobalVariable>(V2));
2688 }
2689 
2690 // A significant optimization not implemented here is assuming that alloca
2691 // addresses are not equal to incoming argument values. They don't *alias*,
2692 // as we say, but that doesn't mean they aren't equal, so we take a
2693 // conservative approach.
2694 //
2695 // This is inspired in part by C++11 5.10p1:
2696 //   "Two pointers of the same type compare equal if and only if they are both
2697 //    null, both point to the same function, or both represent the same
2698 //    address."
2699 //
2700 // This is pretty permissive.
2701 //
2702 // It's also partly due to C11 6.5.9p6:
2703 //   "Two pointers compare equal if and only if both are null pointers, both are
2704 //    pointers to the same object (including a pointer to an object and a
2705 //    subobject at its beginning) or function, both are pointers to one past the
2706 //    last element of the same array object, or one is a pointer to one past the
2707 //    end of one array object and the other is a pointer to the start of a
2708 //    different array object that happens to immediately follow the first array
2709 //    object in the address space.)
2710 //
2711 // C11's version is more restrictive, however there's no reason why an argument
2712 // couldn't be a one-past-the-end value for a stack object in the caller and be
2713 // equal to the beginning of a stack object in the callee.
2714 //
2715 // If the C and C++ standards are ever made sufficiently restrictive in this
2716 // area, it may be possible to update LLVM's semantics accordingly and reinstate
2717 // this optimization.
2718 static Constant *computePointerICmp(CmpInst::Predicate Pred, Value *LHS,
2719                                     Value *RHS, const SimplifyQuery &Q) {
2720   assert(LHS->getType() == RHS->getType() && "Must have same types");
2721   const DataLayout &DL = Q.DL;
2722   const TargetLibraryInfo *TLI = Q.TLI;
2723 
2724   // We can only fold certain predicates on pointer comparisons.
2725   switch (Pred) {
2726   default:
2727     return nullptr;
2728 
2729     // Equality comparisons are easy to fold.
2730   case CmpInst::ICMP_EQ:
2731   case CmpInst::ICMP_NE:
2732     break;
2733 
2734     // We can only handle unsigned relational comparisons because 'inbounds' on
2735     // a GEP only protects against unsigned wrapping.
2736   case CmpInst::ICMP_UGT:
2737   case CmpInst::ICMP_UGE:
2738   case CmpInst::ICMP_ULT:
2739   case CmpInst::ICMP_ULE:
2740     // However, we have to switch them to their signed variants to handle
2741     // negative indices from the base pointer.
2742     Pred = ICmpInst::getSignedPredicate(Pred);
2743     break;
2744   }
2745 
2746   // Strip off any constant offsets so that we can reason about them.
2747   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2748   // here and compare base addresses like AliasAnalysis does, however there are
2749   // numerous hazards. AliasAnalysis and its utilities rely on special rules
2750   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2751   // doesn't need to guarantee pointer inequality when it says NoAlias.
2752 
2753   // Even if an non-inbounds GEP occurs along the path we can still optimize
2754   // equality comparisons concerning the result.
2755   bool AllowNonInbounds = ICmpInst::isEquality(Pred);
2756   unsigned IndexSize = DL.getIndexTypeSizeInBits(LHS->getType());
2757   APInt LHSOffset(IndexSize, 0), RHSOffset(IndexSize, 0);
2758   LHS = LHS->stripAndAccumulateConstantOffsets(DL, LHSOffset, AllowNonInbounds);
2759   RHS = RHS->stripAndAccumulateConstantOffsets(DL, RHSOffset, AllowNonInbounds);
2760 
2761   // If LHS and RHS are related via constant offsets to the same base
2762   // value, we can replace it with an icmp which just compares the offsets.
2763   if (LHS == RHS)
2764     return ConstantInt::get(getCompareTy(LHS),
2765                             ICmpInst::compare(LHSOffset, RHSOffset, Pred));
2766 
2767   // Various optimizations for (in)equality comparisons.
2768   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2769     // Different non-empty allocations that exist at the same time have
2770     // different addresses (if the program can tell). If the offsets are
2771     // within the bounds of their allocations (and not one-past-the-end!
2772     // so we can't use inbounds!), and their allocations aren't the same,
2773     // the pointers are not equal.
2774     if (haveNonOverlappingStorage(LHS, RHS)) {
2775       uint64_t LHSSize, RHSSize;
2776       ObjectSizeOpts Opts;
2777       Opts.EvalMode = ObjectSizeOpts::Mode::Min;
2778       auto *F = [](Value *V) -> Function * {
2779         if (auto *I = dyn_cast<Instruction>(V))
2780           return I->getFunction();
2781         if (auto *A = dyn_cast<Argument>(V))
2782           return A->getParent();
2783         return nullptr;
2784       }(LHS);
2785       Opts.NullIsUnknownSize = F ? NullPointerIsDefined(F) : true;
2786       if (getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2787           getObjectSize(RHS, RHSSize, DL, TLI, Opts)) {
2788         APInt Dist = LHSOffset - RHSOffset;
2789         if (Dist.isNonNegative() ? Dist.ult(LHSSize) : (-Dist).ult(RHSSize))
2790           return ConstantInt::get(getCompareTy(LHS),
2791                                   !CmpInst::isTrueWhenEqual(Pred));
2792       }
2793     }
2794 
2795     // If one side of the equality comparison must come from a noalias call
2796     // (meaning a system memory allocation function), and the other side must
2797     // come from a pointer that cannot overlap with dynamically-allocated
2798     // memory within the lifetime of the current function (allocas, byval
2799     // arguments, globals), then determine the comparison result here.
2800     SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
2801     getUnderlyingObjects(LHS, LHSUObjs);
2802     getUnderlyingObjects(RHS, RHSUObjs);
2803 
2804     // Is the set of underlying objects all noalias calls?
2805     auto IsNAC = [](ArrayRef<const Value *> Objects) {
2806       return all_of(Objects, isNoAliasCall);
2807     };
2808 
2809     // Is the set of underlying objects all things which must be disjoint from
2810     // noalias calls.  We assume that indexing from such disjoint storage
2811     // into the heap is undefined, and thus offsets can be safely ignored.
2812     auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2813       return all_of(Objects, ::isAllocDisjoint);
2814     };
2815 
2816     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2817         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2818       return ConstantInt::get(getCompareTy(LHS),
2819                               !CmpInst::isTrueWhenEqual(Pred));
2820 
2821     // Fold comparisons for non-escaping pointer even if the allocation call
2822     // cannot be elided. We cannot fold malloc comparison to null. Also, the
2823     // dynamic allocation call could be either of the operands.  Note that
2824     // the other operand can not be based on the alloc - if it were, then
2825     // the cmp itself would be a capture.
2826     Value *MI = nullptr;
2827     if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonZero(RHS, Q))
2828       MI = LHS;
2829     else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonZero(LHS, Q))
2830       MI = RHS;
2831     if (MI) {
2832       // FIXME: This is incorrect, see PR54002. While we can assume that the
2833       // allocation is at an address that makes the comparison false, this
2834       // requires that *all* comparisons to that address be false, which
2835       // InstSimplify cannot guarantee.
2836       struct CustomCaptureTracker : public CaptureTracker {
2837         bool Captured = false;
2838         void tooManyUses() override { Captured = true; }
2839         bool captured(const Use *U) override {
2840           if (auto *ICmp = dyn_cast<ICmpInst>(U->getUser())) {
2841             // Comparison against value stored in global variable. Given the
2842             // pointer does not escape, its value cannot be guessed and stored
2843             // separately in a global variable.
2844             unsigned OtherIdx = 1 - U->getOperandNo();
2845             auto *LI = dyn_cast<LoadInst>(ICmp->getOperand(OtherIdx));
2846             if (LI && isa<GlobalVariable>(LI->getPointerOperand()))
2847               return false;
2848           }
2849 
2850           Captured = true;
2851           return true;
2852         }
2853       };
2854       CustomCaptureTracker Tracker;
2855       PointerMayBeCaptured(MI, &Tracker);
2856       if (!Tracker.Captured)
2857         return ConstantInt::get(getCompareTy(LHS),
2858                                 CmpInst::isFalseWhenEqual(Pred));
2859     }
2860   }
2861 
2862   // Otherwise, fail.
2863   return nullptr;
2864 }
2865 
2866 /// Fold an icmp when its operands have i1 scalar type.
2867 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2868                                   Value *RHS, const SimplifyQuery &Q) {
2869   Type *ITy = getCompareTy(LHS); // The return type.
2870   Type *OpTy = LHS->getType();   // The operand type.
2871   if (!OpTy->isIntOrIntVectorTy(1))
2872     return nullptr;
2873 
2874   // A boolean compared to true/false can be reduced in 14 out of the 20
2875   // (10 predicates * 2 constants) possible combinations. The other
2876   // 6 cases require a 'not' of the LHS.
2877 
2878   auto ExtractNotLHS = [](Value *V) -> Value * {
2879     Value *X;
2880     if (match(V, m_Not(m_Value(X))))
2881       return X;
2882     return nullptr;
2883   };
2884 
2885   if (match(RHS, m_Zero())) {
2886     switch (Pred) {
2887     case CmpInst::ICMP_NE:  // X !=  0 -> X
2888     case CmpInst::ICMP_UGT: // X >u  0 -> X
2889     case CmpInst::ICMP_SLT: // X <s  0 -> X
2890       return LHS;
2891 
2892     case CmpInst::ICMP_EQ:  // not(X) ==  0 -> X != 0 -> X
2893     case CmpInst::ICMP_ULE: // not(X) <=u 0 -> X >u 0 -> X
2894     case CmpInst::ICMP_SGE: // not(X) >=s 0 -> X <s 0 -> X
2895       if (Value *X = ExtractNotLHS(LHS))
2896         return X;
2897       break;
2898 
2899     case CmpInst::ICMP_ULT: // X <u  0 -> false
2900     case CmpInst::ICMP_SGT: // X >s  0 -> false
2901       return getFalse(ITy);
2902 
2903     case CmpInst::ICMP_UGE: // X >=u 0 -> true
2904     case CmpInst::ICMP_SLE: // X <=s 0 -> true
2905       return getTrue(ITy);
2906 
2907     default:
2908       break;
2909     }
2910   } else if (match(RHS, m_One())) {
2911     switch (Pred) {
2912     case CmpInst::ICMP_EQ:  // X ==   1 -> X
2913     case CmpInst::ICMP_UGE: // X >=u  1 -> X
2914     case CmpInst::ICMP_SLE: // X <=s -1 -> X
2915       return LHS;
2916 
2917     case CmpInst::ICMP_NE:  // not(X) !=  1 -> X ==   1 -> X
2918     case CmpInst::ICMP_ULT: // not(X) <=u 1 -> X >=u  1 -> X
2919     case CmpInst::ICMP_SGT: // not(X) >s  1 -> X <=s -1 -> X
2920       if (Value *X = ExtractNotLHS(LHS))
2921         return X;
2922       break;
2923 
2924     case CmpInst::ICMP_UGT: // X >u   1 -> false
2925     case CmpInst::ICMP_SLT: // X <s  -1 -> false
2926       return getFalse(ITy);
2927 
2928     case CmpInst::ICMP_ULE: // X <=u  1 -> true
2929     case CmpInst::ICMP_SGE: // X >=s -1 -> true
2930       return getTrue(ITy);
2931 
2932     default:
2933       break;
2934     }
2935   }
2936 
2937   switch (Pred) {
2938   default:
2939     break;
2940   case ICmpInst::ICMP_UGE:
2941     if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
2942       return getTrue(ITy);
2943     break;
2944   case ICmpInst::ICMP_SGE:
2945     /// For signed comparison, the values for an i1 are 0 and -1
2946     /// respectively. This maps into a truth table of:
2947     /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
2948     ///  0  |  0  |  1 (0 >= 0)   |  1
2949     ///  0  |  1  |  1 (0 >= -1)  |  1
2950     ///  1  |  0  |  0 (-1 >= 0)  |  0
2951     ///  1  |  1  |  1 (-1 >= -1) |  1
2952     if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
2953       return getTrue(ITy);
2954     break;
2955   case ICmpInst::ICMP_ULE:
2956     if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
2957       return getTrue(ITy);
2958     break;
2959   case ICmpInst::ICMP_SLE:
2960     /// SLE follows the same logic as SGE with the LHS and RHS swapped.
2961     if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
2962       return getTrue(ITy);
2963     break;
2964   }
2965 
2966   return nullptr;
2967 }
2968 
2969 /// Try hard to fold icmp with zero RHS because this is a common case.
2970 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2971                                    Value *RHS, const SimplifyQuery &Q) {
2972   if (!match(RHS, m_Zero()))
2973     return nullptr;
2974 
2975   Type *ITy = getCompareTy(LHS); // The return type.
2976   switch (Pred) {
2977   default:
2978     llvm_unreachable("Unknown ICmp predicate!");
2979   case ICmpInst::ICMP_ULT:
2980     return getFalse(ITy);
2981   case ICmpInst::ICMP_UGE:
2982     return getTrue(ITy);
2983   case ICmpInst::ICMP_EQ:
2984   case ICmpInst::ICMP_ULE:
2985     if (isKnownNonZero(LHS, Q))
2986       return getFalse(ITy);
2987     break;
2988   case ICmpInst::ICMP_NE:
2989   case ICmpInst::ICMP_UGT:
2990     if (isKnownNonZero(LHS, Q))
2991       return getTrue(ITy);
2992     break;
2993   case ICmpInst::ICMP_SLT: {
2994     KnownBits LHSKnown = computeKnownBits(LHS, /* Depth */ 0, Q);
2995     if (LHSKnown.isNegative())
2996       return getTrue(ITy);
2997     if (LHSKnown.isNonNegative())
2998       return getFalse(ITy);
2999     break;
3000   }
3001   case ICmpInst::ICMP_SLE: {
3002     KnownBits LHSKnown = computeKnownBits(LHS, /* Depth */ 0, Q);
3003     if (LHSKnown.isNegative())
3004       return getTrue(ITy);
3005     if (LHSKnown.isNonNegative() && isKnownNonZero(LHS, Q))
3006       return getFalse(ITy);
3007     break;
3008   }
3009   case ICmpInst::ICMP_SGE: {
3010     KnownBits LHSKnown = computeKnownBits(LHS, /* Depth */ 0, Q);
3011     if (LHSKnown.isNegative())
3012       return getFalse(ITy);
3013     if (LHSKnown.isNonNegative())
3014       return getTrue(ITy);
3015     break;
3016   }
3017   case ICmpInst::ICMP_SGT: {
3018     KnownBits LHSKnown = computeKnownBits(LHS, /* Depth */ 0, Q);
3019     if (LHSKnown.isNegative())
3020       return getFalse(ITy);
3021     if (LHSKnown.isNonNegative() && isKnownNonZero(LHS, Q))
3022       return getTrue(ITy);
3023     break;
3024   }
3025   }
3026 
3027   return nullptr;
3028 }
3029 
3030 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
3031                                        Value *RHS, const InstrInfoQuery &IIQ) {
3032   Type *ITy = getCompareTy(RHS); // The return type.
3033 
3034   Value *X;
3035   const APInt *C;
3036   if (!match(RHS, m_APIntAllowPoison(C)))
3037     return nullptr;
3038 
3039   // Sign-bit checks can be optimized to true/false after unsigned
3040   // floating-point casts:
3041   // icmp slt (bitcast (uitofp X)),  0 --> false
3042   // icmp sgt (bitcast (uitofp X)), -1 --> true
3043   if (match(LHS, m_ElementWiseBitCast(m_UIToFP(m_Value(X))))) {
3044     bool TrueIfSigned;
3045     if (isSignBitCheck(Pred, *C, TrueIfSigned))
3046       return ConstantInt::getBool(ITy, !TrueIfSigned);
3047   }
3048 
3049   // Rule out tautological comparisons (eg., ult 0 or uge 0).
3050   ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
3051   if (RHS_CR.isEmptySet())
3052     return ConstantInt::getFalse(ITy);
3053   if (RHS_CR.isFullSet())
3054     return ConstantInt::getTrue(ITy);
3055 
3056   ConstantRange LHS_CR =
3057       computeConstantRange(LHS, CmpInst::isSigned(Pred), IIQ.UseInstrInfo);
3058   if (!LHS_CR.isFullSet()) {
3059     if (RHS_CR.contains(LHS_CR))
3060       return ConstantInt::getTrue(ITy);
3061     if (RHS_CR.inverse().contains(LHS_CR))
3062       return ConstantInt::getFalse(ITy);
3063   }
3064 
3065   // (mul nuw/nsw X, MulC) != C --> true  (if C is not a multiple of MulC)
3066   // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC)
3067   const APInt *MulC;
3068   if (IIQ.UseInstrInfo && ICmpInst::isEquality(Pred) &&
3069       ((match(LHS, m_NUWMul(m_Value(), m_APIntAllowPoison(MulC))) &&
3070         *MulC != 0 && C->urem(*MulC) != 0) ||
3071        (match(LHS, m_NSWMul(m_Value(), m_APIntAllowPoison(MulC))) &&
3072         *MulC != 0 && C->srem(*MulC) != 0)))
3073     return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE);
3074 
3075   return nullptr;
3076 }
3077 
3078 static Value *simplifyICmpWithBinOpOnLHS(CmpInst::Predicate Pred,
3079                                          BinaryOperator *LBO, Value *RHS,
3080                                          const SimplifyQuery &Q,
3081                                          unsigned MaxRecurse) {
3082   Type *ITy = getCompareTy(RHS); // The return type.
3083 
3084   Value *Y = nullptr;
3085   // icmp pred (or X, Y), X
3086   if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
3087     if (Pred == ICmpInst::ICMP_ULT)
3088       return getFalse(ITy);
3089     if (Pred == ICmpInst::ICMP_UGE)
3090       return getTrue(ITy);
3091 
3092     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
3093       KnownBits RHSKnown = computeKnownBits(RHS, /* Depth */ 0, Q);
3094       KnownBits YKnown = computeKnownBits(Y, /* Depth */ 0, Q);
3095       if (RHSKnown.isNonNegative() && YKnown.isNegative())
3096         return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
3097       if (RHSKnown.isNegative() || YKnown.isNonNegative())
3098         return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
3099     }
3100   }
3101 
3102   // icmp pred (and X, Y), X
3103   if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
3104     if (Pred == ICmpInst::ICMP_UGT)
3105       return getFalse(ITy);
3106     if (Pred == ICmpInst::ICMP_ULE)
3107       return getTrue(ITy);
3108   }
3109 
3110   // icmp pred (urem X, Y), Y
3111   if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
3112     switch (Pred) {
3113     default:
3114       break;
3115     case ICmpInst::ICMP_SGT:
3116     case ICmpInst::ICMP_SGE: {
3117       KnownBits Known = computeKnownBits(RHS, /* Depth */ 0, Q);
3118       if (!Known.isNonNegative())
3119         break;
3120       [[fallthrough]];
3121     }
3122     case ICmpInst::ICMP_EQ:
3123     case ICmpInst::ICMP_UGT:
3124     case ICmpInst::ICMP_UGE:
3125       return getFalse(ITy);
3126     case ICmpInst::ICMP_SLT:
3127     case ICmpInst::ICMP_SLE: {
3128       KnownBits Known = computeKnownBits(RHS, /* Depth */ 0, Q);
3129       if (!Known.isNonNegative())
3130         break;
3131       [[fallthrough]];
3132     }
3133     case ICmpInst::ICMP_NE:
3134     case ICmpInst::ICMP_ULT:
3135     case ICmpInst::ICMP_ULE:
3136       return getTrue(ITy);
3137     }
3138   }
3139 
3140   // icmp pred (urem X, Y), X
3141   if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) {
3142     if (Pred == ICmpInst::ICMP_ULE)
3143       return getTrue(ITy);
3144     if (Pred == ICmpInst::ICMP_UGT)
3145       return getFalse(ITy);
3146   }
3147 
3148   // x >>u y <=u x --> true.
3149   // x >>u y >u  x --> false.
3150   // x udiv y <=u x --> true.
3151   // x udiv y >u  x --> false.
3152   if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
3153       match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
3154     // icmp pred (X op Y), X
3155     if (Pred == ICmpInst::ICMP_UGT)
3156       return getFalse(ITy);
3157     if (Pred == ICmpInst::ICMP_ULE)
3158       return getTrue(ITy);
3159   }
3160 
3161   // If x is nonzero:
3162   // x >>u C <u  x --> true  for C != 0.
3163   // x >>u C !=  x --> true  for C != 0.
3164   // x >>u C >=u x --> false for C != 0.
3165   // x >>u C ==  x --> false for C != 0.
3166   // x udiv C <u  x --> true  for C != 1.
3167   // x udiv C !=  x --> true  for C != 1.
3168   // x udiv C >=u x --> false for C != 1.
3169   // x udiv C ==  x --> false for C != 1.
3170   // TODO: allow non-constant shift amount/divisor
3171   const APInt *C;
3172   if ((match(LBO, m_LShr(m_Specific(RHS), m_APInt(C))) && *C != 0) ||
3173       (match(LBO, m_UDiv(m_Specific(RHS), m_APInt(C))) && *C != 1)) {
3174     if (isKnownNonZero(RHS, Q)) {
3175       switch (Pred) {
3176       default:
3177         break;
3178       case ICmpInst::ICMP_EQ:
3179       case ICmpInst::ICMP_UGE:
3180         return getFalse(ITy);
3181       case ICmpInst::ICMP_NE:
3182       case ICmpInst::ICMP_ULT:
3183         return getTrue(ITy);
3184       case ICmpInst::ICMP_UGT:
3185       case ICmpInst::ICMP_ULE:
3186         // UGT/ULE are handled by the more general case just above
3187         llvm_unreachable("Unexpected UGT/ULE, should have been handled");
3188       }
3189     }
3190   }
3191 
3192   // (x*C1)/C2 <= x for C1 <= C2.
3193   // This holds even if the multiplication overflows: Assume that x != 0 and
3194   // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and
3195   // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x.
3196   //
3197   // Additionally, either the multiplication and division might be represented
3198   // as shifts:
3199   // (x*C1)>>C2 <= x for C1 < 2**C2.
3200   // (x<<C1)/C2 <= x for 2**C1 < C2.
3201   const APInt *C1, *C2;
3202   if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3203        C1->ule(*C2)) ||
3204       (match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3205        C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) ||
3206       (match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3207        (APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) {
3208     if (Pred == ICmpInst::ICMP_UGT)
3209       return getFalse(ITy);
3210     if (Pred == ICmpInst::ICMP_ULE)
3211       return getTrue(ITy);
3212   }
3213 
3214   // (sub C, X) == X, C is odd  --> false
3215   // (sub C, X) != X, C is odd  --> true
3216   if (match(LBO, m_Sub(m_APIntAllowPoison(C), m_Specific(RHS))) &&
3217       (*C & 1) == 1 && ICmpInst::isEquality(Pred))
3218     return (Pred == ICmpInst::ICMP_EQ) ? getFalse(ITy) : getTrue(ITy);
3219 
3220   return nullptr;
3221 }
3222 
3223 // If only one of the icmp's operands has NSW flags, try to prove that:
3224 //
3225 //   icmp slt (x + C1), (x +nsw C2)
3226 //
3227 // is equivalent to:
3228 //
3229 //   icmp slt C1, C2
3230 //
3231 // which is true if x + C2 has the NSW flags set and:
3232 // *) C1 < C2 && C1 >= 0, or
3233 // *) C2 < C1 && C1 <= 0.
3234 //
3235 static bool trySimplifyICmpWithAdds(CmpInst::Predicate Pred, Value *LHS,
3236                                     Value *RHS, const InstrInfoQuery &IIQ) {
3237   // TODO: only support icmp slt for now.
3238   if (Pred != CmpInst::ICMP_SLT || !IIQ.UseInstrInfo)
3239     return false;
3240 
3241   // Canonicalize nsw add as RHS.
3242   if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3243     std::swap(LHS, RHS);
3244   if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3245     return false;
3246 
3247   Value *X;
3248   const APInt *C1, *C2;
3249   if (!match(LHS, m_Add(m_Value(X), m_APInt(C1))) ||
3250       !match(RHS, m_Add(m_Specific(X), m_APInt(C2))))
3251     return false;
3252 
3253   return (C1->slt(*C2) && C1->isNonNegative()) ||
3254          (C2->slt(*C1) && C1->isNonPositive());
3255 }
3256 
3257 /// TODO: A large part of this logic is duplicated in InstCombine's
3258 /// foldICmpBinOp(). We should be able to share that and avoid the code
3259 /// duplication.
3260 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
3261                                     Value *RHS, const SimplifyQuery &Q,
3262                                     unsigned MaxRecurse) {
3263   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
3264   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
3265   if (MaxRecurse && (LBO || RBO)) {
3266     // Analyze the case when either LHS or RHS is an add instruction.
3267     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3268     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
3269     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
3270     if (LBO && LBO->getOpcode() == Instruction::Add) {
3271       A = LBO->getOperand(0);
3272       B = LBO->getOperand(1);
3273       NoLHSWrapProblem =
3274           ICmpInst::isEquality(Pred) ||
3275           (CmpInst::isUnsigned(Pred) &&
3276            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
3277           (CmpInst::isSigned(Pred) &&
3278            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
3279     }
3280     if (RBO && RBO->getOpcode() == Instruction::Add) {
3281       C = RBO->getOperand(0);
3282       D = RBO->getOperand(1);
3283       NoRHSWrapProblem =
3284           ICmpInst::isEquality(Pred) ||
3285           (CmpInst::isUnsigned(Pred) &&
3286            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
3287           (CmpInst::isSigned(Pred) &&
3288            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
3289     }
3290 
3291     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3292     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
3293       if (Value *V = simplifyICmpInst(Pred, A == RHS ? B : A,
3294                                       Constant::getNullValue(RHS->getType()), Q,
3295                                       MaxRecurse - 1))
3296         return V;
3297 
3298     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3299     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
3300       if (Value *V =
3301               simplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
3302                                C == LHS ? D : C, Q, MaxRecurse - 1))
3303         return V;
3304 
3305     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
3306     bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) ||
3307                        trySimplifyICmpWithAdds(Pred, LHS, RHS, Q.IIQ);
3308     if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) {
3309       // Determine Y and Z in the form icmp (X+Y), (X+Z).
3310       Value *Y, *Z;
3311       if (A == C) {
3312         // C + B == C + D  ->  B == D
3313         Y = B;
3314         Z = D;
3315       } else if (A == D) {
3316         // D + B == C + D  ->  B == C
3317         Y = B;
3318         Z = C;
3319       } else if (B == C) {
3320         // A + C == C + D  ->  A == D
3321         Y = A;
3322         Z = D;
3323       } else {
3324         assert(B == D);
3325         // A + D == C + D  ->  A == C
3326         Y = A;
3327         Z = C;
3328       }
3329       if (Value *V = simplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
3330         return V;
3331     }
3332   }
3333 
3334   if (LBO)
3335     if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse))
3336       return V;
3337 
3338   if (RBO)
3339     if (Value *V = simplifyICmpWithBinOpOnLHS(
3340             ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse))
3341       return V;
3342 
3343   // 0 - (zext X) pred C
3344   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
3345     const APInt *C;
3346     if (match(RHS, m_APInt(C))) {
3347       if (C->isStrictlyPositive()) {
3348         if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE)
3349           return ConstantInt::getTrue(getCompareTy(RHS));
3350         if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ)
3351           return ConstantInt::getFalse(getCompareTy(RHS));
3352       }
3353       if (C->isNonNegative()) {
3354         if (Pred == ICmpInst::ICMP_SLE)
3355           return ConstantInt::getTrue(getCompareTy(RHS));
3356         if (Pred == ICmpInst::ICMP_SGT)
3357           return ConstantInt::getFalse(getCompareTy(RHS));
3358       }
3359     }
3360   }
3361 
3362   //   If C2 is a power-of-2 and C is not:
3363   //   (C2 << X) == C --> false
3364   //   (C2 << X) != C --> true
3365   const APInt *C;
3366   if (match(LHS, m_Shl(m_Power2(), m_Value())) &&
3367       match(RHS, m_APIntAllowPoison(C)) && !C->isPowerOf2()) {
3368     // C2 << X can equal zero in some circumstances.
3369     // This simplification might be unsafe if C is zero.
3370     //
3371     // We know it is safe if:
3372     // - The shift is nsw. We can't shift out the one bit.
3373     // - The shift is nuw. We can't shift out the one bit.
3374     // - C2 is one.
3375     // - C isn't zero.
3376     if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3377         Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3378         match(LHS, m_Shl(m_One(), m_Value())) || !C->isZero()) {
3379       if (Pred == ICmpInst::ICMP_EQ)
3380         return ConstantInt::getFalse(getCompareTy(RHS));
3381       if (Pred == ICmpInst::ICMP_NE)
3382         return ConstantInt::getTrue(getCompareTy(RHS));
3383     }
3384   }
3385 
3386   // If C is a power-of-2:
3387   // (C << X)  >u 0x8000 --> false
3388   // (C << X) <=u 0x8000 --> true
3389   if (match(LHS, m_Shl(m_Power2(), m_Value())) && match(RHS, m_SignMask())) {
3390     if (Pred == ICmpInst::ICMP_UGT)
3391       return ConstantInt::getFalse(getCompareTy(RHS));
3392     if (Pred == ICmpInst::ICMP_ULE)
3393       return ConstantInt::getTrue(getCompareTy(RHS));
3394   }
3395 
3396   if (!MaxRecurse || !LBO || !RBO || LBO->getOpcode() != RBO->getOpcode())
3397     return nullptr;
3398 
3399   if (LBO->getOperand(0) == RBO->getOperand(0)) {
3400     switch (LBO->getOpcode()) {
3401     default:
3402       break;
3403     case Instruction::Shl: {
3404       bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3405       bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
3406       if (!NUW || (ICmpInst::isSigned(Pred) && !NSW) ||
3407           !isKnownNonZero(LBO->getOperand(0), Q))
3408         break;
3409       if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(1),
3410                                       RBO->getOperand(1), Q, MaxRecurse - 1))
3411         return V;
3412       break;
3413     }
3414     // If C1 & C2 == C1, A = X and/or C1, B = X and/or C2:
3415     // icmp ule A, B -> true
3416     // icmp ugt A, B -> false
3417     // icmp sle A, B -> true (C1 and C2 are the same sign)
3418     // icmp sgt A, B -> false (C1 and C2 are the same sign)
3419     case Instruction::And:
3420     case Instruction::Or: {
3421       const APInt *C1, *C2;
3422       if (ICmpInst::isRelational(Pred) &&
3423           match(LBO->getOperand(1), m_APInt(C1)) &&
3424           match(RBO->getOperand(1), m_APInt(C2))) {
3425         if (!C1->isSubsetOf(*C2)) {
3426           std::swap(C1, C2);
3427           Pred = ICmpInst::getSwappedPredicate(Pred);
3428         }
3429         if (C1->isSubsetOf(*C2)) {
3430           if (Pred == ICmpInst::ICMP_ULE)
3431             return ConstantInt::getTrue(getCompareTy(LHS));
3432           if (Pred == ICmpInst::ICMP_UGT)
3433             return ConstantInt::getFalse(getCompareTy(LHS));
3434           if (C1->isNonNegative() == C2->isNonNegative()) {
3435             if (Pred == ICmpInst::ICMP_SLE)
3436               return ConstantInt::getTrue(getCompareTy(LHS));
3437             if (Pred == ICmpInst::ICMP_SGT)
3438               return ConstantInt::getFalse(getCompareTy(LHS));
3439           }
3440         }
3441       }
3442       break;
3443     }
3444     }
3445   }
3446 
3447   if (LBO->getOperand(1) == RBO->getOperand(1)) {
3448     switch (LBO->getOpcode()) {
3449     default:
3450       break;
3451     case Instruction::UDiv:
3452     case Instruction::LShr:
3453       if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
3454           !Q.IIQ.isExact(RBO))
3455         break;
3456       if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3457                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3458         return V;
3459       break;
3460     case Instruction::SDiv:
3461       if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
3462           !Q.IIQ.isExact(RBO))
3463         break;
3464       if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3465                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3466         return V;
3467       break;
3468     case Instruction::AShr:
3469       if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
3470         break;
3471       if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3472                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3473         return V;
3474       break;
3475     case Instruction::Shl: {
3476       bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3477       bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
3478       if (!NUW && !NSW)
3479         break;
3480       if (!NSW && ICmpInst::isSigned(Pred))
3481         break;
3482       if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3483                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3484         return V;
3485       break;
3486     }
3487     }
3488   }
3489   return nullptr;
3490 }
3491 
3492 /// simplify integer comparisons where at least one operand of the compare
3493 /// matches an integer min/max idiom.
3494 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
3495                                      Value *RHS, const SimplifyQuery &Q,
3496                                      unsigned MaxRecurse) {
3497   Type *ITy = getCompareTy(LHS); // The return type.
3498   Value *A, *B;
3499   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
3500   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
3501 
3502   // Signed variants on "max(a,b)>=a -> true".
3503   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3504     if (A != RHS)
3505       std::swap(A, B);       // smax(A, B) pred A.
3506     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3507     // We analyze this as smax(A, B) pred A.
3508     P = Pred;
3509   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
3510              (A == LHS || B == LHS)) {
3511     if (A != LHS)
3512       std::swap(A, B);       // A pred smax(A, B).
3513     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3514     // We analyze this as smax(A, B) swapped-pred A.
3515     P = CmpInst::getSwappedPredicate(Pred);
3516   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3517              (A == RHS || B == RHS)) {
3518     if (A != RHS)
3519       std::swap(A, B);       // smin(A, B) pred A.
3520     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3521     // We analyze this as smax(-A, -B) swapped-pred -A.
3522     // Note that we do not need to actually form -A or -B thanks to EqP.
3523     P = CmpInst::getSwappedPredicate(Pred);
3524   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
3525              (A == LHS || B == LHS)) {
3526     if (A != LHS)
3527       std::swap(A, B);       // A pred smin(A, B).
3528     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3529     // We analyze this as smax(-A, -B) pred -A.
3530     // Note that we do not need to actually form -A or -B thanks to EqP.
3531     P = Pred;
3532   }
3533   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3534     // Cases correspond to "max(A, B) p A".
3535     switch (P) {
3536     default:
3537       break;
3538     case CmpInst::ICMP_EQ:
3539     case CmpInst::ICMP_SLE:
3540       // Equivalent to "A EqP B".  This may be the same as the condition tested
3541       // in the max/min; if so, we can just return that.
3542       if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
3543         return V;
3544       if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
3545         return V;
3546       // Otherwise, see if "A EqP B" simplifies.
3547       if (MaxRecurse)
3548         if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3549           return V;
3550       break;
3551     case CmpInst::ICMP_NE:
3552     case CmpInst::ICMP_SGT: {
3553       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3554       // Equivalent to "A InvEqP B".  This may be the same as the condition
3555       // tested in the max/min; if so, we can just return that.
3556       if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
3557         return V;
3558       if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
3559         return V;
3560       // Otherwise, see if "A InvEqP B" simplifies.
3561       if (MaxRecurse)
3562         if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3563           return V;
3564       break;
3565     }
3566     case CmpInst::ICMP_SGE:
3567       // Always true.
3568       return getTrue(ITy);
3569     case CmpInst::ICMP_SLT:
3570       // Always false.
3571       return getFalse(ITy);
3572     }
3573   }
3574 
3575   // Unsigned variants on "max(a,b)>=a -> true".
3576   P = CmpInst::BAD_ICMP_PREDICATE;
3577   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3578     if (A != RHS)
3579       std::swap(A, B);       // umax(A, B) pred A.
3580     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3581     // We analyze this as umax(A, B) pred A.
3582     P = Pred;
3583   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3584              (A == LHS || B == LHS)) {
3585     if (A != LHS)
3586       std::swap(A, B);       // A pred umax(A, B).
3587     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3588     // We analyze this as umax(A, B) swapped-pred A.
3589     P = CmpInst::getSwappedPredicate(Pred);
3590   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3591              (A == RHS || B == RHS)) {
3592     if (A != RHS)
3593       std::swap(A, B);       // umin(A, B) pred A.
3594     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3595     // We analyze this as umax(-A, -B) swapped-pred -A.
3596     // Note that we do not need to actually form -A or -B thanks to EqP.
3597     P = CmpInst::getSwappedPredicate(Pred);
3598   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3599              (A == LHS || B == LHS)) {
3600     if (A != LHS)
3601       std::swap(A, B);       // A pred umin(A, B).
3602     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3603     // We analyze this as umax(-A, -B) pred -A.
3604     // Note that we do not need to actually form -A or -B thanks to EqP.
3605     P = Pred;
3606   }
3607   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3608     // Cases correspond to "max(A, B) p A".
3609     switch (P) {
3610     default:
3611       break;
3612     case CmpInst::ICMP_EQ:
3613     case CmpInst::ICMP_ULE:
3614       // Equivalent to "A EqP B".  This may be the same as the condition tested
3615       // in the max/min; if so, we can just return that.
3616       if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
3617         return V;
3618       if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
3619         return V;
3620       // Otherwise, see if "A EqP B" simplifies.
3621       if (MaxRecurse)
3622         if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3623           return V;
3624       break;
3625     case CmpInst::ICMP_NE:
3626     case CmpInst::ICMP_UGT: {
3627       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3628       // Equivalent to "A InvEqP B".  This may be the same as the condition
3629       // tested in the max/min; if so, we can just return that.
3630       if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
3631         return V;
3632       if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
3633         return V;
3634       // Otherwise, see if "A InvEqP B" simplifies.
3635       if (MaxRecurse)
3636         if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3637           return V;
3638       break;
3639     }
3640     case CmpInst::ICMP_UGE:
3641       return getTrue(ITy);
3642     case CmpInst::ICMP_ULT:
3643       return getFalse(ITy);
3644     }
3645   }
3646 
3647   // Comparing 1 each of min/max with a common operand?
3648   // Canonicalize min operand to RHS.
3649   if (match(LHS, m_UMin(m_Value(), m_Value())) ||
3650       match(LHS, m_SMin(m_Value(), m_Value()))) {
3651     std::swap(LHS, RHS);
3652     Pred = ICmpInst::getSwappedPredicate(Pred);
3653   }
3654 
3655   Value *C, *D;
3656   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3657       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3658       (A == C || A == D || B == C || B == D)) {
3659     // smax(A, B) >=s smin(A, D) --> true
3660     if (Pred == CmpInst::ICMP_SGE)
3661       return getTrue(ITy);
3662     // smax(A, B) <s smin(A, D) --> false
3663     if (Pred == CmpInst::ICMP_SLT)
3664       return getFalse(ITy);
3665   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3666              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3667              (A == C || A == D || B == C || B == D)) {
3668     // umax(A, B) >=u umin(A, D) --> true
3669     if (Pred == CmpInst::ICMP_UGE)
3670       return getTrue(ITy);
3671     // umax(A, B) <u umin(A, D) --> false
3672     if (Pred == CmpInst::ICMP_ULT)
3673       return getFalse(ITy);
3674   }
3675 
3676   return nullptr;
3677 }
3678 
3679 static Value *simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate,
3680                                                Value *LHS, Value *RHS,
3681                                                const SimplifyQuery &Q) {
3682   // Gracefully handle instructions that have not been inserted yet.
3683   if (!Q.AC || !Q.CxtI)
3684     return nullptr;
3685 
3686   for (Value *AssumeBaseOp : {LHS, RHS}) {
3687     for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) {
3688       if (!AssumeVH)
3689         continue;
3690 
3691       CallInst *Assume = cast<CallInst>(AssumeVH);
3692       if (std::optional<bool> Imp = isImpliedCondition(
3693               Assume->getArgOperand(0), Predicate, LHS, RHS, Q.DL))
3694         if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT))
3695           return ConstantInt::get(getCompareTy(LHS), *Imp);
3696     }
3697   }
3698 
3699   return nullptr;
3700 }
3701 
3702 static Value *simplifyICmpWithIntrinsicOnLHS(CmpInst::Predicate Pred,
3703                                              Value *LHS, Value *RHS) {
3704   auto *II = dyn_cast<IntrinsicInst>(LHS);
3705   if (!II)
3706     return nullptr;
3707 
3708   switch (II->getIntrinsicID()) {
3709   case Intrinsic::uadd_sat:
3710     // uadd.sat(X, Y) uge X, uadd.sat(X, Y) uge Y
3711     if (II->getArgOperand(0) == RHS || II->getArgOperand(1) == RHS) {
3712       if (Pred == ICmpInst::ICMP_UGE)
3713         return ConstantInt::getTrue(getCompareTy(II));
3714       if (Pred == ICmpInst::ICMP_ULT)
3715         return ConstantInt::getFalse(getCompareTy(II));
3716     }
3717     return nullptr;
3718   case Intrinsic::usub_sat:
3719     // usub.sat(X, Y) ule X
3720     if (II->getArgOperand(0) == RHS) {
3721       if (Pred == ICmpInst::ICMP_ULE)
3722         return ConstantInt::getTrue(getCompareTy(II));
3723       if (Pred == ICmpInst::ICMP_UGT)
3724         return ConstantInt::getFalse(getCompareTy(II));
3725     }
3726     return nullptr;
3727   default:
3728     return nullptr;
3729   }
3730 }
3731 
3732 /// Helper method to get range from metadata or attribute.
3733 static std::optional<ConstantRange> getRange(Value *V,
3734                                              const InstrInfoQuery &IIQ) {
3735   if (Instruction *I = dyn_cast<Instruction>(V))
3736     if (MDNode *MD = IIQ.getMetadata(I, LLVMContext::MD_range))
3737       return getConstantRangeFromMetadata(*MD);
3738 
3739   if (const Argument *A = dyn_cast<Argument>(V))
3740     return A->getRange();
3741   else if (const CallBase *CB = dyn_cast<CallBase>(V))
3742     return CB->getRange();
3743 
3744   return std::nullopt;
3745 }
3746 
3747 /// Given operands for an ICmpInst, see if we can fold the result.
3748 /// If not, this returns null.
3749 static Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3750                                const SimplifyQuery &Q, unsigned MaxRecurse) {
3751   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3752   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3753 
3754   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3755     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3756       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3757 
3758     // If we have a constant, make sure it is on the RHS.
3759     std::swap(LHS, RHS);
3760     Pred = CmpInst::getSwappedPredicate(Pred);
3761   }
3762   assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3763 
3764   Type *ITy = getCompareTy(LHS); // The return type.
3765 
3766   // icmp poison, X -> poison
3767   if (isa<PoisonValue>(RHS))
3768     return PoisonValue::get(ITy);
3769 
3770   // For EQ and NE, we can always pick a value for the undef to make the
3771   // predicate pass or fail, so we can return undef.
3772   // Matches behavior in llvm::ConstantFoldCompareInstruction.
3773   if (Q.isUndefValue(RHS) && ICmpInst::isEquality(Pred))
3774     return UndefValue::get(ITy);
3775 
3776   // icmp X, X -> true/false
3777   // icmp X, undef -> true/false because undef could be X.
3778   if (LHS == RHS || Q.isUndefValue(RHS))
3779     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3780 
3781   if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3782     return V;
3783 
3784   // TODO: Sink/common this with other potentially expensive calls that use
3785   //       ValueTracking? See comment below for isKnownNonEqual().
3786   if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3787     return V;
3788 
3789   if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
3790     return V;
3791 
3792   // If both operands have range metadata, use the metadata
3793   // to simplify the comparison.
3794   if (std::optional<ConstantRange> RhsCr = getRange(RHS, Q.IIQ))
3795     if (std::optional<ConstantRange> LhsCr = getRange(LHS, Q.IIQ)) {
3796       if (LhsCr->icmp(Pred, *RhsCr))
3797         return ConstantInt::getTrue(ITy);
3798 
3799       if (LhsCr->icmp(CmpInst::getInversePredicate(Pred), *RhsCr))
3800         return ConstantInt::getFalse(ITy);
3801     }
3802 
3803   // Compare of cast, for example (zext X) != 0 -> X != 0
3804   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3805     Instruction *LI = cast<CastInst>(LHS);
3806     Value *SrcOp = LI->getOperand(0);
3807     Type *SrcTy = SrcOp->getType();
3808     Type *DstTy = LI->getType();
3809 
3810     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3811     // if the integer type is the same size as the pointer type.
3812     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3813         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3814       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3815         // Transfer the cast to the constant.
3816         if (Value *V = simplifyICmpInst(Pred, SrcOp,
3817                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
3818                                         Q, MaxRecurse - 1))
3819           return V;
3820       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3821         if (RI->getOperand(0)->getType() == SrcTy)
3822           // Compare without the cast.
3823           if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
3824                                           MaxRecurse - 1))
3825             return V;
3826       }
3827     }
3828 
3829     if (isa<ZExtInst>(LHS)) {
3830       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3831       // same type.
3832       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3833         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3834           // Compare X and Y.  Note that signed predicates become unsigned.
3835           if (Value *V =
3836                   simplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), SrcOp,
3837                                    RI->getOperand(0), Q, MaxRecurse - 1))
3838             return V;
3839       }
3840       // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true.
3841       else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3842         if (SrcOp == RI->getOperand(0)) {
3843           if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE)
3844             return ConstantInt::getTrue(ITy);
3845           if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT)
3846             return ConstantInt::getFalse(ITy);
3847         }
3848       }
3849       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3850       // too.  If not, then try to deduce the result of the comparison.
3851       else if (match(RHS, m_ImmConstant())) {
3852         Constant *C = dyn_cast<Constant>(RHS);
3853         assert(C != nullptr);
3854 
3855         // Compute the constant that would happen if we truncated to SrcTy then
3856         // reextended to DstTy.
3857         Constant *Trunc =
3858             ConstantFoldCastOperand(Instruction::Trunc, C, SrcTy, Q.DL);
3859         assert(Trunc && "Constant-fold of ImmConstant should not fail");
3860         Constant *RExt =
3861             ConstantFoldCastOperand(CastInst::ZExt, Trunc, DstTy, Q.DL);
3862         assert(RExt && "Constant-fold of ImmConstant should not fail");
3863         Constant *AnyEq =
3864             ConstantFoldCompareInstOperands(ICmpInst::ICMP_EQ, RExt, C, Q.DL);
3865         assert(AnyEq && "Constant-fold of ImmConstant should not fail");
3866 
3867         // If the re-extended constant didn't change any of the elements then
3868         // this is effectively also a case of comparing two zero-extended
3869         // values.
3870         if (AnyEq->isAllOnesValue() && MaxRecurse)
3871           if (Value *V = simplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3872                                           SrcOp, Trunc, Q, MaxRecurse - 1))
3873             return V;
3874 
3875         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3876         // there.  Use this to work out the result of the comparison.
3877         if (AnyEq->isNullValue()) {
3878           switch (Pred) {
3879           default:
3880             llvm_unreachable("Unknown ICmp predicate!");
3881           // LHS <u RHS.
3882           case ICmpInst::ICMP_EQ:
3883           case ICmpInst::ICMP_UGT:
3884           case ICmpInst::ICMP_UGE:
3885             return Constant::getNullValue(ITy);
3886 
3887           case ICmpInst::ICMP_NE:
3888           case ICmpInst::ICMP_ULT:
3889           case ICmpInst::ICMP_ULE:
3890             return Constant::getAllOnesValue(ITy);
3891 
3892           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
3893           // is non-negative then LHS <s RHS.
3894           case ICmpInst::ICMP_SGT:
3895           case ICmpInst::ICMP_SGE:
3896             return ConstantFoldCompareInstOperands(
3897                 ICmpInst::ICMP_SLT, C, Constant::getNullValue(C->getType()),
3898                 Q.DL);
3899           case ICmpInst::ICMP_SLT:
3900           case ICmpInst::ICMP_SLE:
3901             return ConstantFoldCompareInstOperands(
3902                 ICmpInst::ICMP_SGE, C, Constant::getNullValue(C->getType()),
3903                 Q.DL);
3904           }
3905         }
3906       }
3907     }
3908 
3909     if (isa<SExtInst>(LHS)) {
3910       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3911       // same type.
3912       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3913         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3914           // Compare X and Y.  Note that the predicate does not change.
3915           if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
3916                                           MaxRecurse - 1))
3917             return V;
3918       }
3919       // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true.
3920       else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3921         if (SrcOp == RI->getOperand(0)) {
3922           if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE)
3923             return ConstantInt::getTrue(ITy);
3924           if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT)
3925             return ConstantInt::getFalse(ITy);
3926         }
3927       }
3928       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3929       // too.  If not, then try to deduce the result of the comparison.
3930       else if (match(RHS, m_ImmConstant())) {
3931         Constant *C = cast<Constant>(RHS);
3932 
3933         // Compute the constant that would happen if we truncated to SrcTy then
3934         // reextended to DstTy.
3935         Constant *Trunc =
3936             ConstantFoldCastOperand(Instruction::Trunc, C, SrcTy, Q.DL);
3937         assert(Trunc && "Constant-fold of ImmConstant should not fail");
3938         Constant *RExt =
3939             ConstantFoldCastOperand(CastInst::SExt, Trunc, DstTy, Q.DL);
3940         assert(RExt && "Constant-fold of ImmConstant should not fail");
3941         Constant *AnyEq =
3942             ConstantFoldCompareInstOperands(ICmpInst::ICMP_EQ, RExt, C, Q.DL);
3943         assert(AnyEq && "Constant-fold of ImmConstant should not fail");
3944 
3945         // If the re-extended constant didn't change then this is effectively
3946         // also a case of comparing two sign-extended values.
3947         if (AnyEq->isAllOnesValue() && MaxRecurse)
3948           if (Value *V =
3949                   simplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse - 1))
3950             return V;
3951 
3952         // Otherwise the upper bits of LHS are all equal, while RHS has varying
3953         // bits there.  Use this to work out the result of the comparison.
3954         if (AnyEq->isNullValue()) {
3955           switch (Pred) {
3956           default:
3957             llvm_unreachable("Unknown ICmp predicate!");
3958           case ICmpInst::ICMP_EQ:
3959             return Constant::getNullValue(ITy);
3960           case ICmpInst::ICMP_NE:
3961             return Constant::getAllOnesValue(ITy);
3962 
3963           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
3964           // LHS >s RHS.
3965           case ICmpInst::ICMP_SGT:
3966           case ICmpInst::ICMP_SGE:
3967             return ConstantFoldCompareInstOperands(
3968                 ICmpInst::ICMP_SLT, C, Constant::getNullValue(C->getType()),
3969                 Q.DL);
3970           case ICmpInst::ICMP_SLT:
3971           case ICmpInst::ICMP_SLE:
3972             return ConstantFoldCompareInstOperands(
3973                 ICmpInst::ICMP_SGE, C, Constant::getNullValue(C->getType()),
3974                 Q.DL);
3975 
3976           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
3977           // LHS >u RHS.
3978           case ICmpInst::ICMP_UGT:
3979           case ICmpInst::ICMP_UGE:
3980             // Comparison is true iff the LHS <s 0.
3981             if (MaxRecurse)
3982               if (Value *V = simplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3983                                               Constant::getNullValue(SrcTy), Q,
3984                                               MaxRecurse - 1))
3985                 return V;
3986             break;
3987           case ICmpInst::ICMP_ULT:
3988           case ICmpInst::ICMP_ULE:
3989             // Comparison is true iff the LHS >=s 0.
3990             if (MaxRecurse)
3991               if (Value *V = simplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3992                                               Constant::getNullValue(SrcTy), Q,
3993                                               MaxRecurse - 1))
3994                 return V;
3995             break;
3996           }
3997         }
3998       }
3999     }
4000   }
4001 
4002   // icmp eq|ne X, Y -> false|true if X != Y
4003   // This is potentially expensive, and we have already computedKnownBits for
4004   // compares with 0 above here, so only try this for a non-zero compare.
4005   if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) &&
4006       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
4007     return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
4008   }
4009 
4010   if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
4011     return V;
4012 
4013   if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
4014     return V;
4015 
4016   if (Value *V = simplifyICmpWithIntrinsicOnLHS(Pred, LHS, RHS))
4017     return V;
4018   if (Value *V = simplifyICmpWithIntrinsicOnLHS(
4019           ICmpInst::getSwappedPredicate(Pred), RHS, LHS))
4020     return V;
4021 
4022   if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q))
4023     return V;
4024 
4025   if (std::optional<bool> Res =
4026           isImpliedByDomCondition(Pred, LHS, RHS, Q.CxtI, Q.DL))
4027     return ConstantInt::getBool(ITy, *Res);
4028 
4029   // Simplify comparisons of related pointers using a powerful, recursive
4030   // GEP-walk when we have target data available..
4031   if (LHS->getType()->isPointerTy())
4032     if (auto *C = computePointerICmp(Pred, LHS, RHS, Q))
4033       return C;
4034   if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
4035     if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
4036       if (CLHS->getPointerOperandType() == CRHS->getPointerOperandType() &&
4037           Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
4038               Q.DL.getTypeSizeInBits(CLHS->getType()))
4039         if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(),
4040                                          CRHS->getPointerOperand(), Q))
4041           return C;
4042 
4043   // If the comparison is with the result of a select instruction, check whether
4044   // comparing with either branch of the select always yields the same value.
4045   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
4046     if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
4047       return V;
4048 
4049   // If the comparison is with the result of a phi instruction, check whether
4050   // doing the compare with each incoming phi value yields a common result.
4051   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
4052     if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
4053       return V;
4054 
4055   return nullptr;
4056 }
4057 
4058 Value *llvm::simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4059                               const SimplifyQuery &Q) {
4060   return ::simplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
4061 }
4062 
4063 /// Given operands for an FCmpInst, see if we can fold the result.
4064 /// If not, this returns null.
4065 static Value *simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4066                                FastMathFlags FMF, const SimplifyQuery &Q,
4067                                unsigned MaxRecurse) {
4068   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
4069   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
4070 
4071   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
4072     if (Constant *CRHS = dyn_cast<Constant>(RHS))
4073       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI,
4074                                              Q.CxtI);
4075 
4076     // If we have a constant, make sure it is on the RHS.
4077     std::swap(LHS, RHS);
4078     Pred = CmpInst::getSwappedPredicate(Pred);
4079   }
4080 
4081   // Fold trivial predicates.
4082   Type *RetTy = getCompareTy(LHS);
4083   if (Pred == FCmpInst::FCMP_FALSE)
4084     return getFalse(RetTy);
4085   if (Pred == FCmpInst::FCMP_TRUE)
4086     return getTrue(RetTy);
4087 
4088   // fcmp pred x, poison and  fcmp pred poison, x
4089   // fold to poison
4090   if (isa<PoisonValue>(LHS) || isa<PoisonValue>(RHS))
4091     return PoisonValue::get(RetTy);
4092 
4093   // fcmp pred x, undef  and  fcmp pred undef, x
4094   // fold to true if unordered, false if ordered
4095   if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) {
4096     // Choosing NaN for the undef will always make unordered comparison succeed
4097     // and ordered comparison fail.
4098     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
4099   }
4100 
4101   // fcmp x,x -> true/false.  Not all compares are foldable.
4102   if (LHS == RHS) {
4103     if (CmpInst::isTrueWhenEqual(Pred))
4104       return getTrue(RetTy);
4105     if (CmpInst::isFalseWhenEqual(Pred))
4106       return getFalse(RetTy);
4107   }
4108 
4109   // Fold (un)ordered comparison if we can determine there are no NaNs.
4110   //
4111   // This catches the 2 variable input case, constants are handled below as a
4112   // class-like compare.
4113   if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) {
4114     KnownFPClass RHSClass =
4115         computeKnownFPClass(RHS, fcAllFlags, /*Depth=*/0, Q);
4116     KnownFPClass LHSClass =
4117         computeKnownFPClass(LHS, fcAllFlags, /*Depth=*/0, Q);
4118 
4119     if (FMF.noNaNs() ||
4120         (RHSClass.isKnownNeverNaN() && LHSClass.isKnownNeverNaN()))
4121       return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
4122 
4123     if (RHSClass.isKnownAlwaysNaN() || LHSClass.isKnownAlwaysNaN())
4124       return ConstantInt::get(RetTy, Pred == CmpInst::FCMP_UNO);
4125   }
4126 
4127   const APFloat *C = nullptr;
4128   match(RHS, m_APFloatAllowPoison(C));
4129   std::optional<KnownFPClass> FullKnownClassLHS;
4130 
4131   // Lazily compute the possible classes for LHS. Avoid computing it twice if
4132   // RHS is a 0.
4133   auto computeLHSClass = [=, &FullKnownClassLHS](FPClassTest InterestedFlags =
4134                                                      fcAllFlags) {
4135     if (FullKnownClassLHS)
4136       return *FullKnownClassLHS;
4137     return computeKnownFPClass(LHS, FMF, InterestedFlags, 0, Q);
4138   };
4139 
4140   if (C && Q.CxtI) {
4141     // Fold out compares that express a class test.
4142     //
4143     // FIXME: Should be able to perform folds without context
4144     // instruction. Always pass in the context function?
4145 
4146     const Function *ParentF = Q.CxtI->getFunction();
4147     auto [ClassVal, ClassTest] = fcmpToClassTest(Pred, *ParentF, LHS, C);
4148     if (ClassVal) {
4149       FullKnownClassLHS = computeLHSClass();
4150       if ((FullKnownClassLHS->KnownFPClasses & ClassTest) == fcNone)
4151         return getFalse(RetTy);
4152       if ((FullKnownClassLHS->KnownFPClasses & ~ClassTest) == fcNone)
4153         return getTrue(RetTy);
4154     }
4155   }
4156 
4157   // Handle fcmp with constant RHS.
4158   if (C) {
4159     // TODO: If we always required a context function, we wouldn't need to
4160     // special case nans.
4161     if (C->isNaN())
4162       return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
4163 
4164     // TODO: Need version fcmpToClassTest which returns implied class when the
4165     // compare isn't a complete class test. e.g. > 1.0 implies fcPositive, but
4166     // isn't implementable as a class call.
4167     if (C->isNegative() && !C->isNegZero()) {
4168       FPClassTest Interested = KnownFPClass::OrderedLessThanZeroMask;
4169 
4170       // TODO: We can catch more cases by using a range check rather than
4171       //       relying on CannotBeOrderedLessThanZero.
4172       switch (Pred) {
4173       case FCmpInst::FCMP_UGE:
4174       case FCmpInst::FCMP_UGT:
4175       case FCmpInst::FCMP_UNE: {
4176         KnownFPClass KnownClass = computeLHSClass(Interested);
4177 
4178         // (X >= 0) implies (X > C) when (C < 0)
4179         if (KnownClass.cannotBeOrderedLessThanZero())
4180           return getTrue(RetTy);
4181         break;
4182       }
4183       case FCmpInst::FCMP_OEQ:
4184       case FCmpInst::FCMP_OLE:
4185       case FCmpInst::FCMP_OLT: {
4186         KnownFPClass KnownClass = computeLHSClass(Interested);
4187 
4188         // (X >= 0) implies !(X < C) when (C < 0)
4189         if (KnownClass.cannotBeOrderedLessThanZero())
4190           return getFalse(RetTy);
4191         break;
4192       }
4193       default:
4194         break;
4195       }
4196     }
4197     // Check comparison of [minnum/maxnum with constant] with other constant.
4198     const APFloat *C2;
4199     if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
4200          *C2 < *C) ||
4201         (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
4202          *C2 > *C)) {
4203       bool IsMaxNum =
4204           cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
4205       // The ordered relationship and minnum/maxnum guarantee that we do not
4206       // have NaN constants, so ordered/unordered preds are handled the same.
4207       switch (Pred) {
4208       case FCmpInst::FCMP_OEQ:
4209       case FCmpInst::FCMP_UEQ:
4210         // minnum(X, LesserC)  == C --> false
4211         // maxnum(X, GreaterC) == C --> false
4212         return getFalse(RetTy);
4213       case FCmpInst::FCMP_ONE:
4214       case FCmpInst::FCMP_UNE:
4215         // minnum(X, LesserC)  != C --> true
4216         // maxnum(X, GreaterC) != C --> true
4217         return getTrue(RetTy);
4218       case FCmpInst::FCMP_OGE:
4219       case FCmpInst::FCMP_UGE:
4220       case FCmpInst::FCMP_OGT:
4221       case FCmpInst::FCMP_UGT:
4222         // minnum(X, LesserC)  >= C --> false
4223         // minnum(X, LesserC)  >  C --> false
4224         // maxnum(X, GreaterC) >= C --> true
4225         // maxnum(X, GreaterC) >  C --> true
4226         return ConstantInt::get(RetTy, IsMaxNum);
4227       case FCmpInst::FCMP_OLE:
4228       case FCmpInst::FCMP_ULE:
4229       case FCmpInst::FCMP_OLT:
4230       case FCmpInst::FCMP_ULT:
4231         // minnum(X, LesserC)  <= C --> true
4232         // minnum(X, LesserC)  <  C --> true
4233         // maxnum(X, GreaterC) <= C --> false
4234         // maxnum(X, GreaterC) <  C --> false
4235         return ConstantInt::get(RetTy, !IsMaxNum);
4236       default:
4237         // TRUE/FALSE/ORD/UNO should be handled before this.
4238         llvm_unreachable("Unexpected fcmp predicate");
4239       }
4240     }
4241   }
4242 
4243   // TODO: Could fold this with above if there were a matcher which returned all
4244   // classes in a non-splat vector.
4245   if (match(RHS, m_AnyZeroFP())) {
4246     switch (Pred) {
4247     case FCmpInst::FCMP_OGE:
4248     case FCmpInst::FCMP_ULT: {
4249       FPClassTest Interested = KnownFPClass::OrderedLessThanZeroMask;
4250       if (!FMF.noNaNs())
4251         Interested |= fcNan;
4252 
4253       KnownFPClass Known = computeLHSClass(Interested);
4254 
4255       // Positive or zero X >= 0.0 --> true
4256       // Positive or zero X <  0.0 --> false
4257       if ((FMF.noNaNs() || Known.isKnownNeverNaN()) &&
4258           Known.cannotBeOrderedLessThanZero())
4259         return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
4260       break;
4261     }
4262     case FCmpInst::FCMP_UGE:
4263     case FCmpInst::FCMP_OLT: {
4264       FPClassTest Interested = KnownFPClass::OrderedLessThanZeroMask;
4265       KnownFPClass Known = computeLHSClass(Interested);
4266 
4267       // Positive or zero or nan X >= 0.0 --> true
4268       // Positive or zero or nan X <  0.0 --> false
4269       if (Known.cannotBeOrderedLessThanZero())
4270         return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
4271       break;
4272     }
4273     default:
4274       break;
4275     }
4276   }
4277 
4278   // If the comparison is with the result of a select instruction, check whether
4279   // comparing with either branch of the select always yields the same value.
4280   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
4281     if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
4282       return V;
4283 
4284   // If the comparison is with the result of a phi instruction, check whether
4285   // doing the compare with each incoming phi value yields a common result.
4286   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
4287     if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
4288       return V;
4289 
4290   return nullptr;
4291 }
4292 
4293 Value *llvm::simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4294                               FastMathFlags FMF, const SimplifyQuery &Q) {
4295   return ::simplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
4296 }
4297 
4298 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4299                                      const SimplifyQuery &Q,
4300                                      bool AllowRefinement,
4301                                      SmallVectorImpl<Instruction *> *DropFlags,
4302                                      unsigned MaxRecurse) {
4303   // Trivial replacement.
4304   if (V == Op)
4305     return RepOp;
4306 
4307   if (!MaxRecurse--)
4308     return nullptr;
4309 
4310   // We cannot replace a constant, and shouldn't even try.
4311   if (isa<Constant>(Op))
4312     return nullptr;
4313 
4314   auto *I = dyn_cast<Instruction>(V);
4315   if (!I)
4316     return nullptr;
4317 
4318   // The arguments of a phi node might refer to a value from a previous
4319   // cycle iteration.
4320   if (isa<PHINode>(I))
4321     return nullptr;
4322 
4323   if (Op->getType()->isVectorTy()) {
4324     // For vector types, the simplification must hold per-lane, so forbid
4325     // potentially cross-lane operations like shufflevector.
4326     if (!I->getType()->isVectorTy() || isa<ShuffleVectorInst>(I) ||
4327         isa<CallBase>(I) || isa<BitCastInst>(I))
4328       return nullptr;
4329   }
4330 
4331   // Don't fold away llvm.is.constant checks based on assumptions.
4332   if (match(I, m_Intrinsic<Intrinsic::is_constant>()))
4333     return nullptr;
4334 
4335   // Don't simplify freeze.
4336   if (isa<FreezeInst>(I))
4337     return nullptr;
4338 
4339   // Replace Op with RepOp in instruction operands.
4340   SmallVector<Value *, 8> NewOps;
4341   bool AnyReplaced = false;
4342   for (Value *InstOp : I->operands()) {
4343     if (Value *NewInstOp = simplifyWithOpReplaced(
4344             InstOp, Op, RepOp, Q, AllowRefinement, DropFlags, MaxRecurse)) {
4345       NewOps.push_back(NewInstOp);
4346       AnyReplaced = InstOp != NewInstOp;
4347     } else {
4348       NewOps.push_back(InstOp);
4349     }
4350   }
4351 
4352   if (!AnyReplaced)
4353     return nullptr;
4354 
4355   if (!AllowRefinement) {
4356     // General InstSimplify functions may refine the result, e.g. by returning
4357     // a constant for a potentially poison value. To avoid this, implement only
4358     // a few non-refining but profitable transforms here.
4359 
4360     if (auto *BO = dyn_cast<BinaryOperator>(I)) {
4361       unsigned Opcode = BO->getOpcode();
4362       // id op x -> x, x op id -> x
4363       if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType()))
4364         return NewOps[1];
4365       if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(),
4366                                                       /* RHS */ true))
4367         return NewOps[0];
4368 
4369       // x & x -> x, x | x -> x
4370       if ((Opcode == Instruction::And || Opcode == Instruction::Or) &&
4371           NewOps[0] == NewOps[1]) {
4372         // or disjoint x, x results in poison.
4373         if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BO)) {
4374           if (PDI->isDisjoint()) {
4375             if (!DropFlags)
4376               return nullptr;
4377             DropFlags->push_back(BO);
4378           }
4379         }
4380         return NewOps[0];
4381       }
4382 
4383       // x - x -> 0, x ^ x -> 0. This is non-refining, because x is non-poison
4384       // by assumption and this case never wraps, so nowrap flags can be
4385       // ignored.
4386       if ((Opcode == Instruction::Sub || Opcode == Instruction::Xor) &&
4387           NewOps[0] == RepOp && NewOps[1] == RepOp)
4388         return Constant::getNullValue(I->getType());
4389 
4390       // If we are substituting an absorber constant into a binop and extra
4391       // poison can't leak if we remove the select -- because both operands of
4392       // the binop are based on the same value -- then it may be safe to replace
4393       // the value with the absorber constant. Examples:
4394       // (Op == 0) ? 0 : (Op & -Op)            --> Op & -Op
4395       // (Op == 0) ? 0 : (Op * (binop Op, C))  --> Op * (binop Op, C)
4396       // (Op == -1) ? -1 : (Op | (binop C, Op) --> Op | (binop C, Op)
4397       Constant *Absorber =
4398           ConstantExpr::getBinOpAbsorber(Opcode, I->getType());
4399       if ((NewOps[0] == Absorber || NewOps[1] == Absorber) &&
4400           impliesPoison(BO, Op))
4401         return Absorber;
4402     }
4403 
4404     if (isa<GetElementPtrInst>(I)) {
4405       // getelementptr x, 0 -> x.
4406       // This never returns poison, even if inbounds is set.
4407       if (NewOps.size() == 2 && match(NewOps[1], m_Zero()))
4408         return NewOps[0];
4409     }
4410   } else {
4411     // The simplification queries below may return the original value. Consider:
4412     //   %div = udiv i32 %arg, %arg2
4413     //   %mul = mul nsw i32 %div, %arg2
4414     //   %cmp = icmp eq i32 %mul, %arg
4415     //   %sel = select i1 %cmp, i32 %div, i32 undef
4416     // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which
4417     // simplifies back to %arg. This can only happen because %mul does not
4418     // dominate %div. To ensure a consistent return value contract, we make sure
4419     // that this case returns nullptr as well.
4420     auto PreventSelfSimplify = [V](Value *Simplified) {
4421       return Simplified != V ? Simplified : nullptr;
4422     };
4423 
4424     return PreventSelfSimplify(
4425         ::simplifyInstructionWithOperands(I, NewOps, Q, MaxRecurse));
4426   }
4427 
4428   // If all operands are constant after substituting Op for RepOp then we can
4429   // constant fold the instruction.
4430   SmallVector<Constant *, 8> ConstOps;
4431   for (Value *NewOp : NewOps) {
4432     if (Constant *ConstOp = dyn_cast<Constant>(NewOp))
4433       ConstOps.push_back(ConstOp);
4434     else
4435       return nullptr;
4436   }
4437 
4438   // Consider:
4439   //   %cmp = icmp eq i32 %x, 2147483647
4440   //   %add = add nsw i32 %x, 1
4441   //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
4442   //
4443   // We can't replace %sel with %add unless we strip away the flags (which
4444   // will be done in InstCombine).
4445   // TODO: This may be unsound, because it only catches some forms of
4446   // refinement.
4447   if (!AllowRefinement) {
4448     if (canCreatePoison(cast<Operator>(I), !DropFlags)) {
4449       // abs cannot create poison if the value is known to never be int_min.
4450       if (auto *II = dyn_cast<IntrinsicInst>(I);
4451           II && II->getIntrinsicID() == Intrinsic::abs) {
4452         if (!ConstOps[0]->isNotMinSignedValue())
4453           return nullptr;
4454       } else
4455         return nullptr;
4456     }
4457     Constant *Res = ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
4458     if (DropFlags && Res && I->hasPoisonGeneratingAnnotations())
4459       DropFlags->push_back(I);
4460     return Res;
4461   }
4462 
4463   return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
4464 }
4465 
4466 Value *llvm::simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4467                                     const SimplifyQuery &Q,
4468                                     bool AllowRefinement,
4469                                     SmallVectorImpl<Instruction *> *DropFlags) {
4470   return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement, DropFlags,
4471                                   RecursionLimit);
4472 }
4473 
4474 /// Try to simplify a select instruction when its condition operand is an
4475 /// integer comparison where one operand of the compare is a constant.
4476 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
4477                                     const APInt *Y, bool TrueWhenUnset) {
4478   const APInt *C;
4479 
4480   // (X & Y) == 0 ? X & ~Y : X  --> X
4481   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
4482   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
4483       *Y == ~*C)
4484     return TrueWhenUnset ? FalseVal : TrueVal;
4485 
4486   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
4487   // (X & Y) != 0 ? X : X & ~Y  --> X
4488   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
4489       *Y == ~*C)
4490     return TrueWhenUnset ? FalseVal : TrueVal;
4491 
4492   if (Y->isPowerOf2()) {
4493     // (X & Y) == 0 ? X | Y : X  --> X | Y
4494     // (X & Y) != 0 ? X | Y : X  --> X
4495     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
4496         *Y == *C) {
4497       // We can't return the or if it has the disjoint flag.
4498       if (TrueWhenUnset && cast<PossiblyDisjointInst>(TrueVal)->isDisjoint())
4499         return nullptr;
4500       return TrueWhenUnset ? TrueVal : FalseVal;
4501     }
4502 
4503     // (X & Y) == 0 ? X : X | Y  --> X
4504     // (X & Y) != 0 ? X : X | Y  --> X | Y
4505     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
4506         *Y == *C) {
4507       // We can't return the or if it has the disjoint flag.
4508       if (!TrueWhenUnset && cast<PossiblyDisjointInst>(FalseVal)->isDisjoint())
4509         return nullptr;
4510       return TrueWhenUnset ? TrueVal : FalseVal;
4511     }
4512   }
4513 
4514   return nullptr;
4515 }
4516 
4517 static Value *simplifyCmpSelOfMaxMin(Value *CmpLHS, Value *CmpRHS,
4518                                      ICmpInst::Predicate Pred, Value *TVal,
4519                                      Value *FVal) {
4520   // Canonicalize common cmp+sel operand as CmpLHS.
4521   if (CmpRHS == TVal || CmpRHS == FVal) {
4522     std::swap(CmpLHS, CmpRHS);
4523     Pred = ICmpInst::getSwappedPredicate(Pred);
4524   }
4525 
4526   // Canonicalize common cmp+sel operand as TVal.
4527   if (CmpLHS == FVal) {
4528     std::swap(TVal, FVal);
4529     Pred = ICmpInst::getInversePredicate(Pred);
4530   }
4531 
4532   // A vector select may be shuffling together elements that are equivalent
4533   // based on the max/min/select relationship.
4534   Value *X = CmpLHS, *Y = CmpRHS;
4535   bool PeekedThroughSelectShuffle = false;
4536   auto *Shuf = dyn_cast<ShuffleVectorInst>(FVal);
4537   if (Shuf && Shuf->isSelect()) {
4538     if (Shuf->getOperand(0) == Y)
4539       FVal = Shuf->getOperand(1);
4540     else if (Shuf->getOperand(1) == Y)
4541       FVal = Shuf->getOperand(0);
4542     else
4543       return nullptr;
4544     PeekedThroughSelectShuffle = true;
4545   }
4546 
4547   // (X pred Y) ? X : max/min(X, Y)
4548   auto *MMI = dyn_cast<MinMaxIntrinsic>(FVal);
4549   if (!MMI || TVal != X ||
4550       !match(FVal, m_c_MaxOrMin(m_Specific(X), m_Specific(Y))))
4551     return nullptr;
4552 
4553   // (X >  Y) ? X : max(X, Y) --> max(X, Y)
4554   // (X >= Y) ? X : max(X, Y) --> max(X, Y)
4555   // (X <  Y) ? X : min(X, Y) --> min(X, Y)
4556   // (X <= Y) ? X : min(X, Y) --> min(X, Y)
4557   //
4558   // The equivalence allows a vector select (shuffle) of max/min and Y. Ex:
4559   // (X > Y) ? X : (Z ? max(X, Y) : Y)
4560   // If Z is true, this reduces as above, and if Z is false:
4561   // (X > Y) ? X : Y --> max(X, Y)
4562   ICmpInst::Predicate MMPred = MMI->getPredicate();
4563   if (MMPred == CmpInst::getStrictPredicate(Pred))
4564     return MMI;
4565 
4566   // Other transforms are not valid with a shuffle.
4567   if (PeekedThroughSelectShuffle)
4568     return nullptr;
4569 
4570   // (X == Y) ? X : max/min(X, Y) --> max/min(X, Y)
4571   if (Pred == CmpInst::ICMP_EQ)
4572     return MMI;
4573 
4574   // (X != Y) ? X : max/min(X, Y) --> X
4575   if (Pred == CmpInst::ICMP_NE)
4576     return X;
4577 
4578   // (X <  Y) ? X : max(X, Y) --> X
4579   // (X <= Y) ? X : max(X, Y) --> X
4580   // (X >  Y) ? X : min(X, Y) --> X
4581   // (X >= Y) ? X : min(X, Y) --> X
4582   ICmpInst::Predicate InvPred = CmpInst::getInversePredicate(Pred);
4583   if (MMPred == CmpInst::getStrictPredicate(InvPred))
4584     return X;
4585 
4586   return nullptr;
4587 }
4588 
4589 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
4590 /// eq/ne.
4591 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
4592                                            ICmpInst::Predicate Pred,
4593                                            Value *TrueVal, Value *FalseVal) {
4594   Value *X;
4595   APInt Mask;
4596   if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
4597     return nullptr;
4598 
4599   return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
4600                                Pred == ICmpInst::ICMP_EQ);
4601 }
4602 
4603 /// Try to simplify a select instruction when its condition operand is an
4604 /// integer equality comparison.
4605 static Value *simplifySelectWithICmpEq(Value *CmpLHS, Value *CmpRHS,
4606                                        Value *TrueVal, Value *FalseVal,
4607                                        const SimplifyQuery &Q,
4608                                        unsigned MaxRecurse) {
4609   if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q,
4610                              /* AllowRefinement */ false,
4611                              /* DropFlags */ nullptr, MaxRecurse) == TrueVal)
4612     return FalseVal;
4613   if (simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q,
4614                              /* AllowRefinement */ true,
4615                              /* DropFlags */ nullptr, MaxRecurse) == FalseVal)
4616     return FalseVal;
4617 
4618   return nullptr;
4619 }
4620 
4621 /// Try to simplify a select instruction when its condition operand is an
4622 /// integer comparison.
4623 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
4624                                          Value *FalseVal,
4625                                          const SimplifyQuery &Q,
4626                                          unsigned MaxRecurse) {
4627   ICmpInst::Predicate Pred;
4628   Value *CmpLHS, *CmpRHS;
4629   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
4630     return nullptr;
4631 
4632   if (Value *V = simplifyCmpSelOfMaxMin(CmpLHS, CmpRHS, Pred, TrueVal, FalseVal))
4633     return V;
4634 
4635   // Canonicalize ne to eq predicate.
4636   if (Pred == ICmpInst::ICMP_NE) {
4637     Pred = ICmpInst::ICMP_EQ;
4638     std::swap(TrueVal, FalseVal);
4639   }
4640 
4641   // Check for integer min/max with a limit constant:
4642   // X > MIN_INT ? X : MIN_INT --> X
4643   // X < MAX_INT ? X : MAX_INT --> X
4644   if (TrueVal->getType()->isIntOrIntVectorTy()) {
4645     Value *X, *Y;
4646     SelectPatternFlavor SPF =
4647         matchDecomposedSelectPattern(cast<ICmpInst>(CondVal), TrueVal, FalseVal,
4648                                      X, Y)
4649             .Flavor;
4650     if (SelectPatternResult::isMinOrMax(SPF) && Pred == getMinMaxPred(SPF)) {
4651       APInt LimitC = getMinMaxLimit(getInverseMinMaxFlavor(SPF),
4652                                     X->getType()->getScalarSizeInBits());
4653       if (match(Y, m_SpecificInt(LimitC)))
4654         return X;
4655     }
4656   }
4657 
4658   if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) {
4659     Value *X;
4660     const APInt *Y;
4661     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
4662       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
4663                                            /*TrueWhenUnset=*/true))
4664         return V;
4665 
4666     // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
4667     Value *ShAmt;
4668     auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)),
4669                              m_FShr(m_Value(), m_Value(X), m_Value(ShAmt)));
4670     // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
4671     // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
4672     if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt)
4673       return X;
4674 
4675     // Test for a zero-shift-guard-op around rotates. These are used to
4676     // avoid UB from oversized shifts in raw IR rotate patterns, but the
4677     // intrinsics do not have that problem.
4678     // We do not allow this transform for the general funnel shift case because
4679     // that would not preserve the poison safety of the original code.
4680     auto isRotate =
4681         m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)),
4682                     m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt)));
4683     // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
4684     // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
4685     if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
4686         Pred == ICmpInst::ICMP_EQ)
4687       return FalseVal;
4688 
4689     // X == 0 ? abs(X) : -abs(X) --> -abs(X)
4690     // X == 0 ? -abs(X) : abs(X) --> abs(X)
4691     if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) &&
4692         match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))))
4693       return FalseVal;
4694     if (match(TrueVal,
4695               m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) &&
4696         match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))
4697       return FalseVal;
4698   }
4699 
4700   // Check for other compares that behave like bit test.
4701   if (Value *V =
4702           simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred, TrueVal, FalseVal))
4703     return V;
4704 
4705   // If we have a scalar equality comparison, then we know the value in one of
4706   // the arms of the select. See if substituting this value into the arm and
4707   // simplifying the result yields the same value as the other arm.
4708   if (Pred == ICmpInst::ICMP_EQ) {
4709     if (Value *V = simplifySelectWithICmpEq(CmpLHS, CmpRHS, TrueVal, FalseVal,
4710                                             Q, MaxRecurse))
4711       return V;
4712     if (Value *V = simplifySelectWithICmpEq(CmpRHS, CmpLHS, TrueVal, FalseVal,
4713                                             Q, MaxRecurse))
4714       return V;
4715 
4716     Value *X;
4717     Value *Y;
4718     // select((X | Y) == 0 ?  X : 0) --> 0 (commuted 2 ways)
4719     if (match(CmpLHS, m_Or(m_Value(X), m_Value(Y))) &&
4720         match(CmpRHS, m_Zero())) {
4721       // (X | Y) == 0 implies X == 0 and Y == 0.
4722       if (Value *V = simplifySelectWithICmpEq(X, CmpRHS, TrueVal, FalseVal, Q,
4723                                               MaxRecurse))
4724         return V;
4725       if (Value *V = simplifySelectWithICmpEq(Y, CmpRHS, TrueVal, FalseVal, Q,
4726                                               MaxRecurse))
4727         return V;
4728     }
4729 
4730     // select((X & Y) == -1 ?  X : -1) --> -1 (commuted 2 ways)
4731     if (match(CmpLHS, m_And(m_Value(X), m_Value(Y))) &&
4732         match(CmpRHS, m_AllOnes())) {
4733       // (X & Y) == -1 implies X == -1 and Y == -1.
4734       if (Value *V = simplifySelectWithICmpEq(X, CmpRHS, TrueVal, FalseVal, Q,
4735                                               MaxRecurse))
4736         return V;
4737       if (Value *V = simplifySelectWithICmpEq(Y, CmpRHS, TrueVal, FalseVal, Q,
4738                                               MaxRecurse))
4739         return V;
4740     }
4741   }
4742 
4743   return nullptr;
4744 }
4745 
4746 /// Try to simplify a select instruction when its condition operand is a
4747 /// floating-point comparison.
4748 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F,
4749                                      const SimplifyQuery &Q) {
4750   FCmpInst::Predicate Pred;
4751   if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
4752       !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
4753     return nullptr;
4754 
4755   // This transform is safe if we do not have (do not care about) -0.0 or if
4756   // at least one operand is known to not be -0.0. Otherwise, the select can
4757   // change the sign of a zero operand.
4758   bool HasNoSignedZeros =
4759       Q.CxtI && isa<FPMathOperator>(Q.CxtI) && Q.CxtI->hasNoSignedZeros();
4760   const APFloat *C;
4761   if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) ||
4762       (match(F, m_APFloat(C)) && C->isNonZero())) {
4763     // (T == F) ? T : F --> F
4764     // (F == T) ? T : F --> F
4765     if (Pred == FCmpInst::FCMP_OEQ)
4766       return F;
4767 
4768     // (T != F) ? T : F --> T
4769     // (F != T) ? T : F --> T
4770     if (Pred == FCmpInst::FCMP_UNE)
4771       return T;
4772   }
4773 
4774   return nullptr;
4775 }
4776 
4777 /// Given operands for a SelectInst, see if we can fold the result.
4778 /// If not, this returns null.
4779 static Value *simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4780                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
4781   if (auto *CondC = dyn_cast<Constant>(Cond)) {
4782     if (auto *TrueC = dyn_cast<Constant>(TrueVal))
4783       if (auto *FalseC = dyn_cast<Constant>(FalseVal))
4784         if (Constant *C = ConstantFoldSelectInstruction(CondC, TrueC, FalseC))
4785           return C;
4786 
4787     // select poison, X, Y -> poison
4788     if (isa<PoisonValue>(CondC))
4789       return PoisonValue::get(TrueVal->getType());
4790 
4791     // select undef, X, Y -> X or Y
4792     if (Q.isUndefValue(CondC))
4793       return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
4794 
4795     // select true,  X, Y --> X
4796     // select false, X, Y --> Y
4797     // For vectors, allow undef/poison elements in the condition to match the
4798     // defined elements, so we can eliminate the select.
4799     if (match(CondC, m_One()))
4800       return TrueVal;
4801     if (match(CondC, m_Zero()))
4802       return FalseVal;
4803   }
4804 
4805   assert(Cond->getType()->isIntOrIntVectorTy(1) &&
4806          "Select must have bool or bool vector condition");
4807   assert(TrueVal->getType() == FalseVal->getType() &&
4808          "Select must have same types for true/false ops");
4809 
4810   if (Cond->getType() == TrueVal->getType()) {
4811     // select i1 Cond, i1 true, i1 false --> i1 Cond
4812     if (match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt()))
4813       return Cond;
4814 
4815     // (X && Y) ? X : Y --> Y (commuted 2 ways)
4816     if (match(Cond, m_c_LogicalAnd(m_Specific(TrueVal), m_Specific(FalseVal))))
4817       return FalseVal;
4818 
4819     // (X || Y) ? X : Y --> X (commuted 2 ways)
4820     if (match(Cond, m_c_LogicalOr(m_Specific(TrueVal), m_Specific(FalseVal))))
4821       return TrueVal;
4822 
4823     // (X || Y) ? false : X --> false (commuted 2 ways)
4824     if (match(Cond, m_c_LogicalOr(m_Specific(FalseVal), m_Value())) &&
4825         match(TrueVal, m_ZeroInt()))
4826       return ConstantInt::getFalse(Cond->getType());
4827 
4828     // Match patterns that end in logical-and.
4829     if (match(FalseVal, m_ZeroInt())) {
4830       // !(X || Y) && X --> false (commuted 2 ways)
4831       if (match(Cond, m_Not(m_c_LogicalOr(m_Specific(TrueVal), m_Value()))))
4832         return ConstantInt::getFalse(Cond->getType());
4833       // X && !(X || Y) --> false (commuted 2 ways)
4834       if (match(TrueVal, m_Not(m_c_LogicalOr(m_Specific(Cond), m_Value()))))
4835         return ConstantInt::getFalse(Cond->getType());
4836 
4837       // (X || Y) && Y --> Y (commuted 2 ways)
4838       if (match(Cond, m_c_LogicalOr(m_Specific(TrueVal), m_Value())))
4839         return TrueVal;
4840       // Y && (X || Y) --> Y (commuted 2 ways)
4841       if (match(TrueVal, m_c_LogicalOr(m_Specific(Cond), m_Value())))
4842         return Cond;
4843 
4844       // (X || Y) && (X || !Y) --> X (commuted 8 ways)
4845       Value *X, *Y;
4846       if (match(Cond, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4847           match(TrueVal, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4848         return X;
4849       if (match(TrueVal, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4850           match(Cond, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4851         return X;
4852     }
4853 
4854     // Match patterns that end in logical-or.
4855     if (match(TrueVal, m_One())) {
4856       // !(X && Y) || X --> true (commuted 2 ways)
4857       if (match(Cond, m_Not(m_c_LogicalAnd(m_Specific(FalseVal), m_Value()))))
4858         return ConstantInt::getTrue(Cond->getType());
4859       // X || !(X && Y) --> true (commuted 2 ways)
4860       if (match(FalseVal, m_Not(m_c_LogicalAnd(m_Specific(Cond), m_Value()))))
4861         return ConstantInt::getTrue(Cond->getType());
4862 
4863       // (X && Y) || Y --> Y (commuted 2 ways)
4864       if (match(Cond, m_c_LogicalAnd(m_Specific(FalseVal), m_Value())))
4865         return FalseVal;
4866       // Y || (X && Y) --> Y (commuted 2 ways)
4867       if (match(FalseVal, m_c_LogicalAnd(m_Specific(Cond), m_Value())))
4868         return Cond;
4869     }
4870   }
4871 
4872   // select ?, X, X -> X
4873   if (TrueVal == FalseVal)
4874     return TrueVal;
4875 
4876   if (Cond == TrueVal) {
4877     // select i1 X, i1 X, i1 false --> X (logical-and)
4878     if (match(FalseVal, m_ZeroInt()))
4879       return Cond;
4880     // select i1 X, i1 X, i1 true --> true
4881     if (match(FalseVal, m_One()))
4882       return ConstantInt::getTrue(Cond->getType());
4883   }
4884   if (Cond == FalseVal) {
4885     // select i1 X, i1 true, i1 X --> X (logical-or)
4886     if (match(TrueVal, m_One()))
4887       return Cond;
4888     // select i1 X, i1 false, i1 X --> false
4889     if (match(TrueVal, m_ZeroInt()))
4890       return ConstantInt::getFalse(Cond->getType());
4891   }
4892 
4893   // If the true or false value is poison, we can fold to the other value.
4894   // If the true or false value is undef, we can fold to the other value as
4895   // long as the other value isn't poison.
4896   // select ?, poison, X -> X
4897   // select ?, undef,  X -> X
4898   if (isa<PoisonValue>(TrueVal) ||
4899       (Q.isUndefValue(TrueVal) && impliesPoison(FalseVal, Cond)))
4900     return FalseVal;
4901   // select ?, X, poison -> X
4902   // select ?, X, undef  -> X
4903   if (isa<PoisonValue>(FalseVal) ||
4904       (Q.isUndefValue(FalseVal) && impliesPoison(TrueVal, Cond)))
4905     return TrueVal;
4906 
4907   // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC''
4908   Constant *TrueC, *FalseC;
4909   if (isa<FixedVectorType>(TrueVal->getType()) &&
4910       match(TrueVal, m_Constant(TrueC)) &&
4911       match(FalseVal, m_Constant(FalseC))) {
4912     unsigned NumElts =
4913         cast<FixedVectorType>(TrueC->getType())->getNumElements();
4914     SmallVector<Constant *, 16> NewC;
4915     for (unsigned i = 0; i != NumElts; ++i) {
4916       // Bail out on incomplete vector constants.
4917       Constant *TEltC = TrueC->getAggregateElement(i);
4918       Constant *FEltC = FalseC->getAggregateElement(i);
4919       if (!TEltC || !FEltC)
4920         break;
4921 
4922       // If the elements match (undef or not), that value is the result. If only
4923       // one element is undef, choose the defined element as the safe result.
4924       if (TEltC == FEltC)
4925         NewC.push_back(TEltC);
4926       else if (isa<PoisonValue>(TEltC) ||
4927                (Q.isUndefValue(TEltC) && isGuaranteedNotToBePoison(FEltC)))
4928         NewC.push_back(FEltC);
4929       else if (isa<PoisonValue>(FEltC) ||
4930                (Q.isUndefValue(FEltC) && isGuaranteedNotToBePoison(TEltC)))
4931         NewC.push_back(TEltC);
4932       else
4933         break;
4934     }
4935     if (NewC.size() == NumElts)
4936       return ConstantVector::get(NewC);
4937   }
4938 
4939   if (Value *V =
4940           simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
4941     return V;
4942 
4943   if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q))
4944     return V;
4945 
4946   if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
4947     return V;
4948 
4949   std::optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
4950   if (Imp)
4951     return *Imp ? TrueVal : FalseVal;
4952 
4953   return nullptr;
4954 }
4955 
4956 Value *llvm::simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4957                                 const SimplifyQuery &Q) {
4958   return ::simplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
4959 }
4960 
4961 /// Given operands for an GetElementPtrInst, see if we can fold the result.
4962 /// If not, this returns null.
4963 static Value *simplifyGEPInst(Type *SrcTy, Value *Ptr,
4964                               ArrayRef<Value *> Indices, GEPNoWrapFlags NW,
4965                               const SimplifyQuery &Q, unsigned) {
4966   // The type of the GEP pointer operand.
4967   unsigned AS =
4968       cast<PointerType>(Ptr->getType()->getScalarType())->getAddressSpace();
4969 
4970   // getelementptr P -> P.
4971   if (Indices.empty())
4972     return Ptr;
4973 
4974   // Compute the (pointer) type returned by the GEP instruction.
4975   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Indices);
4976   Type *GEPTy = Ptr->getType();
4977   if (!GEPTy->isVectorTy()) {
4978     for (Value *Op : Indices) {
4979       // If one of the operands is a vector, the result type is a vector of
4980       // pointers. All vector operands must have the same number of elements.
4981       if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) {
4982         GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4983         break;
4984       }
4985     }
4986   }
4987 
4988   // All-zero GEP is a no-op, unless it performs a vector splat.
4989   if (Ptr->getType() == GEPTy &&
4990       all_of(Indices, [](const auto *V) { return match(V, m_Zero()); }))
4991     return Ptr;
4992 
4993   // getelementptr poison, idx -> poison
4994   // getelementptr baseptr, poison -> poison
4995   if (isa<PoisonValue>(Ptr) ||
4996       any_of(Indices, [](const auto *V) { return isa<PoisonValue>(V); }))
4997     return PoisonValue::get(GEPTy);
4998 
4999   // getelementptr undef, idx -> undef
5000   if (Q.isUndefValue(Ptr))
5001     return UndefValue::get(GEPTy);
5002 
5003   bool IsScalableVec =
5004       SrcTy->isScalableTy() || any_of(Indices, [](const Value *V) {
5005         return isa<ScalableVectorType>(V->getType());
5006       });
5007 
5008   if (Indices.size() == 1) {
5009     Type *Ty = SrcTy;
5010     if (!IsScalableVec && Ty->isSized()) {
5011       Value *P;
5012       uint64_t C;
5013       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
5014       // getelementptr P, N -> P if P points to a type of zero size.
5015       if (TyAllocSize == 0 && Ptr->getType() == GEPTy)
5016         return Ptr;
5017 
5018       // The following transforms are only safe if the ptrtoint cast
5019       // doesn't truncate the pointers.
5020       if (Indices[0]->getType()->getScalarSizeInBits() ==
5021           Q.DL.getPointerSizeInBits(AS)) {
5022         auto CanSimplify = [GEPTy, &P, Ptr]() -> bool {
5023           return P->getType() == GEPTy &&
5024                  getUnderlyingObject(P) == getUnderlyingObject(Ptr);
5025         };
5026         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
5027         if (TyAllocSize == 1 &&
5028             match(Indices[0],
5029                   m_Sub(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Specific(Ptr)))) &&
5030             CanSimplify())
5031           return P;
5032 
5033         // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of
5034         // size 1 << C.
5035         if (match(Indices[0], m_AShr(m_Sub(m_PtrToInt(m_Value(P)),
5036                                            m_PtrToInt(m_Specific(Ptr))),
5037                                      m_ConstantInt(C))) &&
5038             TyAllocSize == 1ULL << C && CanSimplify())
5039           return P;
5040 
5041         // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of
5042         // size C.
5043         if (match(Indices[0], m_SDiv(m_Sub(m_PtrToInt(m_Value(P)),
5044                                            m_PtrToInt(m_Specific(Ptr))),
5045                                      m_SpecificInt(TyAllocSize))) &&
5046             CanSimplify())
5047           return P;
5048       }
5049     }
5050   }
5051 
5052   if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 &&
5053       all_of(Indices.drop_back(1),
5054              [](Value *Idx) { return match(Idx, m_Zero()); })) {
5055     unsigned IdxWidth =
5056         Q.DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace());
5057     if (Q.DL.getTypeSizeInBits(Indices.back()->getType()) == IdxWidth) {
5058       APInt BasePtrOffset(IdxWidth, 0);
5059       Value *StrippedBasePtr =
5060           Ptr->stripAndAccumulateInBoundsConstantOffsets(Q.DL, BasePtrOffset);
5061 
5062       // Avoid creating inttoptr of zero here: While LLVMs treatment of
5063       // inttoptr is generally conservative, this particular case is folded to
5064       // a null pointer, which will have incorrect provenance.
5065 
5066       // gep (gep V, C), (sub 0, V) -> C
5067       if (match(Indices.back(),
5068                 m_Neg(m_PtrToInt(m_Specific(StrippedBasePtr)))) &&
5069           !BasePtrOffset.isZero()) {
5070         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
5071         return ConstantExpr::getIntToPtr(CI, GEPTy);
5072       }
5073       // gep (gep V, C), (xor V, -1) -> C-1
5074       if (match(Indices.back(),
5075                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) &&
5076           !BasePtrOffset.isOne()) {
5077         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
5078         return ConstantExpr::getIntToPtr(CI, GEPTy);
5079       }
5080     }
5081   }
5082 
5083   // Check to see if this is constant foldable.
5084   if (!isa<Constant>(Ptr) ||
5085       !all_of(Indices, [](Value *V) { return isa<Constant>(V); }))
5086     return nullptr;
5087 
5088   if (!ConstantExpr::isSupportedGetElementPtr(SrcTy))
5089     return ConstantFoldGetElementPtr(SrcTy, cast<Constant>(Ptr), std::nullopt,
5090                                      Indices);
5091 
5092   auto *CE =
5093       ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ptr), Indices, NW);
5094   return ConstantFoldConstant(CE, Q.DL);
5095 }
5096 
5097 Value *llvm::simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices,
5098                              GEPNoWrapFlags NW, const SimplifyQuery &Q) {
5099   return ::simplifyGEPInst(SrcTy, Ptr, Indices, NW, Q, RecursionLimit);
5100 }
5101 
5102 /// Given operands for an InsertValueInst, see if we can fold the result.
5103 /// If not, this returns null.
5104 static Value *simplifyInsertValueInst(Value *Agg, Value *Val,
5105                                       ArrayRef<unsigned> Idxs,
5106                                       const SimplifyQuery &Q, unsigned) {
5107   if (Constant *CAgg = dyn_cast<Constant>(Agg))
5108     if (Constant *CVal = dyn_cast<Constant>(Val))
5109       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
5110 
5111   // insertvalue x, poison, n -> x
5112   // insertvalue x, undef, n -> x if x cannot be poison
5113   if (isa<PoisonValue>(Val) ||
5114       (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Agg)))
5115     return Agg;
5116 
5117   // insertvalue x, (extractvalue y, n), n
5118   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
5119     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
5120         EV->getIndices() == Idxs) {
5121       // insertvalue poison, (extractvalue y, n), n -> y
5122       // insertvalue undef, (extractvalue y, n), n -> y if y cannot be poison
5123       if (isa<PoisonValue>(Agg) ||
5124           (Q.isUndefValue(Agg) &&
5125            isGuaranteedNotToBePoison(EV->getAggregateOperand())))
5126         return EV->getAggregateOperand();
5127 
5128       // insertvalue y, (extractvalue y, n), n -> y
5129       if (Agg == EV->getAggregateOperand())
5130         return Agg;
5131     }
5132 
5133   return nullptr;
5134 }
5135 
5136 Value *llvm::simplifyInsertValueInst(Value *Agg, Value *Val,
5137                                      ArrayRef<unsigned> Idxs,
5138                                      const SimplifyQuery &Q) {
5139   return ::simplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
5140 }
5141 
5142 Value *llvm::simplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
5143                                        const SimplifyQuery &Q) {
5144   // Try to constant fold.
5145   auto *VecC = dyn_cast<Constant>(Vec);
5146   auto *ValC = dyn_cast<Constant>(Val);
5147   auto *IdxC = dyn_cast<Constant>(Idx);
5148   if (VecC && ValC && IdxC)
5149     return ConstantExpr::getInsertElement(VecC, ValC, IdxC);
5150 
5151   // For fixed-length vector, fold into poison if index is out of bounds.
5152   if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
5153     if (isa<FixedVectorType>(Vec->getType()) &&
5154         CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements()))
5155       return PoisonValue::get(Vec->getType());
5156   }
5157 
5158   // If index is undef, it might be out of bounds (see above case)
5159   if (Q.isUndefValue(Idx))
5160     return PoisonValue::get(Vec->getType());
5161 
5162   // If the scalar is poison, or it is undef and there is no risk of
5163   // propagating poison from the vector value, simplify to the vector value.
5164   if (isa<PoisonValue>(Val) ||
5165       (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec)))
5166     return Vec;
5167 
5168   // If we are extracting a value from a vector, then inserting it into the same
5169   // place, that's the input vector:
5170   // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
5171   if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx))))
5172     return Vec;
5173 
5174   return nullptr;
5175 }
5176 
5177 /// Given operands for an ExtractValueInst, see if we can fold the result.
5178 /// If not, this returns null.
5179 static Value *simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
5180                                        const SimplifyQuery &, unsigned) {
5181   if (auto *CAgg = dyn_cast<Constant>(Agg))
5182     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
5183 
5184   // extractvalue x, (insertvalue y, elt, n), n -> elt
5185   unsigned NumIdxs = Idxs.size();
5186   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
5187        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
5188     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
5189     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
5190     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
5191     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
5192         Idxs.slice(0, NumCommonIdxs)) {
5193       if (NumIdxs == NumInsertValueIdxs)
5194         return IVI->getInsertedValueOperand();
5195       break;
5196     }
5197   }
5198 
5199   return nullptr;
5200 }
5201 
5202 Value *llvm::simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
5203                                       const SimplifyQuery &Q) {
5204   return ::simplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
5205 }
5206 
5207 /// Given operands for an ExtractElementInst, see if we can fold the result.
5208 /// If not, this returns null.
5209 static Value *simplifyExtractElementInst(Value *Vec, Value *Idx,
5210                                          const SimplifyQuery &Q, unsigned) {
5211   auto *VecVTy = cast<VectorType>(Vec->getType());
5212   if (auto *CVec = dyn_cast<Constant>(Vec)) {
5213     if (auto *CIdx = dyn_cast<Constant>(Idx))
5214       return ConstantExpr::getExtractElement(CVec, CIdx);
5215 
5216     if (Q.isUndefValue(Vec))
5217       return UndefValue::get(VecVTy->getElementType());
5218   }
5219 
5220   // An undef extract index can be arbitrarily chosen to be an out-of-range
5221   // index value, which would result in the instruction being poison.
5222   if (Q.isUndefValue(Idx))
5223     return PoisonValue::get(VecVTy->getElementType());
5224 
5225   // If extracting a specified index from the vector, see if we can recursively
5226   // find a previously computed scalar that was inserted into the vector.
5227   if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
5228     // For fixed-length vector, fold into undef if index is out of bounds.
5229     unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue();
5230     if (isa<FixedVectorType>(VecVTy) && IdxC->getValue().uge(MinNumElts))
5231       return PoisonValue::get(VecVTy->getElementType());
5232     // Handle case where an element is extracted from a splat.
5233     if (IdxC->getValue().ult(MinNumElts))
5234       if (auto *Splat = getSplatValue(Vec))
5235         return Splat;
5236     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
5237       return Elt;
5238   } else {
5239     // extractelt x, (insertelt y, elt, n), n -> elt
5240     // If the possibly-variable indices are trivially known to be equal
5241     // (because they are the same operand) then use the value that was
5242     // inserted directly.
5243     auto *IE = dyn_cast<InsertElementInst>(Vec);
5244     if (IE && IE->getOperand(2) == Idx)
5245       return IE->getOperand(1);
5246 
5247     // The index is not relevant if our vector is a splat.
5248     if (Value *Splat = getSplatValue(Vec))
5249       return Splat;
5250   }
5251   return nullptr;
5252 }
5253 
5254 Value *llvm::simplifyExtractElementInst(Value *Vec, Value *Idx,
5255                                         const SimplifyQuery &Q) {
5256   return ::simplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
5257 }
5258 
5259 /// See if we can fold the given phi. If not, returns null.
5260 static Value *simplifyPHINode(PHINode *PN, ArrayRef<Value *> IncomingValues,
5261                               const SimplifyQuery &Q) {
5262   // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE
5263   //          here, because the PHI we may succeed simplifying to was not
5264   //          def-reachable from the original PHI!
5265 
5266   // If all of the PHI's incoming values are the same then replace the PHI node
5267   // with the common value.
5268   Value *CommonValue = nullptr;
5269   bool HasPoisonInput = false;
5270   bool HasUndefInput = false;
5271   for (Value *Incoming : IncomingValues) {
5272     // If the incoming value is the phi node itself, it can safely be skipped.
5273     if (Incoming == PN)
5274       continue;
5275     if (isa<PoisonValue>(Incoming)) {
5276       HasPoisonInput = true;
5277       continue;
5278     }
5279     if (Q.isUndefValue(Incoming)) {
5280       // Remember that we saw an undef value, but otherwise ignore them.
5281       HasUndefInput = true;
5282       continue;
5283     }
5284     if (CommonValue && Incoming != CommonValue)
5285       return nullptr; // Not the same, bail out.
5286     CommonValue = Incoming;
5287   }
5288 
5289   // If CommonValue is null then all of the incoming values were either undef,
5290   // poison or equal to the phi node itself.
5291   if (!CommonValue)
5292     return HasUndefInput ? UndefValue::get(PN->getType())
5293                          : PoisonValue::get(PN->getType());
5294 
5295   if (HasPoisonInput || HasUndefInput) {
5296     // If we have a PHI node like phi(X, undef, X), where X is defined by some
5297     // instruction, we cannot return X as the result of the PHI node unless it
5298     // dominates the PHI block.
5299     return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
5300   }
5301 
5302   return CommonValue;
5303 }
5304 
5305 static Value *simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
5306                                const SimplifyQuery &Q, unsigned MaxRecurse) {
5307   if (auto *C = dyn_cast<Constant>(Op))
5308     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
5309 
5310   if (auto *CI = dyn_cast<CastInst>(Op)) {
5311     auto *Src = CI->getOperand(0);
5312     Type *SrcTy = Src->getType();
5313     Type *MidTy = CI->getType();
5314     Type *DstTy = Ty;
5315     if (Src->getType() == Ty) {
5316       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
5317       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
5318       Type *SrcIntPtrTy =
5319           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
5320       Type *MidIntPtrTy =
5321           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
5322       Type *DstIntPtrTy =
5323           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
5324       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
5325                                          SrcIntPtrTy, MidIntPtrTy,
5326                                          DstIntPtrTy) == Instruction::BitCast)
5327         return Src;
5328     }
5329   }
5330 
5331   // bitcast x -> x
5332   if (CastOpc == Instruction::BitCast)
5333     if (Op->getType() == Ty)
5334       return Op;
5335 
5336   return nullptr;
5337 }
5338 
5339 Value *llvm::simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
5340                               const SimplifyQuery &Q) {
5341   return ::simplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
5342 }
5343 
5344 /// For the given destination element of a shuffle, peek through shuffles to
5345 /// match a root vector source operand that contains that element in the same
5346 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
5347 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
5348                                    int MaskVal, Value *RootVec,
5349                                    unsigned MaxRecurse) {
5350   if (!MaxRecurse--)
5351     return nullptr;
5352 
5353   // Bail out if any mask value is undefined. That kind of shuffle may be
5354   // simplified further based on demanded bits or other folds.
5355   if (MaskVal == -1)
5356     return nullptr;
5357 
5358   // The mask value chooses which source operand we need to look at next.
5359   int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
5360   int RootElt = MaskVal;
5361   Value *SourceOp = Op0;
5362   if (MaskVal >= InVecNumElts) {
5363     RootElt = MaskVal - InVecNumElts;
5364     SourceOp = Op1;
5365   }
5366 
5367   // If the source operand is a shuffle itself, look through it to find the
5368   // matching root vector.
5369   if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
5370     return foldIdentityShuffles(
5371         DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
5372         SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
5373   }
5374 
5375   // The source operand is not a shuffle. Initialize the root vector value for
5376   // this shuffle if that has not been done yet.
5377   if (!RootVec)
5378     RootVec = SourceOp;
5379 
5380   // Give up as soon as a source operand does not match the existing root value.
5381   if (RootVec != SourceOp)
5382     return nullptr;
5383 
5384   // The element must be coming from the same lane in the source vector
5385   // (although it may have crossed lanes in intermediate shuffles).
5386   if (RootElt != DestElt)
5387     return nullptr;
5388 
5389   return RootVec;
5390 }
5391 
5392 static Value *simplifyShuffleVectorInst(Value *Op0, Value *Op1,
5393                                         ArrayRef<int> Mask, Type *RetTy,
5394                                         const SimplifyQuery &Q,
5395                                         unsigned MaxRecurse) {
5396   if (all_of(Mask, [](int Elem) { return Elem == PoisonMaskElem; }))
5397     return PoisonValue::get(RetTy);
5398 
5399   auto *InVecTy = cast<VectorType>(Op0->getType());
5400   unsigned MaskNumElts = Mask.size();
5401   ElementCount InVecEltCount = InVecTy->getElementCount();
5402 
5403   bool Scalable = InVecEltCount.isScalable();
5404 
5405   SmallVector<int, 32> Indices;
5406   Indices.assign(Mask.begin(), Mask.end());
5407 
5408   // Canonicalization: If mask does not select elements from an input vector,
5409   // replace that input vector with poison.
5410   if (!Scalable) {
5411     bool MaskSelects0 = false, MaskSelects1 = false;
5412     unsigned InVecNumElts = InVecEltCount.getKnownMinValue();
5413     for (unsigned i = 0; i != MaskNumElts; ++i) {
5414       if (Indices[i] == -1)
5415         continue;
5416       if ((unsigned)Indices[i] < InVecNumElts)
5417         MaskSelects0 = true;
5418       else
5419         MaskSelects1 = true;
5420     }
5421     if (!MaskSelects0)
5422       Op0 = PoisonValue::get(InVecTy);
5423     if (!MaskSelects1)
5424       Op1 = PoisonValue::get(InVecTy);
5425   }
5426 
5427   auto *Op0Const = dyn_cast<Constant>(Op0);
5428   auto *Op1Const = dyn_cast<Constant>(Op1);
5429 
5430   // If all operands are constant, constant fold the shuffle. This
5431   // transformation depends on the value of the mask which is not known at
5432   // compile time for scalable vectors
5433   if (Op0Const && Op1Const)
5434     return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask);
5435 
5436   // Canonicalization: if only one input vector is constant, it shall be the
5437   // second one. This transformation depends on the value of the mask which
5438   // is not known at compile time for scalable vectors
5439   if (!Scalable && Op0Const && !Op1Const) {
5440     std::swap(Op0, Op1);
5441     ShuffleVectorInst::commuteShuffleMask(Indices,
5442                                           InVecEltCount.getKnownMinValue());
5443   }
5444 
5445   // A splat of an inserted scalar constant becomes a vector constant:
5446   // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...>
5447   // NOTE: We may have commuted above, so analyze the updated Indices, not the
5448   //       original mask constant.
5449   // NOTE: This transformation depends on the value of the mask which is not
5450   // known at compile time for scalable vectors
5451   Constant *C;
5452   ConstantInt *IndexC;
5453   if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C),
5454                                           m_ConstantInt(IndexC)))) {
5455     // Match a splat shuffle mask of the insert index allowing undef elements.
5456     int InsertIndex = IndexC->getZExtValue();
5457     if (all_of(Indices, [InsertIndex](int MaskElt) {
5458           return MaskElt == InsertIndex || MaskElt == -1;
5459         })) {
5460       assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
5461 
5462       // Shuffle mask poisons become poison constant result elements.
5463       SmallVector<Constant *, 16> VecC(MaskNumElts, C);
5464       for (unsigned i = 0; i != MaskNumElts; ++i)
5465         if (Indices[i] == -1)
5466           VecC[i] = PoisonValue::get(C->getType());
5467       return ConstantVector::get(VecC);
5468     }
5469   }
5470 
5471   // A shuffle of a splat is always the splat itself. Legal if the shuffle's
5472   // value type is same as the input vectors' type.
5473   if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
5474     if (Q.isUndefValue(Op1) && RetTy == InVecTy &&
5475         all_equal(OpShuf->getShuffleMask()))
5476       return Op0;
5477 
5478   // All remaining transformation depend on the value of the mask, which is
5479   // not known at compile time for scalable vectors.
5480   if (Scalable)
5481     return nullptr;
5482 
5483   // Don't fold a shuffle with undef mask elements. This may get folded in a
5484   // better way using demanded bits or other analysis.
5485   // TODO: Should we allow this?
5486   if (is_contained(Indices, -1))
5487     return nullptr;
5488 
5489   // Check if every element of this shuffle can be mapped back to the
5490   // corresponding element of a single root vector. If so, we don't need this
5491   // shuffle. This handles simple identity shuffles as well as chains of
5492   // shuffles that may widen/narrow and/or move elements across lanes and back.
5493   Value *RootVec = nullptr;
5494   for (unsigned i = 0; i != MaskNumElts; ++i) {
5495     // Note that recursion is limited for each vector element, so if any element
5496     // exceeds the limit, this will fail to simplify.
5497     RootVec =
5498         foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
5499 
5500     // We can't replace a widening/narrowing shuffle with one of its operands.
5501     if (!RootVec || RootVec->getType() != RetTy)
5502       return nullptr;
5503   }
5504   return RootVec;
5505 }
5506 
5507 /// Given operands for a ShuffleVectorInst, fold the result or return null.
5508 Value *llvm::simplifyShuffleVectorInst(Value *Op0, Value *Op1,
5509                                        ArrayRef<int> Mask, Type *RetTy,
5510                                        const SimplifyQuery &Q) {
5511   return ::simplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
5512 }
5513 
5514 static Constant *foldConstant(Instruction::UnaryOps Opcode, Value *&Op,
5515                               const SimplifyQuery &Q) {
5516   if (auto *C = dyn_cast<Constant>(Op))
5517     return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
5518   return nullptr;
5519 }
5520 
5521 /// Given the operand for an FNeg, see if we can fold the result.  If not, this
5522 /// returns null.
5523 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
5524                                const SimplifyQuery &Q, unsigned MaxRecurse) {
5525   if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
5526     return C;
5527 
5528   Value *X;
5529   // fneg (fneg X) ==> X
5530   if (match(Op, m_FNeg(m_Value(X))))
5531     return X;
5532 
5533   return nullptr;
5534 }
5535 
5536 Value *llvm::simplifyFNegInst(Value *Op, FastMathFlags FMF,
5537                               const SimplifyQuery &Q) {
5538   return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
5539 }
5540 
5541 /// Try to propagate existing NaN values when possible. If not, replace the
5542 /// constant or elements in the constant with a canonical NaN.
5543 static Constant *propagateNaN(Constant *In) {
5544   Type *Ty = In->getType();
5545   if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
5546     unsigned NumElts = VecTy->getNumElements();
5547     SmallVector<Constant *, 32> NewC(NumElts);
5548     for (unsigned i = 0; i != NumElts; ++i) {
5549       Constant *EltC = In->getAggregateElement(i);
5550       // Poison elements propagate. NaN propagates except signaling is quieted.
5551       // Replace unknown or undef elements with canonical NaN.
5552       if (EltC && isa<PoisonValue>(EltC))
5553         NewC[i] = EltC;
5554       else if (EltC && EltC->isNaN())
5555         NewC[i] = ConstantFP::get(
5556             EltC->getType(), cast<ConstantFP>(EltC)->getValue().makeQuiet());
5557       else
5558         NewC[i] = ConstantFP::getNaN(VecTy->getElementType());
5559     }
5560     return ConstantVector::get(NewC);
5561   }
5562 
5563   // If it is not a fixed vector, but not a simple NaN either, return a
5564   // canonical NaN.
5565   if (!In->isNaN())
5566     return ConstantFP::getNaN(Ty);
5567 
5568   // If we known this is a NaN, and it's scalable vector, we must have a splat
5569   // on our hands. Grab that before splatting a QNaN constant.
5570   if (isa<ScalableVectorType>(Ty)) {
5571     auto *Splat = In->getSplatValue();
5572     assert(Splat && Splat->isNaN() &&
5573            "Found a scalable-vector NaN but not a splat");
5574     In = Splat;
5575   }
5576 
5577   // Propagate an existing QNaN constant. If it is an SNaN, make it quiet, but
5578   // preserve the sign/payload.
5579   return ConstantFP::get(Ty, cast<ConstantFP>(In)->getValue().makeQuiet());
5580 }
5581 
5582 /// Perform folds that are common to any floating-point operation. This implies
5583 /// transforms based on poison/undef/NaN because the operation itself makes no
5584 /// difference to the result.
5585 static Constant *simplifyFPOp(ArrayRef<Value *> Ops, FastMathFlags FMF,
5586                               const SimplifyQuery &Q,
5587                               fp::ExceptionBehavior ExBehavior,
5588                               RoundingMode Rounding) {
5589   // Poison is independent of anything else. It always propagates from an
5590   // operand to a math result.
5591   if (any_of(Ops, [](Value *V) { return match(V, m_Poison()); }))
5592     return PoisonValue::get(Ops[0]->getType());
5593 
5594   for (Value *V : Ops) {
5595     bool IsNan = match(V, m_NaN());
5596     bool IsInf = match(V, m_Inf());
5597     bool IsUndef = Q.isUndefValue(V);
5598 
5599     // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
5600     // (an undef operand can be chosen to be Nan/Inf), then the result of
5601     // this operation is poison.
5602     if (FMF.noNaNs() && (IsNan || IsUndef))
5603       return PoisonValue::get(V->getType());
5604     if (FMF.noInfs() && (IsInf || IsUndef))
5605       return PoisonValue::get(V->getType());
5606 
5607     if (isDefaultFPEnvironment(ExBehavior, Rounding)) {
5608       // Undef does not propagate because undef means that all bits can take on
5609       // any value. If this is undef * NaN for example, then the result values
5610       // (at least the exponent bits) are limited. Assume the undef is a
5611       // canonical NaN and propagate that.
5612       if (IsUndef)
5613         return ConstantFP::getNaN(V->getType());
5614       if (IsNan)
5615         return propagateNaN(cast<Constant>(V));
5616     } else if (ExBehavior != fp::ebStrict) {
5617       if (IsNan)
5618         return propagateNaN(cast<Constant>(V));
5619     }
5620   }
5621   return nullptr;
5622 }
5623 
5624 /// Given operands for an FAdd, see if we can fold the result.  If not, this
5625 /// returns null.
5626 static Value *
5627 simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5628                  const SimplifyQuery &Q, unsigned MaxRecurse,
5629                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5630                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5631   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5632     if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
5633       return C;
5634 
5635   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5636     return C;
5637 
5638   // fadd X, -0 ==> X
5639   // With strict/constrained FP, we have these possible edge cases that do
5640   // not simplify to Op0:
5641   // fadd SNaN, -0.0 --> QNaN
5642   // fadd +0.0, -0.0 --> -0.0 (but only with round toward negative)
5643   if (canIgnoreSNaN(ExBehavior, FMF) &&
5644       (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5645        FMF.noSignedZeros()))
5646     if (match(Op1, m_NegZeroFP()))
5647       return Op0;
5648 
5649   // fadd X, 0 ==> X, when we know X is not -0
5650   if (canIgnoreSNaN(ExBehavior, FMF))
5651     if (match(Op1, m_PosZeroFP()) &&
5652         (FMF.noSignedZeros() || cannotBeNegativeZero(Op0, /*Depth=*/0, Q)))
5653       return Op0;
5654 
5655   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5656     return nullptr;
5657 
5658   if (FMF.noNaNs()) {
5659     // With nnan: X + {+/-}Inf --> {+/-}Inf
5660     if (match(Op1, m_Inf()))
5661       return Op1;
5662 
5663     // With nnan: -X + X --> 0.0 (and commuted variant)
5664     // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
5665     // Negative zeros are allowed because we always end up with positive zero:
5666     // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5667     // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5668     // X =  0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
5669     // X =  0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
5670     if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
5671         match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
5672       return ConstantFP::getZero(Op0->getType());
5673 
5674     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
5675         match(Op1, m_FNeg(m_Specific(Op0))))
5676       return ConstantFP::getZero(Op0->getType());
5677   }
5678 
5679   // (X - Y) + Y --> X
5680   // Y + (X - Y) --> X
5681   Value *X;
5682   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
5683       (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
5684        match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
5685     return X;
5686 
5687   return nullptr;
5688 }
5689 
5690 /// Given operands for an FSub, see if we can fold the result.  If not, this
5691 /// returns null.
5692 static Value *
5693 simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5694                  const SimplifyQuery &Q, unsigned MaxRecurse,
5695                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5696                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5697   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5698     if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
5699       return C;
5700 
5701   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5702     return C;
5703 
5704   // fsub X, +0 ==> X
5705   if (canIgnoreSNaN(ExBehavior, FMF) &&
5706       (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5707        FMF.noSignedZeros()))
5708     if (match(Op1, m_PosZeroFP()))
5709       return Op0;
5710 
5711   // fsub X, -0 ==> X, when we know X is not -0
5712   if (canIgnoreSNaN(ExBehavior, FMF))
5713     if (match(Op1, m_NegZeroFP()) &&
5714         (FMF.noSignedZeros() || cannotBeNegativeZero(Op0, /*Depth=*/0, Q)))
5715       return Op0;
5716 
5717   // fsub -0.0, (fsub -0.0, X) ==> X
5718   // fsub -0.0, (fneg X) ==> X
5719   Value *X;
5720   if (canIgnoreSNaN(ExBehavior, FMF))
5721     if (match(Op0, m_NegZeroFP()) && match(Op1, m_FNeg(m_Value(X))))
5722       return X;
5723 
5724   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
5725   // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
5726   if (canIgnoreSNaN(ExBehavior, FMF))
5727     if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
5728         (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
5729          match(Op1, m_FNeg(m_Value(X)))))
5730       return X;
5731 
5732   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5733     return nullptr;
5734 
5735   if (FMF.noNaNs()) {
5736     // fsub nnan x, x ==> 0.0
5737     if (Op0 == Op1)
5738       return Constant::getNullValue(Op0->getType());
5739 
5740     // With nnan: {+/-}Inf - X --> {+/-}Inf
5741     if (match(Op0, m_Inf()))
5742       return Op0;
5743 
5744     // With nnan: X - {+/-}Inf --> {-/+}Inf
5745     if (match(Op1, m_Inf()))
5746       return foldConstant(Instruction::FNeg, Op1, Q);
5747   }
5748 
5749   // Y - (Y - X) --> X
5750   // (X + Y) - Y --> X
5751   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
5752       (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
5753        match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
5754     return X;
5755 
5756   return nullptr;
5757 }
5758 
5759 static Value *simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5760                               const SimplifyQuery &Q, unsigned MaxRecurse,
5761                               fp::ExceptionBehavior ExBehavior,
5762                               RoundingMode Rounding) {
5763   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5764     return C;
5765 
5766   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5767     return nullptr;
5768 
5769   // Canonicalize special constants as operand 1.
5770   if (match(Op0, m_FPOne()) || match(Op0, m_AnyZeroFP()))
5771     std::swap(Op0, Op1);
5772 
5773   // X * 1.0 --> X
5774   if (match(Op1, m_FPOne()))
5775     return Op0;
5776 
5777   if (match(Op1, m_AnyZeroFP())) {
5778     // X * 0.0 --> 0.0 (with nnan and nsz)
5779     if (FMF.noNaNs() && FMF.noSignedZeros())
5780       return ConstantFP::getZero(Op0->getType());
5781 
5782     KnownFPClass Known =
5783         computeKnownFPClass(Op0, FMF, fcInf | fcNan, /*Depth=*/0, Q);
5784     if (Known.isKnownNever(fcInf | fcNan)) {
5785       // +normal number * (-)0.0 --> (-)0.0
5786       if (Known.SignBit == false)
5787         return Op1;
5788       // -normal number * (-)0.0 --> -(-)0.0
5789       if (Known.SignBit == true)
5790         return foldConstant(Instruction::FNeg, Op1, Q);
5791     }
5792   }
5793 
5794   // sqrt(X) * sqrt(X) --> X, if we can:
5795   // 1. Remove the intermediate rounding (reassociate).
5796   // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
5797   // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
5798   Value *X;
5799   if (Op0 == Op1 && match(Op0, m_Sqrt(m_Value(X))) && FMF.allowReassoc() &&
5800       FMF.noNaNs() && FMF.noSignedZeros())
5801     return X;
5802 
5803   return nullptr;
5804 }
5805 
5806 /// Given the operands for an FMul, see if we can fold the result
5807 static Value *
5808 simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5809                  const SimplifyQuery &Q, unsigned MaxRecurse,
5810                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5811                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5812   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5813     if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
5814       return C;
5815 
5816   // Now apply simplifications that do not require rounding.
5817   return simplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding);
5818 }
5819 
5820 Value *llvm::simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5821                               const SimplifyQuery &Q,
5822                               fp::ExceptionBehavior ExBehavior,
5823                               RoundingMode Rounding) {
5824   return ::simplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5825                             Rounding);
5826 }
5827 
5828 Value *llvm::simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5829                               const SimplifyQuery &Q,
5830                               fp::ExceptionBehavior ExBehavior,
5831                               RoundingMode Rounding) {
5832   return ::simplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5833                             Rounding);
5834 }
5835 
5836 Value *llvm::simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5837                               const SimplifyQuery &Q,
5838                               fp::ExceptionBehavior ExBehavior,
5839                               RoundingMode Rounding) {
5840   return ::simplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5841                             Rounding);
5842 }
5843 
5844 Value *llvm::simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5845                              const SimplifyQuery &Q,
5846                              fp::ExceptionBehavior ExBehavior,
5847                              RoundingMode Rounding) {
5848   return ::simplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5849                            Rounding);
5850 }
5851 
5852 static Value *
5853 simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5854                  const SimplifyQuery &Q, unsigned,
5855                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5856                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5857   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5858     if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
5859       return C;
5860 
5861   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5862     return C;
5863 
5864   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5865     return nullptr;
5866 
5867   // X / 1.0 -> X
5868   if (match(Op1, m_FPOne()))
5869     return Op0;
5870 
5871   // 0 / X -> 0
5872   // Requires that NaNs are off (X could be zero) and signed zeroes are
5873   // ignored (X could be positive or negative, so the output sign is unknown).
5874   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5875     return ConstantFP::getZero(Op0->getType());
5876 
5877   if (FMF.noNaNs()) {
5878     // X / X -> 1.0 is legal when NaNs are ignored.
5879     // We can ignore infinities because INF/INF is NaN.
5880     if (Op0 == Op1)
5881       return ConstantFP::get(Op0->getType(), 1.0);
5882 
5883     // (X * Y) / Y --> X if we can reassociate to the above form.
5884     Value *X;
5885     if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
5886       return X;
5887 
5888     // -X /  X -> -1.0 and
5889     //  X / -X -> -1.0 are legal when NaNs are ignored.
5890     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
5891     if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
5892         match(Op1, m_FNegNSZ(m_Specific(Op0))))
5893       return ConstantFP::get(Op0->getType(), -1.0);
5894 
5895     // nnan ninf X / [-]0.0 -> poison
5896     if (FMF.noInfs() && match(Op1, m_AnyZeroFP()))
5897       return PoisonValue::get(Op1->getType());
5898   }
5899 
5900   return nullptr;
5901 }
5902 
5903 Value *llvm::simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5904                               const SimplifyQuery &Q,
5905                               fp::ExceptionBehavior ExBehavior,
5906                               RoundingMode Rounding) {
5907   return ::simplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5908                             Rounding);
5909 }
5910 
5911 static Value *
5912 simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5913                  const SimplifyQuery &Q, unsigned,
5914                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5915                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5916   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5917     if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
5918       return C;
5919 
5920   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5921     return C;
5922 
5923   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5924     return nullptr;
5925 
5926   // Unlike fdiv, the result of frem always matches the sign of the dividend.
5927   // The constant match may include undef elements in a vector, so return a full
5928   // zero constant as the result.
5929   if (FMF.noNaNs()) {
5930     // +0 % X -> 0
5931     if (match(Op0, m_PosZeroFP()))
5932       return ConstantFP::getZero(Op0->getType());
5933     // -0 % X -> -0
5934     if (match(Op0, m_NegZeroFP()))
5935       return ConstantFP::getNegativeZero(Op0->getType());
5936   }
5937 
5938   return nullptr;
5939 }
5940 
5941 Value *llvm::simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5942                               const SimplifyQuery &Q,
5943                               fp::ExceptionBehavior ExBehavior,
5944                               RoundingMode Rounding) {
5945   return ::simplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5946                             Rounding);
5947 }
5948 
5949 //=== Helper functions for higher up the class hierarchy.
5950 
5951 /// Given the operand for a UnaryOperator, see if we can fold the result.
5952 /// If not, this returns null.
5953 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
5954                            unsigned MaxRecurse) {
5955   switch (Opcode) {
5956   case Instruction::FNeg:
5957     return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
5958   default:
5959     llvm_unreachable("Unexpected opcode");
5960   }
5961 }
5962 
5963 /// Given the operand for a UnaryOperator, see if we can fold the result.
5964 /// If not, this returns null.
5965 /// Try to use FastMathFlags when folding the result.
5966 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
5967                              const FastMathFlags &FMF, const SimplifyQuery &Q,
5968                              unsigned MaxRecurse) {
5969   switch (Opcode) {
5970   case Instruction::FNeg:
5971     return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
5972   default:
5973     return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
5974   }
5975 }
5976 
5977 Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
5978   return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
5979 }
5980 
5981 Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
5982                           const SimplifyQuery &Q) {
5983   return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
5984 }
5985 
5986 /// Given operands for a BinaryOperator, see if we can fold the result.
5987 /// If not, this returns null.
5988 static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5989                             const SimplifyQuery &Q, unsigned MaxRecurse) {
5990   switch (Opcode) {
5991   case Instruction::Add:
5992     return simplifyAddInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
5993                            MaxRecurse);
5994   case Instruction::Sub:
5995     return simplifySubInst(LHS, RHS,  /* IsNSW */ false, /* IsNUW */ false, Q,
5996                            MaxRecurse);
5997   case Instruction::Mul:
5998     return simplifyMulInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
5999                            MaxRecurse);
6000   case Instruction::SDiv:
6001     return simplifySDivInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
6002   case Instruction::UDiv:
6003     return simplifyUDivInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
6004   case Instruction::SRem:
6005     return simplifySRemInst(LHS, RHS, Q, MaxRecurse);
6006   case Instruction::URem:
6007     return simplifyURemInst(LHS, RHS, Q, MaxRecurse);
6008   case Instruction::Shl:
6009     return simplifyShlInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
6010                            MaxRecurse);
6011   case Instruction::LShr:
6012     return simplifyLShrInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
6013   case Instruction::AShr:
6014     return simplifyAShrInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
6015   case Instruction::And:
6016     return simplifyAndInst(LHS, RHS, Q, MaxRecurse);
6017   case Instruction::Or:
6018     return simplifyOrInst(LHS, RHS, Q, MaxRecurse);
6019   case Instruction::Xor:
6020     return simplifyXorInst(LHS, RHS, Q, MaxRecurse);
6021   case Instruction::FAdd:
6022     return simplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6023   case Instruction::FSub:
6024     return simplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6025   case Instruction::FMul:
6026     return simplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6027   case Instruction::FDiv:
6028     return simplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6029   case Instruction::FRem:
6030     return simplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6031   default:
6032     llvm_unreachable("Unexpected opcode");
6033   }
6034 }
6035 
6036 /// Given operands for a BinaryOperator, see if we can fold the result.
6037 /// If not, this returns null.
6038 /// Try to use FastMathFlags when folding the result.
6039 static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6040                             const FastMathFlags &FMF, const SimplifyQuery &Q,
6041                             unsigned MaxRecurse) {
6042   switch (Opcode) {
6043   case Instruction::FAdd:
6044     return simplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
6045   case Instruction::FSub:
6046     return simplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
6047   case Instruction::FMul:
6048     return simplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
6049   case Instruction::FDiv:
6050     return simplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
6051   default:
6052     return simplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
6053   }
6054 }
6055 
6056 Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6057                            const SimplifyQuery &Q) {
6058   return ::simplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
6059 }
6060 
6061 Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6062                            FastMathFlags FMF, const SimplifyQuery &Q) {
6063   return ::simplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
6064 }
6065 
6066 /// Given operands for a CmpInst, see if we can fold the result.
6067 static Value *simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
6068                               const SimplifyQuery &Q, unsigned MaxRecurse) {
6069   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
6070     return simplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
6071   return simplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6072 }
6073 
6074 Value *llvm::simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
6075                              const SimplifyQuery &Q) {
6076   return ::simplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
6077 }
6078 
6079 static bool isIdempotent(Intrinsic::ID ID) {
6080   switch (ID) {
6081   default:
6082     return false;
6083 
6084   // Unary idempotent: f(f(x)) = f(x)
6085   case Intrinsic::fabs:
6086   case Intrinsic::floor:
6087   case Intrinsic::ceil:
6088   case Intrinsic::trunc:
6089   case Intrinsic::rint:
6090   case Intrinsic::nearbyint:
6091   case Intrinsic::round:
6092   case Intrinsic::roundeven:
6093   case Intrinsic::canonicalize:
6094   case Intrinsic::arithmetic_fence:
6095     return true;
6096   }
6097 }
6098 
6099 /// Return true if the intrinsic rounds a floating-point value to an integral
6100 /// floating-point value (not an integer type).
6101 static bool removesFPFraction(Intrinsic::ID ID) {
6102   switch (ID) {
6103   default:
6104     return false;
6105 
6106   case Intrinsic::floor:
6107   case Intrinsic::ceil:
6108   case Intrinsic::trunc:
6109   case Intrinsic::rint:
6110   case Intrinsic::nearbyint:
6111   case Intrinsic::round:
6112   case Intrinsic::roundeven:
6113     return true;
6114   }
6115 }
6116 
6117 static Value *simplifyRelativeLoad(Constant *Ptr, Constant *Offset,
6118                                    const DataLayout &DL) {
6119   GlobalValue *PtrSym;
6120   APInt PtrOffset;
6121   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
6122     return nullptr;
6123 
6124   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
6125 
6126   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
6127   if (!OffsetConstInt || OffsetConstInt->getBitWidth() > 64)
6128     return nullptr;
6129 
6130   APInt OffsetInt = OffsetConstInt->getValue().sextOrTrunc(
6131       DL.getIndexTypeSizeInBits(Ptr->getType()));
6132   if (OffsetInt.srem(4) != 0)
6133     return nullptr;
6134 
6135   Constant *Loaded =
6136       ConstantFoldLoadFromConstPtr(Ptr, Int32Ty, std::move(OffsetInt), DL);
6137   if (!Loaded)
6138     return nullptr;
6139 
6140   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
6141   if (!LoadedCE)
6142     return nullptr;
6143 
6144   if (LoadedCE->getOpcode() == Instruction::Trunc) {
6145     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
6146     if (!LoadedCE)
6147       return nullptr;
6148   }
6149 
6150   if (LoadedCE->getOpcode() != Instruction::Sub)
6151     return nullptr;
6152 
6153   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
6154   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
6155     return nullptr;
6156   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
6157 
6158   Constant *LoadedRHS = LoadedCE->getOperand(1);
6159   GlobalValue *LoadedRHSSym;
6160   APInt LoadedRHSOffset;
6161   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
6162                                   DL) ||
6163       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
6164     return nullptr;
6165 
6166   return LoadedLHSPtr;
6167 }
6168 
6169 // TODO: Need to pass in FastMathFlags
6170 static Value *simplifyLdexp(Value *Op0, Value *Op1, const SimplifyQuery &Q,
6171                             bool IsStrict) {
6172   // ldexp(poison, x) -> poison
6173   // ldexp(x, poison) -> poison
6174   if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1))
6175     return Op0;
6176 
6177   // ldexp(undef, x) -> nan
6178   if (Q.isUndefValue(Op0))
6179     return ConstantFP::getNaN(Op0->getType());
6180 
6181   if (!IsStrict) {
6182     // TODO: Could insert a canonicalize for strict
6183 
6184     // ldexp(x, undef) -> x
6185     if (Q.isUndefValue(Op1))
6186       return Op0;
6187   }
6188 
6189   const APFloat *C = nullptr;
6190   match(Op0, PatternMatch::m_APFloat(C));
6191 
6192   // These cases should be safe, even with strictfp.
6193   // ldexp(0.0, x) -> 0.0
6194   // ldexp(-0.0, x) -> -0.0
6195   // ldexp(inf, x) -> inf
6196   // ldexp(-inf, x) -> -inf
6197   if (C && (C->isZero() || C->isInfinity()))
6198     return Op0;
6199 
6200   // These are canonicalization dropping, could do it if we knew how we could
6201   // ignore denormal flushes and target handling of nan payload bits.
6202   if (IsStrict)
6203     return nullptr;
6204 
6205   // TODO: Could quiet this with strictfp if the exception mode isn't strict.
6206   if (C && C->isNaN())
6207     return ConstantFP::get(Op0->getType(), C->makeQuiet());
6208 
6209   // ldexp(x, 0) -> x
6210 
6211   // TODO: Could fold this if we know the exception mode isn't
6212   // strict, we know the denormal mode and other target modes.
6213   if (match(Op1, PatternMatch::m_ZeroInt()))
6214     return Op0;
6215 
6216   return nullptr;
6217 }
6218 
6219 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
6220                                      const SimplifyQuery &Q,
6221                                      const CallBase *Call) {
6222   // Idempotent functions return the same result when called repeatedly.
6223   Intrinsic::ID IID = F->getIntrinsicID();
6224   if (isIdempotent(IID))
6225     if (auto *II = dyn_cast<IntrinsicInst>(Op0))
6226       if (II->getIntrinsicID() == IID)
6227         return II;
6228 
6229   if (removesFPFraction(IID)) {
6230     // Converting from int or calling a rounding function always results in a
6231     // finite integral number or infinity. For those inputs, rounding functions
6232     // always return the same value, so the (2nd) rounding is eliminated. Ex:
6233     // floor (sitofp x) -> sitofp x
6234     // round (ceil x) -> ceil x
6235     auto *II = dyn_cast<IntrinsicInst>(Op0);
6236     if ((II && removesFPFraction(II->getIntrinsicID())) ||
6237         match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
6238       return Op0;
6239   }
6240 
6241   Value *X;
6242   switch (IID) {
6243   case Intrinsic::fabs:
6244     if (computeKnownFPSignBit(Op0, /*Depth=*/0, Q) == false)
6245       return Op0;
6246     break;
6247   case Intrinsic::bswap:
6248     // bswap(bswap(x)) -> x
6249     if (match(Op0, m_BSwap(m_Value(X))))
6250       return X;
6251     break;
6252   case Intrinsic::bitreverse:
6253     // bitreverse(bitreverse(x)) -> x
6254     if (match(Op0, m_BitReverse(m_Value(X))))
6255       return X;
6256     break;
6257   case Intrinsic::ctpop: {
6258     // ctpop(X) -> 1 iff X is non-zero power of 2.
6259     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ false, 0, Q.AC, Q.CxtI,
6260                                Q.DT))
6261       return ConstantInt::get(Op0->getType(), 1);
6262     // If everything but the lowest bit is zero, that bit is the pop-count. Ex:
6263     // ctpop(and X, 1) --> and X, 1
6264     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6265     if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1),
6266                           Q))
6267       return Op0;
6268     break;
6269   }
6270   case Intrinsic::exp:
6271     // exp(log(x)) -> x
6272     if (Call->hasAllowReassoc() &&
6273         match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X))))
6274       return X;
6275     break;
6276   case Intrinsic::exp2:
6277     // exp2(log2(x)) -> x
6278     if (Call->hasAllowReassoc() &&
6279         match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X))))
6280       return X;
6281     break;
6282   case Intrinsic::exp10:
6283     // exp10(log10(x)) -> x
6284     if (Call->hasAllowReassoc() &&
6285         match(Op0, m_Intrinsic<Intrinsic::log10>(m_Value(X))))
6286       return X;
6287     break;
6288   case Intrinsic::log:
6289     // log(exp(x)) -> x
6290     if (Call->hasAllowReassoc() &&
6291         match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))))
6292       return X;
6293     break;
6294   case Intrinsic::log2:
6295     // log2(exp2(x)) -> x
6296     if (Call->hasAllowReassoc() &&
6297         (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
6298          match(Op0,
6299                m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0), m_Value(X)))))
6300       return X;
6301     break;
6302   case Intrinsic::log10:
6303     // log10(pow(10.0, x)) -> x
6304     // log10(exp10(x)) -> x
6305     if (Call->hasAllowReassoc() &&
6306         (match(Op0, m_Intrinsic<Intrinsic::exp10>(m_Value(X))) ||
6307          match(Op0,
6308                m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0), m_Value(X)))))
6309       return X;
6310     break;
6311   case Intrinsic::vector_reverse:
6312     // vector.reverse(vector.reverse(x)) -> x
6313     if (match(Op0, m_VecReverse(m_Value(X))))
6314       return X;
6315     // vector.reverse(splat(X)) -> splat(X)
6316     if (isSplatValue(Op0))
6317       return Op0;
6318     break;
6319   case Intrinsic::frexp: {
6320     // Frexp is idempotent with the added complication of the struct return.
6321     if (match(Op0, m_ExtractValue<0>(m_Value(X)))) {
6322       if (match(X, m_Intrinsic<Intrinsic::frexp>(m_Value())))
6323         return X;
6324     }
6325 
6326     break;
6327   }
6328   default:
6329     break;
6330   }
6331 
6332   return nullptr;
6333 }
6334 
6335 /// Given a min/max intrinsic, see if it can be removed based on having an
6336 /// operand that is another min/max intrinsic with shared operand(s). The caller
6337 /// is expected to swap the operand arguments to handle commutation.
6338 static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) {
6339   Value *X, *Y;
6340   if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y))))
6341     return nullptr;
6342 
6343   auto *MM0 = dyn_cast<IntrinsicInst>(Op0);
6344   if (!MM0)
6345     return nullptr;
6346   Intrinsic::ID IID0 = MM0->getIntrinsicID();
6347 
6348   if (Op1 == X || Op1 == Y ||
6349       match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) {
6350     // max (max X, Y), X --> max X, Y
6351     if (IID0 == IID)
6352       return MM0;
6353     // max (min X, Y), X --> X
6354     if (IID0 == getInverseMinMaxIntrinsic(IID))
6355       return Op1;
6356   }
6357   return nullptr;
6358 }
6359 
6360 /// Given a min/max intrinsic, see if it can be removed based on having an
6361 /// operand that is another min/max intrinsic with shared operand(s). The caller
6362 /// is expected to swap the operand arguments to handle commutation.
6363 static Value *foldMinimumMaximumSharedOp(Intrinsic::ID IID, Value *Op0,
6364                                          Value *Op1) {
6365   assert((IID == Intrinsic::maxnum || IID == Intrinsic::minnum ||
6366           IID == Intrinsic::maximum || IID == Intrinsic::minimum) &&
6367          "Unsupported intrinsic");
6368 
6369   auto *M0 = dyn_cast<IntrinsicInst>(Op0);
6370   // If Op0 is not the same intrinsic as IID, do not process.
6371   // This is a difference with integer min/max handling. We do not process the
6372   // case like max(min(X,Y),min(X,Y)) => min(X,Y). But it can be handled by GVN.
6373   if (!M0 || M0->getIntrinsicID() != IID)
6374     return nullptr;
6375   Value *X0 = M0->getOperand(0);
6376   Value *Y0 = M0->getOperand(1);
6377   // Simple case, m(m(X,Y), X) => m(X, Y)
6378   //              m(m(X,Y), Y) => m(X, Y)
6379   // For minimum/maximum, X is NaN => m(NaN, Y) == NaN and m(NaN, NaN) == NaN.
6380   // For minimum/maximum, Y is NaN => m(X, NaN) == NaN  and m(NaN, NaN) == NaN.
6381   // For minnum/maxnum, X is NaN => m(NaN, Y) == Y and m(Y, Y) == Y.
6382   // For minnum/maxnum, Y is NaN => m(X, NaN) == X and m(X, NaN) == X.
6383   if (X0 == Op1 || Y0 == Op1)
6384     return M0;
6385 
6386   auto *M1 = dyn_cast<IntrinsicInst>(Op1);
6387   if (!M1)
6388     return nullptr;
6389   Value *X1 = M1->getOperand(0);
6390   Value *Y1 = M1->getOperand(1);
6391   Intrinsic::ID IID1 = M1->getIntrinsicID();
6392   // we have a case m(m(X,Y),m'(X,Y)) taking into account m' is commutative.
6393   // if m' is m or inversion of m => m(m(X,Y),m'(X,Y)) == m(X,Y).
6394   // For minimum/maximum, X is NaN => m(NaN,Y) == m'(NaN, Y) == NaN.
6395   // For minimum/maximum, Y is NaN => m(X,NaN) == m'(X, NaN) == NaN.
6396   // For minnum/maxnum, X is NaN => m(NaN,Y) == m'(NaN, Y) == Y.
6397   // For minnum/maxnum, Y is NaN => m(X,NaN) == m'(X, NaN) == X.
6398   if ((X0 == X1 && Y0 == Y1) || (X0 == Y1 && Y0 == X1))
6399     if (IID1 == IID || getInverseMinMaxIntrinsic(IID1) == IID)
6400       return M0;
6401 
6402   return nullptr;
6403 }
6404 
6405 Value *llvm::simplifyBinaryIntrinsic(Intrinsic::ID IID, Type *ReturnType,
6406                                      Value *Op0, Value *Op1,
6407                                      const SimplifyQuery &Q,
6408                                      const CallBase *Call) {
6409   unsigned BitWidth = ReturnType->getScalarSizeInBits();
6410   switch (IID) {
6411   case Intrinsic::abs:
6412     // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here.
6413     // It is always ok to pick the earlier abs. We'll just lose nsw if its only
6414     // on the outer abs.
6415     if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value())))
6416       return Op0;
6417     break;
6418 
6419   case Intrinsic::cttz: {
6420     Value *X;
6421     if (match(Op0, m_Shl(m_One(), m_Value(X))))
6422       return X;
6423     break;
6424   }
6425   case Intrinsic::ctlz: {
6426     Value *X;
6427     if (match(Op0, m_LShr(m_Negative(), m_Value(X))))
6428       return X;
6429     if (match(Op0, m_AShr(m_Negative(), m_Value())))
6430       return Constant::getNullValue(ReturnType);
6431     break;
6432   }
6433   case Intrinsic::ptrmask: {
6434     if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1))
6435       return PoisonValue::get(Op0->getType());
6436 
6437     // NOTE: We can't apply this simplifications based on the value of Op1
6438     // because we need to preserve provenance.
6439     if (Q.isUndefValue(Op0) || match(Op0, m_Zero()))
6440       return Constant::getNullValue(Op0->getType());
6441 
6442     assert(Op1->getType()->getScalarSizeInBits() ==
6443                Q.DL.getIndexTypeSizeInBits(Op0->getType()) &&
6444            "Invalid mask width");
6445     // If index-width (mask size) is less than pointer-size then mask is
6446     // 1-extended.
6447     if (match(Op1, m_PtrToInt(m_Specific(Op0))))
6448       return Op0;
6449 
6450     // NOTE: We may have attributes associated with the return value of the
6451     // llvm.ptrmask intrinsic that will be lost when we just return the
6452     // operand. We should try to preserve them.
6453     if (match(Op1, m_AllOnes()) || Q.isUndefValue(Op1))
6454       return Op0;
6455 
6456     Constant *C;
6457     if (match(Op1, m_ImmConstant(C))) {
6458       KnownBits PtrKnown = computeKnownBits(Op0, /*Depth=*/0, Q);
6459       // See if we only masking off bits we know are already zero due to
6460       // alignment.
6461       APInt IrrelevantPtrBits =
6462           PtrKnown.Zero.zextOrTrunc(C->getType()->getScalarSizeInBits());
6463       C = ConstantFoldBinaryOpOperands(
6464           Instruction::Or, C, ConstantInt::get(C->getType(), IrrelevantPtrBits),
6465           Q.DL);
6466       if (C != nullptr && C->isAllOnesValue())
6467         return Op0;
6468     }
6469     break;
6470   }
6471   case Intrinsic::smax:
6472   case Intrinsic::smin:
6473   case Intrinsic::umax:
6474   case Intrinsic::umin: {
6475     // If the arguments are the same, this is a no-op.
6476     if (Op0 == Op1)
6477       return Op0;
6478 
6479     // Canonicalize immediate constant operand as Op1.
6480     if (match(Op0, m_ImmConstant()))
6481       std::swap(Op0, Op1);
6482 
6483     // Assume undef is the limit value.
6484     if (Q.isUndefValue(Op1))
6485       return ConstantInt::get(
6486           ReturnType, MinMaxIntrinsic::getSaturationPoint(IID, BitWidth));
6487 
6488     const APInt *C;
6489     if (match(Op1, m_APIntAllowPoison(C))) {
6490       // Clamp to limit value. For example:
6491       // umax(i8 %x, i8 255) --> 255
6492       if (*C == MinMaxIntrinsic::getSaturationPoint(IID, BitWidth))
6493         return ConstantInt::get(ReturnType, *C);
6494 
6495       // If the constant op is the opposite of the limit value, the other must
6496       // be larger/smaller or equal. For example:
6497       // umin(i8 %x, i8 255) --> %x
6498       if (*C == MinMaxIntrinsic::getSaturationPoint(
6499                     getInverseMinMaxIntrinsic(IID), BitWidth))
6500         return Op0;
6501 
6502       // Remove nested call if constant operands allow it. Example:
6503       // max (max X, 7), 5 -> max X, 7
6504       auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0);
6505       if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
6506         // TODO: loosen undef/splat restrictions for vector constants.
6507         Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1);
6508         const APInt *InnerC;
6509         if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) &&
6510             ICmpInst::compare(*InnerC, *C,
6511                               ICmpInst::getNonStrictPredicate(
6512                                   MinMaxIntrinsic::getPredicate(IID))))
6513           return Op0;
6514       }
6515     }
6516 
6517     if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
6518       return V;
6519     if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0))
6520       return V;
6521 
6522     ICmpInst::Predicate Pred =
6523         ICmpInst::getNonStrictPredicate(MinMaxIntrinsic::getPredicate(IID));
6524     if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit))
6525       return Op0;
6526     if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit))
6527       return Op1;
6528 
6529     break;
6530   }
6531   case Intrinsic::scmp:
6532   case Intrinsic::ucmp: {
6533     // Fold to a constant if the relationship between operands can be
6534     // established with certainty
6535     if (isICmpTrue(CmpInst::ICMP_EQ, Op0, Op1, Q, RecursionLimit))
6536       return Constant::getNullValue(ReturnType);
6537 
6538     ICmpInst::Predicate PredGT =
6539         IID == Intrinsic::scmp ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
6540     if (isICmpTrue(PredGT, Op0, Op1, Q, RecursionLimit))
6541       return ConstantInt::get(ReturnType, 1);
6542 
6543     ICmpInst::Predicate PredLT =
6544         IID == Intrinsic::scmp ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
6545     if (isICmpTrue(PredLT, Op0, Op1, Q, RecursionLimit))
6546       return ConstantInt::getSigned(ReturnType, -1);
6547 
6548     break;
6549   }
6550   case Intrinsic::usub_with_overflow:
6551   case Intrinsic::ssub_with_overflow:
6552     // X - X -> { 0, false }
6553     // X - undef -> { 0, false }
6554     // undef - X -> { 0, false }
6555     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
6556       return Constant::getNullValue(ReturnType);
6557     break;
6558   case Intrinsic::uadd_with_overflow:
6559   case Intrinsic::sadd_with_overflow:
6560     // X + undef -> { -1, false }
6561     // undef + x -> { -1, false }
6562     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) {
6563       return ConstantStruct::get(
6564           cast<StructType>(ReturnType),
6565           {Constant::getAllOnesValue(ReturnType->getStructElementType(0)),
6566            Constant::getNullValue(ReturnType->getStructElementType(1))});
6567     }
6568     break;
6569   case Intrinsic::umul_with_overflow:
6570   case Intrinsic::smul_with_overflow:
6571     // 0 * X -> { 0, false }
6572     // X * 0 -> { 0, false }
6573     if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
6574       return Constant::getNullValue(ReturnType);
6575     // undef * X -> { 0, false }
6576     // X * undef -> { 0, false }
6577     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
6578       return Constant::getNullValue(ReturnType);
6579     break;
6580   case Intrinsic::uadd_sat:
6581     // sat(MAX + X) -> MAX
6582     // sat(X + MAX) -> MAX
6583     if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
6584       return Constant::getAllOnesValue(ReturnType);
6585     [[fallthrough]];
6586   case Intrinsic::sadd_sat:
6587     // sat(X + undef) -> -1
6588     // sat(undef + X) -> -1
6589     // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
6590     // For signed: Assume undef is ~X, in which case X + ~X = -1.
6591     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
6592       return Constant::getAllOnesValue(ReturnType);
6593 
6594     // X + 0 -> X
6595     if (match(Op1, m_Zero()))
6596       return Op0;
6597     // 0 + X -> X
6598     if (match(Op0, m_Zero()))
6599       return Op1;
6600     break;
6601   case Intrinsic::usub_sat:
6602     // sat(0 - X) -> 0, sat(X - MAX) -> 0
6603     if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
6604       return Constant::getNullValue(ReturnType);
6605     [[fallthrough]];
6606   case Intrinsic::ssub_sat:
6607     // X - X -> 0, X - undef -> 0, undef - X -> 0
6608     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
6609       return Constant::getNullValue(ReturnType);
6610     // X - 0 -> X
6611     if (match(Op1, m_Zero()))
6612       return Op0;
6613     break;
6614   case Intrinsic::load_relative:
6615     if (auto *C0 = dyn_cast<Constant>(Op0))
6616       if (auto *C1 = dyn_cast<Constant>(Op1))
6617         return simplifyRelativeLoad(C0, C1, Q.DL);
6618     break;
6619   case Intrinsic::powi:
6620     if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
6621       // powi(x, 0) -> 1.0
6622       if (Power->isZero())
6623         return ConstantFP::get(Op0->getType(), 1.0);
6624       // powi(x, 1) -> x
6625       if (Power->isOne())
6626         return Op0;
6627     }
6628     break;
6629   case Intrinsic::ldexp:
6630     return simplifyLdexp(Op0, Op1, Q, false);
6631   case Intrinsic::copysign:
6632     // copysign X, X --> X
6633     if (Op0 == Op1)
6634       return Op0;
6635     // copysign -X, X --> X
6636     // copysign X, -X --> -X
6637     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
6638         match(Op1, m_FNeg(m_Specific(Op0))))
6639       return Op1;
6640     break;
6641   case Intrinsic::is_fpclass: {
6642     if (isa<PoisonValue>(Op0))
6643       return PoisonValue::get(ReturnType);
6644 
6645     uint64_t Mask = cast<ConstantInt>(Op1)->getZExtValue();
6646     // If all tests are made, it doesn't matter what the value is.
6647     if ((Mask & fcAllFlags) == fcAllFlags)
6648       return ConstantInt::get(ReturnType, true);
6649     if ((Mask & fcAllFlags) == 0)
6650       return ConstantInt::get(ReturnType, false);
6651     if (Q.isUndefValue(Op0))
6652       return UndefValue::get(ReturnType);
6653     break;
6654   }
6655   case Intrinsic::maxnum:
6656   case Intrinsic::minnum:
6657   case Intrinsic::maximum:
6658   case Intrinsic::minimum: {
6659     // If the arguments are the same, this is a no-op.
6660     if (Op0 == Op1)
6661       return Op0;
6662 
6663     // Canonicalize constant operand as Op1.
6664     if (isa<Constant>(Op0))
6665       std::swap(Op0, Op1);
6666 
6667     // If an argument is undef, return the other argument.
6668     if (Q.isUndefValue(Op1))
6669       return Op0;
6670 
6671     bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
6672     bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum;
6673 
6674     // minnum(X, nan) -> X
6675     // maxnum(X, nan) -> X
6676     // minimum(X, nan) -> nan
6677     // maximum(X, nan) -> nan
6678     if (match(Op1, m_NaN()))
6679       return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0;
6680 
6681     // In the following folds, inf can be replaced with the largest finite
6682     // float, if the ninf flag is set.
6683     const APFloat *C;
6684     if (match(Op1, m_APFloat(C)) &&
6685         (C->isInfinity() || (Call && Call->hasNoInfs() && C->isLargest()))) {
6686       // minnum(X, -inf) -> -inf
6687       // maxnum(X, +inf) -> +inf
6688       // minimum(X, -inf) -> -inf if nnan
6689       // maximum(X, +inf) -> +inf if nnan
6690       if (C->isNegative() == IsMin &&
6691           (!PropagateNaN || (Call && Call->hasNoNaNs())))
6692         return ConstantFP::get(ReturnType, *C);
6693 
6694       // minnum(X, +inf) -> X if nnan
6695       // maxnum(X, -inf) -> X if nnan
6696       // minimum(X, +inf) -> X
6697       // maximum(X, -inf) -> X
6698       if (C->isNegative() != IsMin &&
6699           (PropagateNaN || (Call && Call->hasNoNaNs())))
6700         return Op0;
6701     }
6702 
6703     // Min/max of the same operation with common operand:
6704     // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
6705     if (Value *V = foldMinimumMaximumSharedOp(IID, Op0, Op1))
6706       return V;
6707     if (Value *V = foldMinimumMaximumSharedOp(IID, Op1, Op0))
6708       return V;
6709 
6710     break;
6711   }
6712   case Intrinsic::vector_extract: {
6713     // (extract_vector (insert_vector _, X, 0), 0) -> X
6714     unsigned IdxN = cast<ConstantInt>(Op1)->getZExtValue();
6715     Value *X = nullptr;
6716     if (match(Op0, m_Intrinsic<Intrinsic::vector_insert>(m_Value(), m_Value(X),
6717                                                          m_Zero())) &&
6718         IdxN == 0 && X->getType() == ReturnType)
6719       return X;
6720 
6721     break;
6722   }
6723   default:
6724     break;
6725   }
6726 
6727   return nullptr;
6728 }
6729 
6730 static Value *simplifyIntrinsic(CallBase *Call, Value *Callee,
6731                                 ArrayRef<Value *> Args,
6732                                 const SimplifyQuery &Q) {
6733   // Operand bundles should not be in Args.
6734   assert(Call->arg_size() == Args.size());
6735   unsigned NumOperands = Args.size();
6736   Function *F = cast<Function>(Callee);
6737   Intrinsic::ID IID = F->getIntrinsicID();
6738 
6739   // Most of the intrinsics with no operands have some kind of side effect.
6740   // Don't simplify.
6741   if (!NumOperands) {
6742     switch (IID) {
6743     case Intrinsic::vscale: {
6744       Type *RetTy = F->getReturnType();
6745       ConstantRange CR = getVScaleRange(Call->getFunction(), 64);
6746       if (const APInt *C = CR.getSingleElement())
6747         return ConstantInt::get(RetTy, C->getZExtValue());
6748       return nullptr;
6749     }
6750     default:
6751       return nullptr;
6752     }
6753   }
6754 
6755   if (NumOperands == 1)
6756     return simplifyUnaryIntrinsic(F, Args[0], Q, Call);
6757 
6758   if (NumOperands == 2)
6759     return simplifyBinaryIntrinsic(IID, F->getReturnType(), Args[0], Args[1], Q,
6760                                    Call);
6761 
6762   // Handle intrinsics with 3 or more arguments.
6763   switch (IID) {
6764   case Intrinsic::masked_load:
6765   case Intrinsic::masked_gather: {
6766     Value *MaskArg = Args[2];
6767     Value *PassthruArg = Args[3];
6768     // If the mask is all zeros or undef, the "passthru" argument is the result.
6769     if (maskIsAllZeroOrUndef(MaskArg))
6770       return PassthruArg;
6771     return nullptr;
6772   }
6773   case Intrinsic::fshl:
6774   case Intrinsic::fshr: {
6775     Value *Op0 = Args[0], *Op1 = Args[1], *ShAmtArg = Args[2];
6776 
6777     // If both operands are undef, the result is undef.
6778     if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1))
6779       return UndefValue::get(F->getReturnType());
6780 
6781     // If shift amount is undef, assume it is zero.
6782     if (Q.isUndefValue(ShAmtArg))
6783       return Args[IID == Intrinsic::fshl ? 0 : 1];
6784 
6785     const APInt *ShAmtC;
6786     if (match(ShAmtArg, m_APInt(ShAmtC))) {
6787       // If there's effectively no shift, return the 1st arg or 2nd arg.
6788       APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
6789       if (ShAmtC->urem(BitWidth).isZero())
6790         return Args[IID == Intrinsic::fshl ? 0 : 1];
6791     }
6792 
6793     // Rotating zero by anything is zero.
6794     if (match(Op0, m_Zero()) && match(Op1, m_Zero()))
6795       return ConstantInt::getNullValue(F->getReturnType());
6796 
6797     // Rotating -1 by anything is -1.
6798     if (match(Op0, m_AllOnes()) && match(Op1, m_AllOnes()))
6799       return ConstantInt::getAllOnesValue(F->getReturnType());
6800 
6801     return nullptr;
6802   }
6803   case Intrinsic::experimental_constrained_fma: {
6804     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6805     if (Value *V = simplifyFPOp(Args, {}, Q, *FPI->getExceptionBehavior(),
6806                                 *FPI->getRoundingMode()))
6807       return V;
6808     return nullptr;
6809   }
6810   case Intrinsic::fma:
6811   case Intrinsic::fmuladd: {
6812     if (Value *V = simplifyFPOp(Args, {}, Q, fp::ebIgnore,
6813                                 RoundingMode::NearestTiesToEven))
6814       return V;
6815     return nullptr;
6816   }
6817   case Intrinsic::smul_fix:
6818   case Intrinsic::smul_fix_sat: {
6819     Value *Op0 = Args[0];
6820     Value *Op1 = Args[1];
6821     Value *Op2 = Args[2];
6822     Type *ReturnType = F->getReturnType();
6823 
6824     // Canonicalize constant operand as Op1 (ConstantFolding handles the case
6825     // when both Op0 and Op1 are constant so we do not care about that special
6826     // case here).
6827     if (isa<Constant>(Op0))
6828       std::swap(Op0, Op1);
6829 
6830     // X * 0 -> 0
6831     if (match(Op1, m_Zero()))
6832       return Constant::getNullValue(ReturnType);
6833 
6834     // X * undef -> 0
6835     if (Q.isUndefValue(Op1))
6836       return Constant::getNullValue(ReturnType);
6837 
6838     // X * (1 << Scale) -> X
6839     APInt ScaledOne =
6840         APInt::getOneBitSet(ReturnType->getScalarSizeInBits(),
6841                             cast<ConstantInt>(Op2)->getZExtValue());
6842     if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne)))
6843       return Op0;
6844 
6845     return nullptr;
6846   }
6847   case Intrinsic::vector_insert: {
6848     Value *Vec = Args[0];
6849     Value *SubVec = Args[1];
6850     Value *Idx = Args[2];
6851     Type *ReturnType = F->getReturnType();
6852 
6853     // (insert_vector Y, (extract_vector X, 0), 0) -> X
6854     // where: Y is X, or Y is undef
6855     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6856     Value *X = nullptr;
6857     if (match(SubVec,
6858               m_Intrinsic<Intrinsic::vector_extract>(m_Value(X), m_Zero())) &&
6859         (Q.isUndefValue(Vec) || Vec == X) && IdxN == 0 &&
6860         X->getType() == ReturnType)
6861       return X;
6862 
6863     return nullptr;
6864   }
6865   case Intrinsic::experimental_constrained_fadd: {
6866     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6867     return simplifyFAddInst(Args[0], Args[1], FPI->getFastMathFlags(), Q,
6868                             *FPI->getExceptionBehavior(),
6869                             *FPI->getRoundingMode());
6870   }
6871   case Intrinsic::experimental_constrained_fsub: {
6872     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6873     return simplifyFSubInst(Args[0], Args[1], FPI->getFastMathFlags(), Q,
6874                             *FPI->getExceptionBehavior(),
6875                             *FPI->getRoundingMode());
6876   }
6877   case Intrinsic::experimental_constrained_fmul: {
6878     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6879     return simplifyFMulInst(Args[0], Args[1], FPI->getFastMathFlags(), Q,
6880                             *FPI->getExceptionBehavior(),
6881                             *FPI->getRoundingMode());
6882   }
6883   case Intrinsic::experimental_constrained_fdiv: {
6884     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6885     return simplifyFDivInst(Args[0], Args[1], FPI->getFastMathFlags(), Q,
6886                             *FPI->getExceptionBehavior(),
6887                             *FPI->getRoundingMode());
6888   }
6889   case Intrinsic::experimental_constrained_frem: {
6890     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6891     return simplifyFRemInst(Args[0], Args[1], FPI->getFastMathFlags(), Q,
6892                             *FPI->getExceptionBehavior(),
6893                             *FPI->getRoundingMode());
6894   }
6895   case Intrinsic::experimental_constrained_ldexp:
6896     return simplifyLdexp(Args[0], Args[1], Q, true);
6897   case Intrinsic::experimental_gc_relocate: {
6898     GCRelocateInst &GCR = *cast<GCRelocateInst>(Call);
6899     Value *DerivedPtr = GCR.getDerivedPtr();
6900     Value *BasePtr = GCR.getBasePtr();
6901 
6902     // Undef is undef, even after relocation.
6903     if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) {
6904       return UndefValue::get(GCR.getType());
6905     }
6906 
6907     if (auto *PT = dyn_cast<PointerType>(GCR.getType())) {
6908       // For now, the assumption is that the relocation of null will be null
6909       // for most any collector. If this ever changes, a corresponding hook
6910       // should be added to GCStrategy and this code should check it first.
6911       if (isa<ConstantPointerNull>(DerivedPtr)) {
6912         // Use null-pointer of gc_relocate's type to replace it.
6913         return ConstantPointerNull::get(PT);
6914       }
6915     }
6916     return nullptr;
6917   }
6918   default:
6919     return nullptr;
6920   }
6921 }
6922 
6923 static Value *tryConstantFoldCall(CallBase *Call, Value *Callee,
6924                                   ArrayRef<Value *> Args,
6925                                   const SimplifyQuery &Q) {
6926   auto *F = dyn_cast<Function>(Callee);
6927   if (!F || !canConstantFoldCallTo(Call, F))
6928     return nullptr;
6929 
6930   SmallVector<Constant *, 4> ConstantArgs;
6931   ConstantArgs.reserve(Args.size());
6932   for (Value *Arg : Args) {
6933     Constant *C = dyn_cast<Constant>(Arg);
6934     if (!C) {
6935       if (isa<MetadataAsValue>(Arg))
6936         continue;
6937       return nullptr;
6938     }
6939     ConstantArgs.push_back(C);
6940   }
6941 
6942   return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
6943 }
6944 
6945 Value *llvm::simplifyCall(CallBase *Call, Value *Callee, ArrayRef<Value *> Args,
6946                           const SimplifyQuery &Q) {
6947   // Args should not contain operand bundle operands.
6948   assert(Call->arg_size() == Args.size());
6949 
6950   // musttail calls can only be simplified if they are also DCEd.
6951   // As we can't guarantee this here, don't simplify them.
6952   if (Call->isMustTailCall())
6953     return nullptr;
6954 
6955   // call undef -> poison
6956   // call null -> poison
6957   if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
6958     return PoisonValue::get(Call->getType());
6959 
6960   if (Value *V = tryConstantFoldCall(Call, Callee, Args, Q))
6961     return V;
6962 
6963   auto *F = dyn_cast<Function>(Callee);
6964   if (F && F->isIntrinsic())
6965     if (Value *Ret = simplifyIntrinsic(Call, Callee, Args, Q))
6966       return Ret;
6967 
6968   return nullptr;
6969 }
6970 
6971 Value *llvm::simplifyConstrainedFPCall(CallBase *Call, const SimplifyQuery &Q) {
6972   assert(isa<ConstrainedFPIntrinsic>(Call));
6973   SmallVector<Value *, 4> Args(Call->args());
6974   if (Value *V = tryConstantFoldCall(Call, Call->getCalledOperand(), Args, Q))
6975     return V;
6976   if (Value *Ret = simplifyIntrinsic(Call, Call->getCalledOperand(), Args, Q))
6977     return Ret;
6978   return nullptr;
6979 }
6980 
6981 /// Given operands for a Freeze, see if we can fold the result.
6982 static Value *simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
6983   // Use a utility function defined in ValueTracking.
6984   if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT))
6985     return Op0;
6986   // We have room for improvement.
6987   return nullptr;
6988 }
6989 
6990 Value *llvm::simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
6991   return ::simplifyFreezeInst(Op0, Q);
6992 }
6993 
6994 Value *llvm::simplifyLoadInst(LoadInst *LI, Value *PtrOp,
6995                               const SimplifyQuery &Q) {
6996   if (LI->isVolatile())
6997     return nullptr;
6998 
6999   if (auto *PtrOpC = dyn_cast<Constant>(PtrOp))
7000     return ConstantFoldLoadFromConstPtr(PtrOpC, LI->getType(), Q.DL);
7001 
7002   // We can only fold the load if it is from a constant global with definitive
7003   // initializer. Skip expensive logic if this is not the case.
7004   auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(PtrOp));
7005   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
7006     return nullptr;
7007 
7008   // If GlobalVariable's initializer is uniform, then return the constant
7009   // regardless of its offset.
7010   if (Constant *C = ConstantFoldLoadFromUniformValue(GV->getInitializer(),
7011                                                      LI->getType(), Q.DL))
7012     return C;
7013 
7014   // Try to convert operand into a constant by stripping offsets while looking
7015   // through invariant.group intrinsics.
7016   APInt Offset(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
7017   PtrOp = PtrOp->stripAndAccumulateConstantOffsets(
7018       Q.DL, Offset, /* AllowNonInbounts */ true,
7019       /* AllowInvariantGroup */ true);
7020   if (PtrOp == GV) {
7021     // Index size may have changed due to address space casts.
7022     Offset = Offset.sextOrTrunc(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()));
7023     return ConstantFoldLoadFromConstPtr(GV, LI->getType(), std::move(Offset),
7024                                         Q.DL);
7025   }
7026 
7027   return nullptr;
7028 }
7029 
7030 /// See if we can compute a simplified version of this instruction.
7031 /// If not, this returns null.
7032 
7033 static Value *simplifyInstructionWithOperands(Instruction *I,
7034                                               ArrayRef<Value *> NewOps,
7035                                               const SimplifyQuery &SQ,
7036                                               unsigned MaxRecurse) {
7037   assert(I->getFunction() && "instruction should be inserted in a function");
7038   assert((!SQ.CxtI || SQ.CxtI->getFunction() == I->getFunction()) &&
7039          "context instruction should be in the same function");
7040 
7041   const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
7042 
7043   switch (I->getOpcode()) {
7044   default:
7045     if (llvm::all_of(NewOps, [](Value *V) { return isa<Constant>(V); })) {
7046       SmallVector<Constant *, 8> NewConstOps(NewOps.size());
7047       transform(NewOps, NewConstOps.begin(),
7048                 [](Value *V) { return cast<Constant>(V); });
7049       return ConstantFoldInstOperands(I, NewConstOps, Q.DL, Q.TLI);
7050     }
7051     return nullptr;
7052   case Instruction::FNeg:
7053     return simplifyFNegInst(NewOps[0], I->getFastMathFlags(), Q, MaxRecurse);
7054   case Instruction::FAdd:
7055     return simplifyFAddInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
7056                             MaxRecurse);
7057   case Instruction::Add:
7058     return simplifyAddInst(
7059         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
7060         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q, MaxRecurse);
7061   case Instruction::FSub:
7062     return simplifyFSubInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
7063                             MaxRecurse);
7064   case Instruction::Sub:
7065     return simplifySubInst(
7066         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
7067         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q, MaxRecurse);
7068   case Instruction::FMul:
7069     return simplifyFMulInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
7070                             MaxRecurse);
7071   case Instruction::Mul:
7072     return simplifyMulInst(
7073         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
7074         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q, MaxRecurse);
7075   case Instruction::SDiv:
7076     return simplifySDivInst(NewOps[0], NewOps[1],
7077                             Q.IIQ.isExact(cast<BinaryOperator>(I)), Q,
7078                             MaxRecurse);
7079   case Instruction::UDiv:
7080     return simplifyUDivInst(NewOps[0], NewOps[1],
7081                             Q.IIQ.isExact(cast<BinaryOperator>(I)), Q,
7082                             MaxRecurse);
7083   case Instruction::FDiv:
7084     return simplifyFDivInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
7085                             MaxRecurse);
7086   case Instruction::SRem:
7087     return simplifySRemInst(NewOps[0], NewOps[1], Q, MaxRecurse);
7088   case Instruction::URem:
7089     return simplifyURemInst(NewOps[0], NewOps[1], Q, MaxRecurse);
7090   case Instruction::FRem:
7091     return simplifyFRemInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
7092                             MaxRecurse);
7093   case Instruction::Shl:
7094     return simplifyShlInst(
7095         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
7096         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q, MaxRecurse);
7097   case Instruction::LShr:
7098     return simplifyLShrInst(NewOps[0], NewOps[1],
7099                             Q.IIQ.isExact(cast<BinaryOperator>(I)), Q,
7100                             MaxRecurse);
7101   case Instruction::AShr:
7102     return simplifyAShrInst(NewOps[0], NewOps[1],
7103                             Q.IIQ.isExact(cast<BinaryOperator>(I)), Q,
7104                             MaxRecurse);
7105   case Instruction::And:
7106     return simplifyAndInst(NewOps[0], NewOps[1], Q, MaxRecurse);
7107   case Instruction::Or:
7108     return simplifyOrInst(NewOps[0], NewOps[1], Q, MaxRecurse);
7109   case Instruction::Xor:
7110     return simplifyXorInst(NewOps[0], NewOps[1], Q, MaxRecurse);
7111   case Instruction::ICmp:
7112     return simplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), NewOps[0],
7113                             NewOps[1], Q, MaxRecurse);
7114   case Instruction::FCmp:
7115     return simplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), NewOps[0],
7116                             NewOps[1], I->getFastMathFlags(), Q, MaxRecurse);
7117   case Instruction::Select:
7118     return simplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q, MaxRecurse);
7119     break;
7120   case Instruction::GetElementPtr: {
7121     auto *GEPI = cast<GetElementPtrInst>(I);
7122     return simplifyGEPInst(GEPI->getSourceElementType(), NewOps[0],
7123                            ArrayRef(NewOps).slice(1), GEPI->getNoWrapFlags(), Q,
7124                            MaxRecurse);
7125   }
7126   case Instruction::InsertValue: {
7127     InsertValueInst *IV = cast<InsertValueInst>(I);
7128     return simplifyInsertValueInst(NewOps[0], NewOps[1], IV->getIndices(), Q,
7129                                    MaxRecurse);
7130   }
7131   case Instruction::InsertElement:
7132     return simplifyInsertElementInst(NewOps[0], NewOps[1], NewOps[2], Q);
7133   case Instruction::ExtractValue: {
7134     auto *EVI = cast<ExtractValueInst>(I);
7135     return simplifyExtractValueInst(NewOps[0], EVI->getIndices(), Q,
7136                                     MaxRecurse);
7137   }
7138   case Instruction::ExtractElement:
7139     return simplifyExtractElementInst(NewOps[0], NewOps[1], Q, MaxRecurse);
7140   case Instruction::ShuffleVector: {
7141     auto *SVI = cast<ShuffleVectorInst>(I);
7142     return simplifyShuffleVectorInst(NewOps[0], NewOps[1],
7143                                      SVI->getShuffleMask(), SVI->getType(), Q,
7144                                      MaxRecurse);
7145   }
7146   case Instruction::PHI:
7147     return simplifyPHINode(cast<PHINode>(I), NewOps, Q);
7148   case Instruction::Call:
7149     return simplifyCall(
7150         cast<CallInst>(I), NewOps.back(),
7151         NewOps.drop_back(1 + cast<CallInst>(I)->getNumTotalBundleOperands()), Q);
7152   case Instruction::Freeze:
7153     return llvm::simplifyFreezeInst(NewOps[0], Q);
7154 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
7155 #include "llvm/IR/Instruction.def"
7156 #undef HANDLE_CAST_INST
7157     return simplifyCastInst(I->getOpcode(), NewOps[0], I->getType(), Q,
7158                             MaxRecurse);
7159   case Instruction::Alloca:
7160     // No simplifications for Alloca and it can't be constant folded.
7161     return nullptr;
7162   case Instruction::Load:
7163     return simplifyLoadInst(cast<LoadInst>(I), NewOps[0], Q);
7164   }
7165 }
7166 
7167 Value *llvm::simplifyInstructionWithOperands(Instruction *I,
7168                                              ArrayRef<Value *> NewOps,
7169                                              const SimplifyQuery &SQ) {
7170   assert(NewOps.size() == I->getNumOperands() &&
7171          "Number of operands should match the instruction!");
7172   return ::simplifyInstructionWithOperands(I, NewOps, SQ, RecursionLimit);
7173 }
7174 
7175 Value *llvm::simplifyInstruction(Instruction *I, const SimplifyQuery &SQ) {
7176   SmallVector<Value *, 8> Ops(I->operands());
7177   Value *Result = ::simplifyInstructionWithOperands(I, Ops, SQ, RecursionLimit);
7178 
7179   /// If called on unreachable code, the instruction may simplify to itself.
7180   /// Make life easier for users by detecting that case here, and returning a
7181   /// safe value instead.
7182   return Result == I ? PoisonValue::get(I->getType()) : Result;
7183 }
7184 
7185 /// Implementation of recursive simplification through an instruction's
7186 /// uses.
7187 ///
7188 /// This is the common implementation of the recursive simplification routines.
7189 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
7190 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
7191 /// instructions to process and attempt to simplify it using
7192 /// InstructionSimplify. Recursively visited users which could not be
7193 /// simplified themselves are to the optional UnsimplifiedUsers set for
7194 /// further processing by the caller.
7195 ///
7196 /// This routine returns 'true' only when *it* simplifies something. The passed
7197 /// in simplified value does not count toward this.
7198 static bool replaceAndRecursivelySimplifyImpl(
7199     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
7200     const DominatorTree *DT, AssumptionCache *AC,
7201     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
7202   bool Simplified = false;
7203   SmallSetVector<Instruction *, 8> Worklist;
7204   const DataLayout &DL = I->getDataLayout();
7205 
7206   // If we have an explicit value to collapse to, do that round of the
7207   // simplification loop by hand initially.
7208   if (SimpleV) {
7209     for (User *U : I->users())
7210       if (U != I)
7211         Worklist.insert(cast<Instruction>(U));
7212 
7213     // Replace the instruction with its simplified value.
7214     I->replaceAllUsesWith(SimpleV);
7215 
7216     if (!I->isEHPad() && !I->isTerminator() && !I->mayHaveSideEffects())
7217       I->eraseFromParent();
7218   } else {
7219     Worklist.insert(I);
7220   }
7221 
7222   // Note that we must test the size on each iteration, the worklist can grow.
7223   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
7224     I = Worklist[Idx];
7225 
7226     // See if this instruction simplifies.
7227     SimpleV = simplifyInstruction(I, {DL, TLI, DT, AC});
7228     if (!SimpleV) {
7229       if (UnsimplifiedUsers)
7230         UnsimplifiedUsers->insert(I);
7231       continue;
7232     }
7233 
7234     Simplified = true;
7235 
7236     // Stash away all the uses of the old instruction so we can check them for
7237     // recursive simplifications after a RAUW. This is cheaper than checking all
7238     // uses of To on the recursive step in most cases.
7239     for (User *U : I->users())
7240       Worklist.insert(cast<Instruction>(U));
7241 
7242     // Replace the instruction with its simplified value.
7243     I->replaceAllUsesWith(SimpleV);
7244 
7245     if (!I->isEHPad() && !I->isTerminator() && !I->mayHaveSideEffects())
7246       I->eraseFromParent();
7247   }
7248   return Simplified;
7249 }
7250 
7251 bool llvm::replaceAndRecursivelySimplify(
7252     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
7253     const DominatorTree *DT, AssumptionCache *AC,
7254     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
7255   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
7256   assert(SimpleV && "Must provide a simplified value.");
7257   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
7258                                            UnsimplifiedUsers);
7259 }
7260 
7261 namespace llvm {
7262 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
7263   auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
7264   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
7265   auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
7266   auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
7267   auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
7268   auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
7269   return {F.getDataLayout(), TLI, DT, AC};
7270 }
7271 
7272 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
7273                                          const DataLayout &DL) {
7274   return {DL, &AR.TLI, &AR.DT, &AR.AC};
7275 }
7276 
7277 template <class T, class... TArgs>
7278 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
7279                                          Function &F) {
7280   auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
7281   auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
7282   auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
7283   return {F.getDataLayout(), TLI, DT, AC};
7284 }
7285 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
7286                                                   Function &);
7287 
7288 bool SimplifyQuery::isUndefValue(Value *V) const {
7289   if (!CanUseUndef)
7290     return false;
7291 
7292   return match(V, m_Undef());
7293 }
7294 
7295 } // namespace llvm
7296 
7297 void InstSimplifyFolder::anchor() {}
7298