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