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