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