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