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