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