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