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 /// Try to simplify and/or of icmp with ctpop intrinsic.
1807 static Value *simplifyAndOrOfICmpsWithCtpop(ICmpInst *Cmp0, ICmpInst *Cmp1,
1808                                             bool IsAnd) {
1809   ICmpInst::Predicate Pred0, Pred1;
1810   Value *X;
1811   const APInt *C;
1812   if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
1813                           m_APInt(C))) ||
1814       !match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())) || C->isZero())
1815     return nullptr;
1816 
1817   // (ctpop(X) == C) || (X != 0) --> X != 0 where C > 0
1818   if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_NE)
1819     return Cmp1;
1820   // (ctpop(X) != C) && (X == 0) --> X == 0 where C > 0
1821   if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_EQ)
1822     return Cmp1;
1823 
1824   return nullptr;
1825 }
1826 
1827 static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1828                                  const SimplifyQuery &Q) {
1829   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true, Q))
1830     return X;
1831   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true, Q))
1832     return X;
1833 
1834   if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1835     return X;
1836   if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0))
1837     return X;
1838 
1839   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
1840     return X;
1841 
1842   if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, true))
1843     return X;
1844 
1845   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
1846     return X;
1847 
1848   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, true))
1849     return X;
1850   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, true))
1851     return X;
1852 
1853   if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1854     return X;
1855   if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1856     return X;
1857 
1858   return nullptr;
1859 }
1860 
1861 static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1862                                        const InstrInfoQuery &IIQ) {
1863   // (icmp (add V, C0), C1) | (icmp V, C0)
1864   ICmpInst::Predicate Pred0, Pred1;
1865   const APInt *C0, *C1;
1866   Value *V;
1867   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1868     return nullptr;
1869 
1870   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1871     return nullptr;
1872 
1873   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1874   if (AddInst->getOperand(1) != Op1->getOperand(1))
1875     return nullptr;
1876 
1877   Type *ITy = Op0->getType();
1878   bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1879   bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1880 
1881   const APInt Delta = *C1 - *C0;
1882   if (C0->isStrictlyPositive()) {
1883     if (Delta == 2) {
1884       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1885         return getTrue(ITy);
1886       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1887         return getTrue(ITy);
1888     }
1889     if (Delta == 1) {
1890       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1891         return getTrue(ITy);
1892       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1893         return getTrue(ITy);
1894     }
1895   }
1896   if (C0->getBoolValue() && isNUW) {
1897     if (Delta == 2)
1898       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1899         return getTrue(ITy);
1900     if (Delta == 1)
1901       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1902         return getTrue(ITy);
1903   }
1904 
1905   return nullptr;
1906 }
1907 
1908 static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1909                                 const SimplifyQuery &Q) {
1910   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false, Q))
1911     return X;
1912   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false, Q))
1913     return X;
1914 
1915   if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1916     return X;
1917   if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0))
1918     return X;
1919 
1920   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1921     return X;
1922 
1923   if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, false))
1924     return X;
1925 
1926   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
1927     return X;
1928 
1929   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, false))
1930     return X;
1931   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, false))
1932     return X;
1933 
1934   if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1935     return X;
1936   if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1937     return X;
1938 
1939   return nullptr;
1940 }
1941 
1942 static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI,
1943                                    FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) {
1944   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1945   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1946   if (LHS0->getType() != RHS0->getType())
1947     return nullptr;
1948 
1949   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1950   if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1951       (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1952     // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
1953     // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
1954     // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
1955     // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
1956     // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
1957     // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
1958     // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
1959     // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
1960     if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
1961         (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1)))
1962       return RHS;
1963 
1964     // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
1965     // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
1966     // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
1967     // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
1968     // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
1969     // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
1970     // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
1971     // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
1972     if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
1973         (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1)))
1974       return LHS;
1975   }
1976 
1977   return nullptr;
1978 }
1979 
1980 static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q,
1981                                   Value *Op0, Value *Op1, bool IsAnd) {
1982   // Look through casts of the 'and' operands to find compares.
1983   auto *Cast0 = dyn_cast<CastInst>(Op0);
1984   auto *Cast1 = dyn_cast<CastInst>(Op1);
1985   if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1986       Cast0->getSrcTy() == Cast1->getSrcTy()) {
1987     Op0 = Cast0->getOperand(0);
1988     Op1 = Cast1->getOperand(0);
1989   }
1990 
1991   Value *V = nullptr;
1992   auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1993   auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1994   if (ICmp0 && ICmp1)
1995     V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q)
1996               : simplifyOrOfICmps(ICmp0, ICmp1, Q);
1997 
1998   auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
1999   auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
2000   if (FCmp0 && FCmp1)
2001     V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd);
2002 
2003   if (!V)
2004     return nullptr;
2005   if (!Cast0)
2006     return V;
2007 
2008   // If we looked through casts, we can only handle a constant simplification
2009   // because we are not allowed to create a cast instruction here.
2010   if (auto *C = dyn_cast<Constant>(V))
2011     return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
2012 
2013   return nullptr;
2014 }
2015 
2016 /// Given a bitwise logic op, check if the operands are add/sub with a common
2017 /// source value and inverted constant (identity: C - X -> ~(X + ~C)).
2018 static Value *simplifyLogicOfAddSub(Value *Op0, Value *Op1,
2019                                     Instruction::BinaryOps Opcode) {
2020   assert(Op0->getType() == Op1->getType() && "Mismatched binop types");
2021   assert(BinaryOperator::isBitwiseLogicOp(Opcode) && "Expected logic op");
2022   Value *X;
2023   Constant *C1, *C2;
2024   if ((match(Op0, m_Add(m_Value(X), m_Constant(C1))) &&
2025        match(Op1, m_Sub(m_Constant(C2), m_Specific(X)))) ||
2026       (match(Op1, m_Add(m_Value(X), m_Constant(C1))) &&
2027        match(Op0, m_Sub(m_Constant(C2), m_Specific(X))))) {
2028     if (ConstantExpr::getNot(C1) == C2) {
2029       // (X + C) & (~C - X) --> (X + C) & ~(X + C) --> 0
2030       // (X + C) | (~C - X) --> (X + C) | ~(X + C) --> -1
2031       // (X + C) ^ (~C - X) --> (X + C) ^ ~(X + C) --> -1
2032       Type *Ty = Op0->getType();
2033       return Opcode == Instruction::And ? ConstantInt::getNullValue(Ty)
2034                                         : ConstantInt::getAllOnesValue(Ty);
2035     }
2036   }
2037   return nullptr;
2038 }
2039 
2040 /// Given operands for an And, see if we can fold the result.
2041 /// If not, this returns null.
2042 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2043                               unsigned MaxRecurse) {
2044   if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
2045     return C;
2046 
2047   // X & poison -> poison
2048   if (isa<PoisonValue>(Op1))
2049     return Op1;
2050 
2051   // X & undef -> 0
2052   if (Q.isUndefValue(Op1))
2053     return Constant::getNullValue(Op0->getType());
2054 
2055   // X & X = X
2056   if (Op0 == Op1)
2057     return Op0;
2058 
2059   // X & 0 = 0
2060   if (match(Op1, m_Zero()))
2061     return Constant::getNullValue(Op0->getType());
2062 
2063   // X & -1 = X
2064   if (match(Op1, m_AllOnes()))
2065     return Op0;
2066 
2067   // A & ~A  =  ~A & A  =  0
2068   if (match(Op0, m_Not(m_Specific(Op1))) ||
2069       match(Op1, m_Not(m_Specific(Op0))))
2070     return Constant::getNullValue(Op0->getType());
2071 
2072   // (A | ?) & A = A
2073   if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
2074     return Op1;
2075 
2076   // A & (A | ?) = A
2077   if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
2078     return Op0;
2079 
2080   // (X | Y) & (X | ~Y) --> X (commuted 8 ways)
2081   Value *X, *Y;
2082   if (match(Op0, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2083       match(Op1, m_c_Or(m_Deferred(X), m_Deferred(Y))))
2084     return X;
2085   if (match(Op1, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2086       match(Op0, m_c_Or(m_Deferred(X), m_Deferred(Y))))
2087     return X;
2088 
2089   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::And))
2090     return V;
2091 
2092   // A mask that only clears known zeros of a shifted value is a no-op.
2093   const APInt *Mask;
2094   const APInt *ShAmt;
2095   if (match(Op1, m_APInt(Mask))) {
2096     // If all bits in the inverted and shifted mask are clear:
2097     // and (shl X, ShAmt), Mask --> shl X, ShAmt
2098     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
2099         (~(*Mask)).lshr(*ShAmt).isZero())
2100       return Op0;
2101 
2102     // If all bits in the inverted and shifted mask are clear:
2103     // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
2104     if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
2105         (~(*Mask)).shl(*ShAmt).isZero())
2106       return Op0;
2107   }
2108 
2109   // If we have a multiplication overflow check that is being 'and'ed with a
2110   // check that one of the multipliers is not zero, we can omit the 'and', and
2111   // only keep the overflow check.
2112   if (isCheckForZeroAndMulWithOverflow(Op0, Op1, true))
2113     return Op1;
2114   if (isCheckForZeroAndMulWithOverflow(Op1, Op0, true))
2115     return Op0;
2116 
2117   // A & (-A) = A if A is a power of two or zero.
2118   if (match(Op0, m_Neg(m_Specific(Op1))) ||
2119       match(Op1, m_Neg(m_Specific(Op0)))) {
2120     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
2121                                Q.DT))
2122       return Op0;
2123     if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
2124                                Q.DT))
2125       return Op1;
2126   }
2127 
2128   // This is a similar pattern used for checking if a value is a power-of-2:
2129   // (A - 1) & A --> 0 (if A is a power-of-2 or 0)
2130   // A & (A - 1) --> 0 (if A is a power-of-2 or 0)
2131   if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) &&
2132       isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
2133     return Constant::getNullValue(Op1->getType());
2134   if (match(Op1, m_Add(m_Specific(Op0), m_AllOnes())) &&
2135       isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
2136     return Constant::getNullValue(Op0->getType());
2137 
2138   if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
2139     return V;
2140 
2141   // Try some generic simplifications for associative operations.
2142   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
2143                                           MaxRecurse))
2144     return V;
2145 
2146   // And distributes over Or.  Try some generic simplifications based on this.
2147   if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2148                                         Instruction::Or, Q, MaxRecurse))
2149     return V;
2150 
2151   // And distributes over Xor.  Try some generic simplifications based on this.
2152   if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2153                                         Instruction::Xor, Q, MaxRecurse))
2154     return V;
2155 
2156   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2157     if (Op0->getType()->isIntOrIntVectorTy(1)) {
2158       // A & (A && B) -> A && B
2159       if (match(Op1, m_Select(m_Specific(Op0), m_Value(), m_Zero())))
2160         return Op1;
2161       else if (match(Op0, m_Select(m_Specific(Op1), m_Value(), m_Zero())))
2162         return Op0;
2163     }
2164     // If the operation is with the result of a select instruction, check
2165     // whether operating on either branch of the select always yields the same
2166     // value.
2167     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
2168                                          MaxRecurse))
2169       return V;
2170   }
2171 
2172   // If the operation is with the result of a phi instruction, check whether
2173   // operating on all incoming values of the phi always yields the same value.
2174   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2175     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
2176                                       MaxRecurse))
2177       return V;
2178 
2179   // Assuming the effective width of Y is not larger than A, i.e. all bits
2180   // from X and Y are disjoint in (X << A) | Y,
2181   // if the mask of this AND op covers all bits of X or Y, while it covers
2182   // no bits from the other, we can bypass this AND op. E.g.,
2183   // ((X << A) | Y) & Mask -> Y,
2184   //     if Mask = ((1 << effective_width_of(Y)) - 1)
2185   // ((X << A) | Y) & Mask -> X << A,
2186   //     if Mask = ((1 << effective_width_of(X)) - 1) << A
2187   // SimplifyDemandedBits in InstCombine can optimize the general case.
2188   // This pattern aims to help other passes for a common case.
2189   Value *XShifted;
2190   if (match(Op1, m_APInt(Mask)) &&
2191       match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
2192                                      m_Value(XShifted)),
2193                         m_Value(Y)))) {
2194     const unsigned Width = Op0->getType()->getScalarSizeInBits();
2195     const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
2196     const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2197     const unsigned EffWidthY = YKnown.countMaxActiveBits();
2198     if (EffWidthY <= ShftCnt) {
2199       const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI,
2200                                                 Q.DT);
2201       const unsigned EffWidthX = XKnown.countMaxActiveBits();
2202       const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
2203       const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
2204       // If the mask is extracting all bits from X or Y as is, we can skip
2205       // this AND op.
2206       if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
2207         return Y;
2208       if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
2209         return XShifted;
2210     }
2211   }
2212 
2213   // ((X | Y) ^ X ) & ((X | Y) ^ Y) --> 0
2214   // ((X | Y) ^ Y ) & ((X | Y) ^ X) --> 0
2215   BinaryOperator *Or;
2216   if (match(Op0, m_c_Xor(m_Value(X),
2217                          m_CombineAnd(m_BinOp(Or),
2218                                       m_c_Or(m_Deferred(X), m_Value(Y))))) &&
2219       match(Op1, m_c_Xor(m_Specific(Or), m_Specific(Y))))
2220     return Constant::getNullValue(Op0->getType());
2221 
2222   return nullptr;
2223 }
2224 
2225 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2226   return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit);
2227 }
2228 
2229 static Value *simplifyOrLogic(Value *X, Value *Y) {
2230   assert(X->getType() == Y->getType() && "Expected same type for 'or' ops");
2231   Type *Ty = X->getType();
2232 
2233   // X | ~X --> -1
2234   if (match(Y, m_Not(m_Specific(X))))
2235     return ConstantInt::getAllOnesValue(Ty);
2236 
2237   // X | ~(X & ?) = -1
2238   if (match(Y, m_Not(m_c_And(m_Specific(X), m_Value()))))
2239     return ConstantInt::getAllOnesValue(Ty);
2240 
2241   // X | (X & ?) --> X
2242   if (match(Y, m_c_And(m_Specific(X), m_Value())))
2243     return X;
2244 
2245   Value *A, *B;
2246 
2247   // (A ^ B) | (A | B) --> A | B
2248   // (A ^ B) | (B | A) --> B | A
2249   if (match(X, m_Xor(m_Value(A), m_Value(B))) &&
2250       match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2251     return Y;
2252 
2253   // ~(A ^ B) | (A | B) --> -1
2254   // ~(A ^ B) | (B | A) --> -1
2255   if (match(X, m_Not(m_Xor(m_Value(A), m_Value(B)))) &&
2256       match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2257     return ConstantInt::getAllOnesValue(Ty);
2258 
2259   // (A & ~B) | (A ^ B) --> A ^ B
2260   // (~B & A) | (A ^ B) --> A ^ B
2261   // (A & ~B) | (B ^ A) --> B ^ A
2262   // (~B & A) | (B ^ A) --> B ^ A
2263   if (match(X, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2264       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2265     return Y;
2266 
2267   // (~A ^ B) | (A & B) --> ~A ^ B
2268   // (B ^ ~A) | (A & B) --> B ^ ~A
2269   // (~A ^ B) | (B & A) --> ~A ^ B
2270   // (B ^ ~A) | (B & A) --> B ^ ~A
2271   if (match(X, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2272       match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2273     return X;
2274 
2275   // (~A | B) | (A ^ B) --> -1
2276   // (~A | B) | (B ^ A) --> -1
2277   // (B | ~A) | (A ^ B) --> -1
2278   // (B | ~A) | (B ^ A) --> -1
2279   if (match(X, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2280       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2281     return ConstantInt::getAllOnesValue(Ty);
2282 
2283   // (~A & B) | ~(A | B) --> ~A
2284   // (~A & B) | ~(B | A) --> ~A
2285   // (B & ~A) | ~(A | B) --> ~A
2286   // (B & ~A) | ~(B | A) --> ~A
2287   Value *NotA;
2288   if (match(X,
2289             m_c_And(m_CombineAnd(m_Value(NotA), m_NotForbidUndef(m_Value(A))),
2290                     m_Value(B))) &&
2291       match(Y, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
2292     return NotA;
2293 
2294   // ~(A ^ B) | (A & B) --> ~(A ^ B)
2295   // ~(A ^ B) | (B & A) --> ~(A ^ B)
2296   Value *NotAB;
2297   if (match(X, m_CombineAnd(m_NotForbidUndef(m_Xor(m_Value(A), m_Value(B))),
2298                             m_Value(NotAB))) &&
2299       match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2300     return NotAB;
2301 
2302   // ~(A & B) | (A ^ B) --> ~(A & B)
2303   // ~(A & B) | (B ^ A) --> ~(A & B)
2304   if (match(X, m_CombineAnd(m_NotForbidUndef(m_And(m_Value(A), m_Value(B))),
2305                             m_Value(NotAB))) &&
2306       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2307     return NotAB;
2308 
2309   return nullptr;
2310 }
2311 
2312 /// Given operands for an Or, see if we can fold the result.
2313 /// If not, this returns null.
2314 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2315                              unsigned MaxRecurse) {
2316   if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
2317     return C;
2318 
2319   // X | poison -> poison
2320   if (isa<PoisonValue>(Op1))
2321     return Op1;
2322 
2323   // X | undef -> -1
2324   // X | -1 = -1
2325   // Do not return Op1 because it may contain undef elements if it's a vector.
2326   if (Q.isUndefValue(Op1) || match(Op1, m_AllOnes()))
2327     return Constant::getAllOnesValue(Op0->getType());
2328 
2329   // X | X = X
2330   // X | 0 = X
2331   if (Op0 == Op1 || match(Op1, m_Zero()))
2332     return Op0;
2333 
2334   if (Value *R = simplifyOrLogic(Op0, Op1))
2335     return R;
2336   if (Value *R = simplifyOrLogic(Op1, Op0))
2337     return R;
2338 
2339   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Or))
2340     return V;
2341 
2342   // Rotated -1 is still -1:
2343   // (-1 << X) | (-1 >> (C - X)) --> -1
2344   // (-1 >> X) | (-1 << (C - X)) --> -1
2345   // ...with C <= bitwidth (and commuted variants).
2346   Value *X, *Y;
2347   if ((match(Op0, m_Shl(m_AllOnes(), m_Value(X))) &&
2348        match(Op1, m_LShr(m_AllOnes(), m_Value(Y)))) ||
2349       (match(Op1, m_Shl(m_AllOnes(), m_Value(X))) &&
2350        match(Op0, m_LShr(m_AllOnes(), m_Value(Y))))) {
2351     const APInt *C;
2352     if ((match(X, m_Sub(m_APInt(C), m_Specific(Y))) ||
2353          match(Y, m_Sub(m_APInt(C), m_Specific(X)))) &&
2354         C->ule(X->getType()->getScalarSizeInBits())) {
2355       return ConstantInt::getAllOnesValue(X->getType());
2356     }
2357   }
2358 
2359   // A funnel shift (rotate) can be decomposed into simpler shifts. See if we
2360   // are mixing in another shift that is redundant with the funnel shift.
2361 
2362   // (fshl X, ?, Y) | (shl X, Y) --> fshl X, ?, Y
2363   // (shl X, Y) | (fshl X, ?, Y) --> fshl X, ?, Y
2364   if (match(Op0,
2365             m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
2366       match(Op1, m_Shl(m_Specific(X), m_Specific(Y))))
2367     return Op0;
2368   if (match(Op1,
2369             m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
2370       match(Op0, m_Shl(m_Specific(X), m_Specific(Y))))
2371     return Op1;
2372 
2373   // (fshr ?, X, Y) | (lshr X, Y) --> fshr ?, X, Y
2374   // (lshr X, Y) | (fshr ?, X, Y) --> fshr ?, X, Y
2375   if (match(Op0,
2376             m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
2377       match(Op1, m_LShr(m_Specific(X), m_Specific(Y))))
2378     return Op0;
2379   if (match(Op1,
2380             m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
2381       match(Op0, m_LShr(m_Specific(X), m_Specific(Y))))
2382     return Op1;
2383 
2384   if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
2385     return V;
2386 
2387   // If we have a multiplication overflow check that is being 'and'ed with a
2388   // check that one of the multipliers is not zero, we can omit the 'and', and
2389   // only keep the overflow check.
2390   if (isCheckForZeroAndMulWithOverflow(Op0, Op1, false))
2391     return Op1;
2392   if (isCheckForZeroAndMulWithOverflow(Op1, Op0, false))
2393     return Op0;
2394 
2395   // Try some generic simplifications for associative operations.
2396   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
2397                                           MaxRecurse))
2398     return V;
2399 
2400   // Or distributes over And.  Try some generic simplifications based on this.
2401   if (Value *V = expandCommutativeBinOp(Instruction::Or, Op0, Op1,
2402                                         Instruction::And, Q, MaxRecurse))
2403     return V;
2404 
2405   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2406     if (Op0->getType()->isIntOrIntVectorTy(1)) {
2407       // A | (A || B) -> A || B
2408       if (match(Op1, m_Select(m_Specific(Op0), m_One(), m_Value())))
2409         return Op1;
2410       else if (match(Op0, m_Select(m_Specific(Op1), m_One(), m_Value())))
2411         return Op0;
2412     }
2413     // If the operation is with the result of a select instruction, check
2414     // whether operating on either branch of the select always yields the same
2415     // value.
2416     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
2417                                          MaxRecurse))
2418       return V;
2419   }
2420 
2421   // (A & C1)|(B & C2)
2422   Value *A, *B;
2423   const APInt *C1, *C2;
2424   if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
2425       match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
2426     if (*C1 == ~*C2) {
2427       // (A & C1)|(B & C2)
2428       // If we have: ((V + N) & C1) | (V & C2)
2429       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2430       // replace with V+N.
2431       Value *N;
2432       if (C2->isMask() && // C2 == 0+1+
2433           match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
2434         // Add commutes, try both ways.
2435         if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2436           return A;
2437       }
2438       // Or commutes, try both ways.
2439       if (C1->isMask() &&
2440           match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
2441         // Add commutes, try both ways.
2442         if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2443           return B;
2444       }
2445     }
2446   }
2447 
2448   // If the operation is with the result of a phi instruction, check whether
2449   // operating on all incoming values of the phi always yields the same value.
2450   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2451     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2452       return V;
2453 
2454   return nullptr;
2455 }
2456 
2457 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2458   return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit);
2459 }
2460 
2461 /// Given operands for a Xor, see if we can fold the result.
2462 /// If not, this returns null.
2463 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2464                               unsigned MaxRecurse) {
2465   if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
2466     return C;
2467 
2468   // X ^ poison -> poison
2469   if (isa<PoisonValue>(Op1))
2470     return Op1;
2471 
2472   // A ^ undef -> undef
2473   if (Q.isUndefValue(Op1))
2474     return Op1;
2475 
2476   // A ^ 0 = A
2477   if (match(Op1, m_Zero()))
2478     return Op0;
2479 
2480   // A ^ A = 0
2481   if (Op0 == Op1)
2482     return Constant::getNullValue(Op0->getType());
2483 
2484   // A ^ ~A  =  ~A ^ A  =  -1
2485   if (match(Op0, m_Not(m_Specific(Op1))) ||
2486       match(Op1, m_Not(m_Specific(Op0))))
2487     return Constant::getAllOnesValue(Op0->getType());
2488 
2489   auto foldAndOrNot = [](Value *X, Value *Y) -> Value * {
2490     Value *A, *B;
2491     // (~A & B) ^ (A | B) --> A -- There are 8 commuted variants.
2492     if (match(X, m_c_And(m_Not(m_Value(A)), m_Value(B))) &&
2493         match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2494       return A;
2495 
2496     // (~A | B) ^ (A & B) --> ~A -- There are 8 commuted variants.
2497     // The 'not' op must contain a complete -1 operand (no undef elements for
2498     // vector) for the transform to be safe.
2499     Value *NotA;
2500     if (match(X,
2501               m_c_Or(m_CombineAnd(m_NotForbidUndef(m_Value(A)), m_Value(NotA)),
2502                      m_Value(B))) &&
2503         match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2504       return NotA;
2505 
2506     return nullptr;
2507   };
2508   if (Value *R = foldAndOrNot(Op0, Op1))
2509     return R;
2510   if (Value *R = foldAndOrNot(Op1, Op0))
2511     return R;
2512 
2513   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Xor))
2514     return V;
2515 
2516   // Try some generic simplifications for associative operations.
2517   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
2518                                           MaxRecurse))
2519     return V;
2520 
2521   // Threading Xor over selects and phi nodes is pointless, so don't bother.
2522   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2523   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2524   // only if B and C are equal.  If B and C are equal then (since we assume
2525   // that operands have already been simplified) "select(cond, B, C)" should
2526   // have been simplified to the common value of B and C already.  Analysing
2527   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
2528   // for threading over phi nodes.
2529 
2530   return nullptr;
2531 }
2532 
2533 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2534   return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit);
2535 }
2536 
2537 
2538 static Type *GetCompareTy(Value *Op) {
2539   return CmpInst::makeCmpResultType(Op->getType());
2540 }
2541 
2542 /// Rummage around inside V looking for something equivalent to the comparison
2543 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
2544 /// Helper function for analyzing max/min idioms.
2545 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2546                                          Value *LHS, Value *RHS) {
2547   SelectInst *SI = dyn_cast<SelectInst>(V);
2548   if (!SI)
2549     return nullptr;
2550   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2551   if (!Cmp)
2552     return nullptr;
2553   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2554   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2555     return Cmp;
2556   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2557       LHS == CmpRHS && RHS == CmpLHS)
2558     return Cmp;
2559   return nullptr;
2560 }
2561 
2562 /// Return true if the underlying object (storage) must be disjoint from
2563 /// storage returned by any noalias return call.
2564 static bool IsAllocDisjoint(const Value *V) {
2565   // For allocas, we consider only static ones (dynamic
2566   // allocas might be transformed into calls to malloc not simultaneously
2567   // live with the compared-to allocation). For globals, we exclude symbols
2568   // that might be resolve lazily to symbols in another dynamically-loaded
2569   // library (and, thus, could be malloc'ed by the implementation).
2570   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2571     return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2572   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2573     return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2574             GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2575       !GV->isThreadLocal();
2576   if (const Argument *A = dyn_cast<Argument>(V))
2577     return A->hasByValAttr();
2578   return false;
2579 }
2580 
2581 /// Return true if V1 and V2 are each the base of some distict storage region
2582 /// [V, object_size(V)] which do not overlap.  Note that zero sized regions
2583 /// *are* possible, and that zero sized regions do not overlap with any other.
2584 static bool HaveNonOverlappingStorage(const Value *V1, const Value *V2) {
2585   // Global variables always exist, so they always exist during the lifetime
2586   // of each other and all allocas.  Global variables themselves usually have
2587   // non-overlapping storage, but since their addresses are constants, the
2588   // case involving two globals does not reach here and is instead handled in
2589   // constant folding.
2590   //
2591   // Two different allocas usually have different addresses...
2592   //
2593   // However, if there's an @llvm.stackrestore dynamically in between two
2594   // allocas, they may have the same address. It's tempting to reduce the
2595   // scope of the problem by only looking at *static* allocas here. That would
2596   // cover the majority of allocas while significantly reducing the likelihood
2597   // of having an @llvm.stackrestore pop up in the middle. However, it's not
2598   // actually impossible for an @llvm.stackrestore to pop up in the middle of
2599   // an entry block. Also, if we have a block that's not attached to a
2600   // function, we can't tell if it's "static" under the current definition.
2601   // Theoretically, this problem could be fixed by creating a new kind of
2602   // instruction kind specifically for static allocas. Such a new instruction
2603   // could be required to be at the top of the entry block, thus preventing it
2604   // from being subject to a @llvm.stackrestore. Instcombine could even
2605   // convert regular allocas into these special allocas. It'd be nifty.
2606   // However, until then, this problem remains open.
2607   //
2608   // So, we'll assume that two non-empty allocas have different addresses
2609   // for now.
2610   auto isByValArg = [](const Value *V) {
2611     const Argument *A = dyn_cast<Argument>(V);
2612     return A && A->hasByValAttr();
2613   };
2614 
2615   // Byval args are backed by store which does not overlap with each other,
2616   // allocas, or globals.
2617   if (isByValArg(V1))
2618     return isa<AllocaInst>(V2) || isa<GlobalVariable>(V2) || isByValArg(V2);
2619   if (isByValArg(V2))
2620     return isa<AllocaInst>(V1) || isa<GlobalVariable>(V1) || isByValArg(V1);
2621 
2622  return isa<AllocaInst>(V1) &&
2623     (isa<AllocaInst>(V2) || isa<GlobalVariable>(V2));
2624 }
2625 
2626 // A significant optimization not implemented here is assuming that alloca
2627 // addresses are not equal to incoming argument values. They don't *alias*,
2628 // as we say, but that doesn't mean they aren't equal, so we take a
2629 // conservative approach.
2630 //
2631 // This is inspired in part by C++11 5.10p1:
2632 //   "Two pointers of the same type compare equal if and only if they are both
2633 //    null, both point to the same function, or both represent the same
2634 //    address."
2635 //
2636 // This is pretty permissive.
2637 //
2638 // It's also partly due to C11 6.5.9p6:
2639 //   "Two pointers compare equal if and only if both are null pointers, both are
2640 //    pointers to the same object (including a pointer to an object and a
2641 //    subobject at its beginning) or function, both are pointers to one past the
2642 //    last element of the same array object, or one is a pointer to one past the
2643 //    end of one array object and the other is a pointer to the start of a
2644 //    different array object that happens to immediately follow the first array
2645 //    object in the address space.)
2646 //
2647 // C11's version is more restrictive, however there's no reason why an argument
2648 // couldn't be a one-past-the-end value for a stack object in the caller and be
2649 // equal to the beginning of a stack object in the callee.
2650 //
2651 // If the C and C++ standards are ever made sufficiently restrictive in this
2652 // area, it may be possible to update LLVM's semantics accordingly and reinstate
2653 // this optimization.
2654 static Constant *
2655 computePointerICmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
2656                    const SimplifyQuery &Q) {
2657   const DataLayout &DL = Q.DL;
2658   const TargetLibraryInfo *TLI = Q.TLI;
2659   const DominatorTree *DT = Q.DT;
2660   const Instruction *CxtI = Q.CxtI;
2661   const InstrInfoQuery &IIQ = Q.IIQ;
2662 
2663   // First, skip past any trivial no-ops.
2664   LHS = LHS->stripPointerCasts();
2665   RHS = RHS->stripPointerCasts();
2666 
2667   // A non-null pointer is not equal to a null pointer.
2668   if (isa<ConstantPointerNull>(RHS) && ICmpInst::isEquality(Pred) &&
2669       llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
2670                            IIQ.UseInstrInfo))
2671     return ConstantInt::get(GetCompareTy(LHS),
2672                             !CmpInst::isTrueWhenEqual(Pred));
2673 
2674   // We can only fold certain predicates on pointer comparisons.
2675   switch (Pred) {
2676   default:
2677     return nullptr;
2678 
2679     // Equality comaprisons are easy to fold.
2680   case CmpInst::ICMP_EQ:
2681   case CmpInst::ICMP_NE:
2682     break;
2683 
2684     // We can only handle unsigned relational comparisons because 'inbounds' on
2685     // a GEP only protects against unsigned wrapping.
2686   case CmpInst::ICMP_UGT:
2687   case CmpInst::ICMP_UGE:
2688   case CmpInst::ICMP_ULT:
2689   case CmpInst::ICMP_ULE:
2690     // However, we have to switch them to their signed variants to handle
2691     // negative indices from the base pointer.
2692     Pred = ICmpInst::getSignedPredicate(Pred);
2693     break;
2694   }
2695 
2696   // Strip off any constant offsets so that we can reason about them.
2697   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2698   // here and compare base addresses like AliasAnalysis does, however there are
2699   // numerous hazards. AliasAnalysis and its utilities rely on special rules
2700   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2701   // doesn't need to guarantee pointer inequality when it says NoAlias.
2702 
2703   // Even if an non-inbounds GEP occurs along the path we can still optimize
2704   // equality comparisons concerning the result.
2705   bool AllowNonInbounds = ICmpInst::isEquality(Pred);
2706   APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS, AllowNonInbounds);
2707   APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS, AllowNonInbounds);
2708 
2709   // If LHS and RHS are related via constant offsets to the same base
2710   // value, we can replace it with an icmp which just compares the offsets.
2711   if (LHS == RHS)
2712     return ConstantInt::get(
2713         GetCompareTy(LHS), ICmpInst::compare(LHSOffset, RHSOffset, Pred));
2714 
2715   // Various optimizations for (in)equality comparisons.
2716   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2717     // Different non-empty allocations that exist at the same time have
2718     // different addresses (if the program can tell). If the offsets are
2719     // within the bounds of their allocations (and not one-past-the-end!
2720     // so we can't use inbounds!), and their allocations aren't the same,
2721     // the pointers are not equal.
2722     if (HaveNonOverlappingStorage(LHS, RHS)) {
2723       uint64_t LHSSize, RHSSize;
2724       ObjectSizeOpts Opts;
2725       Opts.EvalMode = ObjectSizeOpts::Mode::Min;
2726       auto *F = [](Value *V) {
2727         if (auto *I = dyn_cast<Instruction>(V))
2728           return I->getFunction();
2729         return cast<Argument>(V)->getParent();
2730       }(LHS);
2731       Opts.NullIsUnknownSize = NullPointerIsDefined(F);
2732       if (getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2733           getObjectSize(RHS, RHSSize, DL, TLI, Opts) &&
2734           !LHSOffset.isNegative() && !RHSOffset.isNegative() &&
2735           LHSOffset.ult(LHSSize) && RHSOffset.ult(RHSSize)) {
2736         return ConstantInt::get(GetCompareTy(LHS),
2737                                 !CmpInst::isTrueWhenEqual(Pred));
2738       }
2739     }
2740 
2741     // If one side of the equality comparison must come from a noalias call
2742     // (meaning a system memory allocation function), and the other side must
2743     // come from a pointer that cannot overlap with dynamically-allocated
2744     // memory within the lifetime of the current function (allocas, byval
2745     // arguments, globals), then determine the comparison result here.
2746     SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
2747     getUnderlyingObjects(LHS, LHSUObjs);
2748     getUnderlyingObjects(RHS, RHSUObjs);
2749 
2750     // Is the set of underlying objects all noalias calls?
2751     auto IsNAC = [](ArrayRef<const Value *> Objects) {
2752       return all_of(Objects, isNoAliasCall);
2753     };
2754 
2755     // Is the set of underlying objects all things which must be disjoint from
2756     // noalias calls.  We assume that indexing from such disjoint storage
2757     // into the heap is undefined, and thus offsets can be safely ignored.
2758     auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2759       return all_of(Objects, ::IsAllocDisjoint);
2760     };
2761 
2762     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2763         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2764         return ConstantInt::get(GetCompareTy(LHS),
2765                                 !CmpInst::isTrueWhenEqual(Pred));
2766 
2767     // Fold comparisons for non-escaping pointer even if the allocation call
2768     // cannot be elided. We cannot fold malloc comparison to null. Also, the
2769     // dynamic allocation call could be either of the operands.  Note that
2770     // the other operand can not be based on the alloc - if it were, then
2771     // the cmp itself would be a capture.
2772     Value *MI = nullptr;
2773     if (isAllocLikeFn(LHS, TLI) &&
2774         llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
2775       MI = LHS;
2776     else if (isAllocLikeFn(RHS, TLI) &&
2777              llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
2778       MI = RHS;
2779     // FIXME: We should also fold the compare when the pointer escapes, but the
2780     // compare dominates the pointer escape
2781     if (MI && !PointerMayBeCaptured(MI, true, true))
2782       return ConstantInt::get(GetCompareTy(LHS),
2783                               CmpInst::isFalseWhenEqual(Pred));
2784   }
2785 
2786   // Otherwise, fail.
2787   return nullptr;
2788 }
2789 
2790 /// Fold an icmp when its operands have i1 scalar type.
2791 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2792                                   Value *RHS, const SimplifyQuery &Q) {
2793   Type *ITy = GetCompareTy(LHS); // The return type.
2794   Type *OpTy = LHS->getType();   // The operand type.
2795   if (!OpTy->isIntOrIntVectorTy(1))
2796     return nullptr;
2797 
2798   // A boolean compared to true/false can be reduced in 14 out of the 20
2799   // (10 predicates * 2 constants) possible combinations. The other
2800   // 6 cases require a 'not' of the LHS.
2801 
2802   auto ExtractNotLHS = [](Value *V) -> Value * {
2803     Value *X;
2804     if (match(V, m_Not(m_Value(X))))
2805       return X;
2806     return nullptr;
2807   };
2808 
2809   if (match(RHS, m_Zero())) {
2810     switch (Pred) {
2811     case CmpInst::ICMP_NE:  // X !=  0 -> X
2812     case CmpInst::ICMP_UGT: // X >u  0 -> X
2813     case CmpInst::ICMP_SLT: // X <s  0 -> X
2814       return LHS;
2815 
2816     case CmpInst::ICMP_EQ:  // not(X) ==  0 -> X != 0 -> X
2817     case CmpInst::ICMP_ULE: // not(X) <=u 0 -> X >u 0 -> X
2818     case CmpInst::ICMP_SGE: // not(X) >=s 0 -> X <s 0 -> X
2819       if (Value *X = ExtractNotLHS(LHS))
2820         return X;
2821       break;
2822 
2823     case CmpInst::ICMP_ULT: // X <u  0 -> false
2824     case CmpInst::ICMP_SGT: // X >s  0 -> false
2825       return getFalse(ITy);
2826 
2827     case CmpInst::ICMP_UGE: // X >=u 0 -> true
2828     case CmpInst::ICMP_SLE: // X <=s 0 -> true
2829       return getTrue(ITy);
2830 
2831     default: break;
2832     }
2833   } else if (match(RHS, m_One())) {
2834     switch (Pred) {
2835     case CmpInst::ICMP_EQ:  // X ==   1 -> X
2836     case CmpInst::ICMP_UGE: // X >=u  1 -> X
2837     case CmpInst::ICMP_SLE: // X <=s -1 -> X
2838       return LHS;
2839 
2840     case CmpInst::ICMP_NE:  // not(X) !=  1 -> X ==   1 -> X
2841     case CmpInst::ICMP_ULT: // not(X) <=u 1 -> X >=u  1 -> X
2842     case CmpInst::ICMP_SGT: // not(X) >s  1 -> X <=s -1 -> X
2843       if (Value *X = ExtractNotLHS(LHS))
2844         return X;
2845       break;
2846 
2847     case CmpInst::ICMP_UGT: // X >u   1 -> false
2848     case CmpInst::ICMP_SLT: // X <s  -1 -> false
2849       return getFalse(ITy);
2850 
2851     case CmpInst::ICMP_ULE: // X <=u  1 -> true
2852     case CmpInst::ICMP_SGE: // X >=s -1 -> true
2853       return getTrue(ITy);
2854 
2855     default: break;
2856     }
2857   }
2858 
2859   switch (Pred) {
2860   default:
2861     break;
2862   case ICmpInst::ICMP_UGE:
2863     if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2864       return getTrue(ITy);
2865     break;
2866   case ICmpInst::ICMP_SGE:
2867     /// For signed comparison, the values for an i1 are 0 and -1
2868     /// respectively. This maps into a truth table of:
2869     /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
2870     ///  0  |  0  |  1 (0 >= 0)   |  1
2871     ///  0  |  1  |  1 (0 >= -1)  |  1
2872     ///  1  |  0  |  0 (-1 >= 0)  |  0
2873     ///  1  |  1  |  1 (-1 >= -1) |  1
2874     if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2875       return getTrue(ITy);
2876     break;
2877   case ICmpInst::ICMP_ULE:
2878     if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2879       return getTrue(ITy);
2880     break;
2881   }
2882 
2883   return nullptr;
2884 }
2885 
2886 /// Try hard to fold icmp with zero RHS because this is a common case.
2887 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2888                                    Value *RHS, const SimplifyQuery &Q) {
2889   if (!match(RHS, m_Zero()))
2890     return nullptr;
2891 
2892   Type *ITy = GetCompareTy(LHS); // The return type.
2893   switch (Pred) {
2894   default:
2895     llvm_unreachable("Unknown ICmp predicate!");
2896   case ICmpInst::ICMP_ULT:
2897     return getFalse(ITy);
2898   case ICmpInst::ICMP_UGE:
2899     return getTrue(ITy);
2900   case ICmpInst::ICMP_EQ:
2901   case ICmpInst::ICMP_ULE:
2902     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2903       return getFalse(ITy);
2904     break;
2905   case ICmpInst::ICMP_NE:
2906   case ICmpInst::ICMP_UGT:
2907     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2908       return getTrue(ITy);
2909     break;
2910   case ICmpInst::ICMP_SLT: {
2911     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2912     if (LHSKnown.isNegative())
2913       return getTrue(ITy);
2914     if (LHSKnown.isNonNegative())
2915       return getFalse(ITy);
2916     break;
2917   }
2918   case ICmpInst::ICMP_SLE: {
2919     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2920     if (LHSKnown.isNegative())
2921       return getTrue(ITy);
2922     if (LHSKnown.isNonNegative() &&
2923         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2924       return getFalse(ITy);
2925     break;
2926   }
2927   case ICmpInst::ICMP_SGE: {
2928     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2929     if (LHSKnown.isNegative())
2930       return getFalse(ITy);
2931     if (LHSKnown.isNonNegative())
2932       return getTrue(ITy);
2933     break;
2934   }
2935   case ICmpInst::ICMP_SGT: {
2936     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2937     if (LHSKnown.isNegative())
2938       return getFalse(ITy);
2939     if (LHSKnown.isNonNegative() &&
2940         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2941       return getTrue(ITy);
2942     break;
2943   }
2944   }
2945 
2946   return nullptr;
2947 }
2948 
2949 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2950                                        Value *RHS, const InstrInfoQuery &IIQ) {
2951   Type *ITy = GetCompareTy(RHS); // The return type.
2952 
2953   Value *X;
2954   // Sign-bit checks can be optimized to true/false after unsigned
2955   // floating-point casts:
2956   // icmp slt (bitcast (uitofp X)),  0 --> false
2957   // icmp sgt (bitcast (uitofp X)), -1 --> true
2958   if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
2959     if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
2960       return ConstantInt::getFalse(ITy);
2961     if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
2962       return ConstantInt::getTrue(ITy);
2963   }
2964 
2965   const APInt *C;
2966   if (!match(RHS, m_APIntAllowUndef(C)))
2967     return nullptr;
2968 
2969   // Rule out tautological comparisons (eg., ult 0 or uge 0).
2970   ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
2971   if (RHS_CR.isEmptySet())
2972     return ConstantInt::getFalse(ITy);
2973   if (RHS_CR.isFullSet())
2974     return ConstantInt::getTrue(ITy);
2975 
2976   ConstantRange LHS_CR =
2977       computeConstantRange(LHS, CmpInst::isSigned(Pred), IIQ.UseInstrInfo);
2978   if (!LHS_CR.isFullSet()) {
2979     if (RHS_CR.contains(LHS_CR))
2980       return ConstantInt::getTrue(ITy);
2981     if (RHS_CR.inverse().contains(LHS_CR))
2982       return ConstantInt::getFalse(ITy);
2983   }
2984 
2985   // (mul nuw/nsw X, MulC) != C --> true  (if C is not a multiple of MulC)
2986   // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC)
2987   const APInt *MulC;
2988   if (ICmpInst::isEquality(Pred) &&
2989       ((match(LHS, m_NUWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
2990         *MulC != 0 && C->urem(*MulC) != 0) ||
2991        (match(LHS, m_NSWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
2992         *MulC != 0 && C->srem(*MulC) != 0)))
2993     return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE);
2994 
2995   return nullptr;
2996 }
2997 
2998 static Value *simplifyICmpWithBinOpOnLHS(
2999     CmpInst::Predicate Pred, BinaryOperator *LBO, Value *RHS,
3000     const SimplifyQuery &Q, unsigned MaxRecurse) {
3001   Type *ITy = GetCompareTy(RHS); // The return type.
3002 
3003   Value *Y = nullptr;
3004   // icmp pred (or X, Y), X
3005   if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
3006     if (Pred == ICmpInst::ICMP_ULT)
3007       return getFalse(ITy);
3008     if (Pred == ICmpInst::ICMP_UGE)
3009       return getTrue(ITy);
3010 
3011     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
3012       KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3013       KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3014       if (RHSKnown.isNonNegative() && YKnown.isNegative())
3015         return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
3016       if (RHSKnown.isNegative() || YKnown.isNonNegative())
3017         return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
3018     }
3019   }
3020 
3021   // icmp pred (and X, Y), X
3022   if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
3023     if (Pred == ICmpInst::ICMP_UGT)
3024       return getFalse(ITy);
3025     if (Pred == ICmpInst::ICMP_ULE)
3026       return getTrue(ITy);
3027   }
3028 
3029   // icmp pred (urem X, Y), Y
3030   if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
3031     switch (Pred) {
3032     default:
3033       break;
3034     case ICmpInst::ICMP_SGT:
3035     case ICmpInst::ICMP_SGE: {
3036       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3037       if (!Known.isNonNegative())
3038         break;
3039       LLVM_FALLTHROUGH;
3040     }
3041     case ICmpInst::ICMP_EQ:
3042     case ICmpInst::ICMP_UGT:
3043     case ICmpInst::ICMP_UGE:
3044       return getFalse(ITy);
3045     case ICmpInst::ICMP_SLT:
3046     case ICmpInst::ICMP_SLE: {
3047       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3048       if (!Known.isNonNegative())
3049         break;
3050       LLVM_FALLTHROUGH;
3051     }
3052     case ICmpInst::ICMP_NE:
3053     case ICmpInst::ICMP_ULT:
3054     case ICmpInst::ICMP_ULE:
3055       return getTrue(ITy);
3056     }
3057   }
3058 
3059   // icmp pred (urem X, Y), X
3060   if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) {
3061     if (Pred == ICmpInst::ICMP_ULE)
3062       return getTrue(ITy);
3063     if (Pred == ICmpInst::ICMP_UGT)
3064       return getFalse(ITy);
3065   }
3066 
3067   // x >>u y <=u x --> true.
3068   // x >>u y >u  x --> false.
3069   // x udiv y <=u x --> true.
3070   // x udiv y >u  x --> false.
3071   if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
3072       match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
3073     // icmp pred (X op Y), X
3074     if (Pred == ICmpInst::ICMP_UGT)
3075       return getFalse(ITy);
3076     if (Pred == ICmpInst::ICMP_ULE)
3077       return getTrue(ITy);
3078   }
3079 
3080   // If x is nonzero:
3081   // x >>u C <u  x --> true  for C != 0.
3082   // x >>u C !=  x --> true  for C != 0.
3083   // x >>u C >=u x --> false for C != 0.
3084   // x >>u C ==  x --> false for C != 0.
3085   // x udiv C <u  x --> true  for C != 1.
3086   // x udiv C !=  x --> true  for C != 1.
3087   // x udiv C >=u x --> false for C != 1.
3088   // x udiv C ==  x --> false for C != 1.
3089   // TODO: allow non-constant shift amount/divisor
3090   const APInt *C;
3091   if ((match(LBO, m_LShr(m_Specific(RHS), m_APInt(C))) && *C != 0) ||
3092       (match(LBO, m_UDiv(m_Specific(RHS), m_APInt(C))) && *C != 1)) {
3093     if (isKnownNonZero(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) {
3094       switch (Pred) {
3095       default:
3096         break;
3097       case ICmpInst::ICMP_EQ:
3098       case ICmpInst::ICMP_UGE:
3099         return getFalse(ITy);
3100       case ICmpInst::ICMP_NE:
3101       case ICmpInst::ICMP_ULT:
3102         return getTrue(ITy);
3103       case ICmpInst::ICMP_UGT:
3104       case ICmpInst::ICMP_ULE:
3105         // UGT/ULE are handled by the more general case just above
3106         llvm_unreachable("Unexpected UGT/ULE, should have been handled");
3107       }
3108     }
3109   }
3110 
3111   // (x*C1)/C2 <= x for C1 <= C2.
3112   // This holds even if the multiplication overflows: Assume that x != 0 and
3113   // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and
3114   // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x.
3115   //
3116   // Additionally, either the multiplication and division might be represented
3117   // as shifts:
3118   // (x*C1)>>C2 <= x for C1 < 2**C2.
3119   // (x<<C1)/C2 <= x for 2**C1 < C2.
3120   const APInt *C1, *C2;
3121   if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3122        C1->ule(*C2)) ||
3123       (match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3124        C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) ||
3125       (match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3126        (APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) {
3127     if (Pred == ICmpInst::ICMP_UGT)
3128       return getFalse(ITy);
3129     if (Pred == ICmpInst::ICMP_ULE)
3130       return getTrue(ITy);
3131   }
3132 
3133   return nullptr;
3134 }
3135 
3136 
3137 // If only one of the icmp's operands has NSW flags, try to prove that:
3138 //
3139 //   icmp slt (x + C1), (x +nsw C2)
3140 //
3141 // is equivalent to:
3142 //
3143 //   icmp slt C1, C2
3144 //
3145 // which is true if x + C2 has the NSW flags set and:
3146 // *) C1 < C2 && C1 >= 0, or
3147 // *) C2 < C1 && C1 <= 0.
3148 //
3149 static bool trySimplifyICmpWithAdds(CmpInst::Predicate Pred, Value *LHS,
3150                                     Value *RHS) {
3151   // TODO: only support icmp slt for now.
3152   if (Pred != CmpInst::ICMP_SLT)
3153     return false;
3154 
3155   // Canonicalize nsw add as RHS.
3156   if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3157     std::swap(LHS, RHS);
3158   if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3159     return false;
3160 
3161   Value *X;
3162   const APInt *C1, *C2;
3163   if (!match(LHS, m_c_Add(m_Value(X), m_APInt(C1))) ||
3164       !match(RHS, m_c_Add(m_Specific(X), m_APInt(C2))))
3165     return false;
3166 
3167   return (C1->slt(*C2) && C1->isNonNegative()) ||
3168          (C2->slt(*C1) && C1->isNonPositive());
3169 }
3170 
3171 
3172 /// TODO: A large part of this logic is duplicated in InstCombine's
3173 /// foldICmpBinOp(). We should be able to share that and avoid the code
3174 /// duplication.
3175 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
3176                                     Value *RHS, const SimplifyQuery &Q,
3177                                     unsigned MaxRecurse) {
3178   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
3179   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
3180   if (MaxRecurse && (LBO || RBO)) {
3181     // Analyze the case when either LHS or RHS is an add instruction.
3182     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3183     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
3184     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
3185     if (LBO && LBO->getOpcode() == Instruction::Add) {
3186       A = LBO->getOperand(0);
3187       B = LBO->getOperand(1);
3188       NoLHSWrapProblem =
3189           ICmpInst::isEquality(Pred) ||
3190           (CmpInst::isUnsigned(Pred) &&
3191            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
3192           (CmpInst::isSigned(Pred) &&
3193            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
3194     }
3195     if (RBO && RBO->getOpcode() == Instruction::Add) {
3196       C = RBO->getOperand(0);
3197       D = RBO->getOperand(1);
3198       NoRHSWrapProblem =
3199           ICmpInst::isEquality(Pred) ||
3200           (CmpInst::isUnsigned(Pred) &&
3201            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
3202           (CmpInst::isSigned(Pred) &&
3203            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
3204     }
3205 
3206     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3207     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
3208       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
3209                                       Constant::getNullValue(RHS->getType()), Q,
3210                                       MaxRecurse - 1))
3211         return V;
3212 
3213     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3214     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
3215       if (Value *V =
3216               SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
3217                                C == LHS ? D : C, Q, MaxRecurse - 1))
3218         return V;
3219 
3220     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
3221     bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) ||
3222                        trySimplifyICmpWithAdds(Pred, LHS, RHS);
3223     if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) {
3224       // Determine Y and Z in the form icmp (X+Y), (X+Z).
3225       Value *Y, *Z;
3226       if (A == C) {
3227         // C + B == C + D  ->  B == D
3228         Y = B;
3229         Z = D;
3230       } else if (A == D) {
3231         // D + B == C + D  ->  B == C
3232         Y = B;
3233         Z = C;
3234       } else if (B == C) {
3235         // A + C == C + D  ->  A == D
3236         Y = A;
3237         Z = D;
3238       } else {
3239         assert(B == D);
3240         // A + D == C + D  ->  A == C
3241         Y = A;
3242         Z = C;
3243       }
3244       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
3245         return V;
3246     }
3247   }
3248 
3249   if (LBO)
3250     if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse))
3251       return V;
3252 
3253   if (RBO)
3254     if (Value *V = simplifyICmpWithBinOpOnLHS(
3255             ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse))
3256       return V;
3257 
3258   // 0 - (zext X) pred C
3259   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
3260     const APInt *C;
3261     if (match(RHS, m_APInt(C))) {
3262       if (C->isStrictlyPositive()) {
3263         if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE)
3264           return ConstantInt::getTrue(GetCompareTy(RHS));
3265         if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ)
3266           return ConstantInt::getFalse(GetCompareTy(RHS));
3267       }
3268       if (C->isNonNegative()) {
3269         if (Pred == ICmpInst::ICMP_SLE)
3270           return ConstantInt::getTrue(GetCompareTy(RHS));
3271         if (Pred == ICmpInst::ICMP_SGT)
3272           return ConstantInt::getFalse(GetCompareTy(RHS));
3273       }
3274     }
3275   }
3276 
3277   //   If C2 is a power-of-2 and C is not:
3278   //   (C2 << X) == C --> false
3279   //   (C2 << X) != C --> true
3280   const APInt *C;
3281   if (match(LHS, m_Shl(m_Power2(), m_Value())) &&
3282       match(RHS, m_APIntAllowUndef(C)) && !C->isPowerOf2()) {
3283     // C2 << X can equal zero in some circumstances.
3284     // This simplification might be unsafe if C is zero.
3285     //
3286     // We know it is safe if:
3287     // - The shift is nsw. We can't shift out the one bit.
3288     // - The shift is nuw. We can't shift out the one bit.
3289     // - C2 is one.
3290     // - C isn't zero.
3291     if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3292         Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3293         match(LHS, m_Shl(m_One(), m_Value())) || !C->isZero()) {
3294       if (Pred == ICmpInst::ICMP_EQ)
3295         return ConstantInt::getFalse(GetCompareTy(RHS));
3296       if (Pred == ICmpInst::ICMP_NE)
3297         return ConstantInt::getTrue(GetCompareTy(RHS));
3298     }
3299   }
3300 
3301   // TODO: This is overly constrained. LHS can be any power-of-2.
3302   // (1 << X)  >u 0x8000 --> false
3303   // (1 << X) <=u 0x8000 --> true
3304   if (match(LHS, m_Shl(m_One(), m_Value())) && match(RHS, m_SignMask())) {
3305     if (Pred == ICmpInst::ICMP_UGT)
3306       return ConstantInt::getFalse(GetCompareTy(RHS));
3307     if (Pred == ICmpInst::ICMP_ULE)
3308       return ConstantInt::getTrue(GetCompareTy(RHS));
3309   }
3310 
3311   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
3312       LBO->getOperand(1) == RBO->getOperand(1)) {
3313     switch (LBO->getOpcode()) {
3314     default:
3315       break;
3316     case Instruction::UDiv:
3317     case Instruction::LShr:
3318       if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
3319           !Q.IIQ.isExact(RBO))
3320         break;
3321       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3322                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3323           return V;
3324       break;
3325     case Instruction::SDiv:
3326       if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
3327           !Q.IIQ.isExact(RBO))
3328         break;
3329       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3330                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3331         return V;
3332       break;
3333     case Instruction::AShr:
3334       if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
3335         break;
3336       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3337                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3338         return V;
3339       break;
3340     case Instruction::Shl: {
3341       bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3342       bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
3343       if (!NUW && !NSW)
3344         break;
3345       if (!NSW && ICmpInst::isSigned(Pred))
3346         break;
3347       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3348                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3349         return V;
3350       break;
3351     }
3352     }
3353   }
3354   return nullptr;
3355 }
3356 
3357 /// Simplify integer comparisons where at least one operand of the compare
3358 /// matches an integer min/max idiom.
3359 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
3360                                      Value *RHS, const SimplifyQuery &Q,
3361                                      unsigned MaxRecurse) {
3362   Type *ITy = GetCompareTy(LHS); // The return type.
3363   Value *A, *B;
3364   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
3365   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
3366 
3367   // Signed variants on "max(a,b)>=a -> true".
3368   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3369     if (A != RHS)
3370       std::swap(A, B);       // smax(A, B) pred A.
3371     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3372     // We analyze this as smax(A, B) pred A.
3373     P = Pred;
3374   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
3375              (A == LHS || B == LHS)) {
3376     if (A != LHS)
3377       std::swap(A, B);       // A pred smax(A, B).
3378     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3379     // We analyze this as smax(A, B) swapped-pred A.
3380     P = CmpInst::getSwappedPredicate(Pred);
3381   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3382              (A == RHS || B == RHS)) {
3383     if (A != RHS)
3384       std::swap(A, B);       // smin(A, B) pred A.
3385     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3386     // We analyze this as smax(-A, -B) swapped-pred -A.
3387     // Note that we do not need to actually form -A or -B thanks to EqP.
3388     P = CmpInst::getSwappedPredicate(Pred);
3389   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
3390              (A == LHS || B == LHS)) {
3391     if (A != LHS)
3392       std::swap(A, B);       // A pred smin(A, B).
3393     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3394     // We analyze this as smax(-A, -B) pred -A.
3395     // Note that we do not need to actually form -A or -B thanks to EqP.
3396     P = Pred;
3397   }
3398   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3399     // Cases correspond to "max(A, B) p A".
3400     switch (P) {
3401     default:
3402       break;
3403     case CmpInst::ICMP_EQ:
3404     case CmpInst::ICMP_SLE:
3405       // Equivalent to "A EqP B".  This may be the same as the condition tested
3406       // in the max/min; if so, we can just return that.
3407       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3408         return V;
3409       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3410         return V;
3411       // Otherwise, see if "A EqP B" simplifies.
3412       if (MaxRecurse)
3413         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3414           return V;
3415       break;
3416     case CmpInst::ICMP_NE:
3417     case CmpInst::ICMP_SGT: {
3418       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3419       // Equivalent to "A InvEqP B".  This may be the same as the condition
3420       // tested in the max/min; if so, we can just return that.
3421       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3422         return V;
3423       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3424         return V;
3425       // Otherwise, see if "A InvEqP B" simplifies.
3426       if (MaxRecurse)
3427         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3428           return V;
3429       break;
3430     }
3431     case CmpInst::ICMP_SGE:
3432       // Always true.
3433       return getTrue(ITy);
3434     case CmpInst::ICMP_SLT:
3435       // Always false.
3436       return getFalse(ITy);
3437     }
3438   }
3439 
3440   // Unsigned variants on "max(a,b)>=a -> true".
3441   P = CmpInst::BAD_ICMP_PREDICATE;
3442   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3443     if (A != RHS)
3444       std::swap(A, B);       // umax(A, B) pred A.
3445     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3446     // We analyze this as umax(A, B) pred A.
3447     P = Pred;
3448   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3449              (A == LHS || B == LHS)) {
3450     if (A != LHS)
3451       std::swap(A, B);       // A pred umax(A, B).
3452     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3453     // We analyze this as umax(A, B) swapped-pred A.
3454     P = CmpInst::getSwappedPredicate(Pred);
3455   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3456              (A == RHS || B == RHS)) {
3457     if (A != RHS)
3458       std::swap(A, B);       // umin(A, B) pred A.
3459     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3460     // We analyze this as umax(-A, -B) swapped-pred -A.
3461     // Note that we do not need to actually form -A or -B thanks to EqP.
3462     P = CmpInst::getSwappedPredicate(Pred);
3463   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3464              (A == LHS || B == LHS)) {
3465     if (A != LHS)
3466       std::swap(A, B);       // A pred umin(A, B).
3467     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3468     // We analyze this as umax(-A, -B) pred -A.
3469     // Note that we do not need to actually form -A or -B thanks to EqP.
3470     P = Pred;
3471   }
3472   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3473     // Cases correspond to "max(A, B) p A".
3474     switch (P) {
3475     default:
3476       break;
3477     case CmpInst::ICMP_EQ:
3478     case CmpInst::ICMP_ULE:
3479       // Equivalent to "A EqP B".  This may be the same as the condition tested
3480       // in the max/min; if so, we can just return that.
3481       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3482         return V;
3483       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3484         return V;
3485       // Otherwise, see if "A EqP B" simplifies.
3486       if (MaxRecurse)
3487         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3488           return V;
3489       break;
3490     case CmpInst::ICMP_NE:
3491     case CmpInst::ICMP_UGT: {
3492       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3493       // Equivalent to "A InvEqP B".  This may be the same as the condition
3494       // tested in the max/min; if so, we can just return that.
3495       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3496         return V;
3497       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3498         return V;
3499       // Otherwise, see if "A InvEqP B" simplifies.
3500       if (MaxRecurse)
3501         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3502           return V;
3503       break;
3504     }
3505     case CmpInst::ICMP_UGE:
3506       return getTrue(ITy);
3507     case CmpInst::ICMP_ULT:
3508       return getFalse(ITy);
3509     }
3510   }
3511 
3512   // Comparing 1 each of min/max with a common operand?
3513   // Canonicalize min operand to RHS.
3514   if (match(LHS, m_UMin(m_Value(), m_Value())) ||
3515       match(LHS, m_SMin(m_Value(), m_Value()))) {
3516     std::swap(LHS, RHS);
3517     Pred = ICmpInst::getSwappedPredicate(Pred);
3518   }
3519 
3520   Value *C, *D;
3521   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3522       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3523       (A == C || A == D || B == C || B == D)) {
3524     // smax(A, B) >=s smin(A, D) --> true
3525     if (Pred == CmpInst::ICMP_SGE)
3526       return getTrue(ITy);
3527     // smax(A, B) <s smin(A, D) --> false
3528     if (Pred == CmpInst::ICMP_SLT)
3529       return getFalse(ITy);
3530   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3531              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3532              (A == C || A == D || B == C || B == D)) {
3533     // umax(A, B) >=u umin(A, D) --> true
3534     if (Pred == CmpInst::ICMP_UGE)
3535       return getTrue(ITy);
3536     // umax(A, B) <u umin(A, D) --> false
3537     if (Pred == CmpInst::ICMP_ULT)
3538       return getFalse(ITy);
3539   }
3540 
3541   return nullptr;
3542 }
3543 
3544 static Value *simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate,
3545                                                Value *LHS, Value *RHS,
3546                                                const SimplifyQuery &Q) {
3547   // Gracefully handle instructions that have not been inserted yet.
3548   if (!Q.AC || !Q.CxtI || !Q.CxtI->getParent())
3549     return nullptr;
3550 
3551   for (Value *AssumeBaseOp : {LHS, RHS}) {
3552     for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) {
3553       if (!AssumeVH)
3554         continue;
3555 
3556       CallInst *Assume = cast<CallInst>(AssumeVH);
3557       if (Optional<bool> Imp =
3558               isImpliedCondition(Assume->getArgOperand(0), Predicate, LHS, RHS,
3559                                  Q.DL))
3560         if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT))
3561           return ConstantInt::get(GetCompareTy(LHS), *Imp);
3562     }
3563   }
3564 
3565   return nullptr;
3566 }
3567 
3568 /// Given operands for an ICmpInst, see if we can fold the result.
3569 /// If not, this returns null.
3570 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3571                                const SimplifyQuery &Q, unsigned MaxRecurse) {
3572   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3573   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3574 
3575   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3576     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3577       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3578 
3579     // If we have a constant, make sure it is on the RHS.
3580     std::swap(LHS, RHS);
3581     Pred = CmpInst::getSwappedPredicate(Pred);
3582   }
3583   assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3584 
3585   Type *ITy = GetCompareTy(LHS); // The return type.
3586 
3587   // icmp poison, X -> poison
3588   if (isa<PoisonValue>(RHS))
3589     return PoisonValue::get(ITy);
3590 
3591   // For EQ and NE, we can always pick a value for the undef to make the
3592   // predicate pass or fail, so we can return undef.
3593   // Matches behavior in llvm::ConstantFoldCompareInstruction.
3594   if (Q.isUndefValue(RHS) && ICmpInst::isEquality(Pred))
3595     return UndefValue::get(ITy);
3596 
3597   // icmp X, X -> true/false
3598   // icmp X, undef -> true/false because undef could be X.
3599   if (LHS == RHS || Q.isUndefValue(RHS))
3600     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3601 
3602   if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3603     return V;
3604 
3605   // TODO: Sink/common this with other potentially expensive calls that use
3606   //       ValueTracking? See comment below for isKnownNonEqual().
3607   if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3608     return V;
3609 
3610   if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
3611     return V;
3612 
3613   // If both operands have range metadata, use the metadata
3614   // to simplify the comparison.
3615   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3616     auto RHS_Instr = cast<Instruction>(RHS);
3617     auto LHS_Instr = cast<Instruction>(LHS);
3618 
3619     if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3620         Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
3621       auto RHS_CR = getConstantRangeFromMetadata(
3622           *RHS_Instr->getMetadata(LLVMContext::MD_range));
3623       auto LHS_CR = getConstantRangeFromMetadata(
3624           *LHS_Instr->getMetadata(LLVMContext::MD_range));
3625 
3626       if (LHS_CR.icmp(Pred, RHS_CR))
3627         return ConstantInt::getTrue(RHS->getContext());
3628 
3629       if (LHS_CR.icmp(CmpInst::getInversePredicate(Pred), RHS_CR))
3630         return ConstantInt::getFalse(RHS->getContext());
3631     }
3632   }
3633 
3634   // Compare of cast, for example (zext X) != 0 -> X != 0
3635   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3636     Instruction *LI = cast<CastInst>(LHS);
3637     Value *SrcOp = LI->getOperand(0);
3638     Type *SrcTy = SrcOp->getType();
3639     Type *DstTy = LI->getType();
3640 
3641     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3642     // if the integer type is the same size as the pointer type.
3643     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3644         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3645       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3646         // Transfer the cast to the constant.
3647         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3648                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
3649                                         Q, MaxRecurse-1))
3650           return V;
3651       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3652         if (RI->getOperand(0)->getType() == SrcTy)
3653           // Compare without the cast.
3654           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3655                                           Q, MaxRecurse-1))
3656             return V;
3657       }
3658     }
3659 
3660     if (isa<ZExtInst>(LHS)) {
3661       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3662       // same type.
3663       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3664         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3665           // Compare X and Y.  Note that signed predicates become unsigned.
3666           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3667                                           SrcOp, RI->getOperand(0), Q,
3668                                           MaxRecurse-1))
3669             return V;
3670       }
3671       // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true.
3672       else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3673         if (SrcOp == RI->getOperand(0)) {
3674           if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE)
3675             return ConstantInt::getTrue(ITy);
3676           if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT)
3677             return ConstantInt::getFalse(ITy);
3678         }
3679       }
3680       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3681       // too.  If not, then try to deduce the result of the comparison.
3682       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3683         // Compute the constant that would happen if we truncated to SrcTy then
3684         // reextended to DstTy.
3685         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3686         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3687 
3688         // If the re-extended constant didn't change then this is effectively
3689         // also a case of comparing two zero-extended values.
3690         if (RExt == CI && MaxRecurse)
3691           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3692                                         SrcOp, Trunc, Q, MaxRecurse-1))
3693             return V;
3694 
3695         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3696         // there.  Use this to work out the result of the comparison.
3697         if (RExt != CI) {
3698           switch (Pred) {
3699           default: llvm_unreachable("Unknown ICmp predicate!");
3700           // LHS <u RHS.
3701           case ICmpInst::ICMP_EQ:
3702           case ICmpInst::ICMP_UGT:
3703           case ICmpInst::ICMP_UGE:
3704             return ConstantInt::getFalse(CI->getContext());
3705 
3706           case ICmpInst::ICMP_NE:
3707           case ICmpInst::ICMP_ULT:
3708           case ICmpInst::ICMP_ULE:
3709             return ConstantInt::getTrue(CI->getContext());
3710 
3711           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
3712           // is non-negative then LHS <s RHS.
3713           case ICmpInst::ICMP_SGT:
3714           case ICmpInst::ICMP_SGE:
3715             return CI->getValue().isNegative() ?
3716               ConstantInt::getTrue(CI->getContext()) :
3717               ConstantInt::getFalse(CI->getContext());
3718 
3719           case ICmpInst::ICMP_SLT:
3720           case ICmpInst::ICMP_SLE:
3721             return CI->getValue().isNegative() ?
3722               ConstantInt::getFalse(CI->getContext()) :
3723               ConstantInt::getTrue(CI->getContext());
3724           }
3725         }
3726       }
3727     }
3728 
3729     if (isa<SExtInst>(LHS)) {
3730       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3731       // same type.
3732       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3733         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3734           // Compare X and Y.  Note that the predicate does not change.
3735           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3736                                           Q, MaxRecurse-1))
3737             return V;
3738       }
3739       // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true.
3740       else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3741         if (SrcOp == RI->getOperand(0)) {
3742           if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE)
3743             return ConstantInt::getTrue(ITy);
3744           if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT)
3745             return ConstantInt::getFalse(ITy);
3746         }
3747       }
3748       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3749       // too.  If not, then try to deduce the result of the comparison.
3750       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3751         // Compute the constant that would happen if we truncated to SrcTy then
3752         // reextended to DstTy.
3753         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3754         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3755 
3756         // If the re-extended constant didn't change then this is effectively
3757         // also a case of comparing two sign-extended values.
3758         if (RExt == CI && MaxRecurse)
3759           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
3760             return V;
3761 
3762         // Otherwise the upper bits of LHS are all equal, while RHS has varying
3763         // bits there.  Use this to work out the result of the comparison.
3764         if (RExt != CI) {
3765           switch (Pred) {
3766           default: llvm_unreachable("Unknown ICmp predicate!");
3767           case ICmpInst::ICMP_EQ:
3768             return ConstantInt::getFalse(CI->getContext());
3769           case ICmpInst::ICMP_NE:
3770             return ConstantInt::getTrue(CI->getContext());
3771 
3772           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
3773           // LHS >s RHS.
3774           case ICmpInst::ICMP_SGT:
3775           case ICmpInst::ICMP_SGE:
3776             return CI->getValue().isNegative() ?
3777               ConstantInt::getTrue(CI->getContext()) :
3778               ConstantInt::getFalse(CI->getContext());
3779           case ICmpInst::ICMP_SLT:
3780           case ICmpInst::ICMP_SLE:
3781             return CI->getValue().isNegative() ?
3782               ConstantInt::getFalse(CI->getContext()) :
3783               ConstantInt::getTrue(CI->getContext());
3784 
3785           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
3786           // LHS >u RHS.
3787           case ICmpInst::ICMP_UGT:
3788           case ICmpInst::ICMP_UGE:
3789             // Comparison is true iff the LHS <s 0.
3790             if (MaxRecurse)
3791               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3792                                               Constant::getNullValue(SrcTy),
3793                                               Q, MaxRecurse-1))
3794                 return V;
3795             break;
3796           case ICmpInst::ICMP_ULT:
3797           case ICmpInst::ICMP_ULE:
3798             // Comparison is true iff the LHS >=s 0.
3799             if (MaxRecurse)
3800               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3801                                               Constant::getNullValue(SrcTy),
3802                                               Q, MaxRecurse-1))
3803                 return V;
3804             break;
3805           }
3806         }
3807       }
3808     }
3809   }
3810 
3811   // icmp eq|ne X, Y -> false|true if X != Y
3812   // This is potentially expensive, and we have already computedKnownBits for
3813   // compares with 0 above here, so only try this for a non-zero compare.
3814   if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) &&
3815       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
3816     return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
3817   }
3818 
3819   if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3820     return V;
3821 
3822   if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
3823     return V;
3824 
3825   if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q))
3826     return V;
3827 
3828   // Simplify comparisons of related pointers using a powerful, recursive
3829   // GEP-walk when we have target data available..
3830   if (LHS->getType()->isPointerTy())
3831     if (auto *C = computePointerICmp(Pred, LHS, RHS, Q))
3832       return C;
3833   if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3834     if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3835       if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3836               Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3837           Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3838               Q.DL.getTypeSizeInBits(CRHS->getType()))
3839         if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(),
3840                                          CRHS->getPointerOperand(), Q))
3841           return C;
3842 
3843   // If the comparison is with the result of a select instruction, check whether
3844   // comparing with either branch of the select always yields the same value.
3845   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3846     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3847       return V;
3848 
3849   // If the comparison is with the result of a phi instruction, check whether
3850   // doing the compare with each incoming phi value yields a common result.
3851   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3852     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3853       return V;
3854 
3855   return nullptr;
3856 }
3857 
3858 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3859                               const SimplifyQuery &Q) {
3860   return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3861 }
3862 
3863 /// Given operands for an FCmpInst, see if we can fold the result.
3864 /// If not, this returns null.
3865 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3866                                FastMathFlags FMF, const SimplifyQuery &Q,
3867                                unsigned MaxRecurse) {
3868   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3869   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3870 
3871   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3872     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3873       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3874 
3875     // If we have a constant, make sure it is on the RHS.
3876     std::swap(LHS, RHS);
3877     Pred = CmpInst::getSwappedPredicate(Pred);
3878   }
3879 
3880   // Fold trivial predicates.
3881   Type *RetTy = GetCompareTy(LHS);
3882   if (Pred == FCmpInst::FCMP_FALSE)
3883     return getFalse(RetTy);
3884   if (Pred == FCmpInst::FCMP_TRUE)
3885     return getTrue(RetTy);
3886 
3887   // Fold (un)ordered comparison if we can determine there are no NaNs.
3888   if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3889     if (FMF.noNaNs() ||
3890         (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
3891       return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
3892 
3893   // NaN is unordered; NaN is not ordered.
3894   assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3895          "Comparison must be either ordered or unordered");
3896   if (match(RHS, m_NaN()))
3897     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3898 
3899   // fcmp pred x, poison and  fcmp pred poison, x
3900   // fold to poison
3901   if (isa<PoisonValue>(LHS) || isa<PoisonValue>(RHS))
3902     return PoisonValue::get(RetTy);
3903 
3904   // fcmp pred x, undef  and  fcmp pred undef, x
3905   // fold to true if unordered, false if ordered
3906   if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) {
3907     // Choosing NaN for the undef will always make unordered comparison succeed
3908     // and ordered comparison fail.
3909     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3910   }
3911 
3912   // fcmp x,x -> true/false.  Not all compares are foldable.
3913   if (LHS == RHS) {
3914     if (CmpInst::isTrueWhenEqual(Pred))
3915       return getTrue(RetTy);
3916     if (CmpInst::isFalseWhenEqual(Pred))
3917       return getFalse(RetTy);
3918   }
3919 
3920   // Handle fcmp with constant RHS.
3921   // TODO: Use match with a specific FP value, so these work with vectors with
3922   // undef lanes.
3923   const APFloat *C;
3924   if (match(RHS, m_APFloat(C))) {
3925     // Check whether the constant is an infinity.
3926     if (C->isInfinity()) {
3927       if (C->isNegative()) {
3928         switch (Pred) {
3929         case FCmpInst::FCMP_OLT:
3930           // No value is ordered and less than negative infinity.
3931           return getFalse(RetTy);
3932         case FCmpInst::FCMP_UGE:
3933           // All values are unordered with or at least negative infinity.
3934           return getTrue(RetTy);
3935         default:
3936           break;
3937         }
3938       } else {
3939         switch (Pred) {
3940         case FCmpInst::FCMP_OGT:
3941           // No value is ordered and greater than infinity.
3942           return getFalse(RetTy);
3943         case FCmpInst::FCMP_ULE:
3944           // All values are unordered with and at most infinity.
3945           return getTrue(RetTy);
3946         default:
3947           break;
3948         }
3949       }
3950 
3951       // LHS == Inf
3952       if (Pred == FCmpInst::FCMP_OEQ && isKnownNeverInfinity(LHS, Q.TLI))
3953         return getFalse(RetTy);
3954       // LHS != Inf
3955       if (Pred == FCmpInst::FCMP_UNE && isKnownNeverInfinity(LHS, Q.TLI))
3956         return getTrue(RetTy);
3957       // LHS == Inf || LHS == NaN
3958       if (Pred == FCmpInst::FCMP_UEQ && isKnownNeverInfinity(LHS, Q.TLI) &&
3959           isKnownNeverNaN(LHS, Q.TLI))
3960         return getFalse(RetTy);
3961       // LHS != Inf && LHS != NaN
3962       if (Pred == FCmpInst::FCMP_ONE && isKnownNeverInfinity(LHS, Q.TLI) &&
3963           isKnownNeverNaN(LHS, Q.TLI))
3964         return getTrue(RetTy);
3965     }
3966     if (C->isNegative() && !C->isNegZero()) {
3967       assert(!C->isNaN() && "Unexpected NaN constant!");
3968       // TODO: We can catch more cases by using a range check rather than
3969       //       relying on CannotBeOrderedLessThanZero.
3970       switch (Pred) {
3971       case FCmpInst::FCMP_UGE:
3972       case FCmpInst::FCMP_UGT:
3973       case FCmpInst::FCMP_UNE:
3974         // (X >= 0) implies (X > C) when (C < 0)
3975         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3976           return getTrue(RetTy);
3977         break;
3978       case FCmpInst::FCMP_OEQ:
3979       case FCmpInst::FCMP_OLE:
3980       case FCmpInst::FCMP_OLT:
3981         // (X >= 0) implies !(X < C) when (C < 0)
3982         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3983           return getFalse(RetTy);
3984         break;
3985       default:
3986         break;
3987       }
3988     }
3989 
3990     // Check comparison of [minnum/maxnum with constant] with other constant.
3991     const APFloat *C2;
3992     if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
3993          *C2 < *C) ||
3994         (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
3995          *C2 > *C)) {
3996       bool IsMaxNum =
3997           cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
3998       // The ordered relationship and minnum/maxnum guarantee that we do not
3999       // have NaN constants, so ordered/unordered preds are handled the same.
4000       switch (Pred) {
4001       case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_UEQ:
4002         // minnum(X, LesserC)  == C --> false
4003         // maxnum(X, GreaterC) == C --> false
4004         return getFalse(RetTy);
4005       case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_UNE:
4006         // minnum(X, LesserC)  != C --> true
4007         // maxnum(X, GreaterC) != C --> true
4008         return getTrue(RetTy);
4009       case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_UGE:
4010       case FCmpInst::FCMP_OGT: case FCmpInst::FCMP_UGT:
4011         // minnum(X, LesserC)  >= C --> false
4012         // minnum(X, LesserC)  >  C --> false
4013         // maxnum(X, GreaterC) >= C --> true
4014         // maxnum(X, GreaterC) >  C --> true
4015         return ConstantInt::get(RetTy, IsMaxNum);
4016       case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ULE:
4017       case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_ULT:
4018         // minnum(X, LesserC)  <= C --> true
4019         // minnum(X, LesserC)  <  C --> true
4020         // maxnum(X, GreaterC) <= C --> false
4021         // maxnum(X, GreaterC) <  C --> false
4022         return ConstantInt::get(RetTy, !IsMaxNum);
4023       default:
4024         // TRUE/FALSE/ORD/UNO should be handled before this.
4025         llvm_unreachable("Unexpected fcmp predicate");
4026       }
4027     }
4028   }
4029 
4030   if (match(RHS, m_AnyZeroFP())) {
4031     switch (Pred) {
4032     case FCmpInst::FCMP_OGE:
4033     case FCmpInst::FCMP_ULT:
4034       // Positive or zero X >= 0.0 --> true
4035       // Positive or zero X <  0.0 --> false
4036       if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) &&
4037           CannotBeOrderedLessThanZero(LHS, Q.TLI))
4038         return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
4039       break;
4040     case FCmpInst::FCMP_UGE:
4041     case FCmpInst::FCMP_OLT:
4042       // Positive or zero or nan X >= 0.0 --> true
4043       // Positive or zero or nan X <  0.0 --> false
4044       if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
4045         return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
4046       break;
4047     default:
4048       break;
4049     }
4050   }
4051 
4052   // If the comparison is with the result of a select instruction, check whether
4053   // comparing with either branch of the select always yields the same value.
4054   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
4055     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
4056       return V;
4057 
4058   // If the comparison is with the result of a phi instruction, check whether
4059   // doing the compare with each incoming phi value yields a common result.
4060   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
4061     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
4062       return V;
4063 
4064   return nullptr;
4065 }
4066 
4067 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4068                               FastMathFlags FMF, const SimplifyQuery &Q) {
4069   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
4070 }
4071 
4072 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4073                                      const SimplifyQuery &Q,
4074                                      bool AllowRefinement,
4075                                      unsigned MaxRecurse) {
4076   assert(!Op->getType()->isVectorTy() && "This is not safe for vectors");
4077 
4078   // Trivial replacement.
4079   if (V == Op)
4080     return RepOp;
4081 
4082   // We cannot replace a constant, and shouldn't even try.
4083   if (isa<Constant>(Op))
4084     return nullptr;
4085 
4086   auto *I = dyn_cast<Instruction>(V);
4087   if (!I || !is_contained(I->operands(), Op))
4088     return nullptr;
4089 
4090   // Replace Op with RepOp in instruction operands.
4091   SmallVector<Value *, 8> NewOps(I->getNumOperands());
4092   transform(I->operands(), NewOps.begin(),
4093             [&](Value *V) { return V == Op ? RepOp : V; });
4094 
4095   if (!AllowRefinement) {
4096     // General InstSimplify functions may refine the result, e.g. by returning
4097     // a constant for a potentially poison value. To avoid this, implement only
4098     // a few non-refining but profitable transforms here.
4099 
4100     if (auto *BO = dyn_cast<BinaryOperator>(I)) {
4101       unsigned Opcode = BO->getOpcode();
4102       // id op x -> x, x op id -> x
4103       if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType()))
4104         return NewOps[1];
4105       if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(),
4106                                                       /* RHS */ true))
4107         return NewOps[0];
4108 
4109       // x & x -> x, x | x -> x
4110       if ((Opcode == Instruction::And || Opcode == Instruction::Or) &&
4111           NewOps[0] == NewOps[1])
4112         return NewOps[0];
4113     }
4114 
4115     if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
4116       // getelementptr x, 0 -> x
4117       if (NewOps.size() == 2 && match(NewOps[1], m_Zero()) &&
4118           !GEP->isInBounds())
4119         return NewOps[0];
4120     }
4121   } else if (MaxRecurse) {
4122     // The simplification queries below may return the original value. Consider:
4123     //   %div = udiv i32 %arg, %arg2
4124     //   %mul = mul nsw i32 %div, %arg2
4125     //   %cmp = icmp eq i32 %mul, %arg
4126     //   %sel = select i1 %cmp, i32 %div, i32 undef
4127     // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which
4128     // simplifies back to %arg. This can only happen because %mul does not
4129     // dominate %div. To ensure a consistent return value contract, we make sure
4130     // that this case returns nullptr as well.
4131     auto PreventSelfSimplify = [V](Value *Simplified) {
4132       return Simplified != V ? Simplified : nullptr;
4133     };
4134 
4135     if (auto *B = dyn_cast<BinaryOperator>(I))
4136       return PreventSelfSimplify(SimplifyBinOp(B->getOpcode(), NewOps[0],
4137                                                NewOps[1], Q, MaxRecurse - 1));
4138 
4139     if (CmpInst *C = dyn_cast<CmpInst>(I))
4140       return PreventSelfSimplify(SimplifyCmpInst(C->getPredicate(), NewOps[0],
4141                                                  NewOps[1], Q, MaxRecurse - 1));
4142 
4143     if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
4144       return PreventSelfSimplify(SimplifyGEPInst(
4145           GEP->getSourceElementType(), NewOps[0], makeArrayRef(NewOps).slice(1),
4146           GEP->isInBounds(), Q, MaxRecurse - 1));
4147 
4148     if (isa<SelectInst>(I))
4149       return PreventSelfSimplify(
4150           SimplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q,
4151                              MaxRecurse - 1));
4152     // TODO: We could hand off more cases to instsimplify here.
4153   }
4154 
4155   // If all operands are constant after substituting Op for RepOp then we can
4156   // constant fold the instruction.
4157   SmallVector<Constant *, 8> ConstOps;
4158   for (Value *NewOp : NewOps) {
4159     if (Constant *ConstOp = dyn_cast<Constant>(NewOp))
4160       ConstOps.push_back(ConstOp);
4161     else
4162       return nullptr;
4163   }
4164 
4165   // Consider:
4166   //   %cmp = icmp eq i32 %x, 2147483647
4167   //   %add = add nsw i32 %x, 1
4168   //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
4169   //
4170   // We can't replace %sel with %add unless we strip away the flags (which
4171   // will be done in InstCombine).
4172   // TODO: This may be unsound, because it only catches some forms of
4173   // refinement.
4174   if (!AllowRefinement && canCreatePoison(cast<Operator>(I)))
4175     return nullptr;
4176 
4177   if (CmpInst *C = dyn_cast<CmpInst>(I))
4178     return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
4179                                            ConstOps[1], Q.DL, Q.TLI);
4180 
4181   if (LoadInst *LI = dyn_cast<LoadInst>(I))
4182     if (!LI->isVolatile())
4183       return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
4184 
4185   return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
4186 }
4187 
4188 Value *llvm::simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4189                                     const SimplifyQuery &Q,
4190                                     bool AllowRefinement) {
4191   return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement,
4192                                   RecursionLimit);
4193 }
4194 
4195 /// Try to simplify a select instruction when its condition operand is an
4196 /// integer comparison where one operand of the compare is a constant.
4197 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
4198                                     const APInt *Y, bool TrueWhenUnset) {
4199   const APInt *C;
4200 
4201   // (X & Y) == 0 ? X & ~Y : X  --> X
4202   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
4203   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
4204       *Y == ~*C)
4205     return TrueWhenUnset ? FalseVal : TrueVal;
4206 
4207   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
4208   // (X & Y) != 0 ? X : X & ~Y  --> X
4209   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
4210       *Y == ~*C)
4211     return TrueWhenUnset ? FalseVal : TrueVal;
4212 
4213   if (Y->isPowerOf2()) {
4214     // (X & Y) == 0 ? X | Y : X  --> X | Y
4215     // (X & Y) != 0 ? X | Y : X  --> X
4216     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
4217         *Y == *C)
4218       return TrueWhenUnset ? TrueVal : FalseVal;
4219 
4220     // (X & Y) == 0 ? X : X | Y  --> X
4221     // (X & Y) != 0 ? X : X | Y  --> X | Y
4222     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
4223         *Y == *C)
4224       return TrueWhenUnset ? TrueVal : FalseVal;
4225   }
4226 
4227   return nullptr;
4228 }
4229 
4230 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
4231 /// eq/ne.
4232 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
4233                                            ICmpInst::Predicate Pred,
4234                                            Value *TrueVal, Value *FalseVal) {
4235   Value *X;
4236   APInt Mask;
4237   if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
4238     return nullptr;
4239 
4240   return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
4241                                Pred == ICmpInst::ICMP_EQ);
4242 }
4243 
4244 /// Try to simplify a select instruction when its condition operand is an
4245 /// integer comparison.
4246 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
4247                                          Value *FalseVal, const SimplifyQuery &Q,
4248                                          unsigned MaxRecurse) {
4249   ICmpInst::Predicate Pred;
4250   Value *CmpLHS, *CmpRHS;
4251   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
4252     return nullptr;
4253 
4254   // Canonicalize ne to eq predicate.
4255   if (Pred == ICmpInst::ICMP_NE) {
4256     Pred = ICmpInst::ICMP_EQ;
4257     std::swap(TrueVal, FalseVal);
4258   }
4259 
4260   // Check for integer min/max with a limit constant:
4261   // X > MIN_INT ? X : MIN_INT --> X
4262   // X < MAX_INT ? X : MAX_INT --> X
4263   if (TrueVal->getType()->isIntOrIntVectorTy()) {
4264     Value *X, *Y;
4265     SelectPatternFlavor SPF =
4266         matchDecomposedSelectPattern(cast<ICmpInst>(CondVal), TrueVal, FalseVal,
4267                                      X, Y).Flavor;
4268     if (SelectPatternResult::isMinOrMax(SPF) && Pred == getMinMaxPred(SPF)) {
4269       APInt LimitC = getMinMaxLimit(getInverseMinMaxFlavor(SPF),
4270                                     X->getType()->getScalarSizeInBits());
4271       if (match(Y, m_SpecificInt(LimitC)))
4272         return X;
4273     }
4274   }
4275 
4276   if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) {
4277     Value *X;
4278     const APInt *Y;
4279     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
4280       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
4281                                            /*TrueWhenUnset=*/true))
4282         return V;
4283 
4284     // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
4285     Value *ShAmt;
4286     auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)),
4287                              m_FShr(m_Value(), m_Value(X), m_Value(ShAmt)));
4288     // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
4289     // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
4290     if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt)
4291       return X;
4292 
4293     // Test for a zero-shift-guard-op around rotates. These are used to
4294     // avoid UB from oversized shifts in raw IR rotate patterns, but the
4295     // intrinsics do not have that problem.
4296     // We do not allow this transform for the general funnel shift case because
4297     // that would not preserve the poison safety of the original code.
4298     auto isRotate =
4299         m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)),
4300                     m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt)));
4301     // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
4302     // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
4303     if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
4304         Pred == ICmpInst::ICMP_EQ)
4305       return FalseVal;
4306 
4307     // X == 0 ? abs(X) : -abs(X) --> -abs(X)
4308     // X == 0 ? -abs(X) : abs(X) --> abs(X)
4309     if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) &&
4310         match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))))
4311       return FalseVal;
4312     if (match(TrueVal,
4313               m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) &&
4314         match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))
4315       return FalseVal;
4316   }
4317 
4318   // Check for other compares that behave like bit test.
4319   if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
4320                                               TrueVal, FalseVal))
4321     return V;
4322 
4323   // If we have a scalar equality comparison, then we know the value in one of
4324   // the arms of the select. See if substituting this value into the arm and
4325   // simplifying the result yields the same value as the other arm.
4326   // Note that the equivalence/replacement opportunity does not hold for vectors
4327   // because each element of a vector select is chosen independently.
4328   if (Pred == ICmpInst::ICMP_EQ && !CondVal->getType()->isVectorTy()) {
4329     if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q,
4330                                /* AllowRefinement */ false, MaxRecurse) ==
4331             TrueVal ||
4332         simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q,
4333                                /* AllowRefinement */ false, MaxRecurse) ==
4334             TrueVal)
4335       return FalseVal;
4336     if (simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q,
4337                                /* AllowRefinement */ true, MaxRecurse) ==
4338             FalseVal ||
4339         simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q,
4340                                /* AllowRefinement */ true, MaxRecurse) ==
4341             FalseVal)
4342       return FalseVal;
4343   }
4344 
4345   return nullptr;
4346 }
4347 
4348 /// Try to simplify a select instruction when its condition operand is a
4349 /// floating-point comparison.
4350 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F,
4351                                      const SimplifyQuery &Q) {
4352   FCmpInst::Predicate Pred;
4353   if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
4354       !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
4355     return nullptr;
4356 
4357   // This transform is safe if we do not have (do not care about) -0.0 or if
4358   // at least one operand is known to not be -0.0. Otherwise, the select can
4359   // change the sign of a zero operand.
4360   bool HasNoSignedZeros = Q.CxtI && isa<FPMathOperator>(Q.CxtI) &&
4361                           Q.CxtI->hasNoSignedZeros();
4362   const APFloat *C;
4363   if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) ||
4364                           (match(F, m_APFloat(C)) && C->isNonZero())) {
4365     // (T == F) ? T : F --> F
4366     // (F == T) ? T : F --> F
4367     if (Pred == FCmpInst::FCMP_OEQ)
4368       return F;
4369 
4370     // (T != F) ? T : F --> T
4371     // (F != T) ? T : F --> T
4372     if (Pred == FCmpInst::FCMP_UNE)
4373       return T;
4374   }
4375 
4376   return nullptr;
4377 }
4378 
4379 /// Given operands for a SelectInst, see if we can fold the result.
4380 /// If not, this returns null.
4381 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4382                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
4383   if (auto *CondC = dyn_cast<Constant>(Cond)) {
4384     if (auto *TrueC = dyn_cast<Constant>(TrueVal))
4385       if (auto *FalseC = dyn_cast<Constant>(FalseVal))
4386         return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
4387 
4388     // select poison, X, Y -> poison
4389     if (isa<PoisonValue>(CondC))
4390       return PoisonValue::get(TrueVal->getType());
4391 
4392     // select undef, X, Y -> X or Y
4393     if (Q.isUndefValue(CondC))
4394       return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
4395 
4396     // select true,  X, Y --> X
4397     // select false, X, Y --> Y
4398     // For vectors, allow undef/poison elements in the condition to match the
4399     // defined elements, so we can eliminate the select.
4400     if (match(CondC, m_One()))
4401       return TrueVal;
4402     if (match(CondC, m_Zero()))
4403       return FalseVal;
4404   }
4405 
4406   assert(Cond->getType()->isIntOrIntVectorTy(1) &&
4407          "Select must have bool or bool vector condition");
4408   assert(TrueVal->getType() == FalseVal->getType() &&
4409          "Select must have same types for true/false ops");
4410 
4411   if (Cond->getType() == TrueVal->getType()) {
4412     // select i1 Cond, i1 true, i1 false --> i1 Cond
4413     if (match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt()))
4414       return Cond;
4415 
4416     // (X || Y) && (X || !Y) --> X (commuted 8 ways)
4417     Value *X, *Y;
4418     if (match(FalseVal, m_ZeroInt())) {
4419       if (match(Cond, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4420           match(TrueVal, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4421         return X;
4422       if (match(TrueVal, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4423           match(Cond, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4424         return X;
4425     }
4426   }
4427 
4428   // select ?, X, X -> X
4429   if (TrueVal == FalseVal)
4430     return TrueVal;
4431 
4432   // If the true or false value is poison, we can fold to the other value.
4433   // If the true or false value is undef, we can fold to the other value as
4434   // long as the other value isn't poison.
4435   // select ?, poison, X -> X
4436   // select ?, undef,  X -> X
4437   if (isa<PoisonValue>(TrueVal) ||
4438       (Q.isUndefValue(TrueVal) &&
4439        isGuaranteedNotToBePoison(FalseVal, Q.AC, Q.CxtI, Q.DT)))
4440     return FalseVal;
4441   // select ?, X, poison -> X
4442   // select ?, X, undef  -> X
4443   if (isa<PoisonValue>(FalseVal) ||
4444       (Q.isUndefValue(FalseVal) &&
4445        isGuaranteedNotToBePoison(TrueVal, Q.AC, Q.CxtI, Q.DT)))
4446     return TrueVal;
4447 
4448   // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC''
4449   Constant *TrueC, *FalseC;
4450   if (isa<FixedVectorType>(TrueVal->getType()) &&
4451       match(TrueVal, m_Constant(TrueC)) &&
4452       match(FalseVal, m_Constant(FalseC))) {
4453     unsigned NumElts =
4454         cast<FixedVectorType>(TrueC->getType())->getNumElements();
4455     SmallVector<Constant *, 16> NewC;
4456     for (unsigned i = 0; i != NumElts; ++i) {
4457       // Bail out on incomplete vector constants.
4458       Constant *TEltC = TrueC->getAggregateElement(i);
4459       Constant *FEltC = FalseC->getAggregateElement(i);
4460       if (!TEltC || !FEltC)
4461         break;
4462 
4463       // If the elements match (undef or not), that value is the result. If only
4464       // one element is undef, choose the defined element as the safe result.
4465       if (TEltC == FEltC)
4466         NewC.push_back(TEltC);
4467       else if (isa<PoisonValue>(TEltC) ||
4468                (Q.isUndefValue(TEltC) && isGuaranteedNotToBePoison(FEltC)))
4469         NewC.push_back(FEltC);
4470       else if (isa<PoisonValue>(FEltC) ||
4471                (Q.isUndefValue(FEltC) && isGuaranteedNotToBePoison(TEltC)))
4472         NewC.push_back(TEltC);
4473       else
4474         break;
4475     }
4476     if (NewC.size() == NumElts)
4477       return ConstantVector::get(NewC);
4478   }
4479 
4480   if (Value *V =
4481           simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
4482     return V;
4483 
4484   if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q))
4485     return V;
4486 
4487   if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
4488     return V;
4489 
4490   Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
4491   if (Imp)
4492     return *Imp ? TrueVal : FalseVal;
4493 
4494   return nullptr;
4495 }
4496 
4497 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4498                                 const SimplifyQuery &Q) {
4499   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
4500 }
4501 
4502 /// Given operands for an GetElementPtrInst, see if we can fold the result.
4503 /// If not, this returns null.
4504 static Value *SimplifyGEPInst(Type *SrcTy, Value *Ptr,
4505                               ArrayRef<Value *> Indices, bool InBounds,
4506                               const SimplifyQuery &Q, unsigned) {
4507   // The type of the GEP pointer operand.
4508   unsigned AS =
4509       cast<PointerType>(Ptr->getType()->getScalarType())->getAddressSpace();
4510 
4511   // getelementptr P -> P.
4512   if (Indices.empty())
4513     return Ptr;
4514 
4515   // Compute the (pointer) type returned by the GEP instruction.
4516   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Indices);
4517   Type *GEPTy = PointerType::get(LastType, AS);
4518   if (VectorType *VT = dyn_cast<VectorType>(Ptr->getType()))
4519     GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4520   else {
4521     for (Value *Op : Indices) {
4522       // If one of the operands is a vector, the result type is a vector of
4523       // pointers. All vector operands must have the same number of elements.
4524       if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) {
4525         GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4526         break;
4527       }
4528     }
4529   }
4530 
4531   // For opaque pointers an all-zero GEP is a no-op. For typed pointers,
4532   // it may be equivalent to a bitcast.
4533   if (Ptr->getType()->getScalarType()->isOpaquePointerTy() &&
4534       Ptr->getType() == GEPTy &&
4535       all_of(Indices, [](const auto *V) { return match(V, m_Zero()); }))
4536     return Ptr;
4537 
4538   // getelementptr poison, idx -> poison
4539   // getelementptr baseptr, poison -> poison
4540   if (isa<PoisonValue>(Ptr) ||
4541       any_of(Indices, [](const auto *V) { return isa<PoisonValue>(V); }))
4542     return PoisonValue::get(GEPTy);
4543 
4544   if (Q.isUndefValue(Ptr))
4545     // If inbounds, we can choose an out-of-bounds pointer as a base pointer.
4546     return InBounds ? PoisonValue::get(GEPTy) : UndefValue::get(GEPTy);
4547 
4548   bool IsScalableVec =
4549       isa<ScalableVectorType>(SrcTy) || any_of(Indices, [](const Value *V) {
4550         return isa<ScalableVectorType>(V->getType());
4551       });
4552 
4553   if (Indices.size() == 1) {
4554     // getelementptr P, 0 -> P.
4555     if (match(Indices[0], m_Zero()) && Ptr->getType() == GEPTy)
4556       return Ptr;
4557 
4558     Type *Ty = SrcTy;
4559     if (!IsScalableVec && Ty->isSized()) {
4560       Value *P;
4561       uint64_t C;
4562       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
4563       // getelementptr P, N -> P if P points to a type of zero size.
4564       if (TyAllocSize == 0 && Ptr->getType() == GEPTy)
4565         return Ptr;
4566 
4567       // The following transforms are only safe if the ptrtoint cast
4568       // doesn't truncate the pointers.
4569       if (Indices[0]->getType()->getScalarSizeInBits() ==
4570           Q.DL.getPointerSizeInBits(AS)) {
4571         auto CanSimplify = [GEPTy, &P, Ptr]() -> bool {
4572           return P->getType() == GEPTy &&
4573                  getUnderlyingObject(P) == getUnderlyingObject(Ptr);
4574         };
4575         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
4576         if (TyAllocSize == 1 &&
4577             match(Indices[0],
4578                   m_Sub(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Specific(Ptr)))) &&
4579             CanSimplify())
4580           return P;
4581 
4582         // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of
4583         // size 1 << C.
4584         if (match(Indices[0], m_AShr(m_Sub(m_PtrToInt(m_Value(P)),
4585                                            m_PtrToInt(m_Specific(Ptr))),
4586                                      m_ConstantInt(C))) &&
4587             TyAllocSize == 1ULL << C && CanSimplify())
4588           return P;
4589 
4590         // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of
4591         // size C.
4592         if (match(Indices[0], m_SDiv(m_Sub(m_PtrToInt(m_Value(P)),
4593                                            m_PtrToInt(m_Specific(Ptr))),
4594                                      m_SpecificInt(TyAllocSize))) &&
4595             CanSimplify())
4596           return P;
4597       }
4598     }
4599   }
4600 
4601   if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 &&
4602       all_of(Indices.drop_back(1),
4603              [](Value *Idx) { return match(Idx, m_Zero()); })) {
4604     unsigned IdxWidth =
4605         Q.DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace());
4606     if (Q.DL.getTypeSizeInBits(Indices.back()->getType()) == IdxWidth) {
4607       APInt BasePtrOffset(IdxWidth, 0);
4608       Value *StrippedBasePtr =
4609           Ptr->stripAndAccumulateInBoundsConstantOffsets(Q.DL, BasePtrOffset);
4610 
4611       // Avoid creating inttoptr of zero here: While LLVMs treatment of
4612       // inttoptr is generally conservative, this particular case is folded to
4613       // a null pointer, which will have incorrect provenance.
4614 
4615       // gep (gep V, C), (sub 0, V) -> C
4616       if (match(Indices.back(),
4617                 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr)))) &&
4618           !BasePtrOffset.isZero()) {
4619         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
4620         return ConstantExpr::getIntToPtr(CI, GEPTy);
4621       }
4622       // gep (gep V, C), (xor V, -1) -> C-1
4623       if (match(Indices.back(),
4624                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) &&
4625           !BasePtrOffset.isOne()) {
4626         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
4627         return ConstantExpr::getIntToPtr(CI, GEPTy);
4628       }
4629     }
4630   }
4631 
4632   // Check to see if this is constant foldable.
4633   if (!isa<Constant>(Ptr) ||
4634       !all_of(Indices, [](Value *V) { return isa<Constant>(V); }))
4635     return nullptr;
4636 
4637   auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ptr), Indices,
4638                                             InBounds);
4639   return ConstantFoldConstant(CE, Q.DL);
4640 }
4641 
4642 Value *llvm::SimplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices,
4643                              bool InBounds, const SimplifyQuery &Q) {
4644   return ::SimplifyGEPInst(SrcTy, Ptr, Indices, InBounds, Q, RecursionLimit);
4645 }
4646 
4647 /// Given operands for an InsertValueInst, see if we can fold the result.
4648 /// If not, this returns null.
4649 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
4650                                       ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
4651                                       unsigned) {
4652   if (Constant *CAgg = dyn_cast<Constant>(Agg))
4653     if (Constant *CVal = dyn_cast<Constant>(Val))
4654       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
4655 
4656   // insertvalue x, undef, n -> x
4657   if (Q.isUndefValue(Val))
4658     return Agg;
4659 
4660   // insertvalue x, (extractvalue y, n), n
4661   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
4662     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
4663         EV->getIndices() == Idxs) {
4664       // insertvalue undef, (extractvalue y, n), n -> y
4665       if (Q.isUndefValue(Agg))
4666         return EV->getAggregateOperand();
4667 
4668       // insertvalue y, (extractvalue y, n), n -> y
4669       if (Agg == EV->getAggregateOperand())
4670         return Agg;
4671     }
4672 
4673   return nullptr;
4674 }
4675 
4676 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
4677                                      ArrayRef<unsigned> Idxs,
4678                                      const SimplifyQuery &Q) {
4679   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
4680 }
4681 
4682 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
4683                                        const SimplifyQuery &Q) {
4684   // Try to constant fold.
4685   auto *VecC = dyn_cast<Constant>(Vec);
4686   auto *ValC = dyn_cast<Constant>(Val);
4687   auto *IdxC = dyn_cast<Constant>(Idx);
4688   if (VecC && ValC && IdxC)
4689     return ConstantExpr::getInsertElement(VecC, ValC, IdxC);
4690 
4691   // For fixed-length vector, fold into poison if index is out of bounds.
4692   if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
4693     if (isa<FixedVectorType>(Vec->getType()) &&
4694         CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements()))
4695       return PoisonValue::get(Vec->getType());
4696   }
4697 
4698   // If index is undef, it might be out of bounds (see above case)
4699   if (Q.isUndefValue(Idx))
4700     return PoisonValue::get(Vec->getType());
4701 
4702   // If the scalar is poison, or it is undef and there is no risk of
4703   // propagating poison from the vector value, simplify to the vector value.
4704   if (isa<PoisonValue>(Val) ||
4705       (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec)))
4706     return Vec;
4707 
4708   // If we are extracting a value from a vector, then inserting it into the same
4709   // place, that's the input vector:
4710   // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
4711   if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx))))
4712     return Vec;
4713 
4714   return nullptr;
4715 }
4716 
4717 /// Given operands for an ExtractValueInst, see if we can fold the result.
4718 /// If not, this returns null.
4719 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4720                                        const SimplifyQuery &, unsigned) {
4721   if (auto *CAgg = dyn_cast<Constant>(Agg))
4722     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
4723 
4724   // extractvalue x, (insertvalue y, elt, n), n -> elt
4725   unsigned NumIdxs = Idxs.size();
4726   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
4727        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
4728     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
4729     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
4730     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
4731     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
4732         Idxs.slice(0, NumCommonIdxs)) {
4733       if (NumIdxs == NumInsertValueIdxs)
4734         return IVI->getInsertedValueOperand();
4735       break;
4736     }
4737   }
4738 
4739   return nullptr;
4740 }
4741 
4742 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4743                                       const SimplifyQuery &Q) {
4744   return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
4745 }
4746 
4747 /// Given operands for an ExtractElementInst, see if we can fold the result.
4748 /// If not, this returns null.
4749 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx,
4750                                          const SimplifyQuery &Q, unsigned) {
4751   auto *VecVTy = cast<VectorType>(Vec->getType());
4752   if (auto *CVec = dyn_cast<Constant>(Vec)) {
4753     if (auto *CIdx = dyn_cast<Constant>(Idx))
4754       return ConstantExpr::getExtractElement(CVec, CIdx);
4755 
4756     if (Q.isUndefValue(Vec))
4757       return UndefValue::get(VecVTy->getElementType());
4758   }
4759 
4760   // An undef extract index can be arbitrarily chosen to be an out-of-range
4761   // index value, which would result in the instruction being poison.
4762   if (Q.isUndefValue(Idx))
4763     return PoisonValue::get(VecVTy->getElementType());
4764 
4765   // If extracting a specified index from the vector, see if we can recursively
4766   // find a previously computed scalar that was inserted into the vector.
4767   if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4768     // For fixed-length vector, fold into undef if index is out of bounds.
4769     unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue();
4770     if (isa<FixedVectorType>(VecVTy) && IdxC->getValue().uge(MinNumElts))
4771       return PoisonValue::get(VecVTy->getElementType());
4772     // Handle case where an element is extracted from a splat.
4773     if (IdxC->getValue().ult(MinNumElts))
4774       if (auto *Splat = getSplatValue(Vec))
4775         return Splat;
4776     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4777       return Elt;
4778   } else {
4779     // The index is not relevant if our vector is a splat.
4780     if (Value *Splat = getSplatValue(Vec))
4781       return Splat;
4782   }
4783   return nullptr;
4784 }
4785 
4786 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
4787                                         const SimplifyQuery &Q) {
4788   return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4789 }
4790 
4791 /// See if we can fold the given phi. If not, returns null.
4792 static Value *SimplifyPHINode(PHINode *PN, ArrayRef<Value *> IncomingValues,
4793                               const SimplifyQuery &Q) {
4794   // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE
4795   //          here, because the PHI we may succeed simplifying to was not
4796   //          def-reachable from the original PHI!
4797 
4798   // If all of the PHI's incoming values are the same then replace the PHI node
4799   // with the common value.
4800   Value *CommonValue = nullptr;
4801   bool HasUndefInput = false;
4802   for (Value *Incoming : IncomingValues) {
4803     // If the incoming value is the phi node itself, it can safely be skipped.
4804     if (Incoming == PN) continue;
4805     if (Q.isUndefValue(Incoming)) {
4806       // Remember that we saw an undef value, but otherwise ignore them.
4807       HasUndefInput = true;
4808       continue;
4809     }
4810     if (CommonValue && Incoming != CommonValue)
4811       return nullptr;  // Not the same, bail out.
4812     CommonValue = Incoming;
4813   }
4814 
4815   // If CommonValue is null then all of the incoming values were either undef or
4816   // equal to the phi node itself.
4817   if (!CommonValue)
4818     return UndefValue::get(PN->getType());
4819 
4820   if (HasUndefInput) {
4821     // We cannot start executing a trapping constant expression on more control
4822     // flow paths.
4823     auto *CE = dyn_cast<ConstantExpr>(CommonValue);
4824     if (CE && CE->canTrap())
4825       return nullptr;
4826 
4827     // If we have a PHI node like phi(X, undef, X), where X is defined by some
4828     // instruction, we cannot return X as the result of the PHI node unless it
4829     // dominates the PHI block.
4830     return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
4831   }
4832 
4833   return CommonValue;
4834 }
4835 
4836 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4837                                Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
4838   if (auto *C = dyn_cast<Constant>(Op))
4839     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
4840 
4841   if (auto *CI = dyn_cast<CastInst>(Op)) {
4842     auto *Src = CI->getOperand(0);
4843     Type *SrcTy = Src->getType();
4844     Type *MidTy = CI->getType();
4845     Type *DstTy = Ty;
4846     if (Src->getType() == Ty) {
4847       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4848       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4849       Type *SrcIntPtrTy =
4850           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4851       Type *MidIntPtrTy =
4852           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4853       Type *DstIntPtrTy =
4854           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4855       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4856                                          SrcIntPtrTy, MidIntPtrTy,
4857                                          DstIntPtrTy) == Instruction::BitCast)
4858         return Src;
4859     }
4860   }
4861 
4862   // bitcast x -> x
4863   if (CastOpc == Instruction::BitCast)
4864     if (Op->getType() == Ty)
4865       return Op;
4866 
4867   return nullptr;
4868 }
4869 
4870 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4871                               const SimplifyQuery &Q) {
4872   return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4873 }
4874 
4875 /// For the given destination element of a shuffle, peek through shuffles to
4876 /// match a root vector source operand that contains that element in the same
4877 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4878 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4879                                    int MaskVal, Value *RootVec,
4880                                    unsigned MaxRecurse) {
4881   if (!MaxRecurse--)
4882     return nullptr;
4883 
4884   // Bail out if any mask value is undefined. That kind of shuffle may be
4885   // simplified further based on demanded bits or other folds.
4886   if (MaskVal == -1)
4887     return nullptr;
4888 
4889   // The mask value chooses which source operand we need to look at next.
4890   int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
4891   int RootElt = MaskVal;
4892   Value *SourceOp = Op0;
4893   if (MaskVal >= InVecNumElts) {
4894     RootElt = MaskVal - InVecNumElts;
4895     SourceOp = Op1;
4896   }
4897 
4898   // If the source operand is a shuffle itself, look through it to find the
4899   // matching root vector.
4900   if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4901     return foldIdentityShuffles(
4902         DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4903         SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
4904   }
4905 
4906   // TODO: Look through bitcasts? What if the bitcast changes the vector element
4907   // size?
4908 
4909   // The source operand is not a shuffle. Initialize the root vector value for
4910   // this shuffle if that has not been done yet.
4911   if (!RootVec)
4912     RootVec = SourceOp;
4913 
4914   // Give up as soon as a source operand does not match the existing root value.
4915   if (RootVec != SourceOp)
4916     return nullptr;
4917 
4918   // The element must be coming from the same lane in the source vector
4919   // (although it may have crossed lanes in intermediate shuffles).
4920   if (RootElt != DestElt)
4921     return nullptr;
4922 
4923   return RootVec;
4924 }
4925 
4926 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1,
4927                                         ArrayRef<int> Mask, Type *RetTy,
4928                                         const SimplifyQuery &Q,
4929                                         unsigned MaxRecurse) {
4930   if (all_of(Mask, [](int Elem) { return Elem == UndefMaskElem; }))
4931     return UndefValue::get(RetTy);
4932 
4933   auto *InVecTy = cast<VectorType>(Op0->getType());
4934   unsigned MaskNumElts = Mask.size();
4935   ElementCount InVecEltCount = InVecTy->getElementCount();
4936 
4937   bool Scalable = InVecEltCount.isScalable();
4938 
4939   SmallVector<int, 32> Indices;
4940   Indices.assign(Mask.begin(), Mask.end());
4941 
4942   // Canonicalization: If mask does not select elements from an input vector,
4943   // replace that input vector with poison.
4944   if (!Scalable) {
4945     bool MaskSelects0 = false, MaskSelects1 = false;
4946     unsigned InVecNumElts = InVecEltCount.getKnownMinValue();
4947     for (unsigned i = 0; i != MaskNumElts; ++i) {
4948       if (Indices[i] == -1)
4949         continue;
4950       if ((unsigned)Indices[i] < InVecNumElts)
4951         MaskSelects0 = true;
4952       else
4953         MaskSelects1 = true;
4954     }
4955     if (!MaskSelects0)
4956       Op0 = PoisonValue::get(InVecTy);
4957     if (!MaskSelects1)
4958       Op1 = PoisonValue::get(InVecTy);
4959   }
4960 
4961   auto *Op0Const = dyn_cast<Constant>(Op0);
4962   auto *Op1Const = dyn_cast<Constant>(Op1);
4963 
4964   // If all operands are constant, constant fold the shuffle. This
4965   // transformation depends on the value of the mask which is not known at
4966   // compile time for scalable vectors
4967   if (Op0Const && Op1Const)
4968     return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask);
4969 
4970   // Canonicalization: if only one input vector is constant, it shall be the
4971   // second one. This transformation depends on the value of the mask which
4972   // is not known at compile time for scalable vectors
4973   if (!Scalable && Op0Const && !Op1Const) {
4974     std::swap(Op0, Op1);
4975     ShuffleVectorInst::commuteShuffleMask(Indices,
4976                                           InVecEltCount.getKnownMinValue());
4977   }
4978 
4979   // A splat of an inserted scalar constant becomes a vector constant:
4980   // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...>
4981   // NOTE: We may have commuted above, so analyze the updated Indices, not the
4982   //       original mask constant.
4983   // NOTE: This transformation depends on the value of the mask which is not
4984   // known at compile time for scalable vectors
4985   Constant *C;
4986   ConstantInt *IndexC;
4987   if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C),
4988                                           m_ConstantInt(IndexC)))) {
4989     // Match a splat shuffle mask of the insert index allowing undef elements.
4990     int InsertIndex = IndexC->getZExtValue();
4991     if (all_of(Indices, [InsertIndex](int MaskElt) {
4992           return MaskElt == InsertIndex || MaskElt == -1;
4993         })) {
4994       assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
4995 
4996       // Shuffle mask undefs become undefined constant result elements.
4997       SmallVector<Constant *, 16> VecC(MaskNumElts, C);
4998       for (unsigned i = 0; i != MaskNumElts; ++i)
4999         if (Indices[i] == -1)
5000           VecC[i] = UndefValue::get(C->getType());
5001       return ConstantVector::get(VecC);
5002     }
5003   }
5004 
5005   // A shuffle of a splat is always the splat itself. Legal if the shuffle's
5006   // value type is same as the input vectors' type.
5007   if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
5008     if (Q.isUndefValue(Op1) && RetTy == InVecTy &&
5009         is_splat(OpShuf->getShuffleMask()))
5010       return Op0;
5011 
5012   // All remaining transformation depend on the value of the mask, which is
5013   // not known at compile time for scalable vectors.
5014   if (Scalable)
5015     return nullptr;
5016 
5017   // Don't fold a shuffle with undef mask elements. This may get folded in a
5018   // better way using demanded bits or other analysis.
5019   // TODO: Should we allow this?
5020   if (is_contained(Indices, -1))
5021     return nullptr;
5022 
5023   // Check if every element of this shuffle can be mapped back to the
5024   // corresponding element of a single root vector. If so, we don't need this
5025   // shuffle. This handles simple identity shuffles as well as chains of
5026   // shuffles that may widen/narrow and/or move elements across lanes and back.
5027   Value *RootVec = nullptr;
5028   for (unsigned i = 0; i != MaskNumElts; ++i) {
5029     // Note that recursion is limited for each vector element, so if any element
5030     // exceeds the limit, this will fail to simplify.
5031     RootVec =
5032         foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
5033 
5034     // We can't replace a widening/narrowing shuffle with one of its operands.
5035     if (!RootVec || RootVec->getType() != RetTy)
5036       return nullptr;
5037   }
5038   return RootVec;
5039 }
5040 
5041 /// Given operands for a ShuffleVectorInst, fold the result or return null.
5042 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1,
5043                                        ArrayRef<int> Mask, Type *RetTy,
5044                                        const SimplifyQuery &Q) {
5045   return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
5046 }
5047 
5048 static Constant *foldConstant(Instruction::UnaryOps Opcode,
5049                               Value *&Op, const SimplifyQuery &Q) {
5050   if (auto *C = dyn_cast<Constant>(Op))
5051     return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
5052   return nullptr;
5053 }
5054 
5055 /// Given the operand for an FNeg, see if we can fold the result.  If not, this
5056 /// returns null.
5057 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
5058                                const SimplifyQuery &Q, unsigned MaxRecurse) {
5059   if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
5060     return C;
5061 
5062   Value *X;
5063   // fneg (fneg X) ==> X
5064   if (match(Op, m_FNeg(m_Value(X))))
5065     return X;
5066 
5067   return nullptr;
5068 }
5069 
5070 Value *llvm::SimplifyFNegInst(Value *Op, FastMathFlags FMF,
5071                               const SimplifyQuery &Q) {
5072   return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
5073 }
5074 
5075 static Constant *propagateNaN(Constant *In) {
5076   // If the input is a vector with undef elements, just return a default NaN.
5077   if (!In->isNaN())
5078     return ConstantFP::getNaN(In->getType());
5079 
5080   // Propagate the existing NaN constant when possible.
5081   // TODO: Should we quiet a signaling NaN?
5082   return In;
5083 }
5084 
5085 /// Perform folds that are common to any floating-point operation. This implies
5086 /// transforms based on poison/undef/NaN because the operation itself makes no
5087 /// difference to the result.
5088 static Constant *simplifyFPOp(ArrayRef<Value *> Ops, FastMathFlags FMF,
5089                               const SimplifyQuery &Q,
5090                               fp::ExceptionBehavior ExBehavior,
5091                               RoundingMode Rounding) {
5092   // Poison is independent of anything else. It always propagates from an
5093   // operand to a math result.
5094   if (any_of(Ops, [](Value *V) { return match(V, m_Poison()); }))
5095     return PoisonValue::get(Ops[0]->getType());
5096 
5097   for (Value *V : Ops) {
5098     bool IsNan = match(V, m_NaN());
5099     bool IsInf = match(V, m_Inf());
5100     bool IsUndef = Q.isUndefValue(V);
5101 
5102     // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
5103     // (an undef operand can be chosen to be Nan/Inf), then the result of
5104     // this operation is poison.
5105     if (FMF.noNaNs() && (IsNan || IsUndef))
5106       return PoisonValue::get(V->getType());
5107     if (FMF.noInfs() && (IsInf || IsUndef))
5108       return PoisonValue::get(V->getType());
5109 
5110     if (isDefaultFPEnvironment(ExBehavior, Rounding)) {
5111       if (IsUndef || IsNan)
5112         return propagateNaN(cast<Constant>(V));
5113     } else if (ExBehavior != fp::ebStrict) {
5114       if (IsNan)
5115         return propagateNaN(cast<Constant>(V));
5116     }
5117   }
5118   return nullptr;
5119 }
5120 
5121 /// Given operands for an FAdd, see if we can fold the result.  If not, this
5122 /// returns null.
5123 static Value *
5124 SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5125                  const SimplifyQuery &Q, unsigned MaxRecurse,
5126                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5127                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5128   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5129     if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
5130       return C;
5131 
5132   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5133     return C;
5134 
5135   // fadd X, -0 ==> X
5136   // With strict/constrained FP, we have these possible edge cases that do
5137   // not simplify to Op0:
5138   // fadd SNaN, -0.0 --> QNaN
5139   // fadd +0.0, -0.0 --> -0.0 (but only with round toward negative)
5140   if (canIgnoreSNaN(ExBehavior, FMF) &&
5141       (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5142        FMF.noSignedZeros()))
5143     if (match(Op1, m_NegZeroFP()))
5144       return Op0;
5145 
5146   // fadd X, 0 ==> X, when we know X is not -0
5147   if (canIgnoreSNaN(ExBehavior, FMF))
5148     if (match(Op1, m_PosZeroFP()) &&
5149         (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
5150       return Op0;
5151 
5152   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5153     return nullptr;
5154 
5155   // With nnan: -X + X --> 0.0 (and commuted variant)
5156   // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
5157   // Negative zeros are allowed because we always end up with positive zero:
5158   // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5159   // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5160   // X =  0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
5161   // X =  0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
5162   if (FMF.noNaNs()) {
5163     if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
5164         match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
5165       return ConstantFP::getNullValue(Op0->getType());
5166 
5167     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
5168         match(Op1, m_FNeg(m_Specific(Op0))))
5169       return ConstantFP::getNullValue(Op0->getType());
5170   }
5171 
5172   // (X - Y) + Y --> X
5173   // Y + (X - Y) --> X
5174   Value *X;
5175   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
5176       (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
5177        match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
5178     return X;
5179 
5180   return nullptr;
5181 }
5182 
5183 /// Given operands for an FSub, see if we can fold the result.  If not, this
5184 /// returns null.
5185 static Value *
5186 SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5187                  const SimplifyQuery &Q, unsigned MaxRecurse,
5188                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5189                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5190   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5191     if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
5192       return C;
5193 
5194   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5195     return C;
5196 
5197   // fsub X, +0 ==> X
5198   if (canIgnoreSNaN(ExBehavior, FMF) &&
5199       (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5200        FMF.noSignedZeros()))
5201     if (match(Op1, m_PosZeroFP()))
5202       return Op0;
5203 
5204   // fsub X, -0 ==> X, when we know X is not -0
5205   if (canIgnoreSNaN(ExBehavior, FMF))
5206     if (match(Op1, m_NegZeroFP()) &&
5207         (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
5208       return Op0;
5209 
5210   // fsub -0.0, (fsub -0.0, X) ==> X
5211   // fsub -0.0, (fneg X) ==> X
5212   Value *X;
5213   if (canIgnoreSNaN(ExBehavior, FMF))
5214     if (match(Op0, m_NegZeroFP()) &&
5215         match(Op1, m_FNeg(m_Value(X))))
5216       return X;
5217 
5218   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5219     return nullptr;
5220 
5221   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
5222   // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
5223   if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
5224       (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
5225        match(Op1, m_FNeg(m_Value(X)))))
5226     return X;
5227 
5228   // fsub nnan x, x ==> 0.0
5229   if (FMF.noNaNs() && Op0 == Op1)
5230     return Constant::getNullValue(Op0->getType());
5231 
5232   // Y - (Y - X) --> X
5233   // (X + Y) - Y --> X
5234   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
5235       (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
5236        match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
5237     return X;
5238 
5239   return nullptr;
5240 }
5241 
5242 static Value *SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5243                               const SimplifyQuery &Q, unsigned MaxRecurse,
5244                               fp::ExceptionBehavior ExBehavior,
5245                               RoundingMode Rounding) {
5246   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5247     return C;
5248 
5249   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5250     return nullptr;
5251 
5252   // fmul X, 1.0 ==> X
5253   if (match(Op1, m_FPOne()))
5254     return Op0;
5255 
5256   // fmul 1.0, X ==> X
5257   if (match(Op0, m_FPOne()))
5258     return Op1;
5259 
5260   // fmul nnan nsz X, 0 ==> 0
5261   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
5262     return ConstantFP::getNullValue(Op0->getType());
5263 
5264   // fmul nnan nsz 0, X ==> 0
5265   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5266     return ConstantFP::getNullValue(Op1->getType());
5267 
5268   // sqrt(X) * sqrt(X) --> X, if we can:
5269   // 1. Remove the intermediate rounding (reassociate).
5270   // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
5271   // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
5272   Value *X;
5273   if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
5274       FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
5275     return X;
5276 
5277   return nullptr;
5278 }
5279 
5280 /// Given the operands for an FMul, see if we can fold the result
5281 static Value *
5282 SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5283                  const SimplifyQuery &Q, unsigned MaxRecurse,
5284                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5285                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5286   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5287     if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
5288       return C;
5289 
5290   // Now apply simplifications that do not require rounding.
5291   return SimplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding);
5292 }
5293 
5294 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5295                               const SimplifyQuery &Q,
5296                               fp::ExceptionBehavior ExBehavior,
5297                               RoundingMode Rounding) {
5298   return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5299                             Rounding);
5300 }
5301 
5302 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5303                               const SimplifyQuery &Q,
5304                               fp::ExceptionBehavior ExBehavior,
5305                               RoundingMode Rounding) {
5306   return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5307                             Rounding);
5308 }
5309 
5310 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5311                               const SimplifyQuery &Q,
5312                               fp::ExceptionBehavior ExBehavior,
5313                               RoundingMode Rounding) {
5314   return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5315                             Rounding);
5316 }
5317 
5318 Value *llvm::SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5319                              const SimplifyQuery &Q,
5320                              fp::ExceptionBehavior ExBehavior,
5321                              RoundingMode Rounding) {
5322   return ::SimplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5323                            Rounding);
5324 }
5325 
5326 static Value *
5327 SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5328                  const SimplifyQuery &Q, unsigned,
5329                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5330                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5331   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5332     if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
5333       return C;
5334 
5335   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5336     return C;
5337 
5338   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5339     return nullptr;
5340 
5341   // X / 1.0 -> X
5342   if (match(Op1, m_FPOne()))
5343     return Op0;
5344 
5345   // 0 / X -> 0
5346   // Requires that NaNs are off (X could be zero) and signed zeroes are
5347   // ignored (X could be positive or negative, so the output sign is unknown).
5348   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5349     return ConstantFP::getNullValue(Op0->getType());
5350 
5351   if (FMF.noNaNs()) {
5352     // X / X -> 1.0 is legal when NaNs are ignored.
5353     // We can ignore infinities because INF/INF is NaN.
5354     if (Op0 == Op1)
5355       return ConstantFP::get(Op0->getType(), 1.0);
5356 
5357     // (X * Y) / Y --> X if we can reassociate to the above form.
5358     Value *X;
5359     if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
5360       return X;
5361 
5362     // -X /  X -> -1.0 and
5363     //  X / -X -> -1.0 are legal when NaNs are ignored.
5364     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
5365     if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
5366         match(Op1, m_FNegNSZ(m_Specific(Op0))))
5367       return ConstantFP::get(Op0->getType(), -1.0);
5368   }
5369 
5370   return nullptr;
5371 }
5372 
5373 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5374                               const SimplifyQuery &Q,
5375                               fp::ExceptionBehavior ExBehavior,
5376                               RoundingMode Rounding) {
5377   return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5378                             Rounding);
5379 }
5380 
5381 static Value *
5382 SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5383                  const SimplifyQuery &Q, unsigned,
5384                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5385                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5386   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5387     if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
5388       return C;
5389 
5390   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5391     return C;
5392 
5393   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5394     return nullptr;
5395 
5396   // Unlike fdiv, the result of frem always matches the sign of the dividend.
5397   // The constant match may include undef elements in a vector, so return a full
5398   // zero constant as the result.
5399   if (FMF.noNaNs()) {
5400     // +0 % X -> 0
5401     if (match(Op0, m_PosZeroFP()))
5402       return ConstantFP::getNullValue(Op0->getType());
5403     // -0 % X -> -0
5404     if (match(Op0, m_NegZeroFP()))
5405       return ConstantFP::getNegativeZero(Op0->getType());
5406   }
5407 
5408   return nullptr;
5409 }
5410 
5411 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5412                               const SimplifyQuery &Q,
5413                               fp::ExceptionBehavior ExBehavior,
5414                               RoundingMode Rounding) {
5415   return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5416                             Rounding);
5417 }
5418 
5419 //=== Helper functions for higher up the class hierarchy.
5420 
5421 /// Given the operand for a UnaryOperator, see if we can fold the result.
5422 /// If not, this returns null.
5423 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
5424                            unsigned MaxRecurse) {
5425   switch (Opcode) {
5426   case Instruction::FNeg:
5427     return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
5428   default:
5429     llvm_unreachable("Unexpected opcode");
5430   }
5431 }
5432 
5433 /// Given the operand for a UnaryOperator, see if we can fold the result.
5434 /// If not, this returns null.
5435 /// Try to use FastMathFlags when folding the result.
5436 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
5437                              const FastMathFlags &FMF,
5438                              const SimplifyQuery &Q, unsigned MaxRecurse) {
5439   switch (Opcode) {
5440   case Instruction::FNeg:
5441     return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
5442   default:
5443     return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
5444   }
5445 }
5446 
5447 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
5448   return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
5449 }
5450 
5451 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
5452                           const SimplifyQuery &Q) {
5453   return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
5454 }
5455 
5456 /// Given operands for a BinaryOperator, see if we can fold the result.
5457 /// If not, this returns null.
5458 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5459                             const SimplifyQuery &Q, unsigned MaxRecurse) {
5460   switch (Opcode) {
5461   case Instruction::Add:
5462     return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
5463   case Instruction::Sub:
5464     return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
5465   case Instruction::Mul:
5466     return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
5467   case Instruction::SDiv:
5468     return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
5469   case Instruction::UDiv:
5470     return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
5471   case Instruction::SRem:
5472     return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
5473   case Instruction::URem:
5474     return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
5475   case Instruction::Shl:
5476     return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
5477   case Instruction::LShr:
5478     return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
5479   case Instruction::AShr:
5480     return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
5481   case Instruction::And:
5482     return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
5483   case Instruction::Or:
5484     return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
5485   case Instruction::Xor:
5486     return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
5487   case Instruction::FAdd:
5488     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5489   case Instruction::FSub:
5490     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5491   case Instruction::FMul:
5492     return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5493   case Instruction::FDiv:
5494     return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5495   case Instruction::FRem:
5496     return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5497   default:
5498     llvm_unreachable("Unexpected opcode");
5499   }
5500 }
5501 
5502 /// Given operands for a BinaryOperator, see if we can fold the result.
5503 /// If not, this returns null.
5504 /// Try to use FastMathFlags when folding the result.
5505 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5506                             const FastMathFlags &FMF, const SimplifyQuery &Q,
5507                             unsigned MaxRecurse) {
5508   switch (Opcode) {
5509   case Instruction::FAdd:
5510     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
5511   case Instruction::FSub:
5512     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
5513   case Instruction::FMul:
5514     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
5515   case Instruction::FDiv:
5516     return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
5517   default:
5518     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
5519   }
5520 }
5521 
5522 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5523                            const SimplifyQuery &Q) {
5524   return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
5525 }
5526 
5527 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5528                            FastMathFlags FMF, const SimplifyQuery &Q) {
5529   return ::SimplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
5530 }
5531 
5532 /// Given operands for a CmpInst, see if we can fold the result.
5533 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5534                               const SimplifyQuery &Q, unsigned MaxRecurse) {
5535   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
5536     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
5537   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5538 }
5539 
5540 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5541                              const SimplifyQuery &Q) {
5542   return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
5543 }
5544 
5545 static bool IsIdempotent(Intrinsic::ID ID) {
5546   switch (ID) {
5547   default: return false;
5548 
5549   // Unary idempotent: f(f(x)) = f(x)
5550   case Intrinsic::fabs:
5551   case Intrinsic::floor:
5552   case Intrinsic::ceil:
5553   case Intrinsic::trunc:
5554   case Intrinsic::rint:
5555   case Intrinsic::nearbyint:
5556   case Intrinsic::round:
5557   case Intrinsic::roundeven:
5558   case Intrinsic::canonicalize:
5559     return true;
5560   }
5561 }
5562 
5563 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
5564                                    const DataLayout &DL) {
5565   GlobalValue *PtrSym;
5566   APInt PtrOffset;
5567   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
5568     return nullptr;
5569 
5570   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
5571   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
5572   Type *Int32PtrTy = Int32Ty->getPointerTo();
5573   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
5574 
5575   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
5576   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
5577     return nullptr;
5578 
5579   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
5580   if (OffsetInt % 4 != 0)
5581     return nullptr;
5582 
5583   Constant *C = ConstantExpr::getGetElementPtr(
5584       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
5585       ConstantInt::get(Int64Ty, OffsetInt / 4));
5586   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
5587   if (!Loaded)
5588     return nullptr;
5589 
5590   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
5591   if (!LoadedCE)
5592     return nullptr;
5593 
5594   if (LoadedCE->getOpcode() == Instruction::Trunc) {
5595     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5596     if (!LoadedCE)
5597       return nullptr;
5598   }
5599 
5600   if (LoadedCE->getOpcode() != Instruction::Sub)
5601     return nullptr;
5602 
5603   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5604   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
5605     return nullptr;
5606   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
5607 
5608   Constant *LoadedRHS = LoadedCE->getOperand(1);
5609   GlobalValue *LoadedRHSSym;
5610   APInt LoadedRHSOffset;
5611   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
5612                                   DL) ||
5613       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
5614     return nullptr;
5615 
5616   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
5617 }
5618 
5619 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
5620                                      const SimplifyQuery &Q) {
5621   // Idempotent functions return the same result when called repeatedly.
5622   Intrinsic::ID IID = F->getIntrinsicID();
5623   if (IsIdempotent(IID))
5624     if (auto *II = dyn_cast<IntrinsicInst>(Op0))
5625       if (II->getIntrinsicID() == IID)
5626         return II;
5627 
5628   Value *X;
5629   switch (IID) {
5630   case Intrinsic::fabs:
5631     if (SignBitMustBeZero(Op0, Q.TLI)) return Op0;
5632     break;
5633   case Intrinsic::bswap:
5634     // bswap(bswap(x)) -> x
5635     if (match(Op0, m_BSwap(m_Value(X)))) return X;
5636     break;
5637   case Intrinsic::bitreverse:
5638     // bitreverse(bitreverse(x)) -> x
5639     if (match(Op0, m_BitReverse(m_Value(X)))) return X;
5640     break;
5641   case Intrinsic::ctpop: {
5642     // If everything but the lowest bit is zero, that bit is the pop-count. Ex:
5643     // ctpop(and X, 1) --> and X, 1
5644     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
5645     if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1),
5646                           Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
5647       return Op0;
5648     break;
5649   }
5650   case Intrinsic::exp:
5651     // exp(log(x)) -> x
5652     if (Q.CxtI->hasAllowReassoc() &&
5653         match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X;
5654     break;
5655   case Intrinsic::exp2:
5656     // exp2(log2(x)) -> x
5657     if (Q.CxtI->hasAllowReassoc() &&
5658         match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X;
5659     break;
5660   case Intrinsic::log:
5661     // log(exp(x)) -> x
5662     if (Q.CxtI->hasAllowReassoc() &&
5663         match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X;
5664     break;
5665   case Intrinsic::log2:
5666     // log2(exp2(x)) -> x
5667     if (Q.CxtI->hasAllowReassoc() &&
5668         (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
5669          match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0),
5670                                                 m_Value(X))))) return X;
5671     break;
5672   case Intrinsic::log10:
5673     // log10(pow(10.0, x)) -> x
5674     if (Q.CxtI->hasAllowReassoc() &&
5675         match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0),
5676                                                m_Value(X)))) return X;
5677     break;
5678   case Intrinsic::floor:
5679   case Intrinsic::trunc:
5680   case Intrinsic::ceil:
5681   case Intrinsic::round:
5682   case Intrinsic::roundeven:
5683   case Intrinsic::nearbyint:
5684   case Intrinsic::rint: {
5685     // floor (sitofp x) -> sitofp x
5686     // floor (uitofp x) -> uitofp x
5687     //
5688     // Converting from int always results in a finite integral number or
5689     // infinity. For either of those inputs, these rounding functions always
5690     // return the same value, so the rounding can be eliminated.
5691     if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
5692       return Op0;
5693     break;
5694   }
5695   case Intrinsic::experimental_vector_reverse:
5696     // experimental.vector.reverse(experimental.vector.reverse(x)) -> x
5697     if (match(Op0,
5698               m_Intrinsic<Intrinsic::experimental_vector_reverse>(m_Value(X))))
5699       return X;
5700     // experimental.vector.reverse(splat(X)) -> splat(X)
5701     if (isSplatValue(Op0))
5702       return Op0;
5703     break;
5704   default:
5705     break;
5706   }
5707 
5708   return nullptr;
5709 }
5710 
5711 /// Given a min/max intrinsic, see if it can be removed based on having an
5712 /// operand that is another min/max intrinsic with shared operand(s). The caller
5713 /// is expected to swap the operand arguments to handle commutation.
5714 static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) {
5715   Value *X, *Y;
5716   if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y))))
5717     return nullptr;
5718 
5719   auto *MM0 = dyn_cast<IntrinsicInst>(Op0);
5720   if (!MM0)
5721     return nullptr;
5722   Intrinsic::ID IID0 = MM0->getIntrinsicID();
5723 
5724   if (Op1 == X || Op1 == Y ||
5725       match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) {
5726     // max (max X, Y), X --> max X, Y
5727     if (IID0 == IID)
5728       return MM0;
5729     // max (min X, Y), X --> X
5730     if (IID0 == getInverseMinMaxIntrinsic(IID))
5731       return Op1;
5732   }
5733   return nullptr;
5734 }
5735 
5736 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
5737                                       const SimplifyQuery &Q) {
5738   Intrinsic::ID IID = F->getIntrinsicID();
5739   Type *ReturnType = F->getReturnType();
5740   unsigned BitWidth = ReturnType->getScalarSizeInBits();
5741   switch (IID) {
5742   case Intrinsic::abs:
5743     // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here.
5744     // It is always ok to pick the earlier abs. We'll just lose nsw if its only
5745     // on the outer abs.
5746     if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value())))
5747       return Op0;
5748     break;
5749 
5750   case Intrinsic::cttz: {
5751     Value *X;
5752     if (match(Op0, m_Shl(m_One(), m_Value(X))))
5753       return X;
5754     break;
5755   }
5756   case Intrinsic::ctlz: {
5757     Value *X;
5758     if (match(Op0, m_LShr(m_Negative(), m_Value(X))))
5759       return X;
5760     if (match(Op0, m_AShr(m_Negative(), m_Value())))
5761       return Constant::getNullValue(ReturnType);
5762     break;
5763   }
5764   case Intrinsic::smax:
5765   case Intrinsic::smin:
5766   case Intrinsic::umax:
5767   case Intrinsic::umin: {
5768     // If the arguments are the same, this is a no-op.
5769     if (Op0 == Op1)
5770       return Op0;
5771 
5772     // Canonicalize constant operand as Op1.
5773     if (isa<Constant>(Op0))
5774       std::swap(Op0, Op1);
5775 
5776     // Assume undef is the limit value.
5777     if (Q.isUndefValue(Op1))
5778       return ConstantInt::get(
5779           ReturnType, MinMaxIntrinsic::getSaturationPoint(IID, BitWidth));
5780 
5781     const APInt *C;
5782     if (match(Op1, m_APIntAllowUndef(C))) {
5783       // Clamp to limit value. For example:
5784       // umax(i8 %x, i8 255) --> 255
5785       if (*C == MinMaxIntrinsic::getSaturationPoint(IID, BitWidth))
5786         return ConstantInt::get(ReturnType, *C);
5787 
5788       // If the constant op is the opposite of the limit value, the other must
5789       // be larger/smaller or equal. For example:
5790       // umin(i8 %x, i8 255) --> %x
5791       if (*C == MinMaxIntrinsic::getSaturationPoint(
5792                     getInverseMinMaxIntrinsic(IID), BitWidth))
5793         return Op0;
5794 
5795       // Remove nested call if constant operands allow it. Example:
5796       // max (max X, 7), 5 -> max X, 7
5797       auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0);
5798       if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
5799         // TODO: loosen undef/splat restrictions for vector constants.
5800         Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1);
5801         const APInt *InnerC;
5802         if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) &&
5803             ICmpInst::compare(*InnerC, *C,
5804                               ICmpInst::getNonStrictPredicate(
5805                                   MinMaxIntrinsic::getPredicate(IID))))
5806           return Op0;
5807       }
5808     }
5809 
5810     if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
5811       return V;
5812     if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0))
5813       return V;
5814 
5815     ICmpInst::Predicate Pred =
5816         ICmpInst::getNonStrictPredicate(MinMaxIntrinsic::getPredicate(IID));
5817     if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit))
5818       return Op0;
5819     if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit))
5820       return Op1;
5821 
5822     if (Optional<bool> Imp =
5823             isImpliedByDomCondition(Pred, Op0, Op1, Q.CxtI, Q.DL))
5824       return *Imp ? Op0 : Op1;
5825     if (Optional<bool> Imp =
5826             isImpliedByDomCondition(Pred, Op1, Op0, Q.CxtI, Q.DL))
5827       return *Imp ? Op1 : Op0;
5828 
5829     break;
5830   }
5831   case Intrinsic::usub_with_overflow:
5832   case Intrinsic::ssub_with_overflow:
5833     // X - X -> { 0, false }
5834     // X - undef -> { 0, false }
5835     // undef - X -> { 0, false }
5836     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5837       return Constant::getNullValue(ReturnType);
5838     break;
5839   case Intrinsic::uadd_with_overflow:
5840   case Intrinsic::sadd_with_overflow:
5841     // X + undef -> { -1, false }
5842     // undef + x -> { -1, false }
5843     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) {
5844       return ConstantStruct::get(
5845           cast<StructType>(ReturnType),
5846           {Constant::getAllOnesValue(ReturnType->getStructElementType(0)),
5847            Constant::getNullValue(ReturnType->getStructElementType(1))});
5848     }
5849     break;
5850   case Intrinsic::umul_with_overflow:
5851   case Intrinsic::smul_with_overflow:
5852     // 0 * X -> { 0, false }
5853     // X * 0 -> { 0, false }
5854     if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
5855       return Constant::getNullValue(ReturnType);
5856     // undef * X -> { 0, false }
5857     // X * undef -> { 0, false }
5858     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5859       return Constant::getNullValue(ReturnType);
5860     break;
5861   case Intrinsic::uadd_sat:
5862     // sat(MAX + X) -> MAX
5863     // sat(X + MAX) -> MAX
5864     if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
5865       return Constant::getAllOnesValue(ReturnType);
5866     LLVM_FALLTHROUGH;
5867   case Intrinsic::sadd_sat:
5868     // sat(X + undef) -> -1
5869     // sat(undef + X) -> -1
5870     // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
5871     // For signed: Assume undef is ~X, in which case X + ~X = -1.
5872     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5873       return Constant::getAllOnesValue(ReturnType);
5874 
5875     // X + 0 -> X
5876     if (match(Op1, m_Zero()))
5877       return Op0;
5878     // 0 + X -> X
5879     if (match(Op0, m_Zero()))
5880       return Op1;
5881     break;
5882   case Intrinsic::usub_sat:
5883     // sat(0 - X) -> 0, sat(X - MAX) -> 0
5884     if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
5885       return Constant::getNullValue(ReturnType);
5886     LLVM_FALLTHROUGH;
5887   case Intrinsic::ssub_sat:
5888     // X - X -> 0, X - undef -> 0, undef - X -> 0
5889     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5890       return Constant::getNullValue(ReturnType);
5891     // X - 0 -> X
5892     if (match(Op1, m_Zero()))
5893       return Op0;
5894     break;
5895   case Intrinsic::load_relative:
5896     if (auto *C0 = dyn_cast<Constant>(Op0))
5897       if (auto *C1 = dyn_cast<Constant>(Op1))
5898         return SimplifyRelativeLoad(C0, C1, Q.DL);
5899     break;
5900   case Intrinsic::powi:
5901     if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
5902       // powi(x, 0) -> 1.0
5903       if (Power->isZero())
5904         return ConstantFP::get(Op0->getType(), 1.0);
5905       // powi(x, 1) -> x
5906       if (Power->isOne())
5907         return Op0;
5908     }
5909     break;
5910   case Intrinsic::copysign:
5911     // copysign X, X --> X
5912     if (Op0 == Op1)
5913       return Op0;
5914     // copysign -X, X --> X
5915     // copysign X, -X --> -X
5916     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
5917         match(Op1, m_FNeg(m_Specific(Op0))))
5918       return Op1;
5919     break;
5920   case Intrinsic::maxnum:
5921   case Intrinsic::minnum:
5922   case Intrinsic::maximum:
5923   case Intrinsic::minimum: {
5924     // If the arguments are the same, this is a no-op.
5925     if (Op0 == Op1) return Op0;
5926 
5927     // Canonicalize constant operand as Op1.
5928     if (isa<Constant>(Op0))
5929       std::swap(Op0, Op1);
5930 
5931     // If an argument is undef, return the other argument.
5932     if (Q.isUndefValue(Op1))
5933       return Op0;
5934 
5935     bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
5936     bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum;
5937 
5938     // minnum(X, nan) -> X
5939     // maxnum(X, nan) -> X
5940     // minimum(X, nan) -> nan
5941     // maximum(X, nan) -> nan
5942     if (match(Op1, m_NaN()))
5943       return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0;
5944 
5945     // In the following folds, inf can be replaced with the largest finite
5946     // float, if the ninf flag is set.
5947     const APFloat *C;
5948     if (match(Op1, m_APFloat(C)) &&
5949         (C->isInfinity() || (Q.CxtI->hasNoInfs() && C->isLargest()))) {
5950       // minnum(X, -inf) -> -inf
5951       // maxnum(X, +inf) -> +inf
5952       // minimum(X, -inf) -> -inf if nnan
5953       // maximum(X, +inf) -> +inf if nnan
5954       if (C->isNegative() == IsMin && (!PropagateNaN || Q.CxtI->hasNoNaNs()))
5955         return ConstantFP::get(ReturnType, *C);
5956 
5957       // minnum(X, +inf) -> X if nnan
5958       // maxnum(X, -inf) -> X if nnan
5959       // minimum(X, +inf) -> X
5960       // maximum(X, -inf) -> X
5961       if (C->isNegative() != IsMin && (PropagateNaN || Q.CxtI->hasNoNaNs()))
5962         return Op0;
5963     }
5964 
5965     // Min/max of the same operation with common operand:
5966     // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
5967     if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
5968       if (M0->getIntrinsicID() == IID &&
5969           (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
5970         return Op0;
5971     if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
5972       if (M1->getIntrinsicID() == IID &&
5973           (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
5974         return Op1;
5975 
5976     break;
5977   }
5978   case Intrinsic::experimental_vector_extract: {
5979     Type *ReturnType = F->getReturnType();
5980 
5981     // (extract_vector (insert_vector _, X, 0), 0) -> X
5982     unsigned IdxN = cast<ConstantInt>(Op1)->getZExtValue();
5983     Value *X = nullptr;
5984     if (match(Op0, m_Intrinsic<Intrinsic::experimental_vector_insert>(
5985                        m_Value(), m_Value(X), m_Zero())) &&
5986         IdxN == 0 && X->getType() == ReturnType)
5987       return X;
5988 
5989     break;
5990   }
5991   default:
5992     break;
5993   }
5994 
5995   return nullptr;
5996 }
5997 
5998 static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
5999 
6000   unsigned NumOperands = Call->arg_size();
6001   Function *F = cast<Function>(Call->getCalledFunction());
6002   Intrinsic::ID IID = F->getIntrinsicID();
6003 
6004   // Most of the intrinsics with no operands have some kind of side effect.
6005   // Don't simplify.
6006   if (!NumOperands) {
6007     switch (IID) {
6008     case Intrinsic::vscale: {
6009       // Call may not be inserted into the IR yet at point of calling simplify.
6010       if (!Call->getParent() || !Call->getParent()->getParent())
6011         return nullptr;
6012       auto Attr = Call->getFunction()->getFnAttribute(Attribute::VScaleRange);
6013       if (!Attr.isValid())
6014         return nullptr;
6015       unsigned VScaleMin = Attr.getVScaleRangeMin();
6016       Optional<unsigned> VScaleMax = Attr.getVScaleRangeMax();
6017       if (VScaleMax && VScaleMin == VScaleMax)
6018         return ConstantInt::get(F->getReturnType(), VScaleMin);
6019       return nullptr;
6020     }
6021     default:
6022       return nullptr;
6023     }
6024   }
6025 
6026   if (NumOperands == 1)
6027     return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q);
6028 
6029   if (NumOperands == 2)
6030     return simplifyBinaryIntrinsic(F, Call->getArgOperand(0),
6031                                    Call->getArgOperand(1), Q);
6032 
6033   // Handle intrinsics with 3 or more arguments.
6034   switch (IID) {
6035   case Intrinsic::masked_load:
6036   case Intrinsic::masked_gather: {
6037     Value *MaskArg = Call->getArgOperand(2);
6038     Value *PassthruArg = Call->getArgOperand(3);
6039     // If the mask is all zeros or undef, the "passthru" argument is the result.
6040     if (maskIsAllZeroOrUndef(MaskArg))
6041       return PassthruArg;
6042     return nullptr;
6043   }
6044   case Intrinsic::fshl:
6045   case Intrinsic::fshr: {
6046     Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1),
6047           *ShAmtArg = Call->getArgOperand(2);
6048 
6049     // If both operands are undef, the result is undef.
6050     if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1))
6051       return UndefValue::get(F->getReturnType());
6052 
6053     // If shift amount is undef, assume it is zero.
6054     if (Q.isUndefValue(ShAmtArg))
6055       return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
6056 
6057     const APInt *ShAmtC;
6058     if (match(ShAmtArg, m_APInt(ShAmtC))) {
6059       // If there's effectively no shift, return the 1st arg or 2nd arg.
6060       APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
6061       if (ShAmtC->urem(BitWidth).isZero())
6062         return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
6063     }
6064 
6065     // Rotating zero by anything is zero.
6066     if (match(Op0, m_Zero()) && match(Op1, m_Zero()))
6067       return ConstantInt::getNullValue(F->getReturnType());
6068 
6069     // Rotating -1 by anything is -1.
6070     if (match(Op0, m_AllOnes()) && match(Op1, m_AllOnes()))
6071       return ConstantInt::getAllOnesValue(F->getReturnType());
6072 
6073     return nullptr;
6074   }
6075   case Intrinsic::experimental_constrained_fma: {
6076     Value *Op0 = Call->getArgOperand(0);
6077     Value *Op1 = Call->getArgOperand(1);
6078     Value *Op2 = Call->getArgOperand(2);
6079     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6080     if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q,
6081                                 FPI->getExceptionBehavior().getValue(),
6082                                 FPI->getRoundingMode().getValue()))
6083       return V;
6084     return nullptr;
6085   }
6086   case Intrinsic::fma:
6087   case Intrinsic::fmuladd: {
6088     Value *Op0 = Call->getArgOperand(0);
6089     Value *Op1 = Call->getArgOperand(1);
6090     Value *Op2 = Call->getArgOperand(2);
6091     if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, fp::ebIgnore,
6092                                 RoundingMode::NearestTiesToEven))
6093       return V;
6094     return nullptr;
6095   }
6096   case Intrinsic::smul_fix:
6097   case Intrinsic::smul_fix_sat: {
6098     Value *Op0 = Call->getArgOperand(0);
6099     Value *Op1 = Call->getArgOperand(1);
6100     Value *Op2 = Call->getArgOperand(2);
6101     Type *ReturnType = F->getReturnType();
6102 
6103     // Canonicalize constant operand as Op1 (ConstantFolding handles the case
6104     // when both Op0 and Op1 are constant so we do not care about that special
6105     // case here).
6106     if (isa<Constant>(Op0))
6107       std::swap(Op0, Op1);
6108 
6109     // X * 0 -> 0
6110     if (match(Op1, m_Zero()))
6111       return Constant::getNullValue(ReturnType);
6112 
6113     // X * undef -> 0
6114     if (Q.isUndefValue(Op1))
6115       return Constant::getNullValue(ReturnType);
6116 
6117     // X * (1 << Scale) -> X
6118     APInt ScaledOne =
6119         APInt::getOneBitSet(ReturnType->getScalarSizeInBits(),
6120                             cast<ConstantInt>(Op2)->getZExtValue());
6121     if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne)))
6122       return Op0;
6123 
6124     return nullptr;
6125   }
6126   case Intrinsic::experimental_vector_insert: {
6127     Value *Vec = Call->getArgOperand(0);
6128     Value *SubVec = Call->getArgOperand(1);
6129     Value *Idx = Call->getArgOperand(2);
6130     Type *ReturnType = F->getReturnType();
6131 
6132     // (insert_vector Y, (extract_vector X, 0), 0) -> X
6133     // where: Y is X, or Y is undef
6134     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6135     Value *X = nullptr;
6136     if (match(SubVec, m_Intrinsic<Intrinsic::experimental_vector_extract>(
6137                           m_Value(X), m_Zero())) &&
6138         (Q.isUndefValue(Vec) || Vec == X) && IdxN == 0 &&
6139         X->getType() == ReturnType)
6140       return X;
6141 
6142     return nullptr;
6143   }
6144   case Intrinsic::experimental_constrained_fadd: {
6145     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6146     return SimplifyFAddInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6147                             FPI->getFastMathFlags(), Q,
6148                             FPI->getExceptionBehavior().getValue(),
6149                             FPI->getRoundingMode().getValue());
6150     break;
6151   }
6152   case Intrinsic::experimental_constrained_fsub: {
6153     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6154     return SimplifyFSubInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6155                             FPI->getFastMathFlags(), Q,
6156                             FPI->getExceptionBehavior().getValue(),
6157                             FPI->getRoundingMode().getValue());
6158     break;
6159   }
6160   case Intrinsic::experimental_constrained_fmul: {
6161     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6162     return SimplifyFMulInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6163                             FPI->getFastMathFlags(), Q,
6164                             FPI->getExceptionBehavior().getValue(),
6165                             FPI->getRoundingMode().getValue());
6166     break;
6167   }
6168   case Intrinsic::experimental_constrained_fdiv: {
6169     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6170     return SimplifyFDivInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6171                             FPI->getFastMathFlags(), Q,
6172                             FPI->getExceptionBehavior().getValue(),
6173                             FPI->getRoundingMode().getValue());
6174     break;
6175   }
6176   case Intrinsic::experimental_constrained_frem: {
6177     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6178     return SimplifyFRemInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6179                             FPI->getFastMathFlags(), Q,
6180                             FPI->getExceptionBehavior().getValue(),
6181                             FPI->getRoundingMode().getValue());
6182     break;
6183   }
6184   default:
6185     return nullptr;
6186   }
6187 }
6188 
6189 static Value *tryConstantFoldCall(CallBase *Call, const SimplifyQuery &Q) {
6190   auto *F = dyn_cast<Function>(Call->getCalledOperand());
6191   if (!F || !canConstantFoldCallTo(Call, F))
6192     return nullptr;
6193 
6194   SmallVector<Constant *, 4> ConstantArgs;
6195   unsigned NumArgs = Call->arg_size();
6196   ConstantArgs.reserve(NumArgs);
6197   for (auto &Arg : Call->args()) {
6198     Constant *C = dyn_cast<Constant>(&Arg);
6199     if (!C) {
6200       if (isa<MetadataAsValue>(Arg.get()))
6201         continue;
6202       return nullptr;
6203     }
6204     ConstantArgs.push_back(C);
6205   }
6206 
6207   return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
6208 }
6209 
6210 Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) {
6211   // musttail calls can only be simplified if they are also DCEd.
6212   // As we can't guarantee this here, don't simplify them.
6213   if (Call->isMustTailCall())
6214     return nullptr;
6215 
6216   // call undef -> poison
6217   // call null -> poison
6218   Value *Callee = Call->getCalledOperand();
6219   if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
6220     return PoisonValue::get(Call->getType());
6221 
6222   if (Value *V = tryConstantFoldCall(Call, Q))
6223     return V;
6224 
6225   auto *F = dyn_cast<Function>(Callee);
6226   if (F && F->isIntrinsic())
6227     if (Value *Ret = simplifyIntrinsic(Call, Q))
6228       return Ret;
6229 
6230   return nullptr;
6231 }
6232 
6233 /// Given operands for a Freeze, see if we can fold the result.
6234 static Value *SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
6235   // Use a utility function defined in ValueTracking.
6236   if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT))
6237     return Op0;
6238   // We have room for improvement.
6239   return nullptr;
6240 }
6241 
6242 Value *llvm::SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
6243   return ::SimplifyFreezeInst(Op0, Q);
6244 }
6245 
6246 static Value *SimplifyLoadInst(LoadInst *LI, Value *PtrOp,
6247                                const SimplifyQuery &Q) {
6248   if (LI->isVolatile())
6249     return nullptr;
6250 
6251   APInt Offset(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
6252   auto *PtrOpC = dyn_cast<Constant>(PtrOp);
6253   // Try to convert operand into a constant by stripping offsets while looking
6254   // through invariant.group intrinsics. Don't bother if the underlying object
6255   // is not constant, as calculating GEP offsets is expensive.
6256   if (!PtrOpC && isa<Constant>(getUnderlyingObject(PtrOp))) {
6257     PtrOp = PtrOp->stripAndAccumulateConstantOffsets(
6258         Q.DL, Offset, /* AllowNonInbounts */ true,
6259         /* AllowInvariantGroup */ true);
6260     // Index size may have changed due to address space casts.
6261     Offset = Offset.sextOrTrunc(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()));
6262     PtrOpC = dyn_cast<Constant>(PtrOp);
6263   }
6264 
6265   if (PtrOpC)
6266     return ConstantFoldLoadFromConstPtr(PtrOpC, LI->getType(), Offset, Q.DL);
6267   return nullptr;
6268 }
6269 
6270 /// See if we can compute a simplified version of this instruction.
6271 /// If not, this returns null.
6272 
6273 static Value *simplifyInstructionWithOperands(Instruction *I,
6274                                               ArrayRef<Value *> NewOps,
6275                                               const SimplifyQuery &SQ,
6276                                               OptimizationRemarkEmitter *ORE) {
6277   const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
6278   Value *Result = nullptr;
6279 
6280   switch (I->getOpcode()) {
6281   default:
6282     if (llvm::all_of(NewOps, [](Value *V) { return isa<Constant>(V); })) {
6283       SmallVector<Constant *, 8> NewConstOps(NewOps.size());
6284       transform(NewOps, NewConstOps.begin(),
6285                 [](Value *V) { return cast<Constant>(V); });
6286       Result = ConstantFoldInstOperands(I, NewConstOps, Q.DL, Q.TLI);
6287     }
6288     break;
6289   case Instruction::FNeg:
6290     Result = SimplifyFNegInst(NewOps[0], I->getFastMathFlags(), Q);
6291     break;
6292   case Instruction::FAdd:
6293     Result = SimplifyFAddInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6294     break;
6295   case Instruction::Add:
6296     Result = SimplifyAddInst(
6297         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6298         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
6299     break;
6300   case Instruction::FSub:
6301     Result = SimplifyFSubInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6302     break;
6303   case Instruction::Sub:
6304     Result = SimplifySubInst(
6305         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6306         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
6307     break;
6308   case Instruction::FMul:
6309     Result = SimplifyFMulInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6310     break;
6311   case Instruction::Mul:
6312     Result = SimplifyMulInst(NewOps[0], NewOps[1], Q);
6313     break;
6314   case Instruction::SDiv:
6315     Result = SimplifySDivInst(NewOps[0], NewOps[1], Q);
6316     break;
6317   case Instruction::UDiv:
6318     Result = SimplifyUDivInst(NewOps[0], NewOps[1], Q);
6319     break;
6320   case Instruction::FDiv:
6321     Result = SimplifyFDivInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6322     break;
6323   case Instruction::SRem:
6324     Result = SimplifySRemInst(NewOps[0], NewOps[1], Q);
6325     break;
6326   case Instruction::URem:
6327     Result = SimplifyURemInst(NewOps[0], NewOps[1], Q);
6328     break;
6329   case Instruction::FRem:
6330     Result = SimplifyFRemInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6331     break;
6332   case Instruction::Shl:
6333     Result = SimplifyShlInst(
6334         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6335         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
6336     break;
6337   case Instruction::LShr:
6338     Result = SimplifyLShrInst(NewOps[0], NewOps[1],
6339                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
6340     break;
6341   case Instruction::AShr:
6342     Result = SimplifyAShrInst(NewOps[0], NewOps[1],
6343                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
6344     break;
6345   case Instruction::And:
6346     Result = SimplifyAndInst(NewOps[0], NewOps[1], Q);
6347     break;
6348   case Instruction::Or:
6349     Result = SimplifyOrInst(NewOps[0], NewOps[1], Q);
6350     break;
6351   case Instruction::Xor:
6352     Result = SimplifyXorInst(NewOps[0], NewOps[1], Q);
6353     break;
6354   case Instruction::ICmp:
6355     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), NewOps[0],
6356                               NewOps[1], Q);
6357     break;
6358   case Instruction::FCmp:
6359     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), NewOps[0],
6360                               NewOps[1], I->getFastMathFlags(), Q);
6361     break;
6362   case Instruction::Select:
6363     Result = SimplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q);
6364     break;
6365   case Instruction::GetElementPtr: {
6366     auto *GEPI = cast<GetElementPtrInst>(I);
6367     Result =
6368         SimplifyGEPInst(GEPI->getSourceElementType(), NewOps[0],
6369                         makeArrayRef(NewOps).slice(1), GEPI->isInBounds(), Q);
6370     break;
6371   }
6372   case Instruction::InsertValue: {
6373     InsertValueInst *IV = cast<InsertValueInst>(I);
6374     Result = SimplifyInsertValueInst(NewOps[0], NewOps[1], IV->getIndices(), Q);
6375     break;
6376   }
6377   case Instruction::InsertElement: {
6378     Result = SimplifyInsertElementInst(NewOps[0], NewOps[1], NewOps[2], Q);
6379     break;
6380   }
6381   case Instruction::ExtractValue: {
6382     auto *EVI = cast<ExtractValueInst>(I);
6383     Result = SimplifyExtractValueInst(NewOps[0], EVI->getIndices(), Q);
6384     break;
6385   }
6386   case Instruction::ExtractElement: {
6387     Result = SimplifyExtractElementInst(NewOps[0], NewOps[1], Q);
6388     break;
6389   }
6390   case Instruction::ShuffleVector: {
6391     auto *SVI = cast<ShuffleVectorInst>(I);
6392     Result = SimplifyShuffleVectorInst(
6393         NewOps[0], NewOps[1], SVI->getShuffleMask(), SVI->getType(), Q);
6394     break;
6395   }
6396   case Instruction::PHI:
6397     Result = SimplifyPHINode(cast<PHINode>(I), NewOps, Q);
6398     break;
6399   case Instruction::Call: {
6400     // TODO: Use NewOps
6401     Result = SimplifyCall(cast<CallInst>(I), Q);
6402     break;
6403   }
6404   case Instruction::Freeze:
6405     Result = llvm::SimplifyFreezeInst(NewOps[0], Q);
6406     break;
6407 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
6408 #include "llvm/IR/Instruction.def"
6409 #undef HANDLE_CAST_INST
6410     Result = SimplifyCastInst(I->getOpcode(), NewOps[0], I->getType(), Q);
6411     break;
6412   case Instruction::Alloca:
6413     // No simplifications for Alloca and it can't be constant folded.
6414     Result = nullptr;
6415     break;
6416   case Instruction::Load:
6417     Result = SimplifyLoadInst(cast<LoadInst>(I), NewOps[0], Q);
6418     break;
6419   }
6420 
6421   /// If called on unreachable code, the above logic may report that the
6422   /// instruction simplified to itself.  Make life easier for users by
6423   /// detecting that case here, returning a safe value instead.
6424   return Result == I ? UndefValue::get(I->getType()) : Result;
6425 }
6426 
6427 Value *llvm::SimplifyInstructionWithOperands(Instruction *I,
6428                                              ArrayRef<Value *> NewOps,
6429                                              const SimplifyQuery &SQ,
6430                                              OptimizationRemarkEmitter *ORE) {
6431   assert(NewOps.size() == I->getNumOperands() &&
6432          "Number of operands should match the instruction!");
6433   return ::simplifyInstructionWithOperands(I, NewOps, SQ, ORE);
6434 }
6435 
6436 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
6437                                  OptimizationRemarkEmitter *ORE) {
6438   SmallVector<Value *, 8> Ops(I->operands());
6439   return ::simplifyInstructionWithOperands(I, Ops, SQ, ORE);
6440 }
6441 
6442 /// Implementation of recursive simplification through an instruction's
6443 /// uses.
6444 ///
6445 /// This is the common implementation of the recursive simplification routines.
6446 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
6447 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
6448 /// instructions to process and attempt to simplify it using
6449 /// InstructionSimplify. Recursively visited users which could not be
6450 /// simplified themselves are to the optional UnsimplifiedUsers set for
6451 /// further processing by the caller.
6452 ///
6453 /// This routine returns 'true' only when *it* simplifies something. The passed
6454 /// in simplified value does not count toward this.
6455 static bool replaceAndRecursivelySimplifyImpl(
6456     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
6457     const DominatorTree *DT, AssumptionCache *AC,
6458     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
6459   bool Simplified = false;
6460   SmallSetVector<Instruction *, 8> Worklist;
6461   const DataLayout &DL = I->getModule()->getDataLayout();
6462 
6463   // If we have an explicit value to collapse to, do that round of the
6464   // simplification loop by hand initially.
6465   if (SimpleV) {
6466     for (User *U : I->users())
6467       if (U != I)
6468         Worklist.insert(cast<Instruction>(U));
6469 
6470     // Replace the instruction with its simplified value.
6471     I->replaceAllUsesWith(SimpleV);
6472 
6473     // Gracefully handle edge cases where the instruction is not wired into any
6474     // parent block.
6475     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
6476         !I->mayHaveSideEffects())
6477       I->eraseFromParent();
6478   } else {
6479     Worklist.insert(I);
6480   }
6481 
6482   // Note that we must test the size on each iteration, the worklist can grow.
6483   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
6484     I = Worklist[Idx];
6485 
6486     // See if this instruction simplifies.
6487     SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
6488     if (!SimpleV) {
6489       if (UnsimplifiedUsers)
6490         UnsimplifiedUsers->insert(I);
6491       continue;
6492     }
6493 
6494     Simplified = true;
6495 
6496     // Stash away all the uses of the old instruction so we can check them for
6497     // recursive simplifications after a RAUW. This is cheaper than checking all
6498     // uses of To on the recursive step in most cases.
6499     for (User *U : I->users())
6500       Worklist.insert(cast<Instruction>(U));
6501 
6502     // Replace the instruction with its simplified value.
6503     I->replaceAllUsesWith(SimpleV);
6504 
6505     // Gracefully handle edge cases where the instruction is not wired into any
6506     // parent block.
6507     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
6508         !I->mayHaveSideEffects())
6509       I->eraseFromParent();
6510   }
6511   return Simplified;
6512 }
6513 
6514 bool llvm::replaceAndRecursivelySimplify(
6515     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
6516     const DominatorTree *DT, AssumptionCache *AC,
6517     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
6518   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
6519   assert(SimpleV && "Must provide a simplified value.");
6520   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
6521                                            UnsimplifiedUsers);
6522 }
6523 
6524 namespace llvm {
6525 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
6526   auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
6527   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
6528   auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
6529   auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
6530   auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
6531   auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
6532   return {F.getParent()->getDataLayout(), TLI, DT, AC};
6533 }
6534 
6535 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
6536                                          const DataLayout &DL) {
6537   return {DL, &AR.TLI, &AR.DT, &AR.AC};
6538 }
6539 
6540 template <class T, class... TArgs>
6541 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
6542                                          Function &F) {
6543   auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
6544   auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
6545   auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
6546   return {F.getParent()->getDataLayout(), TLI, DT, AC};
6547 }
6548 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
6549                                                   Function &);
6550 }
6551 
6552 void InstSimplifyFolder::anchor() {}
6553