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)
3932     return nullptr;
3933 
3934   // Consider:
3935   //   %cmp = icmp eq i32 %x, 2147483647
3936   //   %add = add nsw i32 %x, 1
3937   //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
3938   //
3939   // We can't replace %sel with %add unless we strip away the flags (which will
3940   // be done in InstCombine).
3941   // TODO: This is unsound, because it only catches some forms of refinement.
3942   if (!AllowRefinement && canCreatePoison(cast<Operator>(I)))
3943     return nullptr;
3944 
3945   // The simplification queries below may return the original value. Consider:
3946   //   %div = udiv i32 %arg, %arg2
3947   //   %mul = mul nsw i32 %div, %arg2
3948   //   %cmp = icmp eq i32 %mul, %arg
3949   //   %sel = select i1 %cmp, i32 %div, i32 undef
3950   // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which
3951   // simplifies back to %arg. This can only happen because %mul does not
3952   // dominate %div. To ensure a consistent return value contract, we make sure
3953   // that this case returns nullptr as well.
3954   auto PreventSelfSimplify = [V](Value *Simplified) {
3955     return Simplified != V ? Simplified : nullptr;
3956   };
3957 
3958   // If this is a binary operator, try to simplify it with the replaced op.
3959   if (auto *B = dyn_cast<BinaryOperator>(I)) {
3960     if (MaxRecurse) {
3961       if (B->getOperand(0) == Op)
3962         return PreventSelfSimplify(SimplifyBinOp(B->getOpcode(), RepOp,
3963                                                  B->getOperand(1), Q,
3964                                                  MaxRecurse - 1));
3965       if (B->getOperand(1) == Op)
3966         return PreventSelfSimplify(SimplifyBinOp(B->getOpcode(),
3967                                                  B->getOperand(0), RepOp, Q,
3968                                                  MaxRecurse - 1));
3969     }
3970   }
3971 
3972   // Same for CmpInsts.
3973   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3974     if (MaxRecurse) {
3975       if (C->getOperand(0) == Op)
3976         return PreventSelfSimplify(SimplifyCmpInst(C->getPredicate(), RepOp,
3977                                                    C->getOperand(1), Q,
3978                                                    MaxRecurse - 1));
3979       if (C->getOperand(1) == Op)
3980         return PreventSelfSimplify(SimplifyCmpInst(C->getPredicate(),
3981                                                    C->getOperand(0), RepOp, Q,
3982                                                    MaxRecurse - 1));
3983     }
3984   }
3985 
3986   // Same for GEPs.
3987   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3988     if (MaxRecurse) {
3989       SmallVector<Value *, 8> NewOps(GEP->getNumOperands());
3990       transform(GEP->operands(), NewOps.begin(),
3991                 [&](Value *V) { return V == Op ? RepOp : V; });
3992       return PreventSelfSimplify(SimplifyGEPInst(GEP->getSourceElementType(),
3993                                                  NewOps, Q, MaxRecurse - 1));
3994     }
3995   }
3996 
3997   // TODO: We could hand off more cases to instsimplify here.
3998 
3999   // If all operands are constant after substituting Op for RepOp then we can
4000   // constant fold the instruction.
4001   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
4002     // Build a list of all constant operands.
4003     SmallVector<Constant *, 8> ConstOps;
4004     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4005       if (I->getOperand(i) == Op)
4006         ConstOps.push_back(CRepOp);
4007       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
4008         ConstOps.push_back(COp);
4009       else
4010         break;
4011     }
4012 
4013     // All operands were constants, fold it.
4014     if (ConstOps.size() == I->getNumOperands()) {
4015       if (CmpInst *C = dyn_cast<CmpInst>(I))
4016         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
4017                                                ConstOps[1], Q.DL, Q.TLI);
4018 
4019       if (LoadInst *LI = dyn_cast<LoadInst>(I))
4020         if (!LI->isVolatile())
4021           return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
4022 
4023       return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
4024     }
4025   }
4026 
4027   return nullptr;
4028 }
4029 
4030 Value *llvm::SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4031                                     const SimplifyQuery &Q,
4032                                     bool AllowRefinement) {
4033   return ::SimplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement,
4034                                   RecursionLimit);
4035 }
4036 
4037 /// Try to simplify a select instruction when its condition operand is an
4038 /// integer comparison where one operand of the compare is a constant.
4039 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
4040                                     const APInt *Y, bool TrueWhenUnset) {
4041   const APInt *C;
4042 
4043   // (X & Y) == 0 ? X & ~Y : X  --> X
4044   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
4045   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
4046       *Y == ~*C)
4047     return TrueWhenUnset ? FalseVal : TrueVal;
4048 
4049   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
4050   // (X & Y) != 0 ? X : X & ~Y  --> X
4051   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
4052       *Y == ~*C)
4053     return TrueWhenUnset ? FalseVal : TrueVal;
4054 
4055   if (Y->isPowerOf2()) {
4056     // (X & Y) == 0 ? X | Y : X  --> X | Y
4057     // (X & Y) != 0 ? X | Y : X  --> X
4058     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
4059         *Y == *C)
4060       return TrueWhenUnset ? TrueVal : FalseVal;
4061 
4062     // (X & Y) == 0 ? X : X | Y  --> X
4063     // (X & Y) != 0 ? X : X | Y  --> X | Y
4064     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
4065         *Y == *C)
4066       return TrueWhenUnset ? TrueVal : FalseVal;
4067   }
4068 
4069   return nullptr;
4070 }
4071 
4072 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
4073 /// eq/ne.
4074 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
4075                                            ICmpInst::Predicate Pred,
4076                                            Value *TrueVal, Value *FalseVal) {
4077   Value *X;
4078   APInt Mask;
4079   if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
4080     return nullptr;
4081 
4082   return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
4083                                Pred == ICmpInst::ICMP_EQ);
4084 }
4085 
4086 /// Try to simplify a select instruction when its condition operand is an
4087 /// integer comparison.
4088 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
4089                                          Value *FalseVal, const SimplifyQuery &Q,
4090                                          unsigned MaxRecurse) {
4091   ICmpInst::Predicate Pred;
4092   Value *CmpLHS, *CmpRHS;
4093   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
4094     return nullptr;
4095 
4096   // Canonicalize ne to eq predicate.
4097   if (Pred == ICmpInst::ICMP_NE) {
4098     Pred = ICmpInst::ICMP_EQ;
4099     std::swap(TrueVal, FalseVal);
4100   }
4101 
4102   if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) {
4103     Value *X;
4104     const APInt *Y;
4105     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
4106       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
4107                                            /*TrueWhenUnset=*/true))
4108         return V;
4109 
4110     // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
4111     Value *ShAmt;
4112     auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)),
4113                              m_FShr(m_Value(), m_Value(X), m_Value(ShAmt)));
4114     // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
4115     // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
4116     if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt)
4117       return X;
4118 
4119     // Test for a zero-shift-guard-op around rotates. These are used to
4120     // avoid UB from oversized shifts in raw IR rotate patterns, but the
4121     // intrinsics do not have that problem.
4122     // We do not allow this transform for the general funnel shift case because
4123     // that would not preserve the poison safety of the original code.
4124     auto isRotate =
4125         m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)),
4126                     m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt)));
4127     // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
4128     // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
4129     if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
4130         Pred == ICmpInst::ICMP_EQ)
4131       return FalseVal;
4132 
4133     // X == 0 ? abs(X) : -abs(X) --> -abs(X)
4134     // X == 0 ? -abs(X) : abs(X) --> abs(X)
4135     if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) &&
4136         match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))))
4137       return FalseVal;
4138     if (match(TrueVal,
4139               m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) &&
4140         match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))
4141       return FalseVal;
4142   }
4143 
4144   // Check for other compares that behave like bit test.
4145   if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
4146                                               TrueVal, FalseVal))
4147     return V;
4148 
4149   // If we have an equality comparison, then we know the value in one of the
4150   // arms of the select. See if substituting this value into the arm and
4151   // simplifying the result yields the same value as the other arm.
4152   if (Pred == ICmpInst::ICMP_EQ) {
4153     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q,
4154                                /* AllowRefinement */ false, MaxRecurse) ==
4155             TrueVal ||
4156         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q,
4157                                /* AllowRefinement */ false, MaxRecurse) ==
4158             TrueVal)
4159       return FalseVal;
4160     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q,
4161                                /* AllowRefinement */ true, MaxRecurse) ==
4162             FalseVal ||
4163         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q,
4164                                /* AllowRefinement */ true, MaxRecurse) ==
4165             FalseVal)
4166       return FalseVal;
4167   }
4168 
4169   return nullptr;
4170 }
4171 
4172 /// Try to simplify a select instruction when its condition operand is a
4173 /// floating-point comparison.
4174 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F,
4175                                      const SimplifyQuery &Q) {
4176   FCmpInst::Predicate Pred;
4177   if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
4178       !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
4179     return nullptr;
4180 
4181   // This transform is safe if we do not have (do not care about) -0.0 or if
4182   // at least one operand is known to not be -0.0. Otherwise, the select can
4183   // change the sign of a zero operand.
4184   bool HasNoSignedZeros = Q.CxtI && isa<FPMathOperator>(Q.CxtI) &&
4185                           Q.CxtI->hasNoSignedZeros();
4186   const APFloat *C;
4187   if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) ||
4188                           (match(F, m_APFloat(C)) && C->isNonZero())) {
4189     // (T == F) ? T : F --> F
4190     // (F == T) ? T : F --> F
4191     if (Pred == FCmpInst::FCMP_OEQ)
4192       return F;
4193 
4194     // (T != F) ? T : F --> T
4195     // (F != T) ? T : F --> T
4196     if (Pred == FCmpInst::FCMP_UNE)
4197       return T;
4198   }
4199 
4200   return nullptr;
4201 }
4202 
4203 /// Given operands for a SelectInst, see if we can fold the result.
4204 /// If not, this returns null.
4205 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4206                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
4207   if (auto *CondC = dyn_cast<Constant>(Cond)) {
4208     if (auto *TrueC = dyn_cast<Constant>(TrueVal))
4209       if (auto *FalseC = dyn_cast<Constant>(FalseVal))
4210         return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
4211 
4212     // select undef, X, Y -> X or Y
4213     if (Q.isUndefValue(CondC))
4214       return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
4215 
4216     // TODO: Vector constants with undef elements don't simplify.
4217 
4218     // select true, X, Y  -> X
4219     if (CondC->isAllOnesValue())
4220       return TrueVal;
4221     // select false, X, Y -> Y
4222     if (CondC->isNullValue())
4223       return FalseVal;
4224   }
4225 
4226   // select i1 Cond, i1 true, i1 false --> i1 Cond
4227   assert(Cond->getType()->isIntOrIntVectorTy(1) &&
4228          "Select must have bool or bool vector condition");
4229   assert(TrueVal->getType() == FalseVal->getType() &&
4230          "Select must have same types for true/false ops");
4231   if (Cond->getType() == TrueVal->getType() &&
4232       match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt()))
4233     return Cond;
4234 
4235   // select ?, X, X -> X
4236   if (TrueVal == FalseVal)
4237     return TrueVal;
4238 
4239   // If the true or false value is undef, we can fold to the other value as
4240   // long as the other value isn't poison.
4241   // select ?, undef, X -> X
4242   if (Q.isUndefValue(TrueVal) &&
4243       isGuaranteedNotToBeUndefOrPoison(FalseVal, Q.AC, Q.CxtI, Q.DT))
4244     return FalseVal;
4245   // select ?, X, undef -> X
4246   if (Q.isUndefValue(FalseVal) &&
4247       isGuaranteedNotToBeUndefOrPoison(TrueVal, Q.AC, Q.CxtI, Q.DT))
4248     return TrueVal;
4249 
4250   // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC''
4251   Constant *TrueC, *FalseC;
4252   if (isa<FixedVectorType>(TrueVal->getType()) &&
4253       match(TrueVal, m_Constant(TrueC)) &&
4254       match(FalseVal, m_Constant(FalseC))) {
4255     unsigned NumElts =
4256         cast<FixedVectorType>(TrueC->getType())->getNumElements();
4257     SmallVector<Constant *, 16> NewC;
4258     for (unsigned i = 0; i != NumElts; ++i) {
4259       // Bail out on incomplete vector constants.
4260       Constant *TEltC = TrueC->getAggregateElement(i);
4261       Constant *FEltC = FalseC->getAggregateElement(i);
4262       if (!TEltC || !FEltC)
4263         break;
4264 
4265       // If the elements match (undef or not), that value is the result. If only
4266       // one element is undef, choose the defined element as the safe result.
4267       if (TEltC == FEltC)
4268         NewC.push_back(TEltC);
4269       else if (Q.isUndefValue(TEltC) &&
4270                isGuaranteedNotToBeUndefOrPoison(FEltC))
4271         NewC.push_back(FEltC);
4272       else if (Q.isUndefValue(FEltC) &&
4273                isGuaranteedNotToBeUndefOrPoison(TEltC))
4274         NewC.push_back(TEltC);
4275       else
4276         break;
4277     }
4278     if (NewC.size() == NumElts)
4279       return ConstantVector::get(NewC);
4280   }
4281 
4282   if (Value *V =
4283           simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
4284     return V;
4285 
4286   if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q))
4287     return V;
4288 
4289   if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
4290     return V;
4291 
4292   Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
4293   if (Imp)
4294     return *Imp ? TrueVal : FalseVal;
4295 
4296   return nullptr;
4297 }
4298 
4299 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4300                                 const SimplifyQuery &Q) {
4301   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
4302 }
4303 
4304 /// Given operands for an GetElementPtrInst, see if we can fold the result.
4305 /// If not, this returns null.
4306 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
4307                               const SimplifyQuery &Q, unsigned) {
4308   // The type of the GEP pointer operand.
4309   unsigned AS =
4310       cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
4311 
4312   // getelementptr P -> P.
4313   if (Ops.size() == 1)
4314     return Ops[0];
4315 
4316   // Compute the (pointer) type returned by the GEP instruction.
4317   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
4318   Type *GEPTy = PointerType::get(LastType, AS);
4319   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
4320     GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4321   else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
4322     GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4323 
4324   // getelementptr poison, idx -> poison
4325   // getelementptr baseptr, poison -> poison
4326   if (any_of(Ops, [](const auto *V) { return isa<PoisonValue>(V); }))
4327     return PoisonValue::get(GEPTy);
4328 
4329   if (Q.isUndefValue(Ops[0]))
4330     return UndefValue::get(GEPTy);
4331 
4332   bool IsScalableVec = isa<ScalableVectorType>(SrcTy);
4333 
4334   if (Ops.size() == 2) {
4335     // getelementptr P, 0 -> P.
4336     if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy)
4337       return Ops[0];
4338 
4339     Type *Ty = SrcTy;
4340     if (!IsScalableVec && Ty->isSized()) {
4341       Value *P;
4342       uint64_t C;
4343       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
4344       // getelementptr P, N -> P if P points to a type of zero size.
4345       if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy)
4346         return Ops[0];
4347 
4348       // The following transforms are only safe if the ptrtoint cast
4349       // doesn't truncate the pointers.
4350       if (Ops[1]->getType()->getScalarSizeInBits() ==
4351           Q.DL.getPointerSizeInBits(AS)) {
4352         auto PtrToInt = [GEPTy](Value *P) -> Value * {
4353           Value *Temp;
4354           if (match(P, m_PtrToInt(m_Value(Temp))))
4355             if (Temp->getType() == GEPTy)
4356               return Temp;
4357           return nullptr;
4358         };
4359 
4360         // FIXME: The following transforms are only legal if P and V have the
4361         // same provenance (PR44403). Check whether getUnderlyingObject() is
4362         // the same?
4363 
4364         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
4365         if (TyAllocSize == 1 &&
4366             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
4367           if (Value *R = PtrToInt(P))
4368             return R;
4369 
4370         // getelementptr V, (ashr (sub P, V), C) -> Q
4371         // if P points to a type of size 1 << C.
4372         if (match(Ops[1],
4373                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
4374                          m_ConstantInt(C))) &&
4375             TyAllocSize == 1ULL << C)
4376           if (Value *R = PtrToInt(P))
4377             return R;
4378 
4379         // getelementptr V, (sdiv (sub P, V), C) -> Q
4380         // if P points to a type of size C.
4381         if (match(Ops[1],
4382                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
4383                          m_SpecificInt(TyAllocSize))))
4384           if (Value *R = PtrToInt(P))
4385             return R;
4386       }
4387     }
4388   }
4389 
4390   if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 &&
4391       all_of(Ops.slice(1).drop_back(1),
4392              [](Value *Idx) { return match(Idx, m_Zero()); })) {
4393     unsigned IdxWidth =
4394         Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
4395     if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) {
4396       APInt BasePtrOffset(IdxWidth, 0);
4397       Value *StrippedBasePtr =
4398           Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
4399                                                             BasePtrOffset);
4400 
4401       // Avoid creating inttoptr of zero here: While LLVMs treatment of
4402       // inttoptr is generally conservative, this particular case is folded to
4403       // a null pointer, which will have incorrect provenance.
4404 
4405       // gep (gep V, C), (sub 0, V) -> C
4406       if (match(Ops.back(),
4407                 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr)))) &&
4408           !BasePtrOffset.isNullValue()) {
4409         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
4410         return ConstantExpr::getIntToPtr(CI, GEPTy);
4411       }
4412       // gep (gep V, C), (xor V, -1) -> C-1
4413       if (match(Ops.back(),
4414                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) &&
4415           !BasePtrOffset.isOneValue()) {
4416         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
4417         return ConstantExpr::getIntToPtr(CI, GEPTy);
4418       }
4419     }
4420   }
4421 
4422   // Check to see if this is constant foldable.
4423   if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); }))
4424     return nullptr;
4425 
4426   auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
4427                                             Ops.slice(1));
4428   return ConstantFoldConstant(CE, Q.DL);
4429 }
4430 
4431 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
4432                              const SimplifyQuery &Q) {
4433   return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
4434 }
4435 
4436 /// Given operands for an InsertValueInst, see if we can fold the result.
4437 /// If not, this returns null.
4438 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
4439                                       ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
4440                                       unsigned) {
4441   if (Constant *CAgg = dyn_cast<Constant>(Agg))
4442     if (Constant *CVal = dyn_cast<Constant>(Val))
4443       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
4444 
4445   // insertvalue x, undef, n -> x
4446   if (Q.isUndefValue(Val))
4447     return Agg;
4448 
4449   // insertvalue x, (extractvalue y, n), n
4450   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
4451     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
4452         EV->getIndices() == Idxs) {
4453       // insertvalue undef, (extractvalue y, n), n -> y
4454       if (Q.isUndefValue(Agg))
4455         return EV->getAggregateOperand();
4456 
4457       // insertvalue y, (extractvalue y, n), n -> y
4458       if (Agg == EV->getAggregateOperand())
4459         return Agg;
4460     }
4461 
4462   return nullptr;
4463 }
4464 
4465 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
4466                                      ArrayRef<unsigned> Idxs,
4467                                      const SimplifyQuery &Q) {
4468   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
4469 }
4470 
4471 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
4472                                        const SimplifyQuery &Q) {
4473   // Try to constant fold.
4474   auto *VecC = dyn_cast<Constant>(Vec);
4475   auto *ValC = dyn_cast<Constant>(Val);
4476   auto *IdxC = dyn_cast<Constant>(Idx);
4477   if (VecC && ValC && IdxC)
4478     return ConstantExpr::getInsertElement(VecC, ValC, IdxC);
4479 
4480   // For fixed-length vector, fold into poison if index is out of bounds.
4481   if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
4482     if (isa<FixedVectorType>(Vec->getType()) &&
4483         CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements()))
4484       return PoisonValue::get(Vec->getType());
4485   }
4486 
4487   // If index is undef, it might be out of bounds (see above case)
4488   if (Q.isUndefValue(Idx))
4489     return PoisonValue::get(Vec->getType());
4490 
4491   // If the scalar is poison, or it is undef and there is no risk of
4492   // propagating poison from the vector value, simplify to the vector value.
4493   if (isa<PoisonValue>(Val) ||
4494       (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec)))
4495     return Vec;
4496 
4497   // If we are extracting a value from a vector, then inserting it into the same
4498   // place, that's the input vector:
4499   // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
4500   if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx))))
4501     return Vec;
4502 
4503   return nullptr;
4504 }
4505 
4506 /// Given operands for an ExtractValueInst, see if we can fold the result.
4507 /// If not, this returns null.
4508 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4509                                        const SimplifyQuery &, unsigned) {
4510   if (auto *CAgg = dyn_cast<Constant>(Agg))
4511     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
4512 
4513   // extractvalue x, (insertvalue y, elt, n), n -> elt
4514   unsigned NumIdxs = Idxs.size();
4515   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
4516        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
4517     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
4518     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
4519     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
4520     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
4521         Idxs.slice(0, NumCommonIdxs)) {
4522       if (NumIdxs == NumInsertValueIdxs)
4523         return IVI->getInsertedValueOperand();
4524       break;
4525     }
4526   }
4527 
4528   return nullptr;
4529 }
4530 
4531 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4532                                       const SimplifyQuery &Q) {
4533   return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
4534 }
4535 
4536 /// Given operands for an ExtractElementInst, see if we can fold the result.
4537 /// If not, this returns null.
4538 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx,
4539                                          const SimplifyQuery &Q, unsigned) {
4540   auto *VecVTy = cast<VectorType>(Vec->getType());
4541   if (auto *CVec = dyn_cast<Constant>(Vec)) {
4542     if (auto *CIdx = dyn_cast<Constant>(Idx))
4543       return ConstantExpr::getExtractElement(CVec, CIdx);
4544 
4545     // The index is not relevant if our vector is a splat.
4546     if (auto *Splat = CVec->getSplatValue())
4547       return Splat;
4548 
4549     if (Q.isUndefValue(Vec))
4550       return UndefValue::get(VecVTy->getElementType());
4551   }
4552 
4553   // If extracting a specified index from the vector, see if we can recursively
4554   // find a previously computed scalar that was inserted into the vector.
4555   if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4556     // For fixed-length vector, fold into undef if index is out of bounds.
4557     if (isa<FixedVectorType>(VecVTy) &&
4558         IdxC->getValue().uge(cast<FixedVectorType>(VecVTy)->getNumElements()))
4559       return PoisonValue::get(VecVTy->getElementType());
4560     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4561       return Elt;
4562   }
4563 
4564   // An undef extract index can be arbitrarily chosen to be an out-of-range
4565   // index value, which would result in the instruction being poison.
4566   if (Q.isUndefValue(Idx))
4567     return PoisonValue::get(VecVTy->getElementType());
4568 
4569   return nullptr;
4570 }
4571 
4572 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
4573                                         const SimplifyQuery &Q) {
4574   return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4575 }
4576 
4577 /// See if we can fold the given phi. If not, returns null.
4578 static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
4579   // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE
4580   //          here, because the PHI we may succeed simplifying to was not
4581   //          def-reachable from the original PHI!
4582 
4583   // If all of the PHI's incoming values are the same then replace the PHI node
4584   // with the common value.
4585   Value *CommonValue = nullptr;
4586   bool HasUndefInput = false;
4587   for (Value *Incoming : PN->incoming_values()) {
4588     // If the incoming value is the phi node itself, it can safely be skipped.
4589     if (Incoming == PN) continue;
4590     if (Q.isUndefValue(Incoming)) {
4591       // Remember that we saw an undef value, but otherwise ignore them.
4592       HasUndefInput = true;
4593       continue;
4594     }
4595     if (CommonValue && Incoming != CommonValue)
4596       return nullptr;  // Not the same, bail out.
4597     CommonValue = Incoming;
4598   }
4599 
4600   // If CommonValue is null then all of the incoming values were either undef or
4601   // equal to the phi node itself.
4602   if (!CommonValue)
4603     return UndefValue::get(PN->getType());
4604 
4605   // If we have a PHI node like phi(X, undef, X), where X is defined by some
4606   // instruction, we cannot return X as the result of the PHI node unless it
4607   // dominates the PHI block.
4608   if (HasUndefInput)
4609     return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
4610 
4611   return CommonValue;
4612 }
4613 
4614 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4615                                Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
4616   if (auto *C = dyn_cast<Constant>(Op))
4617     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
4618 
4619   if (auto *CI = dyn_cast<CastInst>(Op)) {
4620     auto *Src = CI->getOperand(0);
4621     Type *SrcTy = Src->getType();
4622     Type *MidTy = CI->getType();
4623     Type *DstTy = Ty;
4624     if (Src->getType() == Ty) {
4625       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4626       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4627       Type *SrcIntPtrTy =
4628           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4629       Type *MidIntPtrTy =
4630           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4631       Type *DstIntPtrTy =
4632           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4633       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4634                                          SrcIntPtrTy, MidIntPtrTy,
4635                                          DstIntPtrTy) == Instruction::BitCast)
4636         return Src;
4637     }
4638   }
4639 
4640   // bitcast x -> x
4641   if (CastOpc == Instruction::BitCast)
4642     if (Op->getType() == Ty)
4643       return Op;
4644 
4645   return nullptr;
4646 }
4647 
4648 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4649                               const SimplifyQuery &Q) {
4650   return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4651 }
4652 
4653 /// For the given destination element of a shuffle, peek through shuffles to
4654 /// match a root vector source operand that contains that element in the same
4655 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4656 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4657                                    int MaskVal, Value *RootVec,
4658                                    unsigned MaxRecurse) {
4659   if (!MaxRecurse--)
4660     return nullptr;
4661 
4662   // Bail out if any mask value is undefined. That kind of shuffle may be
4663   // simplified further based on demanded bits or other folds.
4664   if (MaskVal == -1)
4665     return nullptr;
4666 
4667   // The mask value chooses which source operand we need to look at next.
4668   int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
4669   int RootElt = MaskVal;
4670   Value *SourceOp = Op0;
4671   if (MaskVal >= InVecNumElts) {
4672     RootElt = MaskVal - InVecNumElts;
4673     SourceOp = Op1;
4674   }
4675 
4676   // If the source operand is a shuffle itself, look through it to find the
4677   // matching root vector.
4678   if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4679     return foldIdentityShuffles(
4680         DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4681         SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
4682   }
4683 
4684   // TODO: Look through bitcasts? What if the bitcast changes the vector element
4685   // size?
4686 
4687   // The source operand is not a shuffle. Initialize the root vector value for
4688   // this shuffle if that has not been done yet.
4689   if (!RootVec)
4690     RootVec = SourceOp;
4691 
4692   // Give up as soon as a source operand does not match the existing root value.
4693   if (RootVec != SourceOp)
4694     return nullptr;
4695 
4696   // The element must be coming from the same lane in the source vector
4697   // (although it may have crossed lanes in intermediate shuffles).
4698   if (RootElt != DestElt)
4699     return nullptr;
4700 
4701   return RootVec;
4702 }
4703 
4704 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1,
4705                                         ArrayRef<int> Mask, Type *RetTy,
4706                                         const SimplifyQuery &Q,
4707                                         unsigned MaxRecurse) {
4708   if (all_of(Mask, [](int Elem) { return Elem == UndefMaskElem; }))
4709     return UndefValue::get(RetTy);
4710 
4711   auto *InVecTy = cast<VectorType>(Op0->getType());
4712   unsigned MaskNumElts = Mask.size();
4713   ElementCount InVecEltCount = InVecTy->getElementCount();
4714 
4715   bool Scalable = InVecEltCount.isScalable();
4716 
4717   SmallVector<int, 32> Indices;
4718   Indices.assign(Mask.begin(), Mask.end());
4719 
4720   // Canonicalization: If mask does not select elements from an input vector,
4721   // replace that input vector with poison.
4722   if (!Scalable) {
4723     bool MaskSelects0 = false, MaskSelects1 = false;
4724     unsigned InVecNumElts = InVecEltCount.getKnownMinValue();
4725     for (unsigned i = 0; i != MaskNumElts; ++i) {
4726       if (Indices[i] == -1)
4727         continue;
4728       if ((unsigned)Indices[i] < InVecNumElts)
4729         MaskSelects0 = true;
4730       else
4731         MaskSelects1 = true;
4732     }
4733     if (!MaskSelects0)
4734       Op0 = PoisonValue::get(InVecTy);
4735     if (!MaskSelects1)
4736       Op1 = PoisonValue::get(InVecTy);
4737   }
4738 
4739   auto *Op0Const = dyn_cast<Constant>(Op0);
4740   auto *Op1Const = dyn_cast<Constant>(Op1);
4741 
4742   // If all operands are constant, constant fold the shuffle. This
4743   // transformation depends on the value of the mask which is not known at
4744   // compile time for scalable vectors
4745   if (Op0Const && Op1Const)
4746     return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask);
4747 
4748   // Canonicalization: if only one input vector is constant, it shall be the
4749   // second one. This transformation depends on the value of the mask which
4750   // is not known at compile time for scalable vectors
4751   if (!Scalable && Op0Const && !Op1Const) {
4752     std::swap(Op0, Op1);
4753     ShuffleVectorInst::commuteShuffleMask(Indices,
4754                                           InVecEltCount.getKnownMinValue());
4755   }
4756 
4757   // A splat of an inserted scalar constant becomes a vector constant:
4758   // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...>
4759   // NOTE: We may have commuted above, so analyze the updated Indices, not the
4760   //       original mask constant.
4761   // NOTE: This transformation depends on the value of the mask which is not
4762   // known at compile time for scalable vectors
4763   Constant *C;
4764   ConstantInt *IndexC;
4765   if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C),
4766                                           m_ConstantInt(IndexC)))) {
4767     // Match a splat shuffle mask of the insert index allowing undef elements.
4768     int InsertIndex = IndexC->getZExtValue();
4769     if (all_of(Indices, [InsertIndex](int MaskElt) {
4770           return MaskElt == InsertIndex || MaskElt == -1;
4771         })) {
4772       assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
4773 
4774       // Shuffle mask undefs become undefined constant result elements.
4775       SmallVector<Constant *, 16> VecC(MaskNumElts, C);
4776       for (unsigned i = 0; i != MaskNumElts; ++i)
4777         if (Indices[i] == -1)
4778           VecC[i] = UndefValue::get(C->getType());
4779       return ConstantVector::get(VecC);
4780     }
4781   }
4782 
4783   // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4784   // value type is same as the input vectors' type.
4785   if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
4786     if (Q.isUndefValue(Op1) && RetTy == InVecTy &&
4787         is_splat(OpShuf->getShuffleMask()))
4788       return Op0;
4789 
4790   // All remaining transformation depend on the value of the mask, which is
4791   // not known at compile time for scalable vectors.
4792   if (Scalable)
4793     return nullptr;
4794 
4795   // Don't fold a shuffle with undef mask elements. This may get folded in a
4796   // better way using demanded bits or other analysis.
4797   // TODO: Should we allow this?
4798   if (is_contained(Indices, -1))
4799     return nullptr;
4800 
4801   // Check if every element of this shuffle can be mapped back to the
4802   // corresponding element of a single root vector. If so, we don't need this
4803   // shuffle. This handles simple identity shuffles as well as chains of
4804   // shuffles that may widen/narrow and/or move elements across lanes and back.
4805   Value *RootVec = nullptr;
4806   for (unsigned i = 0; i != MaskNumElts; ++i) {
4807     // Note that recursion is limited for each vector element, so if any element
4808     // exceeds the limit, this will fail to simplify.
4809     RootVec =
4810         foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
4811 
4812     // We can't replace a widening/narrowing shuffle with one of its operands.
4813     if (!RootVec || RootVec->getType() != RetTy)
4814       return nullptr;
4815   }
4816   return RootVec;
4817 }
4818 
4819 /// Given operands for a ShuffleVectorInst, fold the result or return null.
4820 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1,
4821                                        ArrayRef<int> Mask, Type *RetTy,
4822                                        const SimplifyQuery &Q) {
4823   return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
4824 }
4825 
4826 static Constant *foldConstant(Instruction::UnaryOps Opcode,
4827                               Value *&Op, const SimplifyQuery &Q) {
4828   if (auto *C = dyn_cast<Constant>(Op))
4829     return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
4830   return nullptr;
4831 }
4832 
4833 /// Given the operand for an FNeg, see if we can fold the result.  If not, this
4834 /// returns null.
4835 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
4836                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4837   if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
4838     return C;
4839 
4840   Value *X;
4841   // fneg (fneg X) ==> X
4842   if (match(Op, m_FNeg(m_Value(X))))
4843     return X;
4844 
4845   return nullptr;
4846 }
4847 
4848 Value *llvm::SimplifyFNegInst(Value *Op, FastMathFlags FMF,
4849                               const SimplifyQuery &Q) {
4850   return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
4851 }
4852 
4853 static Constant *propagateNaN(Constant *In) {
4854   // If the input is a vector with undef elements, just return a default NaN.
4855   if (!In->isNaN())
4856     return ConstantFP::getNaN(In->getType());
4857 
4858   // Propagate the existing NaN constant when possible.
4859   // TODO: Should we quiet a signaling NaN?
4860   return In;
4861 }
4862 
4863 /// Perform folds that are common to any floating-point operation. This implies
4864 /// transforms based on undef/NaN because the operation itself makes no
4865 /// difference to the result.
4866 static Constant *simplifyFPOp(ArrayRef<Value *> Ops,
4867                               FastMathFlags FMF,
4868                               const SimplifyQuery &Q) {
4869   for (Value *V : Ops) {
4870     bool IsNan = match(V, m_NaN());
4871     bool IsInf = match(V, m_Inf());
4872     bool IsUndef = Q.isUndefValue(V);
4873 
4874     // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
4875     // (an undef operand can be chosen to be Nan/Inf), then the result of
4876     // this operation is poison.
4877     if (FMF.noNaNs() && (IsNan || IsUndef))
4878       return PoisonValue::get(V->getType());
4879     if (FMF.noInfs() && (IsInf || IsUndef))
4880       return PoisonValue::get(V->getType());
4881 
4882     if (IsUndef || IsNan)
4883       return propagateNaN(cast<Constant>(V));
4884   }
4885   return nullptr;
4886 }
4887 
4888 /// Given operands for an FAdd, see if we can fold the result.  If not, this
4889 /// returns null.
4890 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4891                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4892   if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
4893     return C;
4894 
4895   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q))
4896     return C;
4897 
4898   // fadd X, -0 ==> X
4899   if (match(Op1, m_NegZeroFP()))
4900     return Op0;
4901 
4902   // fadd X, 0 ==> X, when we know X is not -0
4903   if (match(Op1, m_PosZeroFP()) &&
4904       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4905     return Op0;
4906 
4907   // With nnan: -X + X --> 0.0 (and commuted variant)
4908   // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
4909   // Negative zeros are allowed because we always end up with positive zero:
4910   // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4911   // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4912   // X =  0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
4913   // X =  0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
4914   if (FMF.noNaNs()) {
4915     if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
4916         match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
4917       return ConstantFP::getNullValue(Op0->getType());
4918 
4919     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
4920         match(Op1, m_FNeg(m_Specific(Op0))))
4921       return ConstantFP::getNullValue(Op0->getType());
4922   }
4923 
4924   // (X - Y) + Y --> X
4925   // Y + (X - Y) --> X
4926   Value *X;
4927   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4928       (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
4929        match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
4930     return X;
4931 
4932   return nullptr;
4933 }
4934 
4935 /// Given operands for an FSub, see if we can fold the result.  If not, this
4936 /// returns null.
4937 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4938                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4939   if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
4940     return C;
4941 
4942   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q))
4943     return C;
4944 
4945   // fsub X, +0 ==> X
4946   if (match(Op1, m_PosZeroFP()))
4947     return Op0;
4948 
4949   // fsub X, -0 ==> X, when we know X is not -0
4950   if (match(Op1, m_NegZeroFP()) &&
4951       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4952     return Op0;
4953 
4954   // fsub -0.0, (fsub -0.0, X) ==> X
4955   // fsub -0.0, (fneg X) ==> X
4956   Value *X;
4957   if (match(Op0, m_NegZeroFP()) &&
4958       match(Op1, m_FNeg(m_Value(X))))
4959     return X;
4960 
4961   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
4962   // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
4963   if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
4964       (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
4965        match(Op1, m_FNeg(m_Value(X)))))
4966     return X;
4967 
4968   // fsub nnan x, x ==> 0.0
4969   if (FMF.noNaNs() && Op0 == Op1)
4970     return Constant::getNullValue(Op0->getType());
4971 
4972   // Y - (Y - X) --> X
4973   // (X + Y) - Y --> X
4974   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4975       (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
4976        match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
4977     return X;
4978 
4979   return nullptr;
4980 }
4981 
4982 static Value *SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
4983                               const SimplifyQuery &Q, unsigned MaxRecurse) {
4984   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q))
4985     return C;
4986 
4987   // fmul X, 1.0 ==> X
4988   if (match(Op1, m_FPOne()))
4989     return Op0;
4990 
4991   // fmul 1.0, X ==> X
4992   if (match(Op0, m_FPOne()))
4993     return Op1;
4994 
4995   // fmul nnan nsz X, 0 ==> 0
4996   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
4997     return ConstantFP::getNullValue(Op0->getType());
4998 
4999   // fmul nnan nsz 0, X ==> 0
5000   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5001     return ConstantFP::getNullValue(Op1->getType());
5002 
5003   // sqrt(X) * sqrt(X) --> X, if we can:
5004   // 1. Remove the intermediate rounding (reassociate).
5005   // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
5006   // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
5007   Value *X;
5008   if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
5009       FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
5010     return X;
5011 
5012   return nullptr;
5013 }
5014 
5015 /// Given the operands for an FMul, see if we can fold the result
5016 static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5017                                const SimplifyQuery &Q, unsigned MaxRecurse) {
5018   if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
5019     return C;
5020 
5021   // Now apply simplifications that do not require rounding.
5022   return SimplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse);
5023 }
5024 
5025 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5026                               const SimplifyQuery &Q) {
5027   return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
5028 }
5029 
5030 
5031 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5032                               const SimplifyQuery &Q) {
5033   return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
5034 }
5035 
5036 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5037                               const SimplifyQuery &Q) {
5038   return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
5039 }
5040 
5041 Value *llvm::SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5042                              const SimplifyQuery &Q) {
5043   return ::SimplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit);
5044 }
5045 
5046 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5047                                const SimplifyQuery &Q, unsigned) {
5048   if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
5049     return C;
5050 
5051   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q))
5052     return C;
5053 
5054   // X / 1.0 -> X
5055   if (match(Op1, m_FPOne()))
5056     return Op0;
5057 
5058   // 0 / X -> 0
5059   // Requires that NaNs are off (X could be zero) and signed zeroes are
5060   // ignored (X could be positive or negative, so the output sign is unknown).
5061   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5062     return ConstantFP::getNullValue(Op0->getType());
5063 
5064   if (FMF.noNaNs()) {
5065     // X / X -> 1.0 is legal when NaNs are ignored.
5066     // We can ignore infinities because INF/INF is NaN.
5067     if (Op0 == Op1)
5068       return ConstantFP::get(Op0->getType(), 1.0);
5069 
5070     // (X * Y) / Y --> X if we can reassociate to the above form.
5071     Value *X;
5072     if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
5073       return X;
5074 
5075     // -X /  X -> -1.0 and
5076     //  X / -X -> -1.0 are legal when NaNs are ignored.
5077     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
5078     if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
5079         match(Op1, m_FNegNSZ(m_Specific(Op0))))
5080       return ConstantFP::get(Op0->getType(), -1.0);
5081   }
5082 
5083   return nullptr;
5084 }
5085 
5086 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5087                               const SimplifyQuery &Q) {
5088   return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
5089 }
5090 
5091 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5092                                const SimplifyQuery &Q, unsigned) {
5093   if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
5094     return C;
5095 
5096   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q))
5097     return C;
5098 
5099   // Unlike fdiv, the result of frem always matches the sign of the dividend.
5100   // The constant match may include undef elements in a vector, so return a full
5101   // zero constant as the result.
5102   if (FMF.noNaNs()) {
5103     // +0 % X -> 0
5104     if (match(Op0, m_PosZeroFP()))
5105       return ConstantFP::getNullValue(Op0->getType());
5106     // -0 % X -> -0
5107     if (match(Op0, m_NegZeroFP()))
5108       return ConstantFP::getNegativeZero(Op0->getType());
5109   }
5110 
5111   return nullptr;
5112 }
5113 
5114 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5115                               const SimplifyQuery &Q) {
5116   return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
5117 }
5118 
5119 //=== Helper functions for higher up the class hierarchy.
5120 
5121 /// Given the operand for a UnaryOperator, see if we can fold the result.
5122 /// If not, this returns null.
5123 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
5124                            unsigned MaxRecurse) {
5125   switch (Opcode) {
5126   case Instruction::FNeg:
5127     return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
5128   default:
5129     llvm_unreachable("Unexpected opcode");
5130   }
5131 }
5132 
5133 /// Given the operand for a UnaryOperator, see if we can fold the result.
5134 /// If not, this returns null.
5135 /// Try to use FastMathFlags when folding the result.
5136 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
5137                              const FastMathFlags &FMF,
5138                              const SimplifyQuery &Q, unsigned MaxRecurse) {
5139   switch (Opcode) {
5140   case Instruction::FNeg:
5141     return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
5142   default:
5143     return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
5144   }
5145 }
5146 
5147 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
5148   return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
5149 }
5150 
5151 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
5152                           const SimplifyQuery &Q) {
5153   return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
5154 }
5155 
5156 /// Given operands for a BinaryOperator, see if we can fold the result.
5157 /// If not, this returns null.
5158 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5159                             const SimplifyQuery &Q, unsigned MaxRecurse) {
5160   switch (Opcode) {
5161   case Instruction::Add:
5162     return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
5163   case Instruction::Sub:
5164     return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
5165   case Instruction::Mul:
5166     return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
5167   case Instruction::SDiv:
5168     return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
5169   case Instruction::UDiv:
5170     return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
5171   case Instruction::SRem:
5172     return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
5173   case Instruction::URem:
5174     return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
5175   case Instruction::Shl:
5176     return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
5177   case Instruction::LShr:
5178     return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
5179   case Instruction::AShr:
5180     return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
5181   case Instruction::And:
5182     return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
5183   case Instruction::Or:
5184     return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
5185   case Instruction::Xor:
5186     return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
5187   case Instruction::FAdd:
5188     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5189   case Instruction::FSub:
5190     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5191   case Instruction::FMul:
5192     return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5193   case Instruction::FDiv:
5194     return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5195   case Instruction::FRem:
5196     return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5197   default:
5198     llvm_unreachable("Unexpected opcode");
5199   }
5200 }
5201 
5202 /// Given operands for a BinaryOperator, see if we can fold the result.
5203 /// If not, this returns null.
5204 /// Try to use FastMathFlags when folding the result.
5205 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5206                             const FastMathFlags &FMF, const SimplifyQuery &Q,
5207                             unsigned MaxRecurse) {
5208   switch (Opcode) {
5209   case Instruction::FAdd:
5210     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
5211   case Instruction::FSub:
5212     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
5213   case Instruction::FMul:
5214     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
5215   case Instruction::FDiv:
5216     return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
5217   default:
5218     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
5219   }
5220 }
5221 
5222 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5223                            const SimplifyQuery &Q) {
5224   return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
5225 }
5226 
5227 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5228                            FastMathFlags FMF, const SimplifyQuery &Q) {
5229   return ::SimplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
5230 }
5231 
5232 /// Given operands for a CmpInst, see if we can fold the result.
5233 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5234                               const SimplifyQuery &Q, unsigned MaxRecurse) {
5235   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
5236     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
5237   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5238 }
5239 
5240 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5241                              const SimplifyQuery &Q) {
5242   return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
5243 }
5244 
5245 static bool IsIdempotent(Intrinsic::ID ID) {
5246   switch (ID) {
5247   default: return false;
5248 
5249   // Unary idempotent: f(f(x)) = f(x)
5250   case Intrinsic::fabs:
5251   case Intrinsic::floor:
5252   case Intrinsic::ceil:
5253   case Intrinsic::trunc:
5254   case Intrinsic::rint:
5255   case Intrinsic::nearbyint:
5256   case Intrinsic::round:
5257   case Intrinsic::roundeven:
5258   case Intrinsic::canonicalize:
5259     return true;
5260   }
5261 }
5262 
5263 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
5264                                    const DataLayout &DL) {
5265   GlobalValue *PtrSym;
5266   APInt PtrOffset;
5267   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
5268     return nullptr;
5269 
5270   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
5271   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
5272   Type *Int32PtrTy = Int32Ty->getPointerTo();
5273   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
5274 
5275   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
5276   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
5277     return nullptr;
5278 
5279   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
5280   if (OffsetInt % 4 != 0)
5281     return nullptr;
5282 
5283   Constant *C = ConstantExpr::getGetElementPtr(
5284       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
5285       ConstantInt::get(Int64Ty, OffsetInt / 4));
5286   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
5287   if (!Loaded)
5288     return nullptr;
5289 
5290   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
5291   if (!LoadedCE)
5292     return nullptr;
5293 
5294   if (LoadedCE->getOpcode() == Instruction::Trunc) {
5295     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5296     if (!LoadedCE)
5297       return nullptr;
5298   }
5299 
5300   if (LoadedCE->getOpcode() != Instruction::Sub)
5301     return nullptr;
5302 
5303   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5304   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
5305     return nullptr;
5306   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
5307 
5308   Constant *LoadedRHS = LoadedCE->getOperand(1);
5309   GlobalValue *LoadedRHSSym;
5310   APInt LoadedRHSOffset;
5311   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
5312                                   DL) ||
5313       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
5314     return nullptr;
5315 
5316   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
5317 }
5318 
5319 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
5320                                      const SimplifyQuery &Q) {
5321   // Idempotent functions return the same result when called repeatedly.
5322   Intrinsic::ID IID = F->getIntrinsicID();
5323   if (IsIdempotent(IID))
5324     if (auto *II = dyn_cast<IntrinsicInst>(Op0))
5325       if (II->getIntrinsicID() == IID)
5326         return II;
5327 
5328   Value *X;
5329   switch (IID) {
5330   case Intrinsic::fabs:
5331     if (SignBitMustBeZero(Op0, Q.TLI)) return Op0;
5332     break;
5333   case Intrinsic::bswap:
5334     // bswap(bswap(x)) -> x
5335     if (match(Op0, m_BSwap(m_Value(X)))) return X;
5336     break;
5337   case Intrinsic::bitreverse:
5338     // bitreverse(bitreverse(x)) -> x
5339     if (match(Op0, m_BitReverse(m_Value(X)))) return X;
5340     break;
5341   case Intrinsic::ctpop: {
5342     // If everything but the lowest bit is zero, that bit is the pop-count. Ex:
5343     // ctpop(and X, 1) --> and X, 1
5344     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
5345     if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1),
5346                           Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
5347       return Op0;
5348     break;
5349   }
5350   case Intrinsic::exp:
5351     // exp(log(x)) -> x
5352     if (Q.CxtI->hasAllowReassoc() &&
5353         match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X;
5354     break;
5355   case Intrinsic::exp2:
5356     // exp2(log2(x)) -> x
5357     if (Q.CxtI->hasAllowReassoc() &&
5358         match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X;
5359     break;
5360   case Intrinsic::log:
5361     // log(exp(x)) -> x
5362     if (Q.CxtI->hasAllowReassoc() &&
5363         match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X;
5364     break;
5365   case Intrinsic::log2:
5366     // log2(exp2(x)) -> x
5367     if (Q.CxtI->hasAllowReassoc() &&
5368         (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
5369          match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0),
5370                                                 m_Value(X))))) return X;
5371     break;
5372   case Intrinsic::log10:
5373     // log10(pow(10.0, x)) -> x
5374     if (Q.CxtI->hasAllowReassoc() &&
5375         match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0),
5376                                                m_Value(X)))) return X;
5377     break;
5378   case Intrinsic::floor:
5379   case Intrinsic::trunc:
5380   case Intrinsic::ceil:
5381   case Intrinsic::round:
5382   case Intrinsic::roundeven:
5383   case Intrinsic::nearbyint:
5384   case Intrinsic::rint: {
5385     // floor (sitofp x) -> sitofp x
5386     // floor (uitofp x) -> uitofp x
5387     //
5388     // Converting from int always results in a finite integral number or
5389     // infinity. For either of those inputs, these rounding functions always
5390     // return the same value, so the rounding can be eliminated.
5391     if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
5392       return Op0;
5393     break;
5394   }
5395   case Intrinsic::experimental_vector_reverse:
5396     // experimental.vector.reverse(experimental.vector.reverse(x)) -> x
5397     if (match(Op0,
5398               m_Intrinsic<Intrinsic::experimental_vector_reverse>(m_Value(X))))
5399       return X;
5400     break;
5401   default:
5402     break;
5403   }
5404 
5405   return nullptr;
5406 }
5407 
5408 static APInt getMaxMinLimit(Intrinsic::ID IID, unsigned BitWidth) {
5409   switch (IID) {
5410   case Intrinsic::smax: return APInt::getSignedMaxValue(BitWidth);
5411   case Intrinsic::smin: return APInt::getSignedMinValue(BitWidth);
5412   case Intrinsic::umax: return APInt::getMaxValue(BitWidth);
5413   case Intrinsic::umin: return APInt::getMinValue(BitWidth);
5414   default: llvm_unreachable("Unexpected intrinsic");
5415   }
5416 }
5417 
5418 static ICmpInst::Predicate getMaxMinPredicate(Intrinsic::ID IID) {
5419   switch (IID) {
5420   case Intrinsic::smax: return ICmpInst::ICMP_SGE;
5421   case Intrinsic::smin: return ICmpInst::ICMP_SLE;
5422   case Intrinsic::umax: return ICmpInst::ICMP_UGE;
5423   case Intrinsic::umin: return ICmpInst::ICMP_ULE;
5424   default: llvm_unreachable("Unexpected intrinsic");
5425   }
5426 }
5427 
5428 /// Given a min/max intrinsic, see if it can be removed based on having an
5429 /// operand that is another min/max intrinsic with shared operand(s). The caller
5430 /// is expected to swap the operand arguments to handle commutation.
5431 static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) {
5432   Value *X, *Y;
5433   if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y))))
5434     return nullptr;
5435 
5436   auto *MM0 = dyn_cast<IntrinsicInst>(Op0);
5437   if (!MM0)
5438     return nullptr;
5439   Intrinsic::ID IID0 = MM0->getIntrinsicID();
5440 
5441   if (Op1 == X || Op1 == Y ||
5442       match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) {
5443     // max (max X, Y), X --> max X, Y
5444     if (IID0 == IID)
5445       return MM0;
5446     // max (min X, Y), X --> X
5447     if (IID0 == getInverseMinMaxIntrinsic(IID))
5448       return Op1;
5449   }
5450   return nullptr;
5451 }
5452 
5453 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
5454                                       const SimplifyQuery &Q) {
5455   Intrinsic::ID IID = F->getIntrinsicID();
5456   Type *ReturnType = F->getReturnType();
5457   unsigned BitWidth = ReturnType->getScalarSizeInBits();
5458   switch (IID) {
5459   case Intrinsic::abs:
5460     // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here.
5461     // It is always ok to pick the earlier abs. We'll just lose nsw if its only
5462     // on the outer abs.
5463     if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value())))
5464       return Op0;
5465     break;
5466 
5467   case Intrinsic::cttz: {
5468     Value *X;
5469     if (match(Op0, m_Shl(m_One(), m_Value(X))))
5470       return X;
5471     break;
5472   }
5473   case Intrinsic::smax:
5474   case Intrinsic::smin:
5475   case Intrinsic::umax:
5476   case Intrinsic::umin: {
5477     // If the arguments are the same, this is a no-op.
5478     if (Op0 == Op1)
5479       return Op0;
5480 
5481     // Canonicalize constant operand as Op1.
5482     if (isa<Constant>(Op0))
5483       std::swap(Op0, Op1);
5484 
5485     // Assume undef is the limit value.
5486     if (Q.isUndefValue(Op1))
5487       return ConstantInt::get(ReturnType, getMaxMinLimit(IID, BitWidth));
5488 
5489     const APInt *C;
5490     if (match(Op1, m_APIntAllowUndef(C))) {
5491       // Clamp to limit value. For example:
5492       // umax(i8 %x, i8 255) --> 255
5493       if (*C == getMaxMinLimit(IID, BitWidth))
5494         return ConstantInt::get(ReturnType, *C);
5495 
5496       // If the constant op is the opposite of the limit value, the other must
5497       // be larger/smaller or equal. For example:
5498       // umin(i8 %x, i8 255) --> %x
5499       if (*C == getMaxMinLimit(getInverseMinMaxIntrinsic(IID), BitWidth))
5500         return Op0;
5501 
5502       // Remove nested call if constant operands allow it. Example:
5503       // max (max X, 7), 5 -> max X, 7
5504       auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0);
5505       if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
5506         // TODO: loosen undef/splat restrictions for vector constants.
5507         Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1);
5508         const APInt *InnerC;
5509         if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) &&
5510             ((IID == Intrinsic::smax && InnerC->sge(*C)) ||
5511              (IID == Intrinsic::smin && InnerC->sle(*C)) ||
5512              (IID == Intrinsic::umax && InnerC->uge(*C)) ||
5513              (IID == Intrinsic::umin && InnerC->ule(*C))))
5514           return Op0;
5515       }
5516     }
5517 
5518     if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
5519       return V;
5520     if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0))
5521       return V;
5522 
5523     ICmpInst::Predicate Pred = getMaxMinPredicate(IID);
5524     if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit))
5525       return Op0;
5526     if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit))
5527       return Op1;
5528 
5529     if (Optional<bool> Imp =
5530             isImpliedByDomCondition(Pred, Op0, Op1, Q.CxtI, Q.DL))
5531       return *Imp ? Op0 : Op1;
5532     if (Optional<bool> Imp =
5533             isImpliedByDomCondition(Pred, Op1, Op0, Q.CxtI, Q.DL))
5534       return *Imp ? Op1 : Op0;
5535 
5536     break;
5537   }
5538   case Intrinsic::usub_with_overflow:
5539   case Intrinsic::ssub_with_overflow:
5540     // X - X -> { 0, false }
5541     // X - undef -> { 0, false }
5542     // undef - X -> { 0, false }
5543     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5544       return Constant::getNullValue(ReturnType);
5545     break;
5546   case Intrinsic::uadd_with_overflow:
5547   case Intrinsic::sadd_with_overflow:
5548     // X + undef -> { -1, false }
5549     // undef + x -> { -1, false }
5550     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) {
5551       return ConstantStruct::get(
5552           cast<StructType>(ReturnType),
5553           {Constant::getAllOnesValue(ReturnType->getStructElementType(0)),
5554            Constant::getNullValue(ReturnType->getStructElementType(1))});
5555     }
5556     break;
5557   case Intrinsic::umul_with_overflow:
5558   case Intrinsic::smul_with_overflow:
5559     // 0 * X -> { 0, false }
5560     // X * 0 -> { 0, false }
5561     if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
5562       return Constant::getNullValue(ReturnType);
5563     // undef * X -> { 0, false }
5564     // X * undef -> { 0, false }
5565     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5566       return Constant::getNullValue(ReturnType);
5567     break;
5568   case Intrinsic::uadd_sat:
5569     // sat(MAX + X) -> MAX
5570     // sat(X + MAX) -> MAX
5571     if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
5572       return Constant::getAllOnesValue(ReturnType);
5573     LLVM_FALLTHROUGH;
5574   case Intrinsic::sadd_sat:
5575     // sat(X + undef) -> -1
5576     // sat(undef + X) -> -1
5577     // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
5578     // For signed: Assume undef is ~X, in which case X + ~X = -1.
5579     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5580       return Constant::getAllOnesValue(ReturnType);
5581 
5582     // X + 0 -> X
5583     if (match(Op1, m_Zero()))
5584       return Op0;
5585     // 0 + X -> X
5586     if (match(Op0, m_Zero()))
5587       return Op1;
5588     break;
5589   case Intrinsic::usub_sat:
5590     // sat(0 - X) -> 0, sat(X - MAX) -> 0
5591     if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
5592       return Constant::getNullValue(ReturnType);
5593     LLVM_FALLTHROUGH;
5594   case Intrinsic::ssub_sat:
5595     // X - X -> 0, X - undef -> 0, undef - X -> 0
5596     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5597       return Constant::getNullValue(ReturnType);
5598     // X - 0 -> X
5599     if (match(Op1, m_Zero()))
5600       return Op0;
5601     break;
5602   case Intrinsic::load_relative:
5603     if (auto *C0 = dyn_cast<Constant>(Op0))
5604       if (auto *C1 = dyn_cast<Constant>(Op1))
5605         return SimplifyRelativeLoad(C0, C1, Q.DL);
5606     break;
5607   case Intrinsic::powi:
5608     if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
5609       // powi(x, 0) -> 1.0
5610       if (Power->isZero())
5611         return ConstantFP::get(Op0->getType(), 1.0);
5612       // powi(x, 1) -> x
5613       if (Power->isOne())
5614         return Op0;
5615     }
5616     break;
5617   case Intrinsic::copysign:
5618     // copysign X, X --> X
5619     if (Op0 == Op1)
5620       return Op0;
5621     // copysign -X, X --> X
5622     // copysign X, -X --> -X
5623     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
5624         match(Op1, m_FNeg(m_Specific(Op0))))
5625       return Op1;
5626     break;
5627   case Intrinsic::maxnum:
5628   case Intrinsic::minnum:
5629   case Intrinsic::maximum:
5630   case Intrinsic::minimum: {
5631     // If the arguments are the same, this is a no-op.
5632     if (Op0 == Op1) return Op0;
5633 
5634     // Canonicalize constant operand as Op1.
5635     if (isa<Constant>(Op0))
5636       std::swap(Op0, Op1);
5637 
5638     // If an argument is undef, return the other argument.
5639     if (Q.isUndefValue(Op1))
5640       return Op0;
5641 
5642     bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
5643     bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum;
5644 
5645     // minnum(X, nan) -> X
5646     // maxnum(X, nan) -> X
5647     // minimum(X, nan) -> nan
5648     // maximum(X, nan) -> nan
5649     if (match(Op1, m_NaN()))
5650       return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0;
5651 
5652     // In the following folds, inf can be replaced with the largest finite
5653     // float, if the ninf flag is set.
5654     const APFloat *C;
5655     if (match(Op1, m_APFloat(C)) &&
5656         (C->isInfinity() || (Q.CxtI->hasNoInfs() && C->isLargest()))) {
5657       // minnum(X, -inf) -> -inf
5658       // maxnum(X, +inf) -> +inf
5659       // minimum(X, -inf) -> -inf if nnan
5660       // maximum(X, +inf) -> +inf if nnan
5661       if (C->isNegative() == IsMin && (!PropagateNaN || Q.CxtI->hasNoNaNs()))
5662         return ConstantFP::get(ReturnType, *C);
5663 
5664       // minnum(X, +inf) -> X if nnan
5665       // maxnum(X, -inf) -> X if nnan
5666       // minimum(X, +inf) -> X
5667       // maximum(X, -inf) -> X
5668       if (C->isNegative() != IsMin && (PropagateNaN || Q.CxtI->hasNoNaNs()))
5669         return Op0;
5670     }
5671 
5672     // Min/max of the same operation with common operand:
5673     // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
5674     if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
5675       if (M0->getIntrinsicID() == IID &&
5676           (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
5677         return Op0;
5678     if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
5679       if (M1->getIntrinsicID() == IID &&
5680           (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
5681         return Op1;
5682 
5683     break;
5684   }
5685   default:
5686     break;
5687   }
5688 
5689   return nullptr;
5690 }
5691 
5692 static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
5693 
5694   // Intrinsics with no operands have some kind of side effect. Don't simplify.
5695   unsigned NumOperands = Call->getNumArgOperands();
5696   if (!NumOperands)
5697     return nullptr;
5698 
5699   Function *F = cast<Function>(Call->getCalledFunction());
5700   Intrinsic::ID IID = F->getIntrinsicID();
5701   if (NumOperands == 1)
5702     return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q);
5703 
5704   if (NumOperands == 2)
5705     return simplifyBinaryIntrinsic(F, Call->getArgOperand(0),
5706                                    Call->getArgOperand(1), Q);
5707 
5708   // Handle intrinsics with 3 or more arguments.
5709   switch (IID) {
5710   case Intrinsic::masked_load:
5711   case Intrinsic::masked_gather: {
5712     Value *MaskArg = Call->getArgOperand(2);
5713     Value *PassthruArg = Call->getArgOperand(3);
5714     // If the mask is all zeros or undef, the "passthru" argument is the result.
5715     if (maskIsAllZeroOrUndef(MaskArg))
5716       return PassthruArg;
5717     return nullptr;
5718   }
5719   case Intrinsic::fshl:
5720   case Intrinsic::fshr: {
5721     Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1),
5722           *ShAmtArg = Call->getArgOperand(2);
5723 
5724     // If both operands are undef, the result is undef.
5725     if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1))
5726       return UndefValue::get(F->getReturnType());
5727 
5728     // If shift amount is undef, assume it is zero.
5729     if (Q.isUndefValue(ShAmtArg))
5730       return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
5731 
5732     const APInt *ShAmtC;
5733     if (match(ShAmtArg, m_APInt(ShAmtC))) {
5734       // If there's effectively no shift, return the 1st arg or 2nd arg.
5735       APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
5736       if (ShAmtC->urem(BitWidth).isNullValue())
5737         return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
5738     }
5739     return nullptr;
5740   }
5741   case Intrinsic::fma:
5742   case Intrinsic::fmuladd: {
5743     Value *Op0 = Call->getArgOperand(0);
5744     Value *Op1 = Call->getArgOperand(1);
5745     Value *Op2 = Call->getArgOperand(2);
5746     if (Value *V = simplifyFPOp({ Op0, Op1, Op2 }, {}, Q))
5747       return V;
5748     return nullptr;
5749   }
5750   default:
5751     return nullptr;
5752   }
5753 }
5754 
5755 static Value *tryConstantFoldCall(CallBase *Call, const SimplifyQuery &Q) {
5756   auto *F = dyn_cast<Function>(Call->getCalledOperand());
5757   if (!F || !canConstantFoldCallTo(Call, F))
5758     return nullptr;
5759 
5760   SmallVector<Constant *, 4> ConstantArgs;
5761   unsigned NumArgs = Call->getNumArgOperands();
5762   ConstantArgs.reserve(NumArgs);
5763   for (auto &Arg : Call->args()) {
5764     Constant *C = dyn_cast<Constant>(&Arg);
5765     if (!C) {
5766       if (isa<MetadataAsValue>(Arg.get()))
5767         continue;
5768       return nullptr;
5769     }
5770     ConstantArgs.push_back(C);
5771   }
5772 
5773   return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
5774 }
5775 
5776 Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) {
5777   // musttail calls can only be simplified if they are also DCEd.
5778   // As we can't guarantee this here, don't simplify them.
5779   if (Call->isMustTailCall())
5780     return nullptr;
5781 
5782   // call undef -> poison
5783   // call null -> poison
5784   Value *Callee = Call->getCalledOperand();
5785   if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
5786     return PoisonValue::get(Call->getType());
5787 
5788   if (Value *V = tryConstantFoldCall(Call, Q))
5789     return V;
5790 
5791   auto *F = dyn_cast<Function>(Callee);
5792   if (F && F->isIntrinsic())
5793     if (Value *Ret = simplifyIntrinsic(Call, Q))
5794       return Ret;
5795 
5796   return nullptr;
5797 }
5798 
5799 /// Given operands for a Freeze, see if we can fold the result.
5800 static Value *SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
5801   // Use a utility function defined in ValueTracking.
5802   if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT))
5803     return Op0;
5804   // We have room for improvement.
5805   return nullptr;
5806 }
5807 
5808 Value *llvm::SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
5809   return ::SimplifyFreezeInst(Op0, Q);
5810 }
5811 
5812 /// See if we can compute a simplified version of this instruction.
5813 /// If not, this returns null.
5814 
5815 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
5816                                  OptimizationRemarkEmitter *ORE) {
5817   const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
5818   Value *Result;
5819 
5820   switch (I->getOpcode()) {
5821   default:
5822     Result = ConstantFoldInstruction(I, Q.DL, Q.TLI);
5823     break;
5824   case Instruction::FNeg:
5825     Result = SimplifyFNegInst(I->getOperand(0), I->getFastMathFlags(), Q);
5826     break;
5827   case Instruction::FAdd:
5828     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
5829                               I->getFastMathFlags(), Q);
5830     break;
5831   case Instruction::Add:
5832     Result =
5833         SimplifyAddInst(I->getOperand(0), I->getOperand(1),
5834                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5835                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5836     break;
5837   case Instruction::FSub:
5838     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
5839                               I->getFastMathFlags(), Q);
5840     break;
5841   case Instruction::Sub:
5842     Result =
5843         SimplifySubInst(I->getOperand(0), I->getOperand(1),
5844                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5845                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5846     break;
5847   case Instruction::FMul:
5848     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
5849                               I->getFastMathFlags(), Q);
5850     break;
5851   case Instruction::Mul:
5852     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q);
5853     break;
5854   case Instruction::SDiv:
5855     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q);
5856     break;
5857   case Instruction::UDiv:
5858     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q);
5859     break;
5860   case Instruction::FDiv:
5861     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
5862                               I->getFastMathFlags(), Q);
5863     break;
5864   case Instruction::SRem:
5865     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q);
5866     break;
5867   case Instruction::URem:
5868     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q);
5869     break;
5870   case Instruction::FRem:
5871     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
5872                               I->getFastMathFlags(), Q);
5873     break;
5874   case Instruction::Shl:
5875     Result =
5876         SimplifyShlInst(I->getOperand(0), I->getOperand(1),
5877                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5878                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5879     break;
5880   case Instruction::LShr:
5881     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
5882                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5883     break;
5884   case Instruction::AShr:
5885     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
5886                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5887     break;
5888   case Instruction::And:
5889     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q);
5890     break;
5891   case Instruction::Or:
5892     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q);
5893     break;
5894   case Instruction::Xor:
5895     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q);
5896     break;
5897   case Instruction::ICmp:
5898     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
5899                               I->getOperand(0), I->getOperand(1), Q);
5900     break;
5901   case Instruction::FCmp:
5902     Result =
5903         SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
5904                          I->getOperand(1), I->getFastMathFlags(), Q);
5905     break;
5906   case Instruction::Select:
5907     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
5908                                 I->getOperand(2), Q);
5909     break;
5910   case Instruction::GetElementPtr: {
5911     SmallVector<Value *, 8> Ops(I->operands());
5912     Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
5913                              Ops, Q);
5914     break;
5915   }
5916   case Instruction::InsertValue: {
5917     InsertValueInst *IV = cast<InsertValueInst>(I);
5918     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
5919                                      IV->getInsertedValueOperand(),
5920                                      IV->getIndices(), Q);
5921     break;
5922   }
5923   case Instruction::InsertElement: {
5924     auto *IE = cast<InsertElementInst>(I);
5925     Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1),
5926                                        IE->getOperand(2), Q);
5927     break;
5928   }
5929   case Instruction::ExtractValue: {
5930     auto *EVI = cast<ExtractValueInst>(I);
5931     Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
5932                                       EVI->getIndices(), Q);
5933     break;
5934   }
5935   case Instruction::ExtractElement: {
5936     auto *EEI = cast<ExtractElementInst>(I);
5937     Result = SimplifyExtractElementInst(EEI->getVectorOperand(),
5938                                         EEI->getIndexOperand(), Q);
5939     break;
5940   }
5941   case Instruction::ShuffleVector: {
5942     auto *SVI = cast<ShuffleVectorInst>(I);
5943     Result =
5944         SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5945                                   SVI->getShuffleMask(), SVI->getType(), Q);
5946     break;
5947   }
5948   case Instruction::PHI:
5949     Result = SimplifyPHINode(cast<PHINode>(I), Q);
5950     break;
5951   case Instruction::Call: {
5952     Result = SimplifyCall(cast<CallInst>(I), Q);
5953     break;
5954   }
5955   case Instruction::Freeze:
5956     Result = SimplifyFreezeInst(I->getOperand(0), Q);
5957     break;
5958 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
5959 #include "llvm/IR/Instruction.def"
5960 #undef HANDLE_CAST_INST
5961     Result =
5962         SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q);
5963     break;
5964   case Instruction::Alloca:
5965     // No simplifications for Alloca and it can't be constant folded.
5966     Result = nullptr;
5967     break;
5968   }
5969 
5970   /// If called on unreachable code, the above logic may report that the
5971   /// instruction simplified to itself.  Make life easier for users by
5972   /// detecting that case here, returning a safe value instead.
5973   return Result == I ? UndefValue::get(I->getType()) : Result;
5974 }
5975 
5976 /// Implementation of recursive simplification through an instruction's
5977 /// uses.
5978 ///
5979 /// This is the common implementation of the recursive simplification routines.
5980 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
5981 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
5982 /// instructions to process and attempt to simplify it using
5983 /// InstructionSimplify. Recursively visited users which could not be
5984 /// simplified themselves are to the optional UnsimplifiedUsers set for
5985 /// further processing by the caller.
5986 ///
5987 /// This routine returns 'true' only when *it* simplifies something. The passed
5988 /// in simplified value does not count toward this.
5989 static bool replaceAndRecursivelySimplifyImpl(
5990     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
5991     const DominatorTree *DT, AssumptionCache *AC,
5992     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
5993   bool Simplified = false;
5994   SmallSetVector<Instruction *, 8> Worklist;
5995   const DataLayout &DL = I->getModule()->getDataLayout();
5996 
5997   // If we have an explicit value to collapse to, do that round of the
5998   // simplification loop by hand initially.
5999   if (SimpleV) {
6000     for (User *U : I->users())
6001       if (U != I)
6002         Worklist.insert(cast<Instruction>(U));
6003 
6004     // Replace the instruction with its simplified value.
6005     I->replaceAllUsesWith(SimpleV);
6006 
6007     // Gracefully handle edge cases where the instruction is not wired into any
6008     // parent block.
6009     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
6010         !I->mayHaveSideEffects())
6011       I->eraseFromParent();
6012   } else {
6013     Worklist.insert(I);
6014   }
6015 
6016   // Note that we must test the size on each iteration, the worklist can grow.
6017   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
6018     I = Worklist[Idx];
6019 
6020     // See if this instruction simplifies.
6021     SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
6022     if (!SimpleV) {
6023       if (UnsimplifiedUsers)
6024         UnsimplifiedUsers->insert(I);
6025       continue;
6026     }
6027 
6028     Simplified = true;
6029 
6030     // Stash away all the uses of the old instruction so we can check them for
6031     // recursive simplifications after a RAUW. This is cheaper than checking all
6032     // uses of To on the recursive step in most cases.
6033     for (User *U : I->users())
6034       Worklist.insert(cast<Instruction>(U));
6035 
6036     // Replace the instruction with its simplified value.
6037     I->replaceAllUsesWith(SimpleV);
6038 
6039     // Gracefully handle edge cases where the instruction is not wired into any
6040     // parent block.
6041     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
6042         !I->mayHaveSideEffects())
6043       I->eraseFromParent();
6044   }
6045   return Simplified;
6046 }
6047 
6048 bool llvm::replaceAndRecursivelySimplify(
6049     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
6050     const DominatorTree *DT, AssumptionCache *AC,
6051     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
6052   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
6053   assert(SimpleV && "Must provide a simplified value.");
6054   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
6055                                            UnsimplifiedUsers);
6056 }
6057 
6058 namespace llvm {
6059 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
6060   auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
6061   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
6062   auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
6063   auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
6064   auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
6065   auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
6066   return {F.getParent()->getDataLayout(), TLI, DT, AC};
6067 }
6068 
6069 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
6070                                          const DataLayout &DL) {
6071   return {DL, &AR.TLI, &AR.DT, &AR.AC};
6072 }
6073 
6074 template <class T, class... TArgs>
6075 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
6076                                          Function &F) {
6077   auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
6078   auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
6079   auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
6080   return {F.getParent()->getDataLayout(), TLI, DT, AC};
6081 }
6082 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
6083                                                   Function &);
6084 }
6085