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