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