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