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