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