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