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