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