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