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 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2477                                        Value *RHS, const InstrInfoQuery &IIQ) {
2478   Type *ITy = GetCompareTy(RHS); // The return type.
2479 
2480   Value *X;
2481   // Sign-bit checks can be optimized to true/false after unsigned
2482   // floating-point casts:
2483   // icmp slt (bitcast (uitofp X)),  0 --> false
2484   // icmp sgt (bitcast (uitofp X)), -1 --> true
2485   if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
2486     if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
2487       return ConstantInt::getFalse(ITy);
2488     if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
2489       return ConstantInt::getTrue(ITy);
2490   }
2491 
2492   const APInt *C;
2493   if (!match(RHS, m_APInt(C)))
2494     return nullptr;
2495 
2496   // Rule out tautological comparisons (eg., ult 0 or uge 0).
2497   ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
2498   if (RHS_CR.isEmptySet())
2499     return ConstantInt::getFalse(ITy);
2500   if (RHS_CR.isFullSet())
2501     return ConstantInt::getTrue(ITy);
2502 
2503   ConstantRange LHS_CR = computeConstantRange(LHS, IIQ.UseInstrInfo);
2504   if (!LHS_CR.isFullSet()) {
2505     if (RHS_CR.contains(LHS_CR))
2506       return ConstantInt::getTrue(ITy);
2507     if (RHS_CR.inverse().contains(LHS_CR))
2508       return ConstantInt::getFalse(ITy);
2509   }
2510 
2511   return nullptr;
2512 }
2513 
2514 /// TODO: A large part of this logic is duplicated in InstCombine's
2515 /// foldICmpBinOp(). We should be able to share that and avoid the code
2516 /// duplication.
2517 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2518                                     Value *RHS, const SimplifyQuery &Q,
2519                                     unsigned MaxRecurse) {
2520   Type *ITy = GetCompareTy(LHS); // The return type.
2521 
2522   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2523   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2524   if (MaxRecurse && (LBO || RBO)) {
2525     // Analyze the case when either LHS or RHS is an add instruction.
2526     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2527     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2528     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2529     if (LBO && LBO->getOpcode() == Instruction::Add) {
2530       A = LBO->getOperand(0);
2531       B = LBO->getOperand(1);
2532       NoLHSWrapProblem =
2533           ICmpInst::isEquality(Pred) ||
2534           (CmpInst::isUnsigned(Pred) &&
2535            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
2536           (CmpInst::isSigned(Pred) &&
2537            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
2538     }
2539     if (RBO && RBO->getOpcode() == Instruction::Add) {
2540       C = RBO->getOperand(0);
2541       D = RBO->getOperand(1);
2542       NoRHSWrapProblem =
2543           ICmpInst::isEquality(Pred) ||
2544           (CmpInst::isUnsigned(Pred) &&
2545            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
2546           (CmpInst::isSigned(Pred) &&
2547            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
2548     }
2549 
2550     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2551     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2552       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2553                                       Constant::getNullValue(RHS->getType()), Q,
2554                                       MaxRecurse - 1))
2555         return V;
2556 
2557     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2558     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2559       if (Value *V =
2560               SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2561                                C == LHS ? D : C, Q, MaxRecurse - 1))
2562         return V;
2563 
2564     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2565     if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2566         NoRHSWrapProblem) {
2567       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2568       Value *Y, *Z;
2569       if (A == C) {
2570         // C + B == C + D  ->  B == D
2571         Y = B;
2572         Z = D;
2573       } else if (A == D) {
2574         // D + B == C + D  ->  B == C
2575         Y = B;
2576         Z = C;
2577       } else if (B == C) {
2578         // A + C == C + D  ->  A == D
2579         Y = A;
2580         Z = D;
2581       } else {
2582         assert(B == D);
2583         // A + D == C + D  ->  A == C
2584         Y = A;
2585         Z = C;
2586       }
2587       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2588         return V;
2589     }
2590   }
2591 
2592   {
2593     Value *Y = nullptr;
2594     // icmp pred (or X, Y), X
2595     if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2596       if (Pred == ICmpInst::ICMP_ULT)
2597         return getFalse(ITy);
2598       if (Pred == ICmpInst::ICMP_UGE)
2599         return getTrue(ITy);
2600 
2601       if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2602         KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2603         KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2604         if (RHSKnown.isNonNegative() && YKnown.isNegative())
2605           return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2606         if (RHSKnown.isNegative() || YKnown.isNonNegative())
2607           return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2608       }
2609     }
2610     // icmp pred X, (or X, Y)
2611     if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2612       if (Pred == ICmpInst::ICMP_ULE)
2613         return getTrue(ITy);
2614       if (Pred == ICmpInst::ICMP_UGT)
2615         return getFalse(ITy);
2616 
2617       if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2618         KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2619         KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2620         if (LHSKnown.isNonNegative() && YKnown.isNegative())
2621           return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2622         if (LHSKnown.isNegative() || YKnown.isNonNegative())
2623           return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2624       }
2625     }
2626   }
2627 
2628   // icmp pred (and X, Y), X
2629   if (LBO && match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
2630     if (Pred == ICmpInst::ICMP_UGT)
2631       return getFalse(ITy);
2632     if (Pred == ICmpInst::ICMP_ULE)
2633       return getTrue(ITy);
2634   }
2635   // icmp pred X, (and X, Y)
2636   if (RBO && match(RBO, m_c_And(m_Value(), m_Specific(LHS)))) {
2637     if (Pred == ICmpInst::ICMP_UGE)
2638       return getTrue(ITy);
2639     if (Pred == ICmpInst::ICMP_ULT)
2640       return getFalse(ITy);
2641   }
2642 
2643   // 0 - (zext X) pred C
2644   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2645     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2646       if (RHSC->getValue().isStrictlyPositive()) {
2647         if (Pred == ICmpInst::ICMP_SLT)
2648           return ConstantInt::getTrue(RHSC->getContext());
2649         if (Pred == ICmpInst::ICMP_SGE)
2650           return ConstantInt::getFalse(RHSC->getContext());
2651         if (Pred == ICmpInst::ICMP_EQ)
2652           return ConstantInt::getFalse(RHSC->getContext());
2653         if (Pred == ICmpInst::ICMP_NE)
2654           return ConstantInt::getTrue(RHSC->getContext());
2655       }
2656       if (RHSC->getValue().isNonNegative()) {
2657         if (Pred == ICmpInst::ICMP_SLE)
2658           return ConstantInt::getTrue(RHSC->getContext());
2659         if (Pred == ICmpInst::ICMP_SGT)
2660           return ConstantInt::getFalse(RHSC->getContext());
2661       }
2662     }
2663   }
2664 
2665   // icmp pred (urem X, Y), Y
2666   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2667     switch (Pred) {
2668     default:
2669       break;
2670     case ICmpInst::ICMP_SGT:
2671     case ICmpInst::ICMP_SGE: {
2672       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2673       if (!Known.isNonNegative())
2674         break;
2675       LLVM_FALLTHROUGH;
2676     }
2677     case ICmpInst::ICMP_EQ:
2678     case ICmpInst::ICMP_UGT:
2679     case ICmpInst::ICMP_UGE:
2680       return getFalse(ITy);
2681     case ICmpInst::ICMP_SLT:
2682     case ICmpInst::ICMP_SLE: {
2683       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2684       if (!Known.isNonNegative())
2685         break;
2686       LLVM_FALLTHROUGH;
2687     }
2688     case ICmpInst::ICMP_NE:
2689     case ICmpInst::ICMP_ULT:
2690     case ICmpInst::ICMP_ULE:
2691       return getTrue(ITy);
2692     }
2693   }
2694 
2695   // icmp pred X, (urem Y, X)
2696   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2697     switch (Pred) {
2698     default:
2699       break;
2700     case ICmpInst::ICMP_SGT:
2701     case ICmpInst::ICMP_SGE: {
2702       KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2703       if (!Known.isNonNegative())
2704         break;
2705       LLVM_FALLTHROUGH;
2706     }
2707     case ICmpInst::ICMP_NE:
2708     case ICmpInst::ICMP_UGT:
2709     case ICmpInst::ICMP_UGE:
2710       return getTrue(ITy);
2711     case ICmpInst::ICMP_SLT:
2712     case ICmpInst::ICMP_SLE: {
2713       KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2714       if (!Known.isNonNegative())
2715         break;
2716       LLVM_FALLTHROUGH;
2717     }
2718     case ICmpInst::ICMP_EQ:
2719     case ICmpInst::ICMP_ULT:
2720     case ICmpInst::ICMP_ULE:
2721       return getFalse(ITy);
2722     }
2723   }
2724 
2725   // x >> y <=u x
2726   // x udiv y <=u x.
2727   if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2728               match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2729     // icmp pred (X op Y), X
2730     if (Pred == ICmpInst::ICMP_UGT)
2731       return getFalse(ITy);
2732     if (Pred == ICmpInst::ICMP_ULE)
2733       return getTrue(ITy);
2734   }
2735 
2736   // x >=u x >> y
2737   // x >=u x udiv y.
2738   if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2739               match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2740     // icmp pred X, (X op Y)
2741     if (Pred == ICmpInst::ICMP_ULT)
2742       return getFalse(ITy);
2743     if (Pred == ICmpInst::ICMP_UGE)
2744       return getTrue(ITy);
2745   }
2746 
2747   // handle:
2748   //   CI2 << X == CI
2749   //   CI2 << X != CI
2750   //
2751   //   where CI2 is a power of 2 and CI isn't
2752   if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2753     const APInt *CI2Val, *CIVal = &CI->getValue();
2754     if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2755         CI2Val->isPowerOf2()) {
2756       if (!CIVal->isPowerOf2()) {
2757         // CI2 << X can equal zero in some circumstances,
2758         // this simplification is unsafe if CI is zero.
2759         //
2760         // We know it is safe if:
2761         // - The shift is nsw, we can't shift out the one bit.
2762         // - The shift is nuw, we can't shift out the one bit.
2763         // - CI2 is one
2764         // - CI isn't zero
2765         if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
2766             Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
2767             CI2Val->isOneValue() || !CI->isZero()) {
2768           if (Pred == ICmpInst::ICMP_EQ)
2769             return ConstantInt::getFalse(RHS->getContext());
2770           if (Pred == ICmpInst::ICMP_NE)
2771             return ConstantInt::getTrue(RHS->getContext());
2772         }
2773       }
2774       if (CIVal->isSignMask() && CI2Val->isOneValue()) {
2775         if (Pred == ICmpInst::ICMP_UGT)
2776           return ConstantInt::getFalse(RHS->getContext());
2777         if (Pred == ICmpInst::ICMP_ULE)
2778           return ConstantInt::getTrue(RHS->getContext());
2779       }
2780     }
2781   }
2782 
2783   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2784       LBO->getOperand(1) == RBO->getOperand(1)) {
2785     switch (LBO->getOpcode()) {
2786     default:
2787       break;
2788     case Instruction::UDiv:
2789     case Instruction::LShr:
2790       if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
2791           !Q.IIQ.isExact(RBO))
2792         break;
2793       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2794                                       RBO->getOperand(0), Q, MaxRecurse - 1))
2795           return V;
2796       break;
2797     case Instruction::SDiv:
2798       if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
2799           !Q.IIQ.isExact(RBO))
2800         break;
2801       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2802                                       RBO->getOperand(0), Q, MaxRecurse - 1))
2803         return V;
2804       break;
2805     case Instruction::AShr:
2806       if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
2807         break;
2808       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2809                                       RBO->getOperand(0), Q, MaxRecurse - 1))
2810         return V;
2811       break;
2812     case Instruction::Shl: {
2813       bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
2814       bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
2815       if (!NUW && !NSW)
2816         break;
2817       if (!NSW && ICmpInst::isSigned(Pred))
2818         break;
2819       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2820                                       RBO->getOperand(0), Q, MaxRecurse - 1))
2821         return V;
2822       break;
2823     }
2824     }
2825   }
2826   return nullptr;
2827 }
2828 
2829 /// Simplify integer comparisons where at least one operand of the compare
2830 /// matches an integer min/max idiom.
2831 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
2832                                      Value *RHS, const SimplifyQuery &Q,
2833                                      unsigned MaxRecurse) {
2834   Type *ITy = GetCompareTy(LHS); // The return type.
2835   Value *A, *B;
2836   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2837   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2838 
2839   // Signed variants on "max(a,b)>=a -> true".
2840   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2841     if (A != RHS)
2842       std::swap(A, B);       // smax(A, B) pred A.
2843     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2844     // We analyze this as smax(A, B) pred A.
2845     P = Pred;
2846   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2847              (A == LHS || B == LHS)) {
2848     if (A != LHS)
2849       std::swap(A, B);       // A pred smax(A, B).
2850     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2851     // We analyze this as smax(A, B) swapped-pred A.
2852     P = CmpInst::getSwappedPredicate(Pred);
2853   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2854              (A == RHS || B == RHS)) {
2855     if (A != RHS)
2856       std::swap(A, B);       // smin(A, B) pred A.
2857     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2858     // We analyze this as smax(-A, -B) swapped-pred -A.
2859     // Note that we do not need to actually form -A or -B thanks to EqP.
2860     P = CmpInst::getSwappedPredicate(Pred);
2861   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2862              (A == LHS || B == LHS)) {
2863     if (A != LHS)
2864       std::swap(A, B);       // A pred smin(A, B).
2865     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2866     // We analyze this as smax(-A, -B) pred -A.
2867     // Note that we do not need to actually form -A or -B thanks to EqP.
2868     P = Pred;
2869   }
2870   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2871     // Cases correspond to "max(A, B) p A".
2872     switch (P) {
2873     default:
2874       break;
2875     case CmpInst::ICMP_EQ:
2876     case CmpInst::ICMP_SLE:
2877       // Equivalent to "A EqP B".  This may be the same as the condition tested
2878       // in the max/min; if so, we can just return that.
2879       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2880         return V;
2881       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2882         return V;
2883       // Otherwise, see if "A EqP B" simplifies.
2884       if (MaxRecurse)
2885         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2886           return V;
2887       break;
2888     case CmpInst::ICMP_NE:
2889     case CmpInst::ICMP_SGT: {
2890       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2891       // Equivalent to "A InvEqP B".  This may be the same as the condition
2892       // tested in the max/min; if so, we can just return that.
2893       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2894         return V;
2895       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2896         return V;
2897       // Otherwise, see if "A InvEqP B" simplifies.
2898       if (MaxRecurse)
2899         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2900           return V;
2901       break;
2902     }
2903     case CmpInst::ICMP_SGE:
2904       // Always true.
2905       return getTrue(ITy);
2906     case CmpInst::ICMP_SLT:
2907       // Always false.
2908       return getFalse(ITy);
2909     }
2910   }
2911 
2912   // Unsigned variants on "max(a,b)>=a -> true".
2913   P = CmpInst::BAD_ICMP_PREDICATE;
2914   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2915     if (A != RHS)
2916       std::swap(A, B);       // umax(A, B) pred A.
2917     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2918     // We analyze this as umax(A, B) pred A.
2919     P = Pred;
2920   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2921              (A == LHS || B == LHS)) {
2922     if (A != LHS)
2923       std::swap(A, B);       // A pred umax(A, B).
2924     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2925     // We analyze this as umax(A, B) swapped-pred A.
2926     P = CmpInst::getSwappedPredicate(Pred);
2927   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2928              (A == RHS || B == RHS)) {
2929     if (A != RHS)
2930       std::swap(A, B);       // umin(A, B) pred A.
2931     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2932     // We analyze this as umax(-A, -B) swapped-pred -A.
2933     // Note that we do not need to actually form -A or -B thanks to EqP.
2934     P = CmpInst::getSwappedPredicate(Pred);
2935   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2936              (A == LHS || B == LHS)) {
2937     if (A != LHS)
2938       std::swap(A, B);       // A pred umin(A, B).
2939     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2940     // We analyze this as umax(-A, -B) pred -A.
2941     // Note that we do not need to actually form -A or -B thanks to EqP.
2942     P = Pred;
2943   }
2944   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2945     // Cases correspond to "max(A, B) p A".
2946     switch (P) {
2947     default:
2948       break;
2949     case CmpInst::ICMP_EQ:
2950     case CmpInst::ICMP_ULE:
2951       // Equivalent to "A EqP B".  This may be the same as the condition tested
2952       // in the max/min; if so, we can just return that.
2953       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2954         return V;
2955       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2956         return V;
2957       // Otherwise, see if "A EqP B" simplifies.
2958       if (MaxRecurse)
2959         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2960           return V;
2961       break;
2962     case CmpInst::ICMP_NE:
2963     case CmpInst::ICMP_UGT: {
2964       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2965       // Equivalent to "A InvEqP B".  This may be the same as the condition
2966       // tested in the max/min; if so, we can just return that.
2967       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2968         return V;
2969       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2970         return V;
2971       // Otherwise, see if "A InvEqP B" simplifies.
2972       if (MaxRecurse)
2973         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2974           return V;
2975       break;
2976     }
2977     case CmpInst::ICMP_UGE:
2978       // Always true.
2979       return getTrue(ITy);
2980     case CmpInst::ICMP_ULT:
2981       // Always false.
2982       return getFalse(ITy);
2983     }
2984   }
2985 
2986   // Variants on "max(x,y) >= min(x,z)".
2987   Value *C, *D;
2988   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2989       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2990       (A == C || A == D || B == C || B == D)) {
2991     // max(x, ?) pred min(x, ?).
2992     if (Pred == CmpInst::ICMP_SGE)
2993       // Always true.
2994       return getTrue(ITy);
2995     if (Pred == CmpInst::ICMP_SLT)
2996       // Always false.
2997       return getFalse(ITy);
2998   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2999              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3000              (A == C || A == D || B == C || B == D)) {
3001     // min(x, ?) pred max(x, ?).
3002     if (Pred == CmpInst::ICMP_SLE)
3003       // Always true.
3004       return getTrue(ITy);
3005     if (Pred == CmpInst::ICMP_SGT)
3006       // Always false.
3007       return getFalse(ITy);
3008   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3009              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3010              (A == C || A == D || B == C || B == D)) {
3011     // max(x, ?) pred min(x, ?).
3012     if (Pred == CmpInst::ICMP_UGE)
3013       // Always true.
3014       return getTrue(ITy);
3015     if (Pred == CmpInst::ICMP_ULT)
3016       // Always false.
3017       return getFalse(ITy);
3018   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3019              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3020              (A == C || A == D || B == C || B == D)) {
3021     // min(x, ?) pred max(x, ?).
3022     if (Pred == CmpInst::ICMP_ULE)
3023       // Always true.
3024       return getTrue(ITy);
3025     if (Pred == CmpInst::ICMP_UGT)
3026       // Always false.
3027       return getFalse(ITy);
3028   }
3029 
3030   return nullptr;
3031 }
3032 
3033 /// Given operands for an ICmpInst, see if we can fold the result.
3034 /// If not, this returns null.
3035 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3036                                const SimplifyQuery &Q, unsigned MaxRecurse) {
3037   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3038   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3039 
3040   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3041     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3042       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3043 
3044     // If we have a constant, make sure it is on the RHS.
3045     std::swap(LHS, RHS);
3046     Pred = CmpInst::getSwappedPredicate(Pred);
3047   }
3048   assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3049 
3050   Type *ITy = GetCompareTy(LHS); // The return type.
3051 
3052   // For EQ and NE, we can always pick a value for the undef to make the
3053   // predicate pass or fail, so we can return undef.
3054   // Matches behavior in llvm::ConstantFoldCompareInstruction.
3055   if (isa<UndefValue>(RHS) && ICmpInst::isEquality(Pred))
3056     return UndefValue::get(ITy);
3057 
3058   // icmp X, X -> true/false
3059   // icmp X, undef -> true/false because undef could be X.
3060   if (LHS == RHS || isa<UndefValue>(RHS))
3061     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3062 
3063   if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3064     return V;
3065 
3066   if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3067     return V;
3068 
3069   if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
3070     return V;
3071 
3072   // If both operands have range metadata, use the metadata
3073   // to simplify the comparison.
3074   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3075     auto RHS_Instr = cast<Instruction>(RHS);
3076     auto LHS_Instr = cast<Instruction>(LHS);
3077 
3078     if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3079         Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
3080       auto RHS_CR = getConstantRangeFromMetadata(
3081           *RHS_Instr->getMetadata(LLVMContext::MD_range));
3082       auto LHS_CR = getConstantRangeFromMetadata(
3083           *LHS_Instr->getMetadata(LLVMContext::MD_range));
3084 
3085       auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3086       if (Satisfied_CR.contains(LHS_CR))
3087         return ConstantInt::getTrue(RHS->getContext());
3088 
3089       auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3090                 CmpInst::getInversePredicate(Pred), RHS_CR);
3091       if (InversedSatisfied_CR.contains(LHS_CR))
3092         return ConstantInt::getFalse(RHS->getContext());
3093     }
3094   }
3095 
3096   // Compare of cast, for example (zext X) != 0 -> X != 0
3097   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3098     Instruction *LI = cast<CastInst>(LHS);
3099     Value *SrcOp = LI->getOperand(0);
3100     Type *SrcTy = SrcOp->getType();
3101     Type *DstTy = LI->getType();
3102 
3103     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3104     // if the integer type is the same size as the pointer type.
3105     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3106         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3107       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3108         // Transfer the cast to the constant.
3109         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3110                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
3111                                         Q, MaxRecurse-1))
3112           return V;
3113       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3114         if (RI->getOperand(0)->getType() == SrcTy)
3115           // Compare without the cast.
3116           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3117                                           Q, MaxRecurse-1))
3118             return V;
3119       }
3120     }
3121 
3122     if (isa<ZExtInst>(LHS)) {
3123       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3124       // same type.
3125       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3126         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3127           // Compare X and Y.  Note that signed predicates become unsigned.
3128           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3129                                           SrcOp, RI->getOperand(0), Q,
3130                                           MaxRecurse-1))
3131             return V;
3132       }
3133       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3134       // too.  If not, then try to deduce the result of the comparison.
3135       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3136         // Compute the constant that would happen if we truncated to SrcTy then
3137         // reextended to DstTy.
3138         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3139         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3140 
3141         // If the re-extended constant didn't change then this is effectively
3142         // also a case of comparing two zero-extended values.
3143         if (RExt == CI && MaxRecurse)
3144           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3145                                         SrcOp, Trunc, Q, MaxRecurse-1))
3146             return V;
3147 
3148         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3149         // there.  Use this to work out the result of the comparison.
3150         if (RExt != CI) {
3151           switch (Pred) {
3152           default: llvm_unreachable("Unknown ICmp predicate!");
3153           // LHS <u RHS.
3154           case ICmpInst::ICMP_EQ:
3155           case ICmpInst::ICMP_UGT:
3156           case ICmpInst::ICMP_UGE:
3157             return ConstantInt::getFalse(CI->getContext());
3158 
3159           case ICmpInst::ICMP_NE:
3160           case ICmpInst::ICMP_ULT:
3161           case ICmpInst::ICMP_ULE:
3162             return ConstantInt::getTrue(CI->getContext());
3163 
3164           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
3165           // is non-negative then LHS <s RHS.
3166           case ICmpInst::ICMP_SGT:
3167           case ICmpInst::ICMP_SGE:
3168             return CI->getValue().isNegative() ?
3169               ConstantInt::getTrue(CI->getContext()) :
3170               ConstantInt::getFalse(CI->getContext());
3171 
3172           case ICmpInst::ICMP_SLT:
3173           case ICmpInst::ICMP_SLE:
3174             return CI->getValue().isNegative() ?
3175               ConstantInt::getFalse(CI->getContext()) :
3176               ConstantInt::getTrue(CI->getContext());
3177           }
3178         }
3179       }
3180     }
3181 
3182     if (isa<SExtInst>(LHS)) {
3183       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3184       // same type.
3185       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3186         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3187           // Compare X and Y.  Note that the predicate does not change.
3188           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3189                                           Q, MaxRecurse-1))
3190             return V;
3191       }
3192       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3193       // too.  If not, then try to deduce the result of the comparison.
3194       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3195         // Compute the constant that would happen if we truncated to SrcTy then
3196         // reextended to DstTy.
3197         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3198         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3199 
3200         // If the re-extended constant didn't change then this is effectively
3201         // also a case of comparing two sign-extended values.
3202         if (RExt == CI && MaxRecurse)
3203           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
3204             return V;
3205 
3206         // Otherwise the upper bits of LHS are all equal, while RHS has varying
3207         // bits there.  Use this to work out the result of the comparison.
3208         if (RExt != CI) {
3209           switch (Pred) {
3210           default: llvm_unreachable("Unknown ICmp predicate!");
3211           case ICmpInst::ICMP_EQ:
3212             return ConstantInt::getFalse(CI->getContext());
3213           case ICmpInst::ICMP_NE:
3214             return ConstantInt::getTrue(CI->getContext());
3215 
3216           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
3217           // LHS >s RHS.
3218           case ICmpInst::ICMP_SGT:
3219           case ICmpInst::ICMP_SGE:
3220             return CI->getValue().isNegative() ?
3221               ConstantInt::getTrue(CI->getContext()) :
3222               ConstantInt::getFalse(CI->getContext());
3223           case ICmpInst::ICMP_SLT:
3224           case ICmpInst::ICMP_SLE:
3225             return CI->getValue().isNegative() ?
3226               ConstantInt::getFalse(CI->getContext()) :
3227               ConstantInt::getTrue(CI->getContext());
3228 
3229           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
3230           // LHS >u RHS.
3231           case ICmpInst::ICMP_UGT:
3232           case ICmpInst::ICMP_UGE:
3233             // Comparison is true iff the LHS <s 0.
3234             if (MaxRecurse)
3235               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3236                                               Constant::getNullValue(SrcTy),
3237                                               Q, MaxRecurse-1))
3238                 return V;
3239             break;
3240           case ICmpInst::ICMP_ULT:
3241           case ICmpInst::ICMP_ULE:
3242             // Comparison is true iff the LHS >=s 0.
3243             if (MaxRecurse)
3244               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3245                                               Constant::getNullValue(SrcTy),
3246                                               Q, MaxRecurse-1))
3247                 return V;
3248             break;
3249           }
3250         }
3251       }
3252     }
3253   }
3254 
3255   // icmp eq|ne X, Y -> false|true if X != Y
3256   if (ICmpInst::isEquality(Pred) &&
3257       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
3258     return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
3259   }
3260 
3261   if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3262     return V;
3263 
3264   if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
3265     return V;
3266 
3267   // Simplify comparisons of related pointers using a powerful, recursive
3268   // GEP-walk when we have target data available..
3269   if (LHS->getType()->isPointerTy())
3270     if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3271                                      Q.IIQ, LHS, RHS))
3272       return C;
3273   if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3274     if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3275       if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3276               Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3277           Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3278               Q.DL.getTypeSizeInBits(CRHS->getType()))
3279         if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3280                                          Q.IIQ, CLHS->getPointerOperand(),
3281                                          CRHS->getPointerOperand()))
3282           return C;
3283 
3284   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3285     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3286       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3287           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3288           (ICmpInst::isEquality(Pred) ||
3289            (GLHS->isInBounds() && GRHS->isInBounds() &&
3290             Pred == ICmpInst::getSignedPredicate(Pred)))) {
3291         // The bases are equal and the indices are constant.  Build a constant
3292         // expression GEP with the same indices and a null base pointer to see
3293         // what constant folding can make out of it.
3294         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3295         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
3296         Constant *NewLHS = ConstantExpr::getGetElementPtr(
3297             GLHS->getSourceElementType(), Null, IndicesLHS);
3298 
3299         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3300         Constant *NewRHS = ConstantExpr::getGetElementPtr(
3301             GLHS->getSourceElementType(), Null, IndicesRHS);
3302         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3303       }
3304     }
3305   }
3306 
3307   // If the comparison is with the result of a select instruction, check whether
3308   // comparing with either branch of the select always yields the same value.
3309   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3310     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3311       return V;
3312 
3313   // If the comparison is with the result of a phi instruction, check whether
3314   // doing the compare with each incoming phi value yields a common result.
3315   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3316     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3317       return V;
3318 
3319   return nullptr;
3320 }
3321 
3322 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3323                               const SimplifyQuery &Q) {
3324   return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3325 }
3326 
3327 /// Given operands for an FCmpInst, see if we can fold the result.
3328 /// If not, this returns null.
3329 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3330                                FastMathFlags FMF, const SimplifyQuery &Q,
3331                                unsigned MaxRecurse) {
3332   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3333   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3334 
3335   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3336     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3337       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3338 
3339     // If we have a constant, make sure it is on the RHS.
3340     std::swap(LHS, RHS);
3341     Pred = CmpInst::getSwappedPredicate(Pred);
3342   }
3343 
3344   // Fold trivial predicates.
3345   Type *RetTy = GetCompareTy(LHS);
3346   if (Pred == FCmpInst::FCMP_FALSE)
3347     return getFalse(RetTy);
3348   if (Pred == FCmpInst::FCMP_TRUE)
3349     return getTrue(RetTy);
3350 
3351   // Fold (un)ordered comparison if we can determine there are no NaNs.
3352   if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3353     if (FMF.noNaNs() ||
3354         (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
3355       return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
3356 
3357   // NaN is unordered; NaN is not ordered.
3358   assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3359          "Comparison must be either ordered or unordered");
3360   if (match(RHS, m_NaN()))
3361     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3362 
3363   // fcmp pred x, undef  and  fcmp pred undef, x
3364   // fold to true if unordered, false if ordered
3365   if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3366     // Choosing NaN for the undef will always make unordered comparison succeed
3367     // and ordered comparison fail.
3368     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3369   }
3370 
3371   // fcmp x,x -> true/false.  Not all compares are foldable.
3372   if (LHS == RHS) {
3373     if (CmpInst::isTrueWhenEqual(Pred))
3374       return getTrue(RetTy);
3375     if (CmpInst::isFalseWhenEqual(Pred))
3376       return getFalse(RetTy);
3377   }
3378 
3379   // Handle fcmp with constant RHS.
3380   // TODO: Use match with a specific FP value, so these work with vectors with
3381   // undef lanes.
3382   const APFloat *C;
3383   if (match(RHS, m_APFloat(C))) {
3384     // Check whether the constant is an infinity.
3385     if (C->isInfinity()) {
3386       if (C->isNegative()) {
3387         switch (Pred) {
3388         case FCmpInst::FCMP_OLT:
3389           // No value is ordered and less than negative infinity.
3390           return getFalse(RetTy);
3391         case FCmpInst::FCMP_UGE:
3392           // All values are unordered with or at least negative infinity.
3393           return getTrue(RetTy);
3394         default:
3395           break;
3396         }
3397       } else {
3398         switch (Pred) {
3399         case FCmpInst::FCMP_OGT:
3400           // No value is ordered and greater than infinity.
3401           return getFalse(RetTy);
3402         case FCmpInst::FCMP_ULE:
3403           // All values are unordered with and at most infinity.
3404           return getTrue(RetTy);
3405         default:
3406           break;
3407         }
3408       }
3409     }
3410     if (C->isNegative() && !C->isNegZero()) {
3411       assert(!C->isNaN() && "Unexpected NaN constant!");
3412       // TODO: We can catch more cases by using a range check rather than
3413       //       relying on CannotBeOrderedLessThanZero.
3414       switch (Pred) {
3415       case FCmpInst::FCMP_UGE:
3416       case FCmpInst::FCMP_UGT:
3417       case FCmpInst::FCMP_UNE:
3418         // (X >= 0) implies (X > C) when (C < 0)
3419         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3420           return getTrue(RetTy);
3421         break;
3422       case FCmpInst::FCMP_OEQ:
3423       case FCmpInst::FCMP_OLE:
3424       case FCmpInst::FCMP_OLT:
3425         // (X >= 0) implies !(X < C) when (C < 0)
3426         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3427           return getFalse(RetTy);
3428         break;
3429       default:
3430         break;
3431       }
3432     }
3433   }
3434   if (match(RHS, m_AnyZeroFP())) {
3435     switch (Pred) {
3436     case FCmpInst::FCMP_OGE:
3437       if (FMF.noNaNs() && CannotBeOrderedLessThanZero(LHS, Q.TLI))
3438         return getTrue(RetTy);
3439       break;
3440     case FCmpInst::FCMP_UGE:
3441       if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3442         return getTrue(RetTy);
3443       break;
3444     case FCmpInst::FCMP_ULT:
3445       if (FMF.noNaNs() && CannotBeOrderedLessThanZero(LHS, Q.TLI))
3446         return getFalse(RetTy);
3447       break;
3448     case FCmpInst::FCMP_OLT:
3449       if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3450         return getFalse(RetTy);
3451       break;
3452     default:
3453       break;
3454     }
3455   }
3456 
3457   // If the comparison is with the result of a select instruction, check whether
3458   // comparing with either branch of the select always yields the same value.
3459   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3460     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3461       return V;
3462 
3463   // If the comparison is with the result of a phi instruction, check whether
3464   // doing the compare with each incoming phi value yields a common result.
3465   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3466     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3467       return V;
3468 
3469   return nullptr;
3470 }
3471 
3472 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3473                               FastMathFlags FMF, const SimplifyQuery &Q) {
3474   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
3475 }
3476 
3477 /// See if V simplifies when its operand Op is replaced with RepOp.
3478 static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3479                                            const SimplifyQuery &Q,
3480                                            unsigned MaxRecurse) {
3481   // Trivial replacement.
3482   if (V == Op)
3483     return RepOp;
3484 
3485   // We cannot replace a constant, and shouldn't even try.
3486   if (isa<Constant>(Op))
3487     return nullptr;
3488 
3489   auto *I = dyn_cast<Instruction>(V);
3490   if (!I)
3491     return nullptr;
3492 
3493   // If this is a binary operator, try to simplify it with the replaced op.
3494   if (auto *B = dyn_cast<BinaryOperator>(I)) {
3495     // Consider:
3496     //   %cmp = icmp eq i32 %x, 2147483647
3497     //   %add = add nsw i32 %x, 1
3498     //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
3499     //
3500     // We can't replace %sel with %add unless we strip away the flags.
3501     if (isa<OverflowingBinaryOperator>(B))
3502       if (Q.IIQ.hasNoSignedWrap(B) || Q.IIQ.hasNoUnsignedWrap(B))
3503         return nullptr;
3504     if (isa<PossiblyExactOperator>(B) && Q.IIQ.isExact(B))
3505       return nullptr;
3506 
3507     if (MaxRecurse) {
3508       if (B->getOperand(0) == Op)
3509         return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3510                              MaxRecurse - 1);
3511       if (B->getOperand(1) == Op)
3512         return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3513                              MaxRecurse - 1);
3514     }
3515   }
3516 
3517   // Same for CmpInsts.
3518   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3519     if (MaxRecurse) {
3520       if (C->getOperand(0) == Op)
3521         return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3522                                MaxRecurse - 1);
3523       if (C->getOperand(1) == Op)
3524         return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3525                                MaxRecurse - 1);
3526     }
3527   }
3528 
3529   // Same for GEPs.
3530   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3531     if (MaxRecurse) {
3532       SmallVector<Value *, 8> NewOps(GEP->getNumOperands());
3533       transform(GEP->operands(), NewOps.begin(),
3534                 [&](Value *V) { return V == Op ? RepOp : V; });
3535       return SimplifyGEPInst(GEP->getSourceElementType(), NewOps, Q,
3536                              MaxRecurse - 1);
3537     }
3538   }
3539 
3540   // TODO: We could hand off more cases to instsimplify here.
3541 
3542   // If all operands are constant after substituting Op for RepOp then we can
3543   // constant fold the instruction.
3544   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3545     // Build a list of all constant operands.
3546     SmallVector<Constant *, 8> ConstOps;
3547     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3548       if (I->getOperand(i) == Op)
3549         ConstOps.push_back(CRepOp);
3550       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3551         ConstOps.push_back(COp);
3552       else
3553         break;
3554     }
3555 
3556     // All operands were constants, fold it.
3557     if (ConstOps.size() == I->getNumOperands()) {
3558       if (CmpInst *C = dyn_cast<CmpInst>(I))
3559         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3560                                                ConstOps[1], Q.DL, Q.TLI);
3561 
3562       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3563         if (!LI->isVolatile())
3564           return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
3565 
3566       return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
3567     }
3568   }
3569 
3570   return nullptr;
3571 }
3572 
3573 /// Try to simplify a select instruction when its condition operand is an
3574 /// integer comparison where one operand of the compare is a constant.
3575 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3576                                     const APInt *Y, bool TrueWhenUnset) {
3577   const APInt *C;
3578 
3579   // (X & Y) == 0 ? X & ~Y : X  --> X
3580   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
3581   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3582       *Y == ~*C)
3583     return TrueWhenUnset ? FalseVal : TrueVal;
3584 
3585   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
3586   // (X & Y) != 0 ? X : X & ~Y  --> X
3587   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3588       *Y == ~*C)
3589     return TrueWhenUnset ? FalseVal : TrueVal;
3590 
3591   if (Y->isPowerOf2()) {
3592     // (X & Y) == 0 ? X | Y : X  --> X | Y
3593     // (X & Y) != 0 ? X | Y : X  --> X
3594     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3595         *Y == *C)
3596       return TrueWhenUnset ? TrueVal : FalseVal;
3597 
3598     // (X & Y) == 0 ? X : X | Y  --> X
3599     // (X & Y) != 0 ? X : X | Y  --> X | Y
3600     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3601         *Y == *C)
3602       return TrueWhenUnset ? TrueVal : FalseVal;
3603   }
3604 
3605   return nullptr;
3606 }
3607 
3608 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
3609 /// eq/ne.
3610 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
3611                                            ICmpInst::Predicate Pred,
3612                                            Value *TrueVal, Value *FalseVal) {
3613   Value *X;
3614   APInt Mask;
3615   if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
3616     return nullptr;
3617 
3618   return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
3619                                Pred == ICmpInst::ICMP_EQ);
3620 }
3621 
3622 /// Try to simplify a select instruction when its condition operand is an
3623 /// integer comparison.
3624 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3625                                          Value *FalseVal, const SimplifyQuery &Q,
3626                                          unsigned MaxRecurse) {
3627   ICmpInst::Predicate Pred;
3628   Value *CmpLHS, *CmpRHS;
3629   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3630     return nullptr;
3631 
3632   if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3633     Value *X;
3634     const APInt *Y;
3635     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3636       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3637                                            Pred == ICmpInst::ICMP_EQ))
3638         return V;
3639 
3640     // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
3641     Value *ShAmt;
3642     auto isFsh = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(),
3643                                                           m_Value(ShAmt)),
3644                              m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X),
3645                                                           m_Value(ShAmt)));
3646     // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
3647     // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
3648     if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt &&
3649         Pred == ICmpInst::ICMP_EQ)
3650       return X;
3651     // (ShAmt != 0) ? X : fshl(X, *, ShAmt) --> X
3652     // (ShAmt != 0) ? X : fshr(*, X, ShAmt) --> X
3653     if (match(FalseVal, isFsh) && TrueVal == X && CmpLHS == ShAmt &&
3654         Pred == ICmpInst::ICMP_NE)
3655       return X;
3656 
3657     // Test for a zero-shift-guard-op around rotates. These are used to
3658     // avoid UB from oversized shifts in raw IR rotate patterns, but the
3659     // intrinsics do not have that problem.
3660     // We do not allow this transform for the general funnel shift case because
3661     // that would not preserve the poison safety of the original code.
3662     auto isRotate = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X),
3663                                                              m_Deferred(X),
3664                                                              m_Value(ShAmt)),
3665                                 m_Intrinsic<Intrinsic::fshr>(m_Value(X),
3666                                                              m_Deferred(X),
3667                                                              m_Value(ShAmt)));
3668     // (ShAmt != 0) ? fshl(X, X, ShAmt) : X --> fshl(X, X, ShAmt)
3669     // (ShAmt != 0) ? fshr(X, X, ShAmt) : X --> fshr(X, X, ShAmt)
3670     if (match(TrueVal, isRotate) && FalseVal == X && CmpLHS == ShAmt &&
3671         Pred == ICmpInst::ICMP_NE)
3672       return TrueVal;
3673     // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
3674     // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
3675     if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
3676         Pred == ICmpInst::ICMP_EQ)
3677       return FalseVal;
3678   }
3679 
3680   // Check for other compares that behave like bit test.
3681   if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
3682                                               TrueVal, FalseVal))
3683     return V;
3684 
3685   // If we have an equality comparison, then we know the value in one of the
3686   // arms of the select. See if substituting this value into the arm and
3687   // simplifying the result yields the same value as the other arm.
3688   if (Pred == ICmpInst::ICMP_EQ) {
3689     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3690             TrueVal ||
3691         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3692             TrueVal)
3693       return FalseVal;
3694     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3695             FalseVal ||
3696         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3697             FalseVal)
3698       return FalseVal;
3699   } else if (Pred == ICmpInst::ICMP_NE) {
3700     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3701             FalseVal ||
3702         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3703             FalseVal)
3704       return TrueVal;
3705     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3706             TrueVal ||
3707         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3708             TrueVal)
3709       return TrueVal;
3710   }
3711 
3712   return nullptr;
3713 }
3714 
3715 /// Try to simplify a select instruction when its condition operand is a
3716 /// floating-point comparison.
3717 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F) {
3718   FCmpInst::Predicate Pred;
3719   if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
3720       !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
3721     return nullptr;
3722 
3723   // TODO: The transform may not be valid with -0.0. An incomplete way of
3724   // testing for that possibility is to check if at least one operand is a
3725   // non-zero constant.
3726   const APFloat *C;
3727   if ((match(T, m_APFloat(C)) && C->isNonZero()) ||
3728       (match(F, m_APFloat(C)) && C->isNonZero())) {
3729     // (T == F) ? T : F --> F
3730     // (F == T) ? T : F --> F
3731     if (Pred == FCmpInst::FCMP_OEQ)
3732       return F;
3733 
3734     // (T != F) ? T : F --> T
3735     // (F != T) ? T : F --> T
3736     if (Pred == FCmpInst::FCMP_UNE)
3737       return T;
3738   }
3739 
3740   return nullptr;
3741 }
3742 
3743 /// Given operands for a SelectInst, see if we can fold the result.
3744 /// If not, this returns null.
3745 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3746                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
3747   if (auto *CondC = dyn_cast<Constant>(Cond)) {
3748     if (auto *TrueC = dyn_cast<Constant>(TrueVal))
3749       if (auto *FalseC = dyn_cast<Constant>(FalseVal))
3750         return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
3751 
3752     // select undef, X, Y -> X or Y
3753     if (isa<UndefValue>(CondC))
3754       return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
3755 
3756     // TODO: Vector constants with undef elements don't simplify.
3757 
3758     // select true, X, Y  -> X
3759     if (CondC->isAllOnesValue())
3760       return TrueVal;
3761     // select false, X, Y -> Y
3762     if (CondC->isNullValue())
3763       return FalseVal;
3764   }
3765 
3766   // select ?, X, X -> X
3767   if (TrueVal == FalseVal)
3768     return TrueVal;
3769 
3770   if (isa<UndefValue>(TrueVal))   // select ?, undef, X -> X
3771     return FalseVal;
3772   if (isa<UndefValue>(FalseVal))   // select ?, X, undef -> X
3773     return TrueVal;
3774 
3775   if (Value *V =
3776           simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
3777     return V;
3778 
3779   if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal))
3780     return V;
3781 
3782   if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
3783     return V;
3784 
3785   Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
3786   if (Imp)
3787     return *Imp ? TrueVal : FalseVal;
3788 
3789   return nullptr;
3790 }
3791 
3792 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3793                                 const SimplifyQuery &Q) {
3794   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
3795 }
3796 
3797 /// Given operands for an GetElementPtrInst, see if we can fold the result.
3798 /// If not, this returns null.
3799 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3800                               const SimplifyQuery &Q, unsigned) {
3801   // The type of the GEP pointer operand.
3802   unsigned AS =
3803       cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
3804 
3805   // getelementptr P -> P.
3806   if (Ops.size() == 1)
3807     return Ops[0];
3808 
3809   // Compute the (pointer) type returned by the GEP instruction.
3810   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
3811   Type *GEPTy = PointerType::get(LastType, AS);
3812   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3813     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3814   else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
3815     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3816 
3817   if (isa<UndefValue>(Ops[0]))
3818     return UndefValue::get(GEPTy);
3819 
3820   if (Ops.size() == 2) {
3821     // getelementptr P, 0 -> P.
3822     if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy)
3823       return Ops[0];
3824 
3825     Type *Ty = SrcTy;
3826     if (Ty->isSized()) {
3827       Value *P;
3828       uint64_t C;
3829       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
3830       // getelementptr P, N -> P if P points to a type of zero size.
3831       if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy)
3832         return Ops[0];
3833 
3834       // The following transforms are only safe if the ptrtoint cast
3835       // doesn't truncate the pointers.
3836       if (Ops[1]->getType()->getScalarSizeInBits() ==
3837           Q.DL.getIndexSizeInBits(AS)) {
3838         auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3839           if (match(P, m_Zero()))
3840             return Constant::getNullValue(GEPTy);
3841           Value *Temp;
3842           if (match(P, m_PtrToInt(m_Value(Temp))))
3843             if (Temp->getType() == GEPTy)
3844               return Temp;
3845           return nullptr;
3846         };
3847 
3848         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3849         if (TyAllocSize == 1 &&
3850             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3851           if (Value *R = PtrToIntOrZero(P))
3852             return R;
3853 
3854         // getelementptr V, (ashr (sub P, V), C) -> Q
3855         // if P points to a type of size 1 << C.
3856         if (match(Ops[1],
3857                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3858                          m_ConstantInt(C))) &&
3859             TyAllocSize == 1ULL << C)
3860           if (Value *R = PtrToIntOrZero(P))
3861             return R;
3862 
3863         // getelementptr V, (sdiv (sub P, V), C) -> Q
3864         // if P points to a type of size C.
3865         if (match(Ops[1],
3866                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3867                          m_SpecificInt(TyAllocSize))))
3868           if (Value *R = PtrToIntOrZero(P))
3869             return R;
3870       }
3871     }
3872   }
3873 
3874   if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3875       all_of(Ops.slice(1).drop_back(1),
3876              [](Value *Idx) { return match(Idx, m_Zero()); })) {
3877     unsigned IdxWidth =
3878         Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3879     if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) {
3880       APInt BasePtrOffset(IdxWidth, 0);
3881       Value *StrippedBasePtr =
3882           Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3883                                                             BasePtrOffset);
3884 
3885       // gep (gep V, C), (sub 0, V) -> C
3886       if (match(Ops.back(),
3887                 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3888         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3889         return ConstantExpr::getIntToPtr(CI, GEPTy);
3890       }
3891       // gep (gep V, C), (xor V, -1) -> C-1
3892       if (match(Ops.back(),
3893                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3894         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3895         return ConstantExpr::getIntToPtr(CI, GEPTy);
3896       }
3897     }
3898   }
3899 
3900   // Check to see if this is constant foldable.
3901   if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); }))
3902     return nullptr;
3903 
3904   auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3905                                             Ops.slice(1));
3906   if (auto *CEFolded = ConstantFoldConstant(CE, Q.DL))
3907     return CEFolded;
3908   return CE;
3909 }
3910 
3911 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3912                              const SimplifyQuery &Q) {
3913   return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
3914 }
3915 
3916 /// Given operands for an InsertValueInst, see if we can fold the result.
3917 /// If not, this returns null.
3918 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3919                                       ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
3920                                       unsigned) {
3921   if (Constant *CAgg = dyn_cast<Constant>(Agg))
3922     if (Constant *CVal = dyn_cast<Constant>(Val))
3923       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3924 
3925   // insertvalue x, undef, n -> x
3926   if (match(Val, m_Undef()))
3927     return Agg;
3928 
3929   // insertvalue x, (extractvalue y, n), n
3930   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
3931     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3932         EV->getIndices() == Idxs) {
3933       // insertvalue undef, (extractvalue y, n), n -> y
3934       if (match(Agg, m_Undef()))
3935         return EV->getAggregateOperand();
3936 
3937       // insertvalue y, (extractvalue y, n), n -> y
3938       if (Agg == EV->getAggregateOperand())
3939         return Agg;
3940     }
3941 
3942   return nullptr;
3943 }
3944 
3945 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
3946                                      ArrayRef<unsigned> Idxs,
3947                                      const SimplifyQuery &Q) {
3948   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
3949 }
3950 
3951 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
3952                                        const SimplifyQuery &Q) {
3953   // Try to constant fold.
3954   auto *VecC = dyn_cast<Constant>(Vec);
3955   auto *ValC = dyn_cast<Constant>(Val);
3956   auto *IdxC = dyn_cast<Constant>(Idx);
3957   if (VecC && ValC && IdxC)
3958     return ConstantFoldInsertElementInstruction(VecC, ValC, IdxC);
3959 
3960   // Fold into undef if index is out of bounds.
3961   if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
3962     uint64_t NumElements = cast<VectorType>(Vec->getType())->getNumElements();
3963     if (CI->uge(NumElements))
3964       return UndefValue::get(Vec->getType());
3965   }
3966 
3967   // If index is undef, it might be out of bounds (see above case)
3968   if (isa<UndefValue>(Idx))
3969     return UndefValue::get(Vec->getType());
3970 
3971   return nullptr;
3972 }
3973 
3974 /// Given operands for an ExtractValueInst, see if we can fold the result.
3975 /// If not, this returns null.
3976 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3977                                        const SimplifyQuery &, unsigned) {
3978   if (auto *CAgg = dyn_cast<Constant>(Agg))
3979     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3980 
3981   // extractvalue x, (insertvalue y, elt, n), n -> elt
3982   unsigned NumIdxs = Idxs.size();
3983   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3984        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3985     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3986     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3987     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3988     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3989         Idxs.slice(0, NumCommonIdxs)) {
3990       if (NumIdxs == NumInsertValueIdxs)
3991         return IVI->getInsertedValueOperand();
3992       break;
3993     }
3994   }
3995 
3996   return nullptr;
3997 }
3998 
3999 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4000                                       const SimplifyQuery &Q) {
4001   return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
4002 }
4003 
4004 /// Given operands for an ExtractElementInst, see if we can fold the result.
4005 /// If not, this returns null.
4006 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &,
4007                                          unsigned) {
4008   if (auto *CVec = dyn_cast<Constant>(Vec)) {
4009     if (auto *CIdx = dyn_cast<Constant>(Idx))
4010       return ConstantFoldExtractElementInstruction(CVec, CIdx);
4011 
4012     // The index is not relevant if our vector is a splat.
4013     if (auto *Splat = CVec->getSplatValue())
4014       return Splat;
4015 
4016     if (isa<UndefValue>(Vec))
4017       return UndefValue::get(Vec->getType()->getVectorElementType());
4018   }
4019 
4020   // If extracting a specified index from the vector, see if we can recursively
4021   // find a previously computed scalar that was inserted into the vector.
4022   if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4023     if (IdxC->getValue().uge(Vec->getType()->getVectorNumElements()))
4024       // definitely out of bounds, thus undefined result
4025       return UndefValue::get(Vec->getType()->getVectorElementType());
4026     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4027       return Elt;
4028   }
4029 
4030   // An undef extract index can be arbitrarily chosen to be an out-of-range
4031   // index value, which would result in the instruction being undef.
4032   if (isa<UndefValue>(Idx))
4033     return UndefValue::get(Vec->getType()->getVectorElementType());
4034 
4035   return nullptr;
4036 }
4037 
4038 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
4039                                         const SimplifyQuery &Q) {
4040   return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4041 }
4042 
4043 /// See if we can fold the given phi. If not, returns null.
4044 static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
4045   // If all of the PHI's incoming values are the same then replace the PHI node
4046   // with the common value.
4047   Value *CommonValue = nullptr;
4048   bool HasUndefInput = false;
4049   for (Value *Incoming : PN->incoming_values()) {
4050     // If the incoming value is the phi node itself, it can safely be skipped.
4051     if (Incoming == PN) continue;
4052     if (isa<UndefValue>(Incoming)) {
4053       // Remember that we saw an undef value, but otherwise ignore them.
4054       HasUndefInput = true;
4055       continue;
4056     }
4057     if (CommonValue && Incoming != CommonValue)
4058       return nullptr;  // Not the same, bail out.
4059     CommonValue = Incoming;
4060   }
4061 
4062   // If CommonValue is null then all of the incoming values were either undef or
4063   // equal to the phi node itself.
4064   if (!CommonValue)
4065     return UndefValue::get(PN->getType());
4066 
4067   // If we have a PHI node like phi(X, undef, X), where X is defined by some
4068   // instruction, we cannot return X as the result of the PHI node unless it
4069   // dominates the PHI block.
4070   if (HasUndefInput)
4071     return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
4072 
4073   return CommonValue;
4074 }
4075 
4076 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4077                                Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
4078   if (auto *C = dyn_cast<Constant>(Op))
4079     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
4080 
4081   if (auto *CI = dyn_cast<CastInst>(Op)) {
4082     auto *Src = CI->getOperand(0);
4083     Type *SrcTy = Src->getType();
4084     Type *MidTy = CI->getType();
4085     Type *DstTy = Ty;
4086     if (Src->getType() == Ty) {
4087       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4088       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4089       Type *SrcIntPtrTy =
4090           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4091       Type *MidIntPtrTy =
4092           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4093       Type *DstIntPtrTy =
4094           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4095       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4096                                          SrcIntPtrTy, MidIntPtrTy,
4097                                          DstIntPtrTy) == Instruction::BitCast)
4098         return Src;
4099     }
4100   }
4101 
4102   // bitcast x -> x
4103   if (CastOpc == Instruction::BitCast)
4104     if (Op->getType() == Ty)
4105       return Op;
4106 
4107   return nullptr;
4108 }
4109 
4110 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4111                               const SimplifyQuery &Q) {
4112   return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4113 }
4114 
4115 /// For the given destination element of a shuffle, peek through shuffles to
4116 /// match a root vector source operand that contains that element in the same
4117 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4118 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4119                                    int MaskVal, Value *RootVec,
4120                                    unsigned MaxRecurse) {
4121   if (!MaxRecurse--)
4122     return nullptr;
4123 
4124   // Bail out if any mask value is undefined. That kind of shuffle may be
4125   // simplified further based on demanded bits or other folds.
4126   if (MaskVal == -1)
4127     return nullptr;
4128 
4129   // The mask value chooses which source operand we need to look at next.
4130   int InVecNumElts = Op0->getType()->getVectorNumElements();
4131   int RootElt = MaskVal;
4132   Value *SourceOp = Op0;
4133   if (MaskVal >= InVecNumElts) {
4134     RootElt = MaskVal - InVecNumElts;
4135     SourceOp = Op1;
4136   }
4137 
4138   // If the source operand is a shuffle itself, look through it to find the
4139   // matching root vector.
4140   if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4141     return foldIdentityShuffles(
4142         DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4143         SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
4144   }
4145 
4146   // TODO: Look through bitcasts? What if the bitcast changes the vector element
4147   // size?
4148 
4149   // The source operand is not a shuffle. Initialize the root vector value for
4150   // this shuffle if that has not been done yet.
4151   if (!RootVec)
4152     RootVec = SourceOp;
4153 
4154   // Give up as soon as a source operand does not match the existing root value.
4155   if (RootVec != SourceOp)
4156     return nullptr;
4157 
4158   // The element must be coming from the same lane in the source vector
4159   // (although it may have crossed lanes in intermediate shuffles).
4160   if (RootElt != DestElt)
4161     return nullptr;
4162 
4163   return RootVec;
4164 }
4165 
4166 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4167                                         Type *RetTy, const SimplifyQuery &Q,
4168                                         unsigned MaxRecurse) {
4169   if (isa<UndefValue>(Mask))
4170     return UndefValue::get(RetTy);
4171 
4172   Type *InVecTy = Op0->getType();
4173   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
4174   unsigned InVecNumElts = InVecTy->getVectorNumElements();
4175 
4176   SmallVector<int, 32> Indices;
4177   ShuffleVectorInst::getShuffleMask(Mask, Indices);
4178   assert(MaskNumElts == Indices.size() &&
4179          "Size of Indices not same as number of mask elements?");
4180 
4181   // Canonicalization: If mask does not select elements from an input vector,
4182   // replace that input vector with undef.
4183   bool MaskSelects0 = false, MaskSelects1 = false;
4184   for (unsigned i = 0; i != MaskNumElts; ++i) {
4185     if (Indices[i] == -1)
4186       continue;
4187     if ((unsigned)Indices[i] < InVecNumElts)
4188       MaskSelects0 = true;
4189     else
4190       MaskSelects1 = true;
4191   }
4192   if (!MaskSelects0)
4193     Op0 = UndefValue::get(InVecTy);
4194   if (!MaskSelects1)
4195     Op1 = UndefValue::get(InVecTy);
4196 
4197   auto *Op0Const = dyn_cast<Constant>(Op0);
4198   auto *Op1Const = dyn_cast<Constant>(Op1);
4199 
4200   // If all operands are constant, constant fold the shuffle.
4201   if (Op0Const && Op1Const)
4202     return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
4203 
4204   // Canonicalization: if only one input vector is constant, it shall be the
4205   // second one.
4206   if (Op0Const && !Op1Const) {
4207     std::swap(Op0, Op1);
4208     ShuffleVectorInst::commuteShuffleMask(Indices, InVecNumElts);
4209   }
4210 
4211   // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4212   // value type is same as the input vectors' type.
4213   if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
4214     if (isa<UndefValue>(Op1) && RetTy == InVecTy &&
4215         OpShuf->getMask()->getSplatValue())
4216       return Op0;
4217 
4218   // Don't fold a shuffle with undef mask elements. This may get folded in a
4219   // better way using demanded bits or other analysis.
4220   // TODO: Should we allow this?
4221   if (find(Indices, -1) != Indices.end())
4222     return nullptr;
4223 
4224   // Check if every element of this shuffle can be mapped back to the
4225   // corresponding element of a single root vector. If so, we don't need this
4226   // shuffle. This handles simple identity shuffles as well as chains of
4227   // shuffles that may widen/narrow and/or move elements across lanes and back.
4228   Value *RootVec = nullptr;
4229   for (unsigned i = 0; i != MaskNumElts; ++i) {
4230     // Note that recursion is limited for each vector element, so if any element
4231     // exceeds the limit, this will fail to simplify.
4232     RootVec =
4233         foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
4234 
4235     // We can't replace a widening/narrowing shuffle with one of its operands.
4236     if (!RootVec || RootVec->getType() != RetTy)
4237       return nullptr;
4238   }
4239   return RootVec;
4240 }
4241 
4242 /// Given operands for a ShuffleVectorInst, fold the result or return null.
4243 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4244                                        Type *RetTy, const SimplifyQuery &Q) {
4245   return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
4246 }
4247 
4248 static Constant *propagateNaN(Constant *In) {
4249   // If the input is a vector with undef elements, just return a default NaN.
4250   if (!In->isNaN())
4251     return ConstantFP::getNaN(In->getType());
4252 
4253   // Propagate the existing NaN constant when possible.
4254   // TODO: Should we quiet a signaling NaN?
4255   return In;
4256 }
4257 
4258 static Constant *simplifyFPBinop(Value *Op0, Value *Op1) {
4259   if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4260     return ConstantFP::getNaN(Op0->getType());
4261 
4262   if (match(Op0, m_NaN()))
4263     return propagateNaN(cast<Constant>(Op0));
4264   if (match(Op1, m_NaN()))
4265     return propagateNaN(cast<Constant>(Op1));
4266 
4267   return nullptr;
4268 }
4269 
4270 /// Given operands for an FAdd, see if we can fold the result.  If not, this
4271 /// returns null.
4272 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4273                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4274   if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
4275     return C;
4276 
4277   if (Constant *C = simplifyFPBinop(Op0, Op1))
4278     return C;
4279 
4280   // fadd X, -0 ==> X
4281   if (match(Op1, m_NegZeroFP()))
4282     return Op0;
4283 
4284   // fadd X, 0 ==> X, when we know X is not -0
4285   if (match(Op1, m_PosZeroFP()) &&
4286       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4287     return Op0;
4288 
4289   // With nnan: (+/-0.0 - X) + X --> 0.0 (and commuted variant)
4290   // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
4291   // Negative zeros are allowed because we always end up with positive zero:
4292   // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4293   // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4294   // X =  0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
4295   // X =  0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
4296   if (FMF.noNaNs() && (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
4297                        match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0)))))
4298     return ConstantFP::getNullValue(Op0->getType());
4299 
4300   // (X - Y) + Y --> X
4301   // Y + (X - Y) --> X
4302   Value *X;
4303   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4304       (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
4305        match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
4306     return X;
4307 
4308   return nullptr;
4309 }
4310 
4311 /// Given operands for an FSub, see if we can fold the result.  If not, this
4312 /// returns null.
4313 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4314                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4315   if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
4316     return C;
4317 
4318   if (Constant *C = simplifyFPBinop(Op0, Op1))
4319     return C;
4320 
4321   // fsub X, +0 ==> X
4322   if (match(Op1, m_PosZeroFP()))
4323     return Op0;
4324 
4325   // fsub X, -0 ==> X, when we know X is not -0
4326   if (match(Op1, m_NegZeroFP()) &&
4327       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4328     return Op0;
4329 
4330   // fsub -0.0, (fsub -0.0, X) ==> X
4331   Value *X;
4332   if (match(Op0, m_NegZeroFP()) &&
4333       match(Op1, m_FSub(m_NegZeroFP(), m_Value(X))))
4334     return X;
4335 
4336   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
4337   if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
4338       match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))))
4339     return X;
4340 
4341   // fsub nnan x, x ==> 0.0
4342   if (FMF.noNaNs() && Op0 == Op1)
4343     return Constant::getNullValue(Op0->getType());
4344 
4345   // Y - (Y - X) --> X
4346   // (X + Y) - Y --> X
4347   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4348       (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
4349        match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
4350     return X;
4351 
4352   return nullptr;
4353 }
4354 
4355 /// Given the operands for an FMul, see if we can fold the result
4356 static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4357                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4358   if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
4359     return C;
4360 
4361   if (Constant *C = simplifyFPBinop(Op0, Op1))
4362     return C;
4363 
4364   // fmul X, 1.0 ==> X
4365   if (match(Op1, m_FPOne()))
4366     return Op0;
4367 
4368   // fmul nnan nsz X, 0 ==> 0
4369   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
4370     return ConstantFP::getNullValue(Op0->getType());
4371 
4372   // sqrt(X) * sqrt(X) --> X, if we can:
4373   // 1. Remove the intermediate rounding (reassociate).
4374   // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
4375   // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
4376   Value *X;
4377   if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
4378       FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
4379     return X;
4380 
4381   return nullptr;
4382 }
4383 
4384 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4385                               const SimplifyQuery &Q) {
4386   return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
4387 }
4388 
4389 
4390 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4391                               const SimplifyQuery &Q) {
4392   return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
4393 }
4394 
4395 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4396                               const SimplifyQuery &Q) {
4397   return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
4398 }
4399 
4400 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4401                                const SimplifyQuery &Q, unsigned) {
4402   if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
4403     return C;
4404 
4405   if (Constant *C = simplifyFPBinop(Op0, Op1))
4406     return C;
4407 
4408   // X / 1.0 -> X
4409   if (match(Op1, m_FPOne()))
4410     return Op0;
4411 
4412   // 0 / X -> 0
4413   // Requires that NaNs are off (X could be zero) and signed zeroes are
4414   // ignored (X could be positive or negative, so the output sign is unknown).
4415   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
4416     return ConstantFP::getNullValue(Op0->getType());
4417 
4418   if (FMF.noNaNs()) {
4419     // X / X -> 1.0 is legal when NaNs are ignored.
4420     // We can ignore infinities because INF/INF is NaN.
4421     if (Op0 == Op1)
4422       return ConstantFP::get(Op0->getType(), 1.0);
4423 
4424     // (X * Y) / Y --> X if we can reassociate to the above form.
4425     Value *X;
4426     if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
4427       return X;
4428 
4429     // -X /  X -> -1.0 and
4430     //  X / -X -> -1.0 are legal when NaNs are ignored.
4431     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
4432     if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
4433         match(Op1, m_FNegNSZ(m_Specific(Op0))))
4434       return ConstantFP::get(Op0->getType(), -1.0);
4435   }
4436 
4437   return nullptr;
4438 }
4439 
4440 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4441                               const SimplifyQuery &Q) {
4442   return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
4443 }
4444 
4445 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4446                                const SimplifyQuery &Q, unsigned) {
4447   if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
4448     return C;
4449 
4450   if (Constant *C = simplifyFPBinop(Op0, Op1))
4451     return C;
4452 
4453   // Unlike fdiv, the result of frem always matches the sign of the dividend.
4454   // The constant match may include undef elements in a vector, so return a full
4455   // zero constant as the result.
4456   if (FMF.noNaNs()) {
4457     // +0 % X -> 0
4458     if (match(Op0, m_PosZeroFP()))
4459       return ConstantFP::getNullValue(Op0->getType());
4460     // -0 % X -> -0
4461     if (match(Op0, m_NegZeroFP()))
4462       return ConstantFP::getNegativeZero(Op0->getType());
4463   }
4464 
4465   return nullptr;
4466 }
4467 
4468 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4469                               const SimplifyQuery &Q) {
4470   return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
4471 }
4472 
4473 //=== Helper functions for higher up the class hierarchy.
4474 
4475 /// Given operands for a BinaryOperator, see if we can fold the result.
4476 /// If not, this returns null.
4477 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4478                             const SimplifyQuery &Q, unsigned MaxRecurse) {
4479   switch (Opcode) {
4480   case Instruction::Add:
4481     return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
4482   case Instruction::Sub:
4483     return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
4484   case Instruction::Mul:
4485     return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
4486   case Instruction::SDiv:
4487     return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4488   case Instruction::UDiv:
4489     return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
4490   case Instruction::SRem:
4491     return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4492   case Instruction::URem:
4493     return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
4494   case Instruction::Shl:
4495     return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
4496   case Instruction::LShr:
4497     return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
4498   case Instruction::AShr:
4499     return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4500   case Instruction::And:
4501     return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4502   case Instruction::Or:
4503     return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4504   case Instruction::Xor:
4505     return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
4506   case Instruction::FAdd:
4507     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4508   case Instruction::FSub:
4509     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4510   case Instruction::FMul:
4511     return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4512   case Instruction::FDiv:
4513     return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4514   case Instruction::FRem:
4515     return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4516   default:
4517     llvm_unreachable("Unexpected opcode");
4518   }
4519 }
4520 
4521 /// Given operands for a BinaryOperator, see if we can fold the result.
4522 /// If not, this returns null.
4523 /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4524 /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4525 static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4526                               const FastMathFlags &FMF, const SimplifyQuery &Q,
4527                               unsigned MaxRecurse) {
4528   switch (Opcode) {
4529   case Instruction::FAdd:
4530     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4531   case Instruction::FSub:
4532     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4533   case Instruction::FMul:
4534     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
4535   case Instruction::FDiv:
4536     return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
4537   default:
4538     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4539   }
4540 }
4541 
4542 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4543                            const SimplifyQuery &Q) {
4544   return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
4545 }
4546 
4547 Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4548                              FastMathFlags FMF, const SimplifyQuery &Q) {
4549   return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
4550 }
4551 
4552 /// Given operands for a CmpInst, see if we can fold the result.
4553 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4554                               const SimplifyQuery &Q, unsigned MaxRecurse) {
4555   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
4556     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
4557   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4558 }
4559 
4560 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4561                              const SimplifyQuery &Q) {
4562   return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
4563 }
4564 
4565 static bool IsIdempotent(Intrinsic::ID ID) {
4566   switch (ID) {
4567   default: return false;
4568 
4569   // Unary idempotent: f(f(x)) = f(x)
4570   case Intrinsic::fabs:
4571   case Intrinsic::floor:
4572   case Intrinsic::ceil:
4573   case Intrinsic::trunc:
4574   case Intrinsic::rint:
4575   case Intrinsic::nearbyint:
4576   case Intrinsic::round:
4577   case Intrinsic::canonicalize:
4578     return true;
4579   }
4580 }
4581 
4582 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4583                                    const DataLayout &DL) {
4584   GlobalValue *PtrSym;
4585   APInt PtrOffset;
4586   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4587     return nullptr;
4588 
4589   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4590   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4591   Type *Int32PtrTy = Int32Ty->getPointerTo();
4592   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4593 
4594   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4595   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4596     return nullptr;
4597 
4598   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4599   if (OffsetInt % 4 != 0)
4600     return nullptr;
4601 
4602   Constant *C = ConstantExpr::getGetElementPtr(
4603       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4604       ConstantInt::get(Int64Ty, OffsetInt / 4));
4605   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4606   if (!Loaded)
4607     return nullptr;
4608 
4609   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4610   if (!LoadedCE)
4611     return nullptr;
4612 
4613   if (LoadedCE->getOpcode() == Instruction::Trunc) {
4614     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4615     if (!LoadedCE)
4616       return nullptr;
4617   }
4618 
4619   if (LoadedCE->getOpcode() != Instruction::Sub)
4620     return nullptr;
4621 
4622   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4623   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4624     return nullptr;
4625   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4626 
4627   Constant *LoadedRHS = LoadedCE->getOperand(1);
4628   GlobalValue *LoadedRHSSym;
4629   APInt LoadedRHSOffset;
4630   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4631                                   DL) ||
4632       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4633     return nullptr;
4634 
4635   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4636 }
4637 
4638 static bool maskIsAllZeroOrUndef(Value *Mask) {
4639   auto *ConstMask = dyn_cast<Constant>(Mask);
4640   if (!ConstMask)
4641     return false;
4642   if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4643     return true;
4644   for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4645        ++I) {
4646     if (auto *MaskElt = ConstMask->getAggregateElement(I))
4647       if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4648         continue;
4649     return false;
4650   }
4651   return true;
4652 }
4653 
4654 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
4655                                      const SimplifyQuery &Q) {
4656   // Idempotent functions return the same result when called repeatedly.
4657   Intrinsic::ID IID = F->getIntrinsicID();
4658   if (IsIdempotent(IID))
4659     if (auto *II = dyn_cast<IntrinsicInst>(Op0))
4660       if (II->getIntrinsicID() == IID)
4661         return II;
4662 
4663   Value *X;
4664   switch (IID) {
4665   case Intrinsic::fabs:
4666     if (SignBitMustBeZero(Op0, Q.TLI)) return Op0;
4667     break;
4668   case Intrinsic::bswap:
4669     // bswap(bswap(x)) -> x
4670     if (match(Op0, m_BSwap(m_Value(X)))) return X;
4671     break;
4672   case Intrinsic::bitreverse:
4673     // bitreverse(bitreverse(x)) -> x
4674     if (match(Op0, m_BitReverse(m_Value(X)))) return X;
4675     break;
4676   case Intrinsic::exp:
4677     // exp(log(x)) -> x
4678     if (Q.CxtI->hasAllowReassoc() &&
4679         match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X;
4680     break;
4681   case Intrinsic::exp2:
4682     // exp2(log2(x)) -> x
4683     if (Q.CxtI->hasAllowReassoc() &&
4684         match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X;
4685     break;
4686   case Intrinsic::log:
4687     // log(exp(x)) -> x
4688     if (Q.CxtI->hasAllowReassoc() &&
4689         match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X;
4690     break;
4691   case Intrinsic::log2:
4692     // log2(exp2(x)) -> x
4693     if (Q.CxtI->hasAllowReassoc() &&
4694         (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
4695          match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0),
4696                                                 m_Value(X))))) return X;
4697     break;
4698   case Intrinsic::log10:
4699     // log10(pow(10.0, x)) -> x
4700     if (Q.CxtI->hasAllowReassoc() &&
4701         match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0),
4702                                                m_Value(X)))) return X;
4703     break;
4704   case Intrinsic::floor:
4705   case Intrinsic::trunc:
4706   case Intrinsic::ceil:
4707   case Intrinsic::round:
4708   case Intrinsic::nearbyint:
4709   case Intrinsic::rint: {
4710     // floor (sitofp x) -> sitofp x
4711     // floor (uitofp x) -> uitofp x
4712     //
4713     // Converting from int always results in a finite integral number or
4714     // infinity. For either of those inputs, these rounding functions always
4715     // return the same value, so the rounding can be eliminated.
4716     if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
4717       return Op0;
4718     break;
4719   }
4720   default:
4721     break;
4722   }
4723 
4724   return nullptr;
4725 }
4726 
4727 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
4728                                       const SimplifyQuery &Q) {
4729   Intrinsic::ID IID = F->getIntrinsicID();
4730   Type *ReturnType = F->getReturnType();
4731   switch (IID) {
4732   case Intrinsic::usub_with_overflow:
4733   case Intrinsic::ssub_with_overflow:
4734     // X - X -> { 0, false }
4735     if (Op0 == Op1)
4736       return Constant::getNullValue(ReturnType);
4737     // X - undef -> undef
4738     // undef - X -> undef
4739     if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4740       return UndefValue::get(ReturnType);
4741     break;
4742   case Intrinsic::uadd_with_overflow:
4743   case Intrinsic::sadd_with_overflow:
4744     // X + undef -> undef
4745     if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4746       return UndefValue::get(ReturnType);
4747     break;
4748   case Intrinsic::umul_with_overflow:
4749   case Intrinsic::smul_with_overflow:
4750     // 0 * X -> { 0, false }
4751     // X * 0 -> { 0, false }
4752     if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
4753       return Constant::getNullValue(ReturnType);
4754     // undef * X -> { 0, false }
4755     // X * undef -> { 0, false }
4756     if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
4757       return Constant::getNullValue(ReturnType);
4758     break;
4759   case Intrinsic::uadd_sat:
4760     // sat(MAX + X) -> MAX
4761     // sat(X + MAX) -> MAX
4762     if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
4763       return Constant::getAllOnesValue(ReturnType);
4764     LLVM_FALLTHROUGH;
4765   case Intrinsic::sadd_sat:
4766     // sat(X + undef) -> -1
4767     // sat(undef + X) -> -1
4768     // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
4769     // For signed: Assume undef is ~X, in which case X + ~X = -1.
4770     if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
4771       return Constant::getAllOnesValue(ReturnType);
4772 
4773     // X + 0 -> X
4774     if (match(Op1, m_Zero()))
4775       return Op0;
4776     // 0 + X -> X
4777     if (match(Op0, m_Zero()))
4778       return Op1;
4779     break;
4780   case Intrinsic::usub_sat:
4781     // sat(0 - X) -> 0, sat(X - MAX) -> 0
4782     if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
4783       return Constant::getNullValue(ReturnType);
4784     LLVM_FALLTHROUGH;
4785   case Intrinsic::ssub_sat:
4786     // X - X -> 0, X - undef -> 0, undef - X -> 0
4787     if (Op0 == Op1 || match(Op0, m_Undef()) || match(Op1, m_Undef()))
4788       return Constant::getNullValue(ReturnType);
4789     // X - 0 -> X
4790     if (match(Op1, m_Zero()))
4791       return Op0;
4792     break;
4793   case Intrinsic::load_relative:
4794     if (auto *C0 = dyn_cast<Constant>(Op0))
4795       if (auto *C1 = dyn_cast<Constant>(Op1))
4796         return SimplifyRelativeLoad(C0, C1, Q.DL);
4797     break;
4798   case Intrinsic::powi:
4799     if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
4800       // powi(x, 0) -> 1.0
4801       if (Power->isZero())
4802         return ConstantFP::get(Op0->getType(), 1.0);
4803       // powi(x, 1) -> x
4804       if (Power->isOne())
4805         return Op0;
4806     }
4807     break;
4808   case Intrinsic::maxnum:
4809   case Intrinsic::minnum:
4810   case Intrinsic::maximum:
4811   case Intrinsic::minimum: {
4812     // If the arguments are the same, this is a no-op.
4813     if (Op0 == Op1) return Op0;
4814 
4815     // If one argument is undef, return the other argument.
4816     if (match(Op0, m_Undef()))
4817       return Op1;
4818     if (match(Op1, m_Undef()))
4819       return Op0;
4820 
4821     // If one argument is NaN, return other or NaN appropriately.
4822     bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
4823     if (match(Op0, m_NaN()))
4824       return PropagateNaN ? Op0 : Op1;
4825     if (match(Op1, m_NaN()))
4826       return PropagateNaN ? Op1 : Op0;
4827 
4828     // Min/max of the same operation with common operand:
4829     // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
4830     if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
4831       if (M0->getIntrinsicID() == IID &&
4832           (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
4833         return Op0;
4834     if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
4835       if (M1->getIntrinsicID() == IID &&
4836           (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
4837         return Op1;
4838 
4839     // min(X, -Inf) --> -Inf (and commuted variant)
4840     // max(X, +Inf) --> +Inf (and commuted variant)
4841     bool UseNegInf = IID == Intrinsic::minnum || IID == Intrinsic::minimum;
4842     const APFloat *C;
4843     if ((match(Op0, m_APFloat(C)) && C->isInfinity() &&
4844          C->isNegative() == UseNegInf) ||
4845         (match(Op1, m_APFloat(C)) && C->isInfinity() &&
4846          C->isNegative() == UseNegInf))
4847       return ConstantFP::getInfinity(ReturnType, UseNegInf);
4848 
4849     // TODO: minnum(nnan x, inf) -> x
4850     // TODO: minnum(nnan ninf x, flt_max) -> x
4851     // TODO: maxnum(nnan x, -inf) -> x
4852     // TODO: maxnum(nnan ninf x, -flt_max) -> x
4853     break;
4854   }
4855   default:
4856     break;
4857   }
4858 
4859   return nullptr;
4860 }
4861 
4862 template <typename IterTy>
4863 static Value *simplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
4864                                 const SimplifyQuery &Q) {
4865   // Intrinsics with no operands have some kind of side effect. Don't simplify.
4866   unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
4867   if (NumOperands == 0)
4868     return nullptr;
4869 
4870   Intrinsic::ID IID = F->getIntrinsicID();
4871   if (NumOperands == 1)
4872     return simplifyUnaryIntrinsic(F, ArgBegin[0], Q);
4873 
4874   if (NumOperands == 2)
4875     return simplifyBinaryIntrinsic(F, ArgBegin[0], ArgBegin[1], Q);
4876 
4877   // Handle intrinsics with 3 or more arguments.
4878   switch (IID) {
4879   case Intrinsic::masked_load: {
4880     Value *MaskArg = ArgBegin[2];
4881     Value *PassthruArg = ArgBegin[3];
4882     // If the mask is all zeros or undef, the "passthru" argument is the result.
4883     if (maskIsAllZeroOrUndef(MaskArg))
4884       return PassthruArg;
4885     return nullptr;
4886   }
4887   case Intrinsic::fshl:
4888   case Intrinsic::fshr: {
4889     Value *Op0 = ArgBegin[0], *Op1 = ArgBegin[1], *ShAmtArg = ArgBegin[2];
4890 
4891     // If both operands are undef, the result is undef.
4892     if (match(Op0, m_Undef()) && match(Op1, m_Undef()))
4893       return UndefValue::get(F->getReturnType());
4894 
4895     // If shift amount is undef, assume it is zero.
4896     if (match(ShAmtArg, m_Undef()))
4897       return ArgBegin[IID == Intrinsic::fshl ? 0 : 1];
4898 
4899     const APInt *ShAmtC;
4900     if (match(ShAmtArg, m_APInt(ShAmtC))) {
4901       // If there's effectively no shift, return the 1st arg or 2nd arg.
4902       APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
4903       if (ShAmtC->urem(BitWidth).isNullValue())
4904         return ArgBegin[IID == Intrinsic::fshl ? 0 : 1];
4905     }
4906     return nullptr;
4907   }
4908   default:
4909     return nullptr;
4910   }
4911 }
4912 
4913 template <typename IterTy>
4914 static Value *SimplifyCall(CallBase *Call, Value *V, IterTy ArgBegin,
4915                            IterTy ArgEnd, const SimplifyQuery &Q,
4916                            unsigned MaxRecurse) {
4917   Type *Ty = V->getType();
4918   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4919     Ty = PTy->getElementType();
4920   FunctionType *FTy = cast<FunctionType>(Ty);
4921 
4922   // call undef -> undef
4923   // call null -> undef
4924   if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
4925     return UndefValue::get(FTy->getReturnType());
4926 
4927   Function *F = dyn_cast<Function>(V);
4928   if (!F)
4929     return nullptr;
4930 
4931   if (F->isIntrinsic())
4932     if (Value *Ret = simplifyIntrinsic(F, ArgBegin, ArgEnd, Q))
4933       return Ret;
4934 
4935   if (!canConstantFoldCallTo(Call, F))
4936     return nullptr;
4937 
4938   SmallVector<Constant *, 4> ConstantArgs;
4939   ConstantArgs.reserve(ArgEnd - ArgBegin);
4940   for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4941     Constant *C = dyn_cast<Constant>(*I);
4942     if (!C)
4943       return nullptr;
4944     ConstantArgs.push_back(C);
4945   }
4946 
4947   return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
4948 }
4949 
4950 Value *llvm::SimplifyCall(CallBase *Call, Value *V, User::op_iterator ArgBegin,
4951                           User::op_iterator ArgEnd, const SimplifyQuery &Q) {
4952   return ::SimplifyCall(Call, V, ArgBegin, ArgEnd, Q, RecursionLimit);
4953 }
4954 
4955 Value *llvm::SimplifyCall(CallBase *Call, Value *V, ArrayRef<Value *> Args,
4956                           const SimplifyQuery &Q) {
4957   return ::SimplifyCall(Call, V, Args.begin(), Args.end(), Q, RecursionLimit);
4958 }
4959 
4960 Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) {
4961   return ::SimplifyCall(Call, Call->getCalledValue(), Call->arg_begin(),
4962                         Call->arg_end(), Q, RecursionLimit);
4963 }
4964 
4965 /// See if we can compute a simplified version of this instruction.
4966 /// If not, this returns null.
4967 
4968 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
4969                                  OptimizationRemarkEmitter *ORE) {
4970   const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
4971   Value *Result;
4972 
4973   switch (I->getOpcode()) {
4974   default:
4975     Result = ConstantFoldInstruction(I, Q.DL, Q.TLI);
4976     break;
4977   case Instruction::FAdd:
4978     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
4979                               I->getFastMathFlags(), Q);
4980     break;
4981   case Instruction::Add:
4982     Result =
4983         SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4984                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
4985                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
4986     break;
4987   case Instruction::FSub:
4988     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
4989                               I->getFastMathFlags(), Q);
4990     break;
4991   case Instruction::Sub:
4992     Result =
4993         SimplifySubInst(I->getOperand(0), I->getOperand(1),
4994                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
4995                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
4996     break;
4997   case Instruction::FMul:
4998     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
4999                               I->getFastMathFlags(), Q);
5000     break;
5001   case Instruction::Mul:
5002     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q);
5003     break;
5004   case Instruction::SDiv:
5005     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q);
5006     break;
5007   case Instruction::UDiv:
5008     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q);
5009     break;
5010   case Instruction::FDiv:
5011     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
5012                               I->getFastMathFlags(), Q);
5013     break;
5014   case Instruction::SRem:
5015     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q);
5016     break;
5017   case Instruction::URem:
5018     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q);
5019     break;
5020   case Instruction::FRem:
5021     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
5022                               I->getFastMathFlags(), Q);
5023     break;
5024   case Instruction::Shl:
5025     Result =
5026         SimplifyShlInst(I->getOperand(0), I->getOperand(1),
5027                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5028                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5029     break;
5030   case Instruction::LShr:
5031     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
5032                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5033     break;
5034   case Instruction::AShr:
5035     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
5036                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5037     break;
5038   case Instruction::And:
5039     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q);
5040     break;
5041   case Instruction::Or:
5042     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q);
5043     break;
5044   case Instruction::Xor:
5045     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q);
5046     break;
5047   case Instruction::ICmp:
5048     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
5049                               I->getOperand(0), I->getOperand(1), Q);
5050     break;
5051   case Instruction::FCmp:
5052     Result =
5053         SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
5054                          I->getOperand(1), I->getFastMathFlags(), Q);
5055     break;
5056   case Instruction::Select:
5057     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
5058                                 I->getOperand(2), Q);
5059     break;
5060   case Instruction::GetElementPtr: {
5061     SmallVector<Value *, 8> Ops(I->op_begin(), I->op_end());
5062     Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
5063                              Ops, Q);
5064     break;
5065   }
5066   case Instruction::InsertValue: {
5067     InsertValueInst *IV = cast<InsertValueInst>(I);
5068     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
5069                                      IV->getInsertedValueOperand(),
5070                                      IV->getIndices(), Q);
5071     break;
5072   }
5073   case Instruction::InsertElement: {
5074     auto *IE = cast<InsertElementInst>(I);
5075     Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1),
5076                                        IE->getOperand(2), Q);
5077     break;
5078   }
5079   case Instruction::ExtractValue: {
5080     auto *EVI = cast<ExtractValueInst>(I);
5081     Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
5082                                       EVI->getIndices(), Q);
5083     break;
5084   }
5085   case Instruction::ExtractElement: {
5086     auto *EEI = cast<ExtractElementInst>(I);
5087     Result = SimplifyExtractElementInst(EEI->getVectorOperand(),
5088                                         EEI->getIndexOperand(), Q);
5089     break;
5090   }
5091   case Instruction::ShuffleVector: {
5092     auto *SVI = cast<ShuffleVectorInst>(I);
5093     Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5094                                        SVI->getMask(), SVI->getType(), Q);
5095     break;
5096   }
5097   case Instruction::PHI:
5098     Result = SimplifyPHINode(cast<PHINode>(I), Q);
5099     break;
5100   case Instruction::Call: {
5101     Result = SimplifyCall(cast<CallInst>(I), Q);
5102     break;
5103   }
5104 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
5105 #include "llvm/IR/Instruction.def"
5106 #undef HANDLE_CAST_INST
5107     Result =
5108         SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q);
5109     break;
5110   case Instruction::Alloca:
5111     // No simplifications for Alloca and it can't be constant folded.
5112     Result = nullptr;
5113     break;
5114   }
5115 
5116   // In general, it is possible for computeKnownBits to determine all bits in a
5117   // value even when the operands are not all constants.
5118   if (!Result && I->getType()->isIntOrIntVectorTy()) {
5119     KnownBits Known = computeKnownBits(I, Q.DL, /*Depth*/ 0, Q.AC, I, Q.DT, ORE);
5120     if (Known.isConstant())
5121       Result = ConstantInt::get(I->getType(), Known.getConstant());
5122   }
5123 
5124   /// If called on unreachable code, the above logic may report that the
5125   /// instruction simplified to itself.  Make life easier for users by
5126   /// detecting that case here, returning a safe value instead.
5127   return Result == I ? UndefValue::get(I->getType()) : Result;
5128 }
5129 
5130 /// Implementation of recursive simplification through an instruction's
5131 /// uses.
5132 ///
5133 /// This is the common implementation of the recursive simplification routines.
5134 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
5135 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
5136 /// instructions to process and attempt to simplify it using
5137 /// InstructionSimplify.
5138 ///
5139 /// This routine returns 'true' only when *it* simplifies something. The passed
5140 /// in simplified value does not count toward this.
5141 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
5142                                               const TargetLibraryInfo *TLI,
5143                                               const DominatorTree *DT,
5144                                               AssumptionCache *AC) {
5145   bool Simplified = false;
5146   SmallSetVector<Instruction *, 8> Worklist;
5147   const DataLayout &DL = I->getModule()->getDataLayout();
5148 
5149   // If we have an explicit value to collapse to, do that round of the
5150   // simplification loop by hand initially.
5151   if (SimpleV) {
5152     for (User *U : I->users())
5153       if (U != I)
5154         Worklist.insert(cast<Instruction>(U));
5155 
5156     // Replace the instruction with its simplified value.
5157     I->replaceAllUsesWith(SimpleV);
5158 
5159     // Gracefully handle edge cases where the instruction is not wired into any
5160     // parent block.
5161     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
5162         !I->mayHaveSideEffects())
5163       I->eraseFromParent();
5164   } else {
5165     Worklist.insert(I);
5166   }
5167 
5168   // Note that we must test the size on each iteration, the worklist can grow.
5169   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
5170     I = Worklist[Idx];
5171 
5172     // See if this instruction simplifies.
5173     SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
5174     if (!SimpleV)
5175       continue;
5176 
5177     Simplified = true;
5178 
5179     // Stash away all the uses of the old instruction so we can check them for
5180     // recursive simplifications after a RAUW. This is cheaper than checking all
5181     // uses of To on the recursive step in most cases.
5182     for (User *U : I->users())
5183       Worklist.insert(cast<Instruction>(U));
5184 
5185     // Replace the instruction with its simplified value.
5186     I->replaceAllUsesWith(SimpleV);
5187 
5188     // Gracefully handle edge cases where the instruction is not wired into any
5189     // parent block.
5190     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
5191         !I->mayHaveSideEffects())
5192       I->eraseFromParent();
5193   }
5194   return Simplified;
5195 }
5196 
5197 bool llvm::recursivelySimplifyInstruction(Instruction *I,
5198                                           const TargetLibraryInfo *TLI,
5199                                           const DominatorTree *DT,
5200                                           AssumptionCache *AC) {
5201   return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
5202 }
5203 
5204 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
5205                                          const TargetLibraryInfo *TLI,
5206                                          const DominatorTree *DT,
5207                                          AssumptionCache *AC) {
5208   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
5209   assert(SimpleV && "Must provide a simplified value.");
5210   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
5211 }
5212 
5213 namespace llvm {
5214 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
5215   auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
5216   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
5217   auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5218   auto *TLI = TLIWP ? &TLIWP->getTLI() : nullptr;
5219   auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
5220   auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
5221   return {F.getParent()->getDataLayout(), TLI, DT, AC};
5222 }
5223 
5224 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
5225                                          const DataLayout &DL) {
5226   return {DL, &AR.TLI, &AR.DT, &AR.AC};
5227 }
5228 
5229 template <class T, class... TArgs>
5230 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
5231                                          Function &F) {
5232   auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
5233   auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
5234   auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
5235   return {F.getParent()->getDataLayout(), TLI, DT, AC};
5236 }
5237 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
5238                                                   Function &);
5239 }
5240