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   // (mul nuw/nsw X, MulC) != C --> true  (if C is not a multiple of MulC)
2754   // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC)
2755   const APInt *MulC;
2756   if (ICmpInst::isEquality(Pred) &&
2757       ((match(LHS, m_NUWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
2758         C->urem(*MulC) != 0) ||
2759        (match(LHS, m_NSWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
2760         C->srem(*MulC) != 0)))
2761     return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE);
2762 
2763   return nullptr;
2764 }
2765 
2766 static Value *simplifyICmpWithBinOpOnLHS(
2767     CmpInst::Predicate Pred, BinaryOperator *LBO, Value *RHS,
2768     const SimplifyQuery &Q, unsigned MaxRecurse) {
2769   Type *ITy = GetCompareTy(RHS); // The return type.
2770 
2771   Value *Y = nullptr;
2772   // icmp pred (or X, Y), X
2773   if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2774     if (Pred == ICmpInst::ICMP_ULT)
2775       return getFalse(ITy);
2776     if (Pred == ICmpInst::ICMP_UGE)
2777       return getTrue(ITy);
2778 
2779     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2780       KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2781       KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2782       if (RHSKnown.isNonNegative() && YKnown.isNegative())
2783         return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2784       if (RHSKnown.isNegative() || YKnown.isNonNegative())
2785         return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2786     }
2787   }
2788 
2789   // icmp pred (and X, Y), X
2790   if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
2791     if (Pred == ICmpInst::ICMP_UGT)
2792       return getFalse(ITy);
2793     if (Pred == ICmpInst::ICMP_ULE)
2794       return getTrue(ITy);
2795   }
2796 
2797   // icmp pred (urem X, Y), Y
2798   if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2799     switch (Pred) {
2800     default:
2801       break;
2802     case ICmpInst::ICMP_SGT:
2803     case ICmpInst::ICMP_SGE: {
2804       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2805       if (!Known.isNonNegative())
2806         break;
2807       LLVM_FALLTHROUGH;
2808     }
2809     case ICmpInst::ICMP_EQ:
2810     case ICmpInst::ICMP_UGT:
2811     case ICmpInst::ICMP_UGE:
2812       return getFalse(ITy);
2813     case ICmpInst::ICMP_SLT:
2814     case ICmpInst::ICMP_SLE: {
2815       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2816       if (!Known.isNonNegative())
2817         break;
2818       LLVM_FALLTHROUGH;
2819     }
2820     case ICmpInst::ICMP_NE:
2821     case ICmpInst::ICMP_ULT:
2822     case ICmpInst::ICMP_ULE:
2823       return getTrue(ITy);
2824     }
2825   }
2826 
2827   // icmp pred (urem X, Y), X
2828   if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) {
2829     if (Pred == ICmpInst::ICMP_ULE)
2830       return getTrue(ITy);
2831     if (Pred == ICmpInst::ICMP_UGT)
2832       return getFalse(ITy);
2833   }
2834 
2835   // x >> y <=u x
2836   // x udiv y <=u x.
2837   if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2838       match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2839     // icmp pred (X op Y), X
2840     if (Pred == ICmpInst::ICMP_UGT)
2841       return getFalse(ITy);
2842     if (Pred == ICmpInst::ICMP_ULE)
2843       return getTrue(ITy);
2844   }
2845 
2846   return nullptr;
2847 }
2848 
2849 /// TODO: A large part of this logic is duplicated in InstCombine's
2850 /// foldICmpBinOp(). We should be able to share that and avoid the code
2851 /// duplication.
2852 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2853                                     Value *RHS, const SimplifyQuery &Q,
2854                                     unsigned MaxRecurse) {
2855   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2856   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2857   if (MaxRecurse && (LBO || RBO)) {
2858     // Analyze the case when either LHS or RHS is an add instruction.
2859     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2860     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2861     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2862     if (LBO && LBO->getOpcode() == Instruction::Add) {
2863       A = LBO->getOperand(0);
2864       B = LBO->getOperand(1);
2865       NoLHSWrapProblem =
2866           ICmpInst::isEquality(Pred) ||
2867           (CmpInst::isUnsigned(Pred) &&
2868            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
2869           (CmpInst::isSigned(Pred) &&
2870            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
2871     }
2872     if (RBO && RBO->getOpcode() == Instruction::Add) {
2873       C = RBO->getOperand(0);
2874       D = RBO->getOperand(1);
2875       NoRHSWrapProblem =
2876           ICmpInst::isEquality(Pred) ||
2877           (CmpInst::isUnsigned(Pred) &&
2878            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
2879           (CmpInst::isSigned(Pred) &&
2880            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
2881     }
2882 
2883     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2884     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2885       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2886                                       Constant::getNullValue(RHS->getType()), Q,
2887                                       MaxRecurse - 1))
2888         return V;
2889 
2890     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2891     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2892       if (Value *V =
2893               SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2894                                C == LHS ? D : C, Q, MaxRecurse - 1))
2895         return V;
2896 
2897     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2898     if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2899         NoRHSWrapProblem) {
2900       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2901       Value *Y, *Z;
2902       if (A == C) {
2903         // C + B == C + D  ->  B == D
2904         Y = B;
2905         Z = D;
2906       } else if (A == D) {
2907         // D + B == C + D  ->  B == C
2908         Y = B;
2909         Z = C;
2910       } else if (B == C) {
2911         // A + C == C + D  ->  A == D
2912         Y = A;
2913         Z = D;
2914       } else {
2915         assert(B == D);
2916         // A + D == C + D  ->  A == C
2917         Y = A;
2918         Z = C;
2919       }
2920       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2921         return V;
2922     }
2923   }
2924 
2925   if (LBO)
2926     if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse))
2927       return V;
2928 
2929   if (RBO)
2930     if (Value *V = simplifyICmpWithBinOpOnLHS(
2931             ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse))
2932       return V;
2933 
2934   // 0 - (zext X) pred C
2935   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2936     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2937       if (RHSC->getValue().isStrictlyPositive()) {
2938         if (Pred == ICmpInst::ICMP_SLT)
2939           return ConstantInt::getTrue(RHSC->getContext());
2940         if (Pred == ICmpInst::ICMP_SGE)
2941           return ConstantInt::getFalse(RHSC->getContext());
2942         if (Pred == ICmpInst::ICMP_EQ)
2943           return ConstantInt::getFalse(RHSC->getContext());
2944         if (Pred == ICmpInst::ICMP_NE)
2945           return ConstantInt::getTrue(RHSC->getContext());
2946       }
2947       if (RHSC->getValue().isNonNegative()) {
2948         if (Pred == ICmpInst::ICMP_SLE)
2949           return ConstantInt::getTrue(RHSC->getContext());
2950         if (Pred == ICmpInst::ICMP_SGT)
2951           return ConstantInt::getFalse(RHSC->getContext());
2952       }
2953     }
2954   }
2955 
2956   // handle:
2957   //   CI2 << X == CI
2958   //   CI2 << X != CI
2959   //
2960   //   where CI2 is a power of 2 and CI isn't
2961   if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2962     const APInt *CI2Val, *CIVal = &CI->getValue();
2963     if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2964         CI2Val->isPowerOf2()) {
2965       if (!CIVal->isPowerOf2()) {
2966         // CI2 << X can equal zero in some circumstances,
2967         // this simplification is unsafe if CI is zero.
2968         //
2969         // We know it is safe if:
2970         // - The shift is nsw, we can't shift out the one bit.
2971         // - The shift is nuw, we can't shift out the one bit.
2972         // - CI2 is one
2973         // - CI isn't zero
2974         if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
2975             Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
2976             CI2Val->isOneValue() || !CI->isZero()) {
2977           if (Pred == ICmpInst::ICMP_EQ)
2978             return ConstantInt::getFalse(RHS->getContext());
2979           if (Pred == ICmpInst::ICMP_NE)
2980             return ConstantInt::getTrue(RHS->getContext());
2981         }
2982       }
2983       if (CIVal->isSignMask() && CI2Val->isOneValue()) {
2984         if (Pred == ICmpInst::ICMP_UGT)
2985           return ConstantInt::getFalse(RHS->getContext());
2986         if (Pred == ICmpInst::ICMP_ULE)
2987           return ConstantInt::getTrue(RHS->getContext());
2988       }
2989     }
2990   }
2991 
2992   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2993       LBO->getOperand(1) == RBO->getOperand(1)) {
2994     switch (LBO->getOpcode()) {
2995     default:
2996       break;
2997     case Instruction::UDiv:
2998     case Instruction::LShr:
2999       if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
3000           !Q.IIQ.isExact(RBO))
3001         break;
3002       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3003                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3004           return V;
3005       break;
3006     case Instruction::SDiv:
3007       if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
3008           !Q.IIQ.isExact(RBO))
3009         break;
3010       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3011                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3012         return V;
3013       break;
3014     case Instruction::AShr:
3015       if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
3016         break;
3017       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3018                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3019         return V;
3020       break;
3021     case Instruction::Shl: {
3022       bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3023       bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
3024       if (!NUW && !NSW)
3025         break;
3026       if (!NSW && ICmpInst::isSigned(Pred))
3027         break;
3028       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3029                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3030         return V;
3031       break;
3032     }
3033     }
3034   }
3035   return nullptr;
3036 }
3037 
3038 /// Simplify integer comparisons where at least one operand of the compare
3039 /// matches an integer min/max idiom.
3040 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
3041                                      Value *RHS, const SimplifyQuery &Q,
3042                                      unsigned MaxRecurse) {
3043   Type *ITy = GetCompareTy(LHS); // The return type.
3044   Value *A, *B;
3045   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
3046   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
3047 
3048   // Signed variants on "max(a,b)>=a -> true".
3049   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3050     if (A != RHS)
3051       std::swap(A, B);       // smax(A, B) pred A.
3052     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3053     // We analyze this as smax(A, B) pred A.
3054     P = Pred;
3055   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
3056              (A == LHS || B == LHS)) {
3057     if (A != LHS)
3058       std::swap(A, B);       // A pred smax(A, B).
3059     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3060     // We analyze this as smax(A, B) swapped-pred A.
3061     P = CmpInst::getSwappedPredicate(Pred);
3062   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3063              (A == RHS || B == RHS)) {
3064     if (A != RHS)
3065       std::swap(A, B);       // smin(A, B) pred A.
3066     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3067     // We analyze this as smax(-A, -B) swapped-pred -A.
3068     // Note that we do not need to actually form -A or -B thanks to EqP.
3069     P = CmpInst::getSwappedPredicate(Pred);
3070   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
3071              (A == LHS || B == LHS)) {
3072     if (A != LHS)
3073       std::swap(A, B);       // A pred smin(A, B).
3074     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3075     // We analyze this as smax(-A, -B) pred -A.
3076     // Note that we do not need to actually form -A or -B thanks to EqP.
3077     P = Pred;
3078   }
3079   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3080     // Cases correspond to "max(A, B) p A".
3081     switch (P) {
3082     default:
3083       break;
3084     case CmpInst::ICMP_EQ:
3085     case CmpInst::ICMP_SLE:
3086       // Equivalent to "A EqP B".  This may be the same as the condition tested
3087       // in the max/min; if so, we can just return that.
3088       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3089         return V;
3090       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3091         return V;
3092       // Otherwise, see if "A EqP B" simplifies.
3093       if (MaxRecurse)
3094         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3095           return V;
3096       break;
3097     case CmpInst::ICMP_NE:
3098     case CmpInst::ICMP_SGT: {
3099       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3100       // Equivalent to "A InvEqP B".  This may be the same as the condition
3101       // tested in the max/min; if so, we can just return that.
3102       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3103         return V;
3104       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3105         return V;
3106       // Otherwise, see if "A InvEqP B" simplifies.
3107       if (MaxRecurse)
3108         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3109           return V;
3110       break;
3111     }
3112     case CmpInst::ICMP_SGE:
3113       // Always true.
3114       return getTrue(ITy);
3115     case CmpInst::ICMP_SLT:
3116       // Always false.
3117       return getFalse(ITy);
3118     }
3119   }
3120 
3121   // Unsigned variants on "max(a,b)>=a -> true".
3122   P = CmpInst::BAD_ICMP_PREDICATE;
3123   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3124     if (A != RHS)
3125       std::swap(A, B);       // umax(A, B) pred A.
3126     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3127     // We analyze this as umax(A, B) pred A.
3128     P = Pred;
3129   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3130              (A == LHS || B == LHS)) {
3131     if (A != LHS)
3132       std::swap(A, B);       // A pred umax(A, B).
3133     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3134     // We analyze this as umax(A, B) swapped-pred A.
3135     P = CmpInst::getSwappedPredicate(Pred);
3136   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3137              (A == RHS || B == RHS)) {
3138     if (A != RHS)
3139       std::swap(A, B);       // umin(A, B) pred A.
3140     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3141     // We analyze this as umax(-A, -B) swapped-pred -A.
3142     // Note that we do not need to actually form -A or -B thanks to EqP.
3143     P = CmpInst::getSwappedPredicate(Pred);
3144   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3145              (A == LHS || B == LHS)) {
3146     if (A != LHS)
3147       std::swap(A, B);       // A pred umin(A, B).
3148     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3149     // We analyze this as umax(-A, -B) pred -A.
3150     // Note that we do not need to actually form -A or -B thanks to EqP.
3151     P = Pred;
3152   }
3153   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3154     // Cases correspond to "max(A, B) p A".
3155     switch (P) {
3156     default:
3157       break;
3158     case CmpInst::ICMP_EQ:
3159     case CmpInst::ICMP_ULE:
3160       // Equivalent to "A EqP B".  This may be the same as the condition tested
3161       // in the max/min; if so, we can just return that.
3162       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3163         return V;
3164       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3165         return V;
3166       // Otherwise, see if "A EqP B" simplifies.
3167       if (MaxRecurse)
3168         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3169           return V;
3170       break;
3171     case CmpInst::ICMP_NE:
3172     case CmpInst::ICMP_UGT: {
3173       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3174       // Equivalent to "A InvEqP B".  This may be the same as the condition
3175       // tested in the max/min; if so, we can just return that.
3176       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3177         return V;
3178       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3179         return V;
3180       // Otherwise, see if "A InvEqP B" simplifies.
3181       if (MaxRecurse)
3182         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3183           return V;
3184       break;
3185     }
3186     case CmpInst::ICMP_UGE:
3187       return getTrue(ITy);
3188     case CmpInst::ICMP_ULT:
3189       return getFalse(ITy);
3190     }
3191   }
3192 
3193   // Comparing 1 each of min/max with a common operand?
3194   // Canonicalize min operand to RHS.
3195   if (match(LHS, m_UMin(m_Value(), m_Value())) ||
3196       match(LHS, m_SMin(m_Value(), m_Value()))) {
3197     std::swap(LHS, RHS);
3198     Pred = ICmpInst::getSwappedPredicate(Pred);
3199   }
3200 
3201   Value *C, *D;
3202   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3203       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3204       (A == C || A == D || B == C || B == D)) {
3205     // smax(A, B) >=s smin(A, D) --> true
3206     if (Pred == CmpInst::ICMP_SGE)
3207       return getTrue(ITy);
3208     // smax(A, B) <s smin(A, D) --> false
3209     if (Pred == CmpInst::ICMP_SLT)
3210       return getFalse(ITy);
3211   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3212              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3213              (A == C || A == D || B == C || B == D)) {
3214     // umax(A, B) >=u umin(A, D) --> true
3215     if (Pred == CmpInst::ICMP_UGE)
3216       return getTrue(ITy);
3217     // umax(A, B) <u umin(A, D) --> false
3218     if (Pred == CmpInst::ICMP_ULT)
3219       return getFalse(ITy);
3220   }
3221 
3222   return nullptr;
3223 }
3224 
3225 static Value *simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate,
3226                                                Value *LHS, Value *RHS,
3227                                                const SimplifyQuery &Q) {
3228   // Gracefully handle instructions that have not been inserted yet.
3229   if (!Q.AC || !Q.CxtI || !Q.CxtI->getParent())
3230     return nullptr;
3231 
3232   for (Value *AssumeBaseOp : {LHS, RHS}) {
3233     for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) {
3234       if (!AssumeVH)
3235         continue;
3236 
3237       CallInst *Assume = cast<CallInst>(AssumeVH);
3238       if (Optional<bool> Imp =
3239               isImpliedCondition(Assume->getArgOperand(0), Predicate, LHS, RHS,
3240                                  Q.DL))
3241         if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT))
3242           return ConstantInt::get(GetCompareTy(LHS), *Imp);
3243     }
3244   }
3245 
3246   return nullptr;
3247 }
3248 
3249 /// Given operands for an ICmpInst, see if we can fold the result.
3250 /// If not, this returns null.
3251 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3252                                const SimplifyQuery &Q, unsigned MaxRecurse) {
3253   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3254   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3255 
3256   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3257     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3258       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3259 
3260     // If we have a constant, make sure it is on the RHS.
3261     std::swap(LHS, RHS);
3262     Pred = CmpInst::getSwappedPredicate(Pred);
3263   }
3264   assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3265 
3266   Type *ITy = GetCompareTy(LHS); // The return type.
3267 
3268   // For EQ and NE, we can always pick a value for the undef to make the
3269   // predicate pass or fail, so we can return undef.
3270   // Matches behavior in llvm::ConstantFoldCompareInstruction.
3271   if (isa<UndefValue>(RHS) && ICmpInst::isEquality(Pred))
3272     return UndefValue::get(ITy);
3273 
3274   // icmp X, X -> true/false
3275   // icmp X, undef -> true/false because undef could be X.
3276   if (LHS == RHS || isa<UndefValue>(RHS))
3277     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3278 
3279   if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3280     return V;
3281 
3282   if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3283     return V;
3284 
3285   if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
3286     return V;
3287 
3288   // If both operands have range metadata, use the metadata
3289   // to simplify the comparison.
3290   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3291     auto RHS_Instr = cast<Instruction>(RHS);
3292     auto LHS_Instr = cast<Instruction>(LHS);
3293 
3294     if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3295         Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
3296       auto RHS_CR = getConstantRangeFromMetadata(
3297           *RHS_Instr->getMetadata(LLVMContext::MD_range));
3298       auto LHS_CR = getConstantRangeFromMetadata(
3299           *LHS_Instr->getMetadata(LLVMContext::MD_range));
3300 
3301       auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3302       if (Satisfied_CR.contains(LHS_CR))
3303         return ConstantInt::getTrue(RHS->getContext());
3304 
3305       auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3306                 CmpInst::getInversePredicate(Pred), RHS_CR);
3307       if (InversedSatisfied_CR.contains(LHS_CR))
3308         return ConstantInt::getFalse(RHS->getContext());
3309     }
3310   }
3311 
3312   // Compare of cast, for example (zext X) != 0 -> X != 0
3313   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3314     Instruction *LI = cast<CastInst>(LHS);
3315     Value *SrcOp = LI->getOperand(0);
3316     Type *SrcTy = SrcOp->getType();
3317     Type *DstTy = LI->getType();
3318 
3319     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3320     // if the integer type is the same size as the pointer type.
3321     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3322         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3323       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3324         // Transfer the cast to the constant.
3325         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3326                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
3327                                         Q, MaxRecurse-1))
3328           return V;
3329       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3330         if (RI->getOperand(0)->getType() == SrcTy)
3331           // Compare without the cast.
3332           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3333                                           Q, MaxRecurse-1))
3334             return V;
3335       }
3336     }
3337 
3338     if (isa<ZExtInst>(LHS)) {
3339       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3340       // same type.
3341       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3342         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3343           // Compare X and Y.  Note that signed predicates become unsigned.
3344           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3345                                           SrcOp, RI->getOperand(0), Q,
3346                                           MaxRecurse-1))
3347             return V;
3348       }
3349       // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true.
3350       else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3351         if (SrcOp == RI->getOperand(0)) {
3352           if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE)
3353             return ConstantInt::getTrue(ITy);
3354           if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT)
3355             return ConstantInt::getFalse(ITy);
3356         }
3357       }
3358       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3359       // too.  If not, then try to deduce the result of the comparison.
3360       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3361         // Compute the constant that would happen if we truncated to SrcTy then
3362         // reextended to DstTy.
3363         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3364         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3365 
3366         // If the re-extended constant didn't change then this is effectively
3367         // also a case of comparing two zero-extended values.
3368         if (RExt == CI && MaxRecurse)
3369           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3370                                         SrcOp, Trunc, Q, MaxRecurse-1))
3371             return V;
3372 
3373         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3374         // there.  Use this to work out the result of the comparison.
3375         if (RExt != CI) {
3376           switch (Pred) {
3377           default: llvm_unreachable("Unknown ICmp predicate!");
3378           // LHS <u RHS.
3379           case ICmpInst::ICMP_EQ:
3380           case ICmpInst::ICMP_UGT:
3381           case ICmpInst::ICMP_UGE:
3382             return ConstantInt::getFalse(CI->getContext());
3383 
3384           case ICmpInst::ICMP_NE:
3385           case ICmpInst::ICMP_ULT:
3386           case ICmpInst::ICMP_ULE:
3387             return ConstantInt::getTrue(CI->getContext());
3388 
3389           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
3390           // is non-negative then LHS <s RHS.
3391           case ICmpInst::ICMP_SGT:
3392           case ICmpInst::ICMP_SGE:
3393             return CI->getValue().isNegative() ?
3394               ConstantInt::getTrue(CI->getContext()) :
3395               ConstantInt::getFalse(CI->getContext());
3396 
3397           case ICmpInst::ICMP_SLT:
3398           case ICmpInst::ICMP_SLE:
3399             return CI->getValue().isNegative() ?
3400               ConstantInt::getFalse(CI->getContext()) :
3401               ConstantInt::getTrue(CI->getContext());
3402           }
3403         }
3404       }
3405     }
3406 
3407     if (isa<SExtInst>(LHS)) {
3408       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3409       // same type.
3410       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3411         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3412           // Compare X and Y.  Note that the predicate does not change.
3413           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3414                                           Q, MaxRecurse-1))
3415             return V;
3416       }
3417       // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true.
3418       else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3419         if (SrcOp == RI->getOperand(0)) {
3420           if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE)
3421             return ConstantInt::getTrue(ITy);
3422           if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT)
3423             return ConstantInt::getFalse(ITy);
3424         }
3425       }
3426       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3427       // too.  If not, then try to deduce the result of the comparison.
3428       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3429         // Compute the constant that would happen if we truncated to SrcTy then
3430         // reextended to DstTy.
3431         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3432         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3433 
3434         // If the re-extended constant didn't change then this is effectively
3435         // also a case of comparing two sign-extended values.
3436         if (RExt == CI && MaxRecurse)
3437           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
3438             return V;
3439 
3440         // Otherwise the upper bits of LHS are all equal, while RHS has varying
3441         // bits there.  Use this to work out the result of the comparison.
3442         if (RExt != CI) {
3443           switch (Pred) {
3444           default: llvm_unreachable("Unknown ICmp predicate!");
3445           case ICmpInst::ICMP_EQ:
3446             return ConstantInt::getFalse(CI->getContext());
3447           case ICmpInst::ICMP_NE:
3448             return ConstantInt::getTrue(CI->getContext());
3449 
3450           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
3451           // LHS >s RHS.
3452           case ICmpInst::ICMP_SGT:
3453           case ICmpInst::ICMP_SGE:
3454             return CI->getValue().isNegative() ?
3455               ConstantInt::getTrue(CI->getContext()) :
3456               ConstantInt::getFalse(CI->getContext());
3457           case ICmpInst::ICMP_SLT:
3458           case ICmpInst::ICMP_SLE:
3459             return CI->getValue().isNegative() ?
3460               ConstantInt::getFalse(CI->getContext()) :
3461               ConstantInt::getTrue(CI->getContext());
3462 
3463           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
3464           // LHS >u RHS.
3465           case ICmpInst::ICMP_UGT:
3466           case ICmpInst::ICMP_UGE:
3467             // Comparison is true iff the LHS <s 0.
3468             if (MaxRecurse)
3469               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3470                                               Constant::getNullValue(SrcTy),
3471                                               Q, MaxRecurse-1))
3472                 return V;
3473             break;
3474           case ICmpInst::ICMP_ULT:
3475           case ICmpInst::ICMP_ULE:
3476             // Comparison is true iff the LHS >=s 0.
3477             if (MaxRecurse)
3478               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3479                                               Constant::getNullValue(SrcTy),
3480                                               Q, MaxRecurse-1))
3481                 return V;
3482             break;
3483           }
3484         }
3485       }
3486     }
3487   }
3488 
3489   // icmp eq|ne X, Y -> false|true if X != Y
3490   if (ICmpInst::isEquality(Pred) &&
3491       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
3492     return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
3493   }
3494 
3495   if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3496     return V;
3497 
3498   if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
3499     return V;
3500 
3501   if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q))
3502     return V;
3503 
3504   // Simplify comparisons of related pointers using a powerful, recursive
3505   // GEP-walk when we have target data available..
3506   if (LHS->getType()->isPointerTy())
3507     if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3508                                      Q.IIQ, LHS, RHS))
3509       return C;
3510   if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3511     if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3512       if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3513               Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3514           Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3515               Q.DL.getTypeSizeInBits(CRHS->getType()))
3516         if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3517                                          Q.IIQ, CLHS->getPointerOperand(),
3518                                          CRHS->getPointerOperand()))
3519           return C;
3520 
3521   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3522     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3523       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3524           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3525           (ICmpInst::isEquality(Pred) ||
3526            (GLHS->isInBounds() && GRHS->isInBounds() &&
3527             Pred == ICmpInst::getSignedPredicate(Pred)))) {
3528         // The bases are equal and the indices are constant.  Build a constant
3529         // expression GEP with the same indices and a null base pointer to see
3530         // what constant folding can make out of it.
3531         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3532         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
3533         Constant *NewLHS = ConstantExpr::getGetElementPtr(
3534             GLHS->getSourceElementType(), Null, IndicesLHS);
3535 
3536         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3537         Constant *NewRHS = ConstantExpr::getGetElementPtr(
3538             GLHS->getSourceElementType(), Null, IndicesRHS);
3539         Constant *NewICmp = ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3540         return ConstantFoldConstant(NewICmp, Q.DL);
3541       }
3542     }
3543   }
3544 
3545   // If the comparison is with the result of a select instruction, check whether
3546   // comparing with either branch of the select always yields the same value.
3547   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3548     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3549       return V;
3550 
3551   // If the comparison is with the result of a phi instruction, check whether
3552   // doing the compare with each incoming phi value yields a common result.
3553   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3554     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3555       return V;
3556 
3557   return nullptr;
3558 }
3559 
3560 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3561                               const SimplifyQuery &Q) {
3562   return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3563 }
3564 
3565 /// Given operands for an FCmpInst, see if we can fold the result.
3566 /// If not, this returns null.
3567 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3568                                FastMathFlags FMF, const SimplifyQuery &Q,
3569                                unsigned MaxRecurse) {
3570   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3571   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3572 
3573   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3574     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3575       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3576 
3577     // If we have a constant, make sure it is on the RHS.
3578     std::swap(LHS, RHS);
3579     Pred = CmpInst::getSwappedPredicate(Pred);
3580   }
3581 
3582   // Fold trivial predicates.
3583   Type *RetTy = GetCompareTy(LHS);
3584   if (Pred == FCmpInst::FCMP_FALSE)
3585     return getFalse(RetTy);
3586   if (Pred == FCmpInst::FCMP_TRUE)
3587     return getTrue(RetTy);
3588 
3589   // Fold (un)ordered comparison if we can determine there are no NaNs.
3590   if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3591     if (FMF.noNaNs() ||
3592         (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
3593       return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
3594 
3595   // NaN is unordered; NaN is not ordered.
3596   assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3597          "Comparison must be either ordered or unordered");
3598   if (match(RHS, m_NaN()))
3599     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3600 
3601   // fcmp pred x, undef  and  fcmp pred undef, x
3602   // fold to true if unordered, false if ordered
3603   if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3604     // Choosing NaN for the undef will always make unordered comparison succeed
3605     // and ordered comparison fail.
3606     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3607   }
3608 
3609   // fcmp x,x -> true/false.  Not all compares are foldable.
3610   if (LHS == RHS) {
3611     if (CmpInst::isTrueWhenEqual(Pred))
3612       return getTrue(RetTy);
3613     if (CmpInst::isFalseWhenEqual(Pred))
3614       return getFalse(RetTy);
3615   }
3616 
3617   // Handle fcmp with constant RHS.
3618   // TODO: Use match with a specific FP value, so these work with vectors with
3619   // undef lanes.
3620   const APFloat *C;
3621   if (match(RHS, m_APFloat(C))) {
3622     // Check whether the constant is an infinity.
3623     if (C->isInfinity()) {
3624       if (C->isNegative()) {
3625         switch (Pred) {
3626         case FCmpInst::FCMP_OLT:
3627           // No value is ordered and less than negative infinity.
3628           return getFalse(RetTy);
3629         case FCmpInst::FCMP_UGE:
3630           // All values are unordered with or at least negative infinity.
3631           return getTrue(RetTy);
3632         default:
3633           break;
3634         }
3635       } else {
3636         switch (Pred) {
3637         case FCmpInst::FCMP_OGT:
3638           // No value is ordered and greater than infinity.
3639           return getFalse(RetTy);
3640         case FCmpInst::FCMP_ULE:
3641           // All values are unordered with and at most infinity.
3642           return getTrue(RetTy);
3643         default:
3644           break;
3645         }
3646       }
3647 
3648       // LHS == Inf
3649       if (Pred == FCmpInst::FCMP_OEQ && isKnownNeverInfinity(LHS, Q.TLI))
3650         return getFalse(RetTy);
3651       // LHS != Inf
3652       if (Pred == FCmpInst::FCMP_UNE && isKnownNeverInfinity(LHS, Q.TLI))
3653         return getTrue(RetTy);
3654       // LHS == Inf || LHS == NaN
3655       if (Pred == FCmpInst::FCMP_UEQ && isKnownNeverInfinity(LHS, Q.TLI) &&
3656           isKnownNeverNaN(LHS, Q.TLI))
3657         return getFalse(RetTy);
3658       // LHS != Inf && LHS != NaN
3659       if (Pred == FCmpInst::FCMP_ONE && isKnownNeverInfinity(LHS, Q.TLI) &&
3660           isKnownNeverNaN(LHS, Q.TLI))
3661         return getTrue(RetTy);
3662     }
3663     if (C->isNegative() && !C->isNegZero()) {
3664       assert(!C->isNaN() && "Unexpected NaN constant!");
3665       // TODO: We can catch more cases by using a range check rather than
3666       //       relying on CannotBeOrderedLessThanZero.
3667       switch (Pred) {
3668       case FCmpInst::FCMP_UGE:
3669       case FCmpInst::FCMP_UGT:
3670       case FCmpInst::FCMP_UNE:
3671         // (X >= 0) implies (X > C) when (C < 0)
3672         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3673           return getTrue(RetTy);
3674         break;
3675       case FCmpInst::FCMP_OEQ:
3676       case FCmpInst::FCMP_OLE:
3677       case FCmpInst::FCMP_OLT:
3678         // (X >= 0) implies !(X < C) when (C < 0)
3679         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3680           return getFalse(RetTy);
3681         break;
3682       default:
3683         break;
3684       }
3685     }
3686 
3687     // Check comparison of [minnum/maxnum with constant] with other constant.
3688     const APFloat *C2;
3689     if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
3690          *C2 < *C) ||
3691         (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
3692          *C2 > *C)) {
3693       bool IsMaxNum =
3694           cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
3695       // The ordered relationship and minnum/maxnum guarantee that we do not
3696       // have NaN constants, so ordered/unordered preds are handled the same.
3697       switch (Pred) {
3698       case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_UEQ:
3699         // minnum(X, LesserC)  == C --> false
3700         // maxnum(X, GreaterC) == C --> false
3701         return getFalse(RetTy);
3702       case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_UNE:
3703         // minnum(X, LesserC)  != C --> true
3704         // maxnum(X, GreaterC) != C --> true
3705         return getTrue(RetTy);
3706       case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_UGE:
3707       case FCmpInst::FCMP_OGT: case FCmpInst::FCMP_UGT:
3708         // minnum(X, LesserC)  >= C --> false
3709         // minnum(X, LesserC)  >  C --> false
3710         // maxnum(X, GreaterC) >= C --> true
3711         // maxnum(X, GreaterC) >  C --> true
3712         return ConstantInt::get(RetTy, IsMaxNum);
3713       case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ULE:
3714       case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_ULT:
3715         // minnum(X, LesserC)  <= C --> true
3716         // minnum(X, LesserC)  <  C --> true
3717         // maxnum(X, GreaterC) <= C --> false
3718         // maxnum(X, GreaterC) <  C --> false
3719         return ConstantInt::get(RetTy, !IsMaxNum);
3720       default:
3721         // TRUE/FALSE/ORD/UNO should be handled before this.
3722         llvm_unreachable("Unexpected fcmp predicate");
3723       }
3724     }
3725   }
3726 
3727   if (match(RHS, m_AnyZeroFP())) {
3728     switch (Pred) {
3729     case FCmpInst::FCMP_OGE:
3730     case FCmpInst::FCMP_ULT:
3731       // Positive or zero X >= 0.0 --> true
3732       // Positive or zero X <  0.0 --> false
3733       if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) &&
3734           CannotBeOrderedLessThanZero(LHS, Q.TLI))
3735         return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
3736       break;
3737     case FCmpInst::FCMP_UGE:
3738     case FCmpInst::FCMP_OLT:
3739       // Positive or zero or nan X >= 0.0 --> true
3740       // Positive or zero or nan X <  0.0 --> false
3741       if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3742         return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
3743       break;
3744     default:
3745       break;
3746     }
3747   }
3748 
3749   // If the comparison is with the result of a select instruction, check whether
3750   // comparing with either branch of the select always yields the same value.
3751   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3752     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3753       return V;
3754 
3755   // If the comparison is with the result of a phi instruction, check whether
3756   // doing the compare with each incoming phi value yields a common result.
3757   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3758     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3759       return V;
3760 
3761   return nullptr;
3762 }
3763 
3764 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3765                               FastMathFlags FMF, const SimplifyQuery &Q) {
3766   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
3767 }
3768 
3769 /// See if V simplifies when its operand Op is replaced with RepOp.
3770 static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3771                                            const SimplifyQuery &Q,
3772                                            unsigned MaxRecurse) {
3773   // Trivial replacement.
3774   if (V == Op)
3775     return RepOp;
3776 
3777   // We cannot replace a constant, and shouldn't even try.
3778   if (isa<Constant>(Op))
3779     return nullptr;
3780 
3781   auto *I = dyn_cast<Instruction>(V);
3782   if (!I)
3783     return nullptr;
3784 
3785   // If this is a binary operator, try to simplify it with the replaced op.
3786   if (auto *B = dyn_cast<BinaryOperator>(I)) {
3787     // Consider:
3788     //   %cmp = icmp eq i32 %x, 2147483647
3789     //   %add = add nsw i32 %x, 1
3790     //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
3791     //
3792     // We can't replace %sel with %add unless we strip away the flags.
3793     // TODO: This is an unusual limitation because better analysis results in
3794     //       worse simplification. InstCombine can do this fold more generally
3795     //       by dropping the flags. Remove this fold to save compile-time?
3796     if (isa<OverflowingBinaryOperator>(B))
3797       if (Q.IIQ.hasNoSignedWrap(B) || Q.IIQ.hasNoUnsignedWrap(B))
3798         return nullptr;
3799     if (isa<PossiblyExactOperator>(B) && Q.IIQ.isExact(B))
3800       return nullptr;
3801 
3802     if (MaxRecurse) {
3803       if (B->getOperand(0) == Op)
3804         return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3805                              MaxRecurse - 1);
3806       if (B->getOperand(1) == Op)
3807         return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3808                              MaxRecurse - 1);
3809     }
3810   }
3811 
3812   // Same for CmpInsts.
3813   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3814     if (MaxRecurse) {
3815       if (C->getOperand(0) == Op)
3816         return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3817                                MaxRecurse - 1);
3818       if (C->getOperand(1) == Op)
3819         return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3820                                MaxRecurse - 1);
3821     }
3822   }
3823 
3824   // Same for GEPs.
3825   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3826     if (MaxRecurse) {
3827       SmallVector<Value *, 8> NewOps(GEP->getNumOperands());
3828       transform(GEP->operands(), NewOps.begin(),
3829                 [&](Value *V) { return V == Op ? RepOp : V; });
3830       return SimplifyGEPInst(GEP->getSourceElementType(), NewOps, Q,
3831                              MaxRecurse - 1);
3832     }
3833   }
3834 
3835   // TODO: We could hand off more cases to instsimplify here.
3836 
3837   // If all operands are constant after substituting Op for RepOp then we can
3838   // constant fold the instruction.
3839   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3840     // Build a list of all constant operands.
3841     SmallVector<Constant *, 8> ConstOps;
3842     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3843       if (I->getOperand(i) == Op)
3844         ConstOps.push_back(CRepOp);
3845       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3846         ConstOps.push_back(COp);
3847       else
3848         break;
3849     }
3850 
3851     // All operands were constants, fold it.
3852     if (ConstOps.size() == I->getNumOperands()) {
3853       if (CmpInst *C = dyn_cast<CmpInst>(I))
3854         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3855                                                ConstOps[1], Q.DL, Q.TLI);
3856 
3857       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3858         if (!LI->isVolatile())
3859           return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
3860 
3861       return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
3862     }
3863   }
3864 
3865   return nullptr;
3866 }
3867 
3868 /// Try to simplify a select instruction when its condition operand is an
3869 /// integer comparison where one operand of the compare is a constant.
3870 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3871                                     const APInt *Y, bool TrueWhenUnset) {
3872   const APInt *C;
3873 
3874   // (X & Y) == 0 ? X & ~Y : X  --> X
3875   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
3876   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3877       *Y == ~*C)
3878     return TrueWhenUnset ? FalseVal : TrueVal;
3879 
3880   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
3881   // (X & Y) != 0 ? X : X & ~Y  --> X
3882   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3883       *Y == ~*C)
3884     return TrueWhenUnset ? FalseVal : TrueVal;
3885 
3886   if (Y->isPowerOf2()) {
3887     // (X & Y) == 0 ? X | Y : X  --> X | Y
3888     // (X & Y) != 0 ? X | Y : X  --> X
3889     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3890         *Y == *C)
3891       return TrueWhenUnset ? TrueVal : FalseVal;
3892 
3893     // (X & Y) == 0 ? X : X | Y  --> X
3894     // (X & Y) != 0 ? X : X | Y  --> X | Y
3895     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3896         *Y == *C)
3897       return TrueWhenUnset ? TrueVal : FalseVal;
3898   }
3899 
3900   return nullptr;
3901 }
3902 
3903 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
3904 /// eq/ne.
3905 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
3906                                            ICmpInst::Predicate Pred,
3907                                            Value *TrueVal, Value *FalseVal) {
3908   Value *X;
3909   APInt Mask;
3910   if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
3911     return nullptr;
3912 
3913   return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
3914                                Pred == ICmpInst::ICMP_EQ);
3915 }
3916 
3917 /// Try to simplify a select instruction when its condition operand is an
3918 /// integer comparison.
3919 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3920                                          Value *FalseVal, const SimplifyQuery &Q,
3921                                          unsigned MaxRecurse) {
3922   ICmpInst::Predicate Pred;
3923   Value *CmpLHS, *CmpRHS;
3924   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3925     return nullptr;
3926 
3927   if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3928     Value *X;
3929     const APInt *Y;
3930     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3931       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3932                                            Pred == ICmpInst::ICMP_EQ))
3933         return V;
3934 
3935     // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
3936     Value *ShAmt;
3937     auto isFsh = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(),
3938                                                           m_Value(ShAmt)),
3939                              m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X),
3940                                                           m_Value(ShAmt)));
3941     // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
3942     // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
3943     if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt &&
3944         Pred == ICmpInst::ICMP_EQ)
3945       return X;
3946     // (ShAmt != 0) ? X : fshl(X, *, ShAmt) --> X
3947     // (ShAmt != 0) ? X : fshr(*, X, ShAmt) --> X
3948     if (match(FalseVal, isFsh) && TrueVal == X && CmpLHS == ShAmt &&
3949         Pred == ICmpInst::ICMP_NE)
3950       return X;
3951 
3952     // Test for a zero-shift-guard-op around rotates. These are used to
3953     // avoid UB from oversized shifts in raw IR rotate patterns, but the
3954     // intrinsics do not have that problem.
3955     // We do not allow this transform for the general funnel shift case because
3956     // that would not preserve the poison safety of the original code.
3957     auto isRotate = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X),
3958                                                              m_Deferred(X),
3959                                                              m_Value(ShAmt)),
3960                                 m_Intrinsic<Intrinsic::fshr>(m_Value(X),
3961                                                              m_Deferred(X),
3962                                                              m_Value(ShAmt)));
3963     // (ShAmt != 0) ? fshl(X, X, ShAmt) : X --> fshl(X, X, ShAmt)
3964     // (ShAmt != 0) ? fshr(X, X, ShAmt) : X --> fshr(X, X, ShAmt)
3965     if (match(TrueVal, isRotate) && FalseVal == X && CmpLHS == ShAmt &&
3966         Pred == ICmpInst::ICMP_NE)
3967       return TrueVal;
3968     // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
3969     // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
3970     if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
3971         Pred == ICmpInst::ICMP_EQ)
3972       return FalseVal;
3973   }
3974 
3975   // Check for other compares that behave like bit test.
3976   if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
3977                                               TrueVal, FalseVal))
3978     return V;
3979 
3980   // If we have an equality comparison, then we know the value in one of the
3981   // arms of the select. See if substituting this value into the arm and
3982   // simplifying the result yields the same value as the other arm.
3983   if (Pred == ICmpInst::ICMP_EQ) {
3984     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3985             TrueVal ||
3986         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3987             TrueVal)
3988       return FalseVal;
3989     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3990             FalseVal ||
3991         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3992             FalseVal)
3993       return FalseVal;
3994   } else if (Pred == ICmpInst::ICMP_NE) {
3995     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3996             FalseVal ||
3997         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3998             FalseVal)
3999       return TrueVal;
4000     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
4001             TrueVal ||
4002         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
4003             TrueVal)
4004       return TrueVal;
4005   }
4006 
4007   return nullptr;
4008 }
4009 
4010 /// Try to simplify a select instruction when its condition operand is a
4011 /// floating-point comparison.
4012 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F,
4013                                      const SimplifyQuery &Q) {
4014   FCmpInst::Predicate Pred;
4015   if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
4016       !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
4017     return nullptr;
4018 
4019   // This transform is safe if we do not have (do not care about) -0.0 or if
4020   // at least one operand is known to not be -0.0. Otherwise, the select can
4021   // change the sign of a zero operand.
4022   bool HasNoSignedZeros = Q.CxtI && isa<FPMathOperator>(Q.CxtI) &&
4023                           Q.CxtI->hasNoSignedZeros();
4024   const APFloat *C;
4025   if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) ||
4026                           (match(F, m_APFloat(C)) && C->isNonZero())) {
4027     // (T == F) ? T : F --> F
4028     // (F == T) ? T : F --> F
4029     if (Pred == FCmpInst::FCMP_OEQ)
4030       return F;
4031 
4032     // (T != F) ? T : F --> T
4033     // (F != T) ? T : F --> T
4034     if (Pred == FCmpInst::FCMP_UNE)
4035       return T;
4036   }
4037 
4038   return nullptr;
4039 }
4040 
4041 /// Given operands for a SelectInst, see if we can fold the result.
4042 /// If not, this returns null.
4043 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4044                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
4045   if (auto *CondC = dyn_cast<Constant>(Cond)) {
4046     if (auto *TrueC = dyn_cast<Constant>(TrueVal))
4047       if (auto *FalseC = dyn_cast<Constant>(FalseVal))
4048         return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
4049 
4050     // select undef, X, Y -> X or Y
4051     if (isa<UndefValue>(CondC))
4052       return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
4053 
4054     // TODO: Vector constants with undef elements don't simplify.
4055 
4056     // select true, X, Y  -> X
4057     if (CondC->isAllOnesValue())
4058       return TrueVal;
4059     // select false, X, Y -> Y
4060     if (CondC->isNullValue())
4061       return FalseVal;
4062   }
4063 
4064   // select i1 Cond, i1 true, i1 false --> i1 Cond
4065   assert(Cond->getType()->isIntOrIntVectorTy(1) &&
4066          "Select must have bool or bool vector condition");
4067   assert(TrueVal->getType() == FalseVal->getType() &&
4068          "Select must have same types for true/false ops");
4069   if (Cond->getType() == TrueVal->getType() &&
4070       match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt()))
4071     return Cond;
4072 
4073   // select ?, X, X -> X
4074   if (TrueVal == FalseVal)
4075     return TrueVal;
4076 
4077   if (isa<UndefValue>(TrueVal))   // select ?, undef, X -> X
4078     return FalseVal;
4079   if (isa<UndefValue>(FalseVal))   // select ?, X, undef -> X
4080     return TrueVal;
4081 
4082   // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC''
4083   Constant *TrueC, *FalseC;
4084   if (TrueVal->getType()->isVectorTy() && match(TrueVal, m_Constant(TrueC)) &&
4085       match(FalseVal, m_Constant(FalseC))) {
4086     unsigned NumElts =
4087         cast<FixedVectorType>(TrueC->getType())->getNumElements();
4088     SmallVector<Constant *, 16> NewC;
4089     for (unsigned i = 0; i != NumElts; ++i) {
4090       // Bail out on incomplete vector constants.
4091       Constant *TEltC = TrueC->getAggregateElement(i);
4092       Constant *FEltC = FalseC->getAggregateElement(i);
4093       if (!TEltC || !FEltC)
4094         break;
4095 
4096       // If the elements match (undef or not), that value is the result. If only
4097       // one element is undef, choose the defined element as the safe result.
4098       if (TEltC == FEltC)
4099         NewC.push_back(TEltC);
4100       else if (isa<UndefValue>(TEltC))
4101         NewC.push_back(FEltC);
4102       else if (isa<UndefValue>(FEltC))
4103         NewC.push_back(TEltC);
4104       else
4105         break;
4106     }
4107     if (NewC.size() == NumElts)
4108       return ConstantVector::get(NewC);
4109   }
4110 
4111   if (Value *V =
4112           simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
4113     return V;
4114 
4115   if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q))
4116     return V;
4117 
4118   if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
4119     return V;
4120 
4121   Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
4122   if (Imp)
4123     return *Imp ? TrueVal : FalseVal;
4124 
4125   return nullptr;
4126 }
4127 
4128 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4129                                 const SimplifyQuery &Q) {
4130   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
4131 }
4132 
4133 /// Given operands for an GetElementPtrInst, see if we can fold the result.
4134 /// If not, this returns null.
4135 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
4136                               const SimplifyQuery &Q, unsigned) {
4137   // The type of the GEP pointer operand.
4138   unsigned AS =
4139       cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
4140 
4141   // getelementptr P -> P.
4142   if (Ops.size() == 1)
4143     return Ops[0];
4144 
4145   // Compute the (pointer) type returned by the GEP instruction.
4146   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
4147   Type *GEPTy = PointerType::get(LastType, AS);
4148   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
4149     GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4150   else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
4151     GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4152 
4153   if (isa<UndefValue>(Ops[0]))
4154     return UndefValue::get(GEPTy);
4155 
4156   bool IsScalableVec = isa<ScalableVectorType>(SrcTy);
4157 
4158   if (Ops.size() == 2) {
4159     // getelementptr P, 0 -> P.
4160     if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy)
4161       return Ops[0];
4162 
4163     Type *Ty = SrcTy;
4164     if (!IsScalableVec && Ty->isSized()) {
4165       Value *P;
4166       uint64_t C;
4167       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
4168       // getelementptr P, N -> P if P points to a type of zero size.
4169       if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy)
4170         return Ops[0];
4171 
4172       // The following transforms are only safe if the ptrtoint cast
4173       // doesn't truncate the pointers.
4174       if (Ops[1]->getType()->getScalarSizeInBits() ==
4175           Q.DL.getPointerSizeInBits(AS)) {
4176         auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
4177           if (match(P, m_Zero()))
4178             return Constant::getNullValue(GEPTy);
4179           Value *Temp;
4180           if (match(P, m_PtrToInt(m_Value(Temp))))
4181             if (Temp->getType() == GEPTy)
4182               return Temp;
4183           return nullptr;
4184         };
4185 
4186         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
4187         if (TyAllocSize == 1 &&
4188             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
4189           if (Value *R = PtrToIntOrZero(P))
4190             return R;
4191 
4192         // getelementptr V, (ashr (sub P, V), C) -> Q
4193         // if P points to a type of size 1 << C.
4194         if (match(Ops[1],
4195                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
4196                          m_ConstantInt(C))) &&
4197             TyAllocSize == 1ULL << C)
4198           if (Value *R = PtrToIntOrZero(P))
4199             return R;
4200 
4201         // getelementptr V, (sdiv (sub P, V), C) -> Q
4202         // if P points to a type of size C.
4203         if (match(Ops[1],
4204                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
4205                          m_SpecificInt(TyAllocSize))))
4206           if (Value *R = PtrToIntOrZero(P))
4207             return R;
4208       }
4209     }
4210   }
4211 
4212   if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 &&
4213       all_of(Ops.slice(1).drop_back(1),
4214              [](Value *Idx) { return match(Idx, m_Zero()); })) {
4215     unsigned IdxWidth =
4216         Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
4217     if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) {
4218       APInt BasePtrOffset(IdxWidth, 0);
4219       Value *StrippedBasePtr =
4220           Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
4221                                                             BasePtrOffset);
4222 
4223       // gep (gep V, C), (sub 0, V) -> C
4224       if (match(Ops.back(),
4225                 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
4226         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
4227         return ConstantExpr::getIntToPtr(CI, GEPTy);
4228       }
4229       // gep (gep V, C), (xor V, -1) -> C-1
4230       if (match(Ops.back(),
4231                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
4232         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
4233         return ConstantExpr::getIntToPtr(CI, GEPTy);
4234       }
4235     }
4236   }
4237 
4238   // Check to see if this is constant foldable.
4239   if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); }))
4240     return nullptr;
4241 
4242   auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
4243                                             Ops.slice(1));
4244   return ConstantFoldConstant(CE, Q.DL);
4245 }
4246 
4247 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
4248                              const SimplifyQuery &Q) {
4249   return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
4250 }
4251 
4252 /// Given operands for an InsertValueInst, see if we can fold the result.
4253 /// If not, this returns null.
4254 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
4255                                       ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
4256                                       unsigned) {
4257   if (Constant *CAgg = dyn_cast<Constant>(Agg))
4258     if (Constant *CVal = dyn_cast<Constant>(Val))
4259       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
4260 
4261   // insertvalue x, undef, n -> x
4262   if (match(Val, m_Undef()))
4263     return Agg;
4264 
4265   // insertvalue x, (extractvalue y, n), n
4266   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
4267     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
4268         EV->getIndices() == Idxs) {
4269       // insertvalue undef, (extractvalue y, n), n -> y
4270       if (match(Agg, m_Undef()))
4271         return EV->getAggregateOperand();
4272 
4273       // insertvalue y, (extractvalue y, n), n -> y
4274       if (Agg == EV->getAggregateOperand())
4275         return Agg;
4276     }
4277 
4278   return nullptr;
4279 }
4280 
4281 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
4282                                      ArrayRef<unsigned> Idxs,
4283                                      const SimplifyQuery &Q) {
4284   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
4285 }
4286 
4287 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
4288                                        const SimplifyQuery &Q) {
4289   // Try to constant fold.
4290   auto *VecC = dyn_cast<Constant>(Vec);
4291   auto *ValC = dyn_cast<Constant>(Val);
4292   auto *IdxC = dyn_cast<Constant>(Idx);
4293   if (VecC && ValC && IdxC)
4294     return ConstantFoldInsertElementInstruction(VecC, ValC, IdxC);
4295 
4296   // For fixed-length vector, fold into undef if index is out of bounds.
4297   if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
4298     if (isa<FixedVectorType>(Vec->getType()) &&
4299         CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements()))
4300       return UndefValue::get(Vec->getType());
4301   }
4302 
4303   // If index is undef, it might be out of bounds (see above case)
4304   if (isa<UndefValue>(Idx))
4305     return UndefValue::get(Vec->getType());
4306 
4307   // If the scalar is undef, and there is no risk of propagating poison from the
4308   // vector value, simplify to the vector value.
4309   if (isa<UndefValue>(Val) && isGuaranteedNotToBeUndefOrPoison(Vec))
4310     return Vec;
4311 
4312   // If we are extracting a value from a vector, then inserting it into the same
4313   // place, that's the input vector:
4314   // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
4315   if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx))))
4316     return Vec;
4317 
4318   return nullptr;
4319 }
4320 
4321 /// Given operands for an ExtractValueInst, see if we can fold the result.
4322 /// If not, this returns null.
4323 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4324                                        const SimplifyQuery &, unsigned) {
4325   if (auto *CAgg = dyn_cast<Constant>(Agg))
4326     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
4327 
4328   // extractvalue x, (insertvalue y, elt, n), n -> elt
4329   unsigned NumIdxs = Idxs.size();
4330   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
4331        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
4332     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
4333     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
4334     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
4335     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
4336         Idxs.slice(0, NumCommonIdxs)) {
4337       if (NumIdxs == NumInsertValueIdxs)
4338         return IVI->getInsertedValueOperand();
4339       break;
4340     }
4341   }
4342 
4343   return nullptr;
4344 }
4345 
4346 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4347                                       const SimplifyQuery &Q) {
4348   return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
4349 }
4350 
4351 /// Given operands for an ExtractElementInst, see if we can fold the result.
4352 /// If not, this returns null.
4353 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &,
4354                                          unsigned) {
4355   auto *VecVTy = cast<VectorType>(Vec->getType());
4356   if (auto *CVec = dyn_cast<Constant>(Vec)) {
4357     if (auto *CIdx = dyn_cast<Constant>(Idx))
4358       return ConstantFoldExtractElementInstruction(CVec, CIdx);
4359 
4360     // The index is not relevant if our vector is a splat.
4361     if (auto *Splat = CVec->getSplatValue())
4362       return Splat;
4363 
4364     if (isa<UndefValue>(Vec))
4365       return UndefValue::get(VecVTy->getElementType());
4366   }
4367 
4368   // If extracting a specified index from the vector, see if we can recursively
4369   // find a previously computed scalar that was inserted into the vector.
4370   if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4371     // For fixed-length vector, fold into undef if index is out of bounds.
4372     if (isa<FixedVectorType>(VecVTy) &&
4373         IdxC->getValue().uge(cast<FixedVectorType>(VecVTy)->getNumElements()))
4374       return UndefValue::get(VecVTy->getElementType());
4375     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4376       return Elt;
4377   }
4378 
4379   // An undef extract index can be arbitrarily chosen to be an out-of-range
4380   // index value, which would result in the instruction being undef.
4381   if (isa<UndefValue>(Idx))
4382     return UndefValue::get(VecVTy->getElementType());
4383 
4384   return nullptr;
4385 }
4386 
4387 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
4388                                         const SimplifyQuery &Q) {
4389   return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4390 }
4391 
4392 /// See if we can fold the given phi. If not, returns null.
4393 static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
4394   // If all of the PHI's incoming values are the same then replace the PHI node
4395   // with the common value.
4396   Value *CommonValue = nullptr;
4397   bool HasUndefInput = false;
4398   for (Value *Incoming : PN->incoming_values()) {
4399     // If the incoming value is the phi node itself, it can safely be skipped.
4400     if (Incoming == PN) continue;
4401     if (isa<UndefValue>(Incoming)) {
4402       // Remember that we saw an undef value, but otherwise ignore them.
4403       HasUndefInput = true;
4404       continue;
4405     }
4406     if (CommonValue && Incoming != CommonValue)
4407       return nullptr;  // Not the same, bail out.
4408     CommonValue = Incoming;
4409   }
4410 
4411   // If CommonValue is null then all of the incoming values were either undef or
4412   // equal to the phi node itself.
4413   if (!CommonValue)
4414     return UndefValue::get(PN->getType());
4415 
4416   // If we have a PHI node like phi(X, undef, X), where X is defined by some
4417   // instruction, we cannot return X as the result of the PHI node unless it
4418   // dominates the PHI block.
4419   if (HasUndefInput)
4420     return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
4421 
4422   return CommonValue;
4423 }
4424 
4425 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4426                                Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
4427   if (auto *C = dyn_cast<Constant>(Op))
4428     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
4429 
4430   if (auto *CI = dyn_cast<CastInst>(Op)) {
4431     auto *Src = CI->getOperand(0);
4432     Type *SrcTy = Src->getType();
4433     Type *MidTy = CI->getType();
4434     Type *DstTy = Ty;
4435     if (Src->getType() == Ty) {
4436       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4437       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4438       Type *SrcIntPtrTy =
4439           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4440       Type *MidIntPtrTy =
4441           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4442       Type *DstIntPtrTy =
4443           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4444       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4445                                          SrcIntPtrTy, MidIntPtrTy,
4446                                          DstIntPtrTy) == Instruction::BitCast)
4447         return Src;
4448     }
4449   }
4450 
4451   // bitcast x -> x
4452   if (CastOpc == Instruction::BitCast)
4453     if (Op->getType() == Ty)
4454       return Op;
4455 
4456   return nullptr;
4457 }
4458 
4459 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4460                               const SimplifyQuery &Q) {
4461   return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4462 }
4463 
4464 /// For the given destination element of a shuffle, peek through shuffles to
4465 /// match a root vector source operand that contains that element in the same
4466 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4467 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4468                                    int MaskVal, Value *RootVec,
4469                                    unsigned MaxRecurse) {
4470   if (!MaxRecurse--)
4471     return nullptr;
4472 
4473   // Bail out if any mask value is undefined. That kind of shuffle may be
4474   // simplified further based on demanded bits or other folds.
4475   if (MaskVal == -1)
4476     return nullptr;
4477 
4478   // The mask value chooses which source operand we need to look at next.
4479   int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
4480   int RootElt = MaskVal;
4481   Value *SourceOp = Op0;
4482   if (MaskVal >= InVecNumElts) {
4483     RootElt = MaskVal - InVecNumElts;
4484     SourceOp = Op1;
4485   }
4486 
4487   // If the source operand is a shuffle itself, look through it to find the
4488   // matching root vector.
4489   if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4490     return foldIdentityShuffles(
4491         DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4492         SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
4493   }
4494 
4495   // TODO: Look through bitcasts? What if the bitcast changes the vector element
4496   // size?
4497 
4498   // The source operand is not a shuffle. Initialize the root vector value for
4499   // this shuffle if that has not been done yet.
4500   if (!RootVec)
4501     RootVec = SourceOp;
4502 
4503   // Give up as soon as a source operand does not match the existing root value.
4504   if (RootVec != SourceOp)
4505     return nullptr;
4506 
4507   // The element must be coming from the same lane in the source vector
4508   // (although it may have crossed lanes in intermediate shuffles).
4509   if (RootElt != DestElt)
4510     return nullptr;
4511 
4512   return RootVec;
4513 }
4514 
4515 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1,
4516                                         ArrayRef<int> Mask, Type *RetTy,
4517                                         const SimplifyQuery &Q,
4518                                         unsigned MaxRecurse) {
4519   if (all_of(Mask, [](int Elem) { return Elem == UndefMaskElem; }))
4520     return UndefValue::get(RetTy);
4521 
4522   auto *InVecTy = cast<VectorType>(Op0->getType());
4523   unsigned MaskNumElts = Mask.size();
4524   ElementCount InVecEltCount = InVecTy->getElementCount();
4525 
4526   bool Scalable = InVecEltCount.Scalable;
4527 
4528   SmallVector<int, 32> Indices;
4529   Indices.assign(Mask.begin(), Mask.end());
4530 
4531   // Canonicalization: If mask does not select elements from an input vector,
4532   // replace that input vector with undef.
4533   if (!Scalable) {
4534     bool MaskSelects0 = false, MaskSelects1 = false;
4535     unsigned InVecNumElts = InVecEltCount.Min;
4536     for (unsigned i = 0; i != MaskNumElts; ++i) {
4537       if (Indices[i] == -1)
4538         continue;
4539       if ((unsigned)Indices[i] < InVecNumElts)
4540         MaskSelects0 = true;
4541       else
4542         MaskSelects1 = true;
4543     }
4544     if (!MaskSelects0)
4545       Op0 = UndefValue::get(InVecTy);
4546     if (!MaskSelects1)
4547       Op1 = UndefValue::get(InVecTy);
4548   }
4549 
4550   auto *Op0Const = dyn_cast<Constant>(Op0);
4551   auto *Op1Const = dyn_cast<Constant>(Op1);
4552 
4553   // If all operands are constant, constant fold the shuffle. This
4554   // transformation depends on the value of the mask which is not known at
4555   // compile time for scalable vectors
4556   if (!Scalable && Op0Const && Op1Const)
4557     return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
4558 
4559   // Canonicalization: if only one input vector is constant, it shall be the
4560   // second one. This transformation depends on the value of the mask which
4561   // is not known at compile time for scalable vectors
4562   if (!Scalable && Op0Const && !Op1Const) {
4563     std::swap(Op0, Op1);
4564     ShuffleVectorInst::commuteShuffleMask(Indices, InVecEltCount.Min);
4565   }
4566 
4567   // A splat of an inserted scalar constant becomes a vector constant:
4568   // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...>
4569   // NOTE: We may have commuted above, so analyze the updated Indices, not the
4570   //       original mask constant.
4571   // NOTE: This transformation depends on the value of the mask which is not
4572   // known at compile time for scalable vectors
4573   Constant *C;
4574   ConstantInt *IndexC;
4575   if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C),
4576                                           m_ConstantInt(IndexC)))) {
4577     // Match a splat shuffle mask of the insert index allowing undef elements.
4578     int InsertIndex = IndexC->getZExtValue();
4579     if (all_of(Indices, [InsertIndex](int MaskElt) {
4580           return MaskElt == InsertIndex || MaskElt == -1;
4581         })) {
4582       assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
4583 
4584       // Shuffle mask undefs become undefined constant result elements.
4585       SmallVector<Constant *, 16> VecC(MaskNumElts, C);
4586       for (unsigned i = 0; i != MaskNumElts; ++i)
4587         if (Indices[i] == -1)
4588           VecC[i] = UndefValue::get(C->getType());
4589       return ConstantVector::get(VecC);
4590     }
4591   }
4592 
4593   // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4594   // value type is same as the input vectors' type.
4595   if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
4596     if (isa<UndefValue>(Op1) && RetTy == InVecTy &&
4597         is_splat(OpShuf->getShuffleMask()))
4598       return Op0;
4599 
4600   // All remaining transformation depend on the value of the mask, which is
4601   // not known at compile time for scalable vectors.
4602   if (Scalable)
4603     return nullptr;
4604 
4605   // Don't fold a shuffle with undef mask elements. This may get folded in a
4606   // better way using demanded bits or other analysis.
4607   // TODO: Should we allow this?
4608   if (find(Indices, -1) != Indices.end())
4609     return nullptr;
4610 
4611   // Check if every element of this shuffle can be mapped back to the
4612   // corresponding element of a single root vector. If so, we don't need this
4613   // shuffle. This handles simple identity shuffles as well as chains of
4614   // shuffles that may widen/narrow and/or move elements across lanes and back.
4615   Value *RootVec = nullptr;
4616   for (unsigned i = 0; i != MaskNumElts; ++i) {
4617     // Note that recursion is limited for each vector element, so if any element
4618     // exceeds the limit, this will fail to simplify.
4619     RootVec =
4620         foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
4621 
4622     // We can't replace a widening/narrowing shuffle with one of its operands.
4623     if (!RootVec || RootVec->getType() != RetTy)
4624       return nullptr;
4625   }
4626   return RootVec;
4627 }
4628 
4629 /// Given operands for a ShuffleVectorInst, fold the result or return null.
4630 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1,
4631                                        ArrayRef<int> Mask, Type *RetTy,
4632                                        const SimplifyQuery &Q) {
4633   return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
4634 }
4635 
4636 static Constant *foldConstant(Instruction::UnaryOps Opcode,
4637                               Value *&Op, const SimplifyQuery &Q) {
4638   if (auto *C = dyn_cast<Constant>(Op))
4639     return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
4640   return nullptr;
4641 }
4642 
4643 /// Given the operand for an FNeg, see if we can fold the result.  If not, this
4644 /// returns null.
4645 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
4646                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4647   if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
4648     return C;
4649 
4650   Value *X;
4651   // fneg (fneg X) ==> X
4652   if (match(Op, m_FNeg(m_Value(X))))
4653     return X;
4654 
4655   return nullptr;
4656 }
4657 
4658 Value *llvm::SimplifyFNegInst(Value *Op, FastMathFlags FMF,
4659                               const SimplifyQuery &Q) {
4660   return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
4661 }
4662 
4663 static Constant *propagateNaN(Constant *In) {
4664   // If the input is a vector with undef elements, just return a default NaN.
4665   if (!In->isNaN())
4666     return ConstantFP::getNaN(In->getType());
4667 
4668   // Propagate the existing NaN constant when possible.
4669   // TODO: Should we quiet a signaling NaN?
4670   return In;
4671 }
4672 
4673 /// Perform folds that are common to any floating-point operation. This implies
4674 /// transforms based on undef/NaN because the operation itself makes no
4675 /// difference to the result.
4676 static Constant *simplifyFPOp(ArrayRef<Value *> Ops,
4677                               FastMathFlags FMF = FastMathFlags()) {
4678   for (Value *V : Ops) {
4679     bool IsNan = match(V, m_NaN());
4680     bool IsInf = match(V, m_Inf());
4681     bool IsUndef = match(V, m_Undef());
4682 
4683     // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
4684     // (an undef operand can be chosen to be Nan/Inf), then the result of
4685     // this operation is poison. That result can be relaxed to undef.
4686     if (FMF.noNaNs() && (IsNan || IsUndef))
4687       return UndefValue::get(V->getType());
4688     if (FMF.noInfs() && (IsInf || IsUndef))
4689       return UndefValue::get(V->getType());
4690 
4691     if (IsUndef || IsNan)
4692       return propagateNaN(cast<Constant>(V));
4693   }
4694   return nullptr;
4695 }
4696 
4697 /// Given operands for an FAdd, see if we can fold the result.  If not, this
4698 /// returns null.
4699 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4700                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4701   if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
4702     return C;
4703 
4704   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF))
4705     return C;
4706 
4707   // fadd X, -0 ==> X
4708   if (match(Op1, m_NegZeroFP()))
4709     return Op0;
4710 
4711   // fadd X, 0 ==> X, when we know X is not -0
4712   if (match(Op1, m_PosZeroFP()) &&
4713       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4714     return Op0;
4715 
4716   // With nnan: -X + X --> 0.0 (and commuted variant)
4717   // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
4718   // Negative zeros are allowed because we always end up with positive zero:
4719   // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4720   // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4721   // X =  0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
4722   // X =  0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
4723   if (FMF.noNaNs()) {
4724     if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
4725         match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
4726       return ConstantFP::getNullValue(Op0->getType());
4727 
4728     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
4729         match(Op1, m_FNeg(m_Specific(Op0))))
4730       return ConstantFP::getNullValue(Op0->getType());
4731   }
4732 
4733   // (X - Y) + Y --> X
4734   // Y + (X - Y) --> X
4735   Value *X;
4736   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4737       (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
4738        match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
4739     return X;
4740 
4741   return nullptr;
4742 }
4743 
4744 /// Given operands for an FSub, see if we can fold the result.  If not, this
4745 /// returns null.
4746 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4747                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4748   if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
4749     return C;
4750 
4751   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF))
4752     return C;
4753 
4754   // fsub X, +0 ==> X
4755   if (match(Op1, m_PosZeroFP()))
4756     return Op0;
4757 
4758   // fsub X, -0 ==> X, when we know X is not -0
4759   if (match(Op1, m_NegZeroFP()) &&
4760       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4761     return Op0;
4762 
4763   // fsub -0.0, (fsub -0.0, X) ==> X
4764   // fsub -0.0, (fneg X) ==> X
4765   Value *X;
4766   if (match(Op0, m_NegZeroFP()) &&
4767       match(Op1, m_FNeg(m_Value(X))))
4768     return X;
4769 
4770   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
4771   // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
4772   if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
4773       (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
4774        match(Op1, m_FNeg(m_Value(X)))))
4775     return X;
4776 
4777   // fsub nnan x, x ==> 0.0
4778   if (FMF.noNaNs() && Op0 == Op1)
4779     return Constant::getNullValue(Op0->getType());
4780 
4781   // Y - (Y - X) --> X
4782   // (X + Y) - Y --> X
4783   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4784       (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
4785        match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
4786     return X;
4787 
4788   return nullptr;
4789 }
4790 
4791 static Value *SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
4792                               const SimplifyQuery &Q, unsigned MaxRecurse) {
4793   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF))
4794     return C;
4795 
4796   // fmul X, 1.0 ==> X
4797   if (match(Op1, m_FPOne()))
4798     return Op0;
4799 
4800   // fmul 1.0, X ==> X
4801   if (match(Op0, m_FPOne()))
4802     return Op1;
4803 
4804   // fmul nnan nsz X, 0 ==> 0
4805   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
4806     return ConstantFP::getNullValue(Op0->getType());
4807 
4808   // fmul nnan nsz 0, X ==> 0
4809   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
4810     return ConstantFP::getNullValue(Op1->getType());
4811 
4812   // sqrt(X) * sqrt(X) --> X, if we can:
4813   // 1. Remove the intermediate rounding (reassociate).
4814   // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
4815   // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
4816   Value *X;
4817   if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
4818       FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
4819     return X;
4820 
4821   return nullptr;
4822 }
4823 
4824 /// Given the operands for an FMul, see if we can fold the result
4825 static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4826                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4827   if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
4828     return C;
4829 
4830   // Now apply simplifications that do not require rounding.
4831   return SimplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse);
4832 }
4833 
4834 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4835                               const SimplifyQuery &Q) {
4836   return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
4837 }
4838 
4839 
4840 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4841                               const SimplifyQuery &Q) {
4842   return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
4843 }
4844 
4845 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4846                               const SimplifyQuery &Q) {
4847   return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
4848 }
4849 
4850 Value *llvm::SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
4851                              const SimplifyQuery &Q) {
4852   return ::SimplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit);
4853 }
4854 
4855 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4856                                const SimplifyQuery &Q, unsigned) {
4857   if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
4858     return C;
4859 
4860   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF))
4861     return C;
4862 
4863   // X / 1.0 -> X
4864   if (match(Op1, m_FPOne()))
4865     return Op0;
4866 
4867   // 0 / X -> 0
4868   // Requires that NaNs are off (X could be zero) and signed zeroes are
4869   // ignored (X could be positive or negative, so the output sign is unknown).
4870   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
4871     return ConstantFP::getNullValue(Op0->getType());
4872 
4873   if (FMF.noNaNs()) {
4874     // X / X -> 1.0 is legal when NaNs are ignored.
4875     // We can ignore infinities because INF/INF is NaN.
4876     if (Op0 == Op1)
4877       return ConstantFP::get(Op0->getType(), 1.0);
4878 
4879     // (X * Y) / Y --> X if we can reassociate to the above form.
4880     Value *X;
4881     if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
4882       return X;
4883 
4884     // -X /  X -> -1.0 and
4885     //  X / -X -> -1.0 are legal when NaNs are ignored.
4886     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
4887     if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
4888         match(Op1, m_FNegNSZ(m_Specific(Op0))))
4889       return ConstantFP::get(Op0->getType(), -1.0);
4890   }
4891 
4892   return nullptr;
4893 }
4894 
4895 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4896                               const SimplifyQuery &Q) {
4897   return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
4898 }
4899 
4900 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4901                                const SimplifyQuery &Q, unsigned) {
4902   if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
4903     return C;
4904 
4905   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF))
4906     return C;
4907 
4908   // Unlike fdiv, the result of frem always matches the sign of the dividend.
4909   // The constant match may include undef elements in a vector, so return a full
4910   // zero constant as the result.
4911   if (FMF.noNaNs()) {
4912     // +0 % X -> 0
4913     if (match(Op0, m_PosZeroFP()))
4914       return ConstantFP::getNullValue(Op0->getType());
4915     // -0 % X -> -0
4916     if (match(Op0, m_NegZeroFP()))
4917       return ConstantFP::getNegativeZero(Op0->getType());
4918   }
4919 
4920   return nullptr;
4921 }
4922 
4923 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4924                               const SimplifyQuery &Q) {
4925   return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
4926 }
4927 
4928 //=== Helper functions for higher up the class hierarchy.
4929 
4930 /// Given the operand for a UnaryOperator, see if we can fold the result.
4931 /// If not, this returns null.
4932 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
4933                            unsigned MaxRecurse) {
4934   switch (Opcode) {
4935   case Instruction::FNeg:
4936     return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
4937   default:
4938     llvm_unreachable("Unexpected opcode");
4939   }
4940 }
4941 
4942 /// Given the operand for a UnaryOperator, see if we can fold the result.
4943 /// If not, this returns null.
4944 /// Try to use FastMathFlags when folding the result.
4945 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
4946                              const FastMathFlags &FMF,
4947                              const SimplifyQuery &Q, unsigned MaxRecurse) {
4948   switch (Opcode) {
4949   case Instruction::FNeg:
4950     return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
4951   default:
4952     return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
4953   }
4954 }
4955 
4956 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
4957   return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
4958 }
4959 
4960 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
4961                           const SimplifyQuery &Q) {
4962   return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
4963 }
4964 
4965 /// Given operands for a BinaryOperator, see if we can fold the result.
4966 /// If not, this returns null.
4967 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4968                             const SimplifyQuery &Q, unsigned MaxRecurse) {
4969   switch (Opcode) {
4970   case Instruction::Add:
4971     return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
4972   case Instruction::Sub:
4973     return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
4974   case Instruction::Mul:
4975     return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
4976   case Instruction::SDiv:
4977     return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4978   case Instruction::UDiv:
4979     return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
4980   case Instruction::SRem:
4981     return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4982   case Instruction::URem:
4983     return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
4984   case Instruction::Shl:
4985     return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
4986   case Instruction::LShr:
4987     return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
4988   case Instruction::AShr:
4989     return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4990   case Instruction::And:
4991     return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4992   case Instruction::Or:
4993     return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4994   case Instruction::Xor:
4995     return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
4996   case Instruction::FAdd:
4997     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4998   case Instruction::FSub:
4999     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5000   case Instruction::FMul:
5001     return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5002   case Instruction::FDiv:
5003     return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5004   case Instruction::FRem:
5005     return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5006   default:
5007     llvm_unreachable("Unexpected opcode");
5008   }
5009 }
5010 
5011 /// Given operands for a BinaryOperator, see if we can fold the result.
5012 /// If not, this returns null.
5013 /// Try to use FastMathFlags when folding the result.
5014 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5015                             const FastMathFlags &FMF, const SimplifyQuery &Q,
5016                             unsigned MaxRecurse) {
5017   switch (Opcode) {
5018   case Instruction::FAdd:
5019     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
5020   case Instruction::FSub:
5021     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
5022   case Instruction::FMul:
5023     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
5024   case Instruction::FDiv:
5025     return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
5026   default:
5027     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
5028   }
5029 }
5030 
5031 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5032                            const SimplifyQuery &Q) {
5033   return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
5034 }
5035 
5036 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5037                            FastMathFlags FMF, const SimplifyQuery &Q) {
5038   return ::SimplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
5039 }
5040 
5041 /// Given operands for a CmpInst, see if we can fold the result.
5042 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5043                               const SimplifyQuery &Q, unsigned MaxRecurse) {
5044   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
5045     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
5046   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5047 }
5048 
5049 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5050                              const SimplifyQuery &Q) {
5051   return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
5052 }
5053 
5054 static bool IsIdempotent(Intrinsic::ID ID) {
5055   switch (ID) {
5056   default: return false;
5057 
5058   // Unary idempotent: f(f(x)) = f(x)
5059   case Intrinsic::fabs:
5060   case Intrinsic::floor:
5061   case Intrinsic::ceil:
5062   case Intrinsic::trunc:
5063   case Intrinsic::rint:
5064   case Intrinsic::nearbyint:
5065   case Intrinsic::round:
5066   case Intrinsic::roundeven:
5067   case Intrinsic::canonicalize:
5068     return true;
5069   }
5070 }
5071 
5072 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
5073                                    const DataLayout &DL) {
5074   GlobalValue *PtrSym;
5075   APInt PtrOffset;
5076   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
5077     return nullptr;
5078 
5079   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
5080   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
5081   Type *Int32PtrTy = Int32Ty->getPointerTo();
5082   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
5083 
5084   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
5085   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
5086     return nullptr;
5087 
5088   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
5089   if (OffsetInt % 4 != 0)
5090     return nullptr;
5091 
5092   Constant *C = ConstantExpr::getGetElementPtr(
5093       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
5094       ConstantInt::get(Int64Ty, OffsetInt / 4));
5095   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
5096   if (!Loaded)
5097     return nullptr;
5098 
5099   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
5100   if (!LoadedCE)
5101     return nullptr;
5102 
5103   if (LoadedCE->getOpcode() == Instruction::Trunc) {
5104     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5105     if (!LoadedCE)
5106       return nullptr;
5107   }
5108 
5109   if (LoadedCE->getOpcode() != Instruction::Sub)
5110     return nullptr;
5111 
5112   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5113   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
5114     return nullptr;
5115   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
5116 
5117   Constant *LoadedRHS = LoadedCE->getOperand(1);
5118   GlobalValue *LoadedRHSSym;
5119   APInt LoadedRHSOffset;
5120   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
5121                                   DL) ||
5122       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
5123     return nullptr;
5124 
5125   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
5126 }
5127 
5128 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
5129                                      const SimplifyQuery &Q) {
5130   // Idempotent functions return the same result when called repeatedly.
5131   Intrinsic::ID IID = F->getIntrinsicID();
5132   if (IsIdempotent(IID))
5133     if (auto *II = dyn_cast<IntrinsicInst>(Op0))
5134       if (II->getIntrinsicID() == IID)
5135         return II;
5136 
5137   Value *X;
5138   switch (IID) {
5139   case Intrinsic::fabs:
5140     if (SignBitMustBeZero(Op0, Q.TLI)) return Op0;
5141     break;
5142   case Intrinsic::bswap:
5143     // bswap(bswap(x)) -> x
5144     if (match(Op0, m_BSwap(m_Value(X)))) return X;
5145     break;
5146   case Intrinsic::bitreverse:
5147     // bitreverse(bitreverse(x)) -> x
5148     if (match(Op0, m_BitReverse(m_Value(X)))) return X;
5149     break;
5150   case Intrinsic::exp:
5151     // exp(log(x)) -> x
5152     if (Q.CxtI->hasAllowReassoc() &&
5153         match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X;
5154     break;
5155   case Intrinsic::exp2:
5156     // exp2(log2(x)) -> x
5157     if (Q.CxtI->hasAllowReassoc() &&
5158         match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X;
5159     break;
5160   case Intrinsic::log:
5161     // log(exp(x)) -> x
5162     if (Q.CxtI->hasAllowReassoc() &&
5163         match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X;
5164     break;
5165   case Intrinsic::log2:
5166     // log2(exp2(x)) -> x
5167     if (Q.CxtI->hasAllowReassoc() &&
5168         (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
5169          match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0),
5170                                                 m_Value(X))))) return X;
5171     break;
5172   case Intrinsic::log10:
5173     // log10(pow(10.0, x)) -> x
5174     if (Q.CxtI->hasAllowReassoc() &&
5175         match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0),
5176                                                m_Value(X)))) return X;
5177     break;
5178   case Intrinsic::floor:
5179   case Intrinsic::trunc:
5180   case Intrinsic::ceil:
5181   case Intrinsic::round:
5182   case Intrinsic::roundeven:
5183   case Intrinsic::nearbyint:
5184   case Intrinsic::rint: {
5185     // floor (sitofp x) -> sitofp x
5186     // floor (uitofp x) -> uitofp x
5187     //
5188     // Converting from int always results in a finite integral number or
5189     // infinity. For either of those inputs, these rounding functions always
5190     // return the same value, so the rounding can be eliminated.
5191     if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
5192       return Op0;
5193     break;
5194   }
5195   default:
5196     break;
5197   }
5198 
5199   return nullptr;
5200 }
5201 
5202 static Intrinsic::ID getMaxMinOpposite(Intrinsic::ID IID) {
5203   switch (IID) {
5204   case Intrinsic::smax: return Intrinsic::smin;
5205   case Intrinsic::smin: return Intrinsic::smax;
5206   case Intrinsic::umax: return Intrinsic::umin;
5207   case Intrinsic::umin: return Intrinsic::umax;
5208   default: llvm_unreachable("Unexpected intrinsic");
5209   }
5210 }
5211 
5212 static APInt getMaxMinLimit(Intrinsic::ID IID, unsigned BitWidth) {
5213   switch (IID) {
5214   case Intrinsic::smax: return APInt::getSignedMaxValue(BitWidth);
5215   case Intrinsic::smin: return APInt::getSignedMinValue(BitWidth);
5216   case Intrinsic::umax: return APInt::getMaxValue(BitWidth);
5217   case Intrinsic::umin: return APInt::getMinValue(BitWidth);
5218   default: llvm_unreachable("Unexpected intrinsic");
5219   }
5220 }
5221 
5222 static bool isMinMax(Intrinsic::ID IID) {
5223   return IID == Intrinsic::smax || IID == Intrinsic::smin ||
5224          IID == Intrinsic::umax || IID == Intrinsic::umin;
5225 }
5226 
5227 /// Given a min/max intrinsic, see if it can be removed based on having an
5228 /// operand that is another min/max intrinsic with shared operand(s). The caller
5229 /// is expected to swap the operand arguments to handle commutation.
5230 static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) {
5231   assert(isMinMax(IID) && "Expected min/max intrinsic");
5232   auto *InnerMM = dyn_cast<IntrinsicInst>(Op0);
5233   if (!InnerMM)
5234     return nullptr;
5235   Intrinsic::ID InnerID = InnerMM->getIntrinsicID();
5236   if (!isMinMax(InnerID))
5237     return nullptr;
5238 
5239   if (Op1 == InnerMM->getOperand(0) || Op1 == InnerMM->getOperand(1)) {
5240     // max (max X, Y), X --> max X, Y
5241     if (InnerID == IID)
5242       return InnerMM;
5243     // max (min X, Y), X --> X
5244     if (InnerID == getMaxMinOpposite(IID))
5245       return Op1;
5246   }
5247   return nullptr;
5248 }
5249 
5250 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
5251                                       const SimplifyQuery &Q) {
5252   Intrinsic::ID IID = F->getIntrinsicID();
5253   Type *ReturnType = F->getReturnType();
5254   unsigned BitWidth = ReturnType->getScalarSizeInBits();
5255   switch (IID) {
5256   case Intrinsic::abs:
5257     // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here.
5258     // It is always ok to pick the earlier abs. We'll just lose nsw if its only
5259     // on the outer abs.
5260     if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value())))
5261       return Op0;
5262     // If the sign bit is clear already, then abs does not do anything.
5263     if (isKnownNonNegative(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
5264       return Op0;
5265     break;
5266 
5267   case Intrinsic::smax:
5268   case Intrinsic::smin:
5269   case Intrinsic::umax:
5270   case Intrinsic::umin: {
5271     // If the arguments are the same, this is a no-op.
5272     if (Op0 == Op1)
5273       return Op0;
5274 
5275     // Canonicalize constant operand as Op1.
5276     if (isa<Constant>(Op0))
5277       std::swap(Op0, Op1);
5278 
5279     // Assume undef is the limit value.
5280     if (isa<UndefValue>(Op1))
5281       return ConstantInt::get(ReturnType, getMaxMinLimit(IID, BitWidth));
5282 
5283     const APInt *C;
5284     if (match(Op1, m_APIntAllowUndef(C))) {
5285       // Clamp to limit value. For example:
5286       // umax(i8 %x, i8 255) --> 255
5287       if (*C == getMaxMinLimit(IID, BitWidth))
5288         return ConstantInt::get(ReturnType, *C);
5289 
5290       // If the constant op is the opposite of the limit value, the other must
5291       // be larger/smaller or equal. For example:
5292       // umin(i8 %x, i8 255) --> %x
5293       if (*C == getMaxMinLimit(getMaxMinOpposite(IID), BitWidth))
5294         return Op0;
5295 
5296       // Remove nested call if constant operands allow it. Example:
5297       // max (max X, 7), 5 -> max X, 7
5298       auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0);
5299       if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
5300         // TODO: loosen undef/splat restrictions for vector constants.
5301         Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1);
5302         const APInt *InnerC;
5303         if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) &&
5304             ((IID == Intrinsic::smax && InnerC->sge(*C)) ||
5305              (IID == Intrinsic::smin && InnerC->sle(*C)) ||
5306              (IID == Intrinsic::umax && InnerC->uge(*C)) ||
5307              (IID == Intrinsic::umin && InnerC->ule(*C))))
5308           return Op0;
5309       }
5310     }
5311 
5312     if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
5313       return V;
5314     if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0))
5315       return V;
5316 
5317     break;
5318   }
5319   case Intrinsic::usub_with_overflow:
5320   case Intrinsic::ssub_with_overflow:
5321     // X - X -> { 0, false }
5322     if (Op0 == Op1)
5323       return Constant::getNullValue(ReturnType);
5324     LLVM_FALLTHROUGH;
5325   case Intrinsic::uadd_with_overflow:
5326   case Intrinsic::sadd_with_overflow:
5327     // X - undef -> { undef, false }
5328     // undef - X -> { undef, false }
5329     // X + undef -> { undef, false }
5330     // undef + x -> { undef, false }
5331     if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1)) {
5332       return ConstantStruct::get(
5333           cast<StructType>(ReturnType),
5334           {UndefValue::get(ReturnType->getStructElementType(0)),
5335            Constant::getNullValue(ReturnType->getStructElementType(1))});
5336     }
5337     break;
5338   case Intrinsic::umul_with_overflow:
5339   case Intrinsic::smul_with_overflow:
5340     // 0 * X -> { 0, false }
5341     // X * 0 -> { 0, false }
5342     if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
5343       return Constant::getNullValue(ReturnType);
5344     // undef * X -> { 0, false }
5345     // X * undef -> { 0, false }
5346     if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
5347       return Constant::getNullValue(ReturnType);
5348     break;
5349   case Intrinsic::uadd_sat:
5350     // sat(MAX + X) -> MAX
5351     // sat(X + MAX) -> MAX
5352     if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
5353       return Constant::getAllOnesValue(ReturnType);
5354     LLVM_FALLTHROUGH;
5355   case Intrinsic::sadd_sat:
5356     // sat(X + undef) -> -1
5357     // sat(undef + X) -> -1
5358     // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
5359     // For signed: Assume undef is ~X, in which case X + ~X = -1.
5360     if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
5361       return Constant::getAllOnesValue(ReturnType);
5362 
5363     // X + 0 -> X
5364     if (match(Op1, m_Zero()))
5365       return Op0;
5366     // 0 + X -> X
5367     if (match(Op0, m_Zero()))
5368       return Op1;
5369     break;
5370   case Intrinsic::usub_sat:
5371     // sat(0 - X) -> 0, sat(X - MAX) -> 0
5372     if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
5373       return Constant::getNullValue(ReturnType);
5374     LLVM_FALLTHROUGH;
5375   case Intrinsic::ssub_sat:
5376     // X - X -> 0, X - undef -> 0, undef - X -> 0
5377     if (Op0 == Op1 || match(Op0, m_Undef()) || match(Op1, m_Undef()))
5378       return Constant::getNullValue(ReturnType);
5379     // X - 0 -> X
5380     if (match(Op1, m_Zero()))
5381       return Op0;
5382     break;
5383   case Intrinsic::load_relative:
5384     if (auto *C0 = dyn_cast<Constant>(Op0))
5385       if (auto *C1 = dyn_cast<Constant>(Op1))
5386         return SimplifyRelativeLoad(C0, C1, Q.DL);
5387     break;
5388   case Intrinsic::powi:
5389     if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
5390       // powi(x, 0) -> 1.0
5391       if (Power->isZero())
5392         return ConstantFP::get(Op0->getType(), 1.0);
5393       // powi(x, 1) -> x
5394       if (Power->isOne())
5395         return Op0;
5396     }
5397     break;
5398   case Intrinsic::copysign:
5399     // copysign X, X --> X
5400     if (Op0 == Op1)
5401       return Op0;
5402     // copysign -X, X --> X
5403     // copysign X, -X --> -X
5404     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
5405         match(Op1, m_FNeg(m_Specific(Op0))))
5406       return Op1;
5407     break;
5408   case Intrinsic::maxnum:
5409   case Intrinsic::minnum:
5410   case Intrinsic::maximum:
5411   case Intrinsic::minimum: {
5412     // If the arguments are the same, this is a no-op.
5413     if (Op0 == Op1) return Op0;
5414 
5415     // If one argument is undef, return the other argument.
5416     if (match(Op0, m_Undef()))
5417       return Op1;
5418     if (match(Op1, m_Undef()))
5419       return Op0;
5420 
5421     // If one argument is NaN, return other or NaN appropriately.
5422     bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
5423     if (match(Op0, m_NaN()))
5424       return PropagateNaN ? Op0 : Op1;
5425     if (match(Op1, m_NaN()))
5426       return PropagateNaN ? Op1 : Op0;
5427 
5428     // Min/max of the same operation with common operand:
5429     // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
5430     if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
5431       if (M0->getIntrinsicID() == IID &&
5432           (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
5433         return Op0;
5434     if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
5435       if (M1->getIntrinsicID() == IID &&
5436           (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
5437         return Op1;
5438 
5439     // min(X, -Inf) --> -Inf (and commuted variant)
5440     // max(X, +Inf) --> +Inf (and commuted variant)
5441     bool UseNegInf = IID == Intrinsic::minnum || IID == Intrinsic::minimum;
5442     const APFloat *C;
5443     if ((match(Op0, m_APFloat(C)) && C->isInfinity() &&
5444          C->isNegative() == UseNegInf) ||
5445         (match(Op1, m_APFloat(C)) && C->isInfinity() &&
5446          C->isNegative() == UseNegInf))
5447       return ConstantFP::getInfinity(ReturnType, UseNegInf);
5448 
5449     // TODO: minnum(nnan x, inf) -> x
5450     // TODO: minnum(nnan ninf x, flt_max) -> x
5451     // TODO: maxnum(nnan x, -inf) -> x
5452     // TODO: maxnum(nnan ninf x, -flt_max) -> x
5453     break;
5454   }
5455   default:
5456     break;
5457   }
5458 
5459   return nullptr;
5460 }
5461 
5462 static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
5463 
5464   // Intrinsics with no operands have some kind of side effect. Don't simplify.
5465   unsigned NumOperands = Call->getNumArgOperands();
5466   if (!NumOperands)
5467     return nullptr;
5468 
5469   Function *F = cast<Function>(Call->getCalledFunction());
5470   Intrinsic::ID IID = F->getIntrinsicID();
5471   if (NumOperands == 1)
5472     return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q);
5473 
5474   if (NumOperands == 2)
5475     return simplifyBinaryIntrinsic(F, Call->getArgOperand(0),
5476                                    Call->getArgOperand(1), Q);
5477 
5478   // Handle intrinsics with 3 or more arguments.
5479   switch (IID) {
5480   case Intrinsic::masked_load:
5481   case Intrinsic::masked_gather: {
5482     Value *MaskArg = Call->getArgOperand(2);
5483     Value *PassthruArg = Call->getArgOperand(3);
5484     // If the mask is all zeros or undef, the "passthru" argument is the result.
5485     if (maskIsAllZeroOrUndef(MaskArg))
5486       return PassthruArg;
5487     return nullptr;
5488   }
5489   case Intrinsic::fshl:
5490   case Intrinsic::fshr: {
5491     Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1),
5492           *ShAmtArg = Call->getArgOperand(2);
5493 
5494     // If both operands are undef, the result is undef.
5495     if (match(Op0, m_Undef()) && match(Op1, m_Undef()))
5496       return UndefValue::get(F->getReturnType());
5497 
5498     // If shift amount is undef, assume it is zero.
5499     if (match(ShAmtArg, m_Undef()))
5500       return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
5501 
5502     const APInt *ShAmtC;
5503     if (match(ShAmtArg, m_APInt(ShAmtC))) {
5504       // If there's effectively no shift, return the 1st arg or 2nd arg.
5505       APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
5506       if (ShAmtC->urem(BitWidth).isNullValue())
5507         return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
5508     }
5509     return nullptr;
5510   }
5511   case Intrinsic::fma:
5512   case Intrinsic::fmuladd: {
5513     Value *Op0 = Call->getArgOperand(0);
5514     Value *Op1 = Call->getArgOperand(1);
5515     Value *Op2 = Call->getArgOperand(2);
5516     if (Value *V = simplifyFPOp({ Op0, Op1, Op2 }))
5517       return V;
5518     return nullptr;
5519   }
5520   default:
5521     return nullptr;
5522   }
5523 }
5524 
5525 static Value *tryConstantFoldCall(CallBase *Call, const SimplifyQuery &Q) {
5526   auto *F = dyn_cast<Function>(Call->getCalledOperand());
5527   if (!F || !canConstantFoldCallTo(Call, F))
5528     return nullptr;
5529 
5530   SmallVector<Constant *, 4> ConstantArgs;
5531   unsigned NumArgs = Call->getNumArgOperands();
5532   ConstantArgs.reserve(NumArgs);
5533   for (auto &Arg : Call->args()) {
5534     Constant *C = dyn_cast<Constant>(&Arg);
5535     if (!C) {
5536       if (isa<MetadataAsValue>(Arg.get()))
5537         continue;
5538       return nullptr;
5539     }
5540     ConstantArgs.push_back(C);
5541   }
5542 
5543   return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
5544 }
5545 
5546 Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) {
5547   // musttail calls can only be simplified if they are also DCEd.
5548   // As we can't guarantee this here, don't simplify them.
5549   if (Call->isMustTailCall())
5550     return nullptr;
5551 
5552   // call undef -> undef
5553   // call null -> undef
5554   Value *Callee = Call->getCalledOperand();
5555   if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
5556     return UndefValue::get(Call->getType());
5557 
5558   if (Value *V = tryConstantFoldCall(Call, Q))
5559     return V;
5560 
5561   auto *F = dyn_cast<Function>(Callee);
5562   if (F && F->isIntrinsic())
5563     if (Value *Ret = simplifyIntrinsic(Call, Q))
5564       return Ret;
5565 
5566   return nullptr;
5567 }
5568 
5569 /// Given operands for a Freeze, see if we can fold the result.
5570 static Value *SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
5571   // Use a utility function defined in ValueTracking.
5572   if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.CxtI, Q.DT))
5573     return Op0;
5574   // We have room for improvement.
5575   return nullptr;
5576 }
5577 
5578 Value *llvm::SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
5579   return ::SimplifyFreezeInst(Op0, Q);
5580 }
5581 
5582 /// See if we can compute a simplified version of this instruction.
5583 /// If not, this returns null.
5584 
5585 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
5586                                  OptimizationRemarkEmitter *ORE) {
5587   const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
5588   Value *Result;
5589 
5590   switch (I->getOpcode()) {
5591   default:
5592     Result = ConstantFoldInstruction(I, Q.DL, Q.TLI);
5593     break;
5594   case Instruction::FNeg:
5595     Result = SimplifyFNegInst(I->getOperand(0), I->getFastMathFlags(), Q);
5596     break;
5597   case Instruction::FAdd:
5598     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
5599                               I->getFastMathFlags(), Q);
5600     break;
5601   case Instruction::Add:
5602     Result =
5603         SimplifyAddInst(I->getOperand(0), I->getOperand(1),
5604                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5605                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5606     break;
5607   case Instruction::FSub:
5608     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
5609                               I->getFastMathFlags(), Q);
5610     break;
5611   case Instruction::Sub:
5612     Result =
5613         SimplifySubInst(I->getOperand(0), I->getOperand(1),
5614                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5615                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5616     break;
5617   case Instruction::FMul:
5618     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
5619                               I->getFastMathFlags(), Q);
5620     break;
5621   case Instruction::Mul:
5622     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q);
5623     break;
5624   case Instruction::SDiv:
5625     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q);
5626     break;
5627   case Instruction::UDiv:
5628     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q);
5629     break;
5630   case Instruction::FDiv:
5631     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
5632                               I->getFastMathFlags(), Q);
5633     break;
5634   case Instruction::SRem:
5635     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q);
5636     break;
5637   case Instruction::URem:
5638     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q);
5639     break;
5640   case Instruction::FRem:
5641     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
5642                               I->getFastMathFlags(), Q);
5643     break;
5644   case Instruction::Shl:
5645     Result =
5646         SimplifyShlInst(I->getOperand(0), I->getOperand(1),
5647                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5648                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5649     break;
5650   case Instruction::LShr:
5651     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
5652                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5653     break;
5654   case Instruction::AShr:
5655     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
5656                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5657     break;
5658   case Instruction::And:
5659     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q);
5660     break;
5661   case Instruction::Or:
5662     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q);
5663     break;
5664   case Instruction::Xor:
5665     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q);
5666     break;
5667   case Instruction::ICmp:
5668     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
5669                               I->getOperand(0), I->getOperand(1), Q);
5670     break;
5671   case Instruction::FCmp:
5672     Result =
5673         SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
5674                          I->getOperand(1), I->getFastMathFlags(), Q);
5675     break;
5676   case Instruction::Select:
5677     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
5678                                 I->getOperand(2), Q);
5679     break;
5680   case Instruction::GetElementPtr: {
5681     SmallVector<Value *, 8> Ops(I->op_begin(), I->op_end());
5682     Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
5683                              Ops, Q);
5684     break;
5685   }
5686   case Instruction::InsertValue: {
5687     InsertValueInst *IV = cast<InsertValueInst>(I);
5688     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
5689                                      IV->getInsertedValueOperand(),
5690                                      IV->getIndices(), Q);
5691     break;
5692   }
5693   case Instruction::InsertElement: {
5694     auto *IE = cast<InsertElementInst>(I);
5695     Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1),
5696                                        IE->getOperand(2), Q);
5697     break;
5698   }
5699   case Instruction::ExtractValue: {
5700     auto *EVI = cast<ExtractValueInst>(I);
5701     Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
5702                                       EVI->getIndices(), Q);
5703     break;
5704   }
5705   case Instruction::ExtractElement: {
5706     auto *EEI = cast<ExtractElementInst>(I);
5707     Result = SimplifyExtractElementInst(EEI->getVectorOperand(),
5708                                         EEI->getIndexOperand(), Q);
5709     break;
5710   }
5711   case Instruction::ShuffleVector: {
5712     auto *SVI = cast<ShuffleVectorInst>(I);
5713     Result =
5714         SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5715                                   SVI->getShuffleMask(), SVI->getType(), Q);
5716     break;
5717   }
5718   case Instruction::PHI:
5719     Result = SimplifyPHINode(cast<PHINode>(I), Q);
5720     break;
5721   case Instruction::Call: {
5722     Result = SimplifyCall(cast<CallInst>(I), Q);
5723     break;
5724   }
5725   case Instruction::Freeze:
5726     Result = SimplifyFreezeInst(I->getOperand(0), Q);
5727     break;
5728 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
5729 #include "llvm/IR/Instruction.def"
5730 #undef HANDLE_CAST_INST
5731     Result =
5732         SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q);
5733     break;
5734   case Instruction::Alloca:
5735     // No simplifications for Alloca and it can't be constant folded.
5736     Result = nullptr;
5737     break;
5738   }
5739 
5740   /// If called on unreachable code, the above logic may report that the
5741   /// instruction simplified to itself.  Make life easier for users by
5742   /// detecting that case here, returning a safe value instead.
5743   return Result == I ? UndefValue::get(I->getType()) : Result;
5744 }
5745 
5746 /// Implementation of recursive simplification through an instruction's
5747 /// uses.
5748 ///
5749 /// This is the common implementation of the recursive simplification routines.
5750 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
5751 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
5752 /// instructions to process and attempt to simplify it using
5753 /// InstructionSimplify. Recursively visited users which could not be
5754 /// simplified themselves are to the optional UnsimplifiedUsers set for
5755 /// further processing by the caller.
5756 ///
5757 /// This routine returns 'true' only when *it* simplifies something. The passed
5758 /// in simplified value does not count toward this.
5759 static bool replaceAndRecursivelySimplifyImpl(
5760     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
5761     const DominatorTree *DT, AssumptionCache *AC,
5762     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
5763   bool Simplified = false;
5764   SmallSetVector<Instruction *, 8> Worklist;
5765   const DataLayout &DL = I->getModule()->getDataLayout();
5766 
5767   // If we have an explicit value to collapse to, do that round of the
5768   // simplification loop by hand initially.
5769   if (SimpleV) {
5770     for (User *U : I->users())
5771       if (U != I)
5772         Worklist.insert(cast<Instruction>(U));
5773 
5774     // Replace the instruction with its simplified value.
5775     I->replaceAllUsesWith(SimpleV);
5776 
5777     // Gracefully handle edge cases where the instruction is not wired into any
5778     // parent block.
5779     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
5780         !I->mayHaveSideEffects())
5781       I->eraseFromParent();
5782   } else {
5783     Worklist.insert(I);
5784   }
5785 
5786   // Note that we must test the size on each iteration, the worklist can grow.
5787   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
5788     I = Worklist[Idx];
5789 
5790     // See if this instruction simplifies.
5791     SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
5792     if (!SimpleV) {
5793       if (UnsimplifiedUsers)
5794         UnsimplifiedUsers->insert(I);
5795       continue;
5796     }
5797 
5798     Simplified = true;
5799 
5800     // Stash away all the uses of the old instruction so we can check them for
5801     // recursive simplifications after a RAUW. This is cheaper than checking all
5802     // uses of To on the recursive step in most cases.
5803     for (User *U : I->users())
5804       Worklist.insert(cast<Instruction>(U));
5805 
5806     // Replace the instruction with its simplified value.
5807     I->replaceAllUsesWith(SimpleV);
5808 
5809     // Gracefully handle edge cases where the instruction is not wired into any
5810     // parent block.
5811     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
5812         !I->mayHaveSideEffects())
5813       I->eraseFromParent();
5814   }
5815   return Simplified;
5816 }
5817 
5818 bool llvm::recursivelySimplifyInstruction(Instruction *I,
5819                                           const TargetLibraryInfo *TLI,
5820                                           const DominatorTree *DT,
5821                                           AssumptionCache *AC) {
5822   return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC, nullptr);
5823 }
5824 
5825 bool llvm::replaceAndRecursivelySimplify(
5826     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
5827     const DominatorTree *DT, AssumptionCache *AC,
5828     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
5829   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
5830   assert(SimpleV && "Must provide a simplified value.");
5831   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
5832                                            UnsimplifiedUsers);
5833 }
5834 
5835 namespace llvm {
5836 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
5837   auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
5838   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
5839   auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5840   auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
5841   auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
5842   auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
5843   return {F.getParent()->getDataLayout(), TLI, DT, AC};
5844 }
5845 
5846 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
5847                                          const DataLayout &DL) {
5848   return {DL, &AR.TLI, &AR.DT, &AR.AC};
5849 }
5850 
5851 template <class T, class... TArgs>
5852 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
5853                                          Function &F) {
5854   auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
5855   auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
5856   auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
5857   return {F.getParent()->getDataLayout(), TLI, DT, AC};
5858 }
5859 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
5860                                                   Function &);
5861 }
5862