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