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