1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements routines for folding instructions into simpler forms
11 // that do not require creating new instructions.  This does constant folding
12 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
14 // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
15 // simplified: This is usually true and assuming it simplifies the logic (if
16 // they have not been simplified then results are correct but maybe suboptimal).
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Analysis/VectorUtils.h"
29 #include "llvm/IR/ConstantRange.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/IR/ValueHandle.h"
37 #include <algorithm>
38 using namespace llvm;
39 using namespace llvm::PatternMatch;
40 
41 #define DEBUG_TYPE "instsimplify"
42 
43 enum { RecursionLimit = 3 };
44 
45 STATISTIC(NumExpand,  "Number of expansions");
46 STATISTIC(NumReassoc, "Number of reassociations");
47 
48 namespace {
49 struct Query {
50   const DataLayout &DL;
51   const TargetLibraryInfo *TLI;
52   const DominatorTree *DT;
53   AssumptionCache *AC;
54   const Instruction *CxtI;
55 
56   Query(const DataLayout &DL, const TargetLibraryInfo *tli,
57         const DominatorTree *dt, AssumptionCache *ac = nullptr,
58         const Instruction *cxti = nullptr)
59       : DL(DL), TLI(tli), DT(dt), AC(ac), CxtI(cxti) {}
60 };
61 } // end anonymous namespace
62 
63 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
64 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
65                             unsigned);
66 static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
67                               const Query &, unsigned);
68 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
69                               unsigned);
70 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
71 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
72 static Value *SimplifyCastInst(unsigned, Value *, Type *,
73                                const Query &, unsigned);
74 
75 /// For a boolean type, or a vector of boolean type, return false, or
76 /// a vector with every element false, as appropriate for the type.
77 static Constant *getFalse(Type *Ty) {
78   assert(Ty->getScalarType()->isIntegerTy(1) &&
79          "Expected i1 type or a vector of i1!");
80   return Constant::getNullValue(Ty);
81 }
82 
83 /// For a boolean type, or a vector of boolean type, return true, or
84 /// a vector with every element true, as appropriate for the type.
85 static Constant *getTrue(Type *Ty) {
86   assert(Ty->getScalarType()->isIntegerTy(1) &&
87          "Expected i1 type or a vector of i1!");
88   return Constant::getAllOnesValue(Ty);
89 }
90 
91 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
92 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
93                           Value *RHS) {
94   CmpInst *Cmp = dyn_cast<CmpInst>(V);
95   if (!Cmp)
96     return false;
97   CmpInst::Predicate CPred = Cmp->getPredicate();
98   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
99   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
100     return true;
101   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
102     CRHS == LHS;
103 }
104 
105 /// Does the given value dominate the specified phi node?
106 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
107   Instruction *I = dyn_cast<Instruction>(V);
108   if (!I)
109     // Arguments and constants dominate all instructions.
110     return true;
111 
112   // If we are processing instructions (and/or basic blocks) that have not been
113   // fully added to a function, the parent nodes may still be null. Simply
114   // return the conservative answer in these cases.
115   if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
116     return false;
117 
118   // If we have a DominatorTree then do a precise test.
119   if (DT) {
120     if (!DT->isReachableFromEntry(P->getParent()))
121       return true;
122     if (!DT->isReachableFromEntry(I->getParent()))
123       return false;
124     return DT->dominates(I, P);
125   }
126 
127   // Otherwise, if the instruction is in the entry block and is not an invoke,
128   // then it obviously dominates all phi nodes.
129   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
130       !isa<InvokeInst>(I))
131     return true;
132 
133   return false;
134 }
135 
136 /// Simplify "A op (B op' C)" by distributing op over op', turning it into
137 /// "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
138 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
139 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
140 /// Returns the simplified value, or null if no simplification was performed.
141 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
142                           unsigned OpcToExpand, const Query &Q,
143                           unsigned MaxRecurse) {
144   Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
145   // Recursion is always used, so bail out at once if we already hit the limit.
146   if (!MaxRecurse--)
147     return nullptr;
148 
149   // Check whether the expression has the form "(A op' B) op C".
150   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
151     if (Op0->getOpcode() == OpcodeToExpand) {
152       // It does!  Try turning it into "(A op C) op' (B op C)".
153       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
154       // Do "A op C" and "B op C" both simplify?
155       if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
156         if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
157           // They do! Return "L op' R" if it simplifies or is already available.
158           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
159           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
160                                      && L == B && R == A)) {
161             ++NumExpand;
162             return LHS;
163           }
164           // Otherwise return "L op' R" if it simplifies.
165           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
166             ++NumExpand;
167             return V;
168           }
169         }
170     }
171 
172   // Check whether the expression has the form "A op (B op' C)".
173   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
174     if (Op1->getOpcode() == OpcodeToExpand) {
175       // It does!  Try turning it into "(A op B) op' (A op C)".
176       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
177       // Do "A op B" and "A op C" both simplify?
178       if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
179         if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
180           // They do! Return "L op' R" if it simplifies or is already available.
181           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
182           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
183                                      && L == C && R == B)) {
184             ++NumExpand;
185             return RHS;
186           }
187           // Otherwise return "L op' R" if it simplifies.
188           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
189             ++NumExpand;
190             return V;
191           }
192         }
193     }
194 
195   return nullptr;
196 }
197 
198 /// Generic simplifications for associative binary operations.
199 /// Returns the simpler value, or null if none was found.
200 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
201                                        const Query &Q, unsigned MaxRecurse) {
202   Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
203   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
204 
205   // Recursion is always used, so bail out at once if we already hit the limit.
206   if (!MaxRecurse--)
207     return nullptr;
208 
209   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
210   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
211 
212   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
213   if (Op0 && Op0->getOpcode() == Opcode) {
214     Value *A = Op0->getOperand(0);
215     Value *B = Op0->getOperand(1);
216     Value *C = RHS;
217 
218     // Does "B op C" simplify?
219     if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
220       // It does!  Return "A op V" if it simplifies or is already available.
221       // If V equals B then "A op V" is just the LHS.
222       if (V == B) return LHS;
223       // Otherwise return "A op V" if it simplifies.
224       if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
225         ++NumReassoc;
226         return W;
227       }
228     }
229   }
230 
231   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
232   if (Op1 && Op1->getOpcode() == Opcode) {
233     Value *A = LHS;
234     Value *B = Op1->getOperand(0);
235     Value *C = Op1->getOperand(1);
236 
237     // Does "A op B" simplify?
238     if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
239       // It does!  Return "V op C" if it simplifies or is already available.
240       // If V equals B then "V op C" is just the RHS.
241       if (V == B) return RHS;
242       // Otherwise return "V op C" if it simplifies.
243       if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
244         ++NumReassoc;
245         return W;
246       }
247     }
248   }
249 
250   // The remaining transforms require commutativity as well as associativity.
251   if (!Instruction::isCommutative(Opcode))
252     return nullptr;
253 
254   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
255   if (Op0 && Op0->getOpcode() == Opcode) {
256     Value *A = Op0->getOperand(0);
257     Value *B = Op0->getOperand(1);
258     Value *C = RHS;
259 
260     // Does "C op A" simplify?
261     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
262       // It does!  Return "V op B" if it simplifies or is already available.
263       // If V equals A then "V op B" is just the LHS.
264       if (V == A) return LHS;
265       // Otherwise return "V op B" if it simplifies.
266       if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
267         ++NumReassoc;
268         return W;
269       }
270     }
271   }
272 
273   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
274   if (Op1 && Op1->getOpcode() == Opcode) {
275     Value *A = LHS;
276     Value *B = Op1->getOperand(0);
277     Value *C = Op1->getOperand(1);
278 
279     // Does "C op A" simplify?
280     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
281       // It does!  Return "B op V" if it simplifies or is already available.
282       // If V equals C then "B op V" is just the RHS.
283       if (V == C) return RHS;
284       // Otherwise return "B op V" if it simplifies.
285       if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
286         ++NumReassoc;
287         return W;
288       }
289     }
290   }
291 
292   return nullptr;
293 }
294 
295 /// In the case of a binary operation with a select instruction as an operand,
296 /// try to simplify the binop by seeing whether evaluating it on both branches
297 /// of the select results in the same value. Returns the common value if so,
298 /// otherwise returns null.
299 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
300                                     const Query &Q, unsigned MaxRecurse) {
301   // Recursion is always used, so bail out at once if we already hit the limit.
302   if (!MaxRecurse--)
303     return nullptr;
304 
305   SelectInst *SI;
306   if (isa<SelectInst>(LHS)) {
307     SI = cast<SelectInst>(LHS);
308   } else {
309     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
310     SI = cast<SelectInst>(RHS);
311   }
312 
313   // Evaluate the BinOp on the true and false branches of the select.
314   Value *TV;
315   Value *FV;
316   if (SI == LHS) {
317     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
318     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
319   } else {
320     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
321     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
322   }
323 
324   // If they simplified to the same value, then return the common value.
325   // If they both failed to simplify then return null.
326   if (TV == FV)
327     return TV;
328 
329   // If one branch simplified to undef, return the other one.
330   if (TV && isa<UndefValue>(TV))
331     return FV;
332   if (FV && isa<UndefValue>(FV))
333     return TV;
334 
335   // If applying the operation did not change the true and false select values,
336   // then the result of the binop is the select itself.
337   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
338     return SI;
339 
340   // If one branch simplified and the other did not, and the simplified
341   // value is equal to the unsimplified one, return the simplified value.
342   // For example, select (cond, X, X & Z) & Z -> X & Z.
343   if ((FV && !TV) || (TV && !FV)) {
344     // Check that the simplified value has the form "X op Y" where "op" is the
345     // same as the original operation.
346     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
347     if (Simplified && Simplified->getOpcode() == Opcode) {
348       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
349       // We already know that "op" is the same as for the simplified value.  See
350       // if the operands match too.  If so, return the simplified value.
351       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
352       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
353       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
354       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
355           Simplified->getOperand(1) == UnsimplifiedRHS)
356         return Simplified;
357       if (Simplified->isCommutative() &&
358           Simplified->getOperand(1) == UnsimplifiedLHS &&
359           Simplified->getOperand(0) == UnsimplifiedRHS)
360         return Simplified;
361     }
362   }
363 
364   return nullptr;
365 }
366 
367 /// In the case of a comparison with a select instruction, try to simplify the
368 /// comparison by seeing whether both branches of the select result in the same
369 /// value. Returns the common value if so, otherwise returns null.
370 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
371                                   Value *RHS, const Query &Q,
372                                   unsigned MaxRecurse) {
373   // Recursion is always used, so bail out at once if we already hit the limit.
374   if (!MaxRecurse--)
375     return nullptr;
376 
377   // Make sure the select is on the LHS.
378   if (!isa<SelectInst>(LHS)) {
379     std::swap(LHS, RHS);
380     Pred = CmpInst::getSwappedPredicate(Pred);
381   }
382   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
383   SelectInst *SI = cast<SelectInst>(LHS);
384   Value *Cond = SI->getCondition();
385   Value *TV = SI->getTrueValue();
386   Value *FV = SI->getFalseValue();
387 
388   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
389   // Does "cmp TV, RHS" simplify?
390   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
391   if (TCmp == Cond) {
392     // It not only simplified, it simplified to the select condition.  Replace
393     // it with 'true'.
394     TCmp = getTrue(Cond->getType());
395   } else if (!TCmp) {
396     // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
397     // condition then we can replace it with 'true'.  Otherwise give up.
398     if (!isSameCompare(Cond, Pred, TV, RHS))
399       return nullptr;
400     TCmp = getTrue(Cond->getType());
401   }
402 
403   // Does "cmp FV, RHS" simplify?
404   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
405   if (FCmp == Cond) {
406     // It not only simplified, it simplified to the select condition.  Replace
407     // it with 'false'.
408     FCmp = getFalse(Cond->getType());
409   } else if (!FCmp) {
410     // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
411     // condition then we can replace it with 'false'.  Otherwise give up.
412     if (!isSameCompare(Cond, Pred, FV, RHS))
413       return nullptr;
414     FCmp = getFalse(Cond->getType());
415   }
416 
417   // If both sides simplified to the same value, then use it as the result of
418   // the original comparison.
419   if (TCmp == FCmp)
420     return TCmp;
421 
422   // The remaining cases only make sense if the select condition has the same
423   // type as the result of the comparison, so bail out if this is not so.
424   if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
425     return nullptr;
426   // If the false value simplified to false, then the result of the compare
427   // is equal to "Cond && TCmp".  This also catches the case when the false
428   // value simplified to false and the true value to true, returning "Cond".
429   if (match(FCmp, m_Zero()))
430     if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
431       return V;
432   // If the true value simplified to true, then the result of the compare
433   // is equal to "Cond || FCmp".
434   if (match(TCmp, m_One()))
435     if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
436       return V;
437   // Finally, if the false value simplified to true and the true value to
438   // false, then the result of the compare is equal to "!Cond".
439   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
440     if (Value *V =
441         SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
442                         Q, MaxRecurse))
443       return V;
444 
445   return nullptr;
446 }
447 
448 /// In the case of a binary operation with an operand that is a PHI instruction,
449 /// try to simplify the binop by seeing whether evaluating it on the incoming
450 /// phi values yields the same result for every value. If so returns the common
451 /// value, otherwise returns null.
452 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
453                                  const Query &Q, unsigned MaxRecurse) {
454   // Recursion is always used, so bail out at once if we already hit the limit.
455   if (!MaxRecurse--)
456     return nullptr;
457 
458   PHINode *PI;
459   if (isa<PHINode>(LHS)) {
460     PI = cast<PHINode>(LHS);
461     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
462     if (!ValueDominatesPHI(RHS, PI, Q.DT))
463       return nullptr;
464   } else {
465     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
466     PI = cast<PHINode>(RHS);
467     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
468     if (!ValueDominatesPHI(LHS, PI, Q.DT))
469       return nullptr;
470   }
471 
472   // Evaluate the BinOp on the incoming phi values.
473   Value *CommonValue = nullptr;
474   for (Value *Incoming : PI->incoming_values()) {
475     // If the incoming value is the phi node itself, it can safely be skipped.
476     if (Incoming == PI) continue;
477     Value *V = PI == LHS ?
478       SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
479       SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
480     // If the operation failed to simplify, or simplified to a different value
481     // to previously, then give up.
482     if (!V || (CommonValue && V != CommonValue))
483       return nullptr;
484     CommonValue = V;
485   }
486 
487   return CommonValue;
488 }
489 
490 /// In the case of a comparison with a PHI instruction, try to simplify the
491 /// comparison by seeing whether comparing with all of the incoming phi values
492 /// yields the same result every time. If so returns the common result,
493 /// otherwise returns null.
494 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
495                                const Query &Q, unsigned MaxRecurse) {
496   // Recursion is always used, so bail out at once if we already hit the limit.
497   if (!MaxRecurse--)
498     return nullptr;
499 
500   // Make sure the phi is on the LHS.
501   if (!isa<PHINode>(LHS)) {
502     std::swap(LHS, RHS);
503     Pred = CmpInst::getSwappedPredicate(Pred);
504   }
505   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
506   PHINode *PI = cast<PHINode>(LHS);
507 
508   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
509   if (!ValueDominatesPHI(RHS, PI, Q.DT))
510     return nullptr;
511 
512   // Evaluate the BinOp on the incoming phi values.
513   Value *CommonValue = nullptr;
514   for (Value *Incoming : PI->incoming_values()) {
515     // If the incoming value is the phi node itself, it can safely be skipped.
516     if (Incoming == PI) continue;
517     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
518     // If the operation failed to simplify, or simplified to a different value
519     // to previously, then give up.
520     if (!V || (CommonValue && V != CommonValue))
521       return nullptr;
522     CommonValue = V;
523   }
524 
525   return CommonValue;
526 }
527 
528 /// Given operands for an Add, see if we can fold the result.
529 /// If not, this returns null.
530 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
531                               const Query &Q, unsigned MaxRecurse) {
532   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
533     if (Constant *CRHS = dyn_cast<Constant>(Op1))
534       return ConstantFoldBinaryOpOperands(Instruction::Add, CLHS, CRHS, Q.DL);
535 
536     // Canonicalize the constant to the RHS.
537     std::swap(Op0, Op1);
538   }
539 
540   // X + undef -> undef
541   if (match(Op1, m_Undef()))
542     return Op1;
543 
544   // X + 0 -> X
545   if (match(Op1, m_Zero()))
546     return Op0;
547 
548   // X + (Y - X) -> Y
549   // (Y - X) + X -> Y
550   // Eg: X + -X -> 0
551   Value *Y = nullptr;
552   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
553       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
554     return Y;
555 
556   // X + ~X -> -1   since   ~X = -X-1
557   if (match(Op0, m_Not(m_Specific(Op1))) ||
558       match(Op1, m_Not(m_Specific(Op0))))
559     return Constant::getAllOnesValue(Op0->getType());
560 
561   /// i1 add -> xor.
562   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
563     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
564       return V;
565 
566   // Try some generic simplifications for associative operations.
567   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
568                                           MaxRecurse))
569     return V;
570 
571   // Threading Add over selects and phi nodes is pointless, so don't bother.
572   // Threading over the select in "A + select(cond, B, C)" means evaluating
573   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
574   // only if B and C are equal.  If B and C are equal then (since we assume
575   // that operands have already been simplified) "select(cond, B, C)" should
576   // have been simplified to the common value of B and C already.  Analysing
577   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
578   // for threading over phi nodes.
579 
580   return nullptr;
581 }
582 
583 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
584                              const DataLayout &DL, const TargetLibraryInfo *TLI,
585                              const DominatorTree *DT, AssumptionCache *AC,
586                              const Instruction *CxtI) {
587   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
588                            RecursionLimit);
589 }
590 
591 /// \brief Compute the base pointer and cumulative constant offsets for V.
592 ///
593 /// This strips all constant offsets off of V, leaving it the base pointer, and
594 /// accumulates the total constant offset applied in the returned constant. It
595 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
596 /// no constant offsets applied.
597 ///
598 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
599 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
600 /// folding.
601 static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
602                                                 bool AllowNonInbounds = false) {
603   assert(V->getType()->getScalarType()->isPointerTy());
604 
605   Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
606   APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
607 
608   // Even though we don't look through PHI nodes, we could be called on an
609   // instruction in an unreachable block, which may be on a cycle.
610   SmallPtrSet<Value *, 4> Visited;
611   Visited.insert(V);
612   do {
613     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
614       if ((!AllowNonInbounds && !GEP->isInBounds()) ||
615           !GEP->accumulateConstantOffset(DL, Offset))
616         break;
617       V = GEP->getPointerOperand();
618     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
619       V = cast<Operator>(V)->getOperand(0);
620     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
621       if (GA->isInterposable())
622         break;
623       V = GA->getAliasee();
624     } else {
625       if (auto CS = CallSite(V))
626         if (Value *RV = CS.getReturnedArgOperand()) {
627           V = RV;
628           continue;
629         }
630       break;
631     }
632     assert(V->getType()->getScalarType()->isPointerTy() &&
633            "Unexpected operand type!");
634   } while (Visited.insert(V).second);
635 
636   Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
637   if (V->getType()->isVectorTy())
638     return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
639                                     OffsetIntPtr);
640   return OffsetIntPtr;
641 }
642 
643 /// \brief Compute the constant difference between two pointer values.
644 /// If the difference is not a constant, returns zero.
645 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
646                                           Value *RHS) {
647   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
648   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
649 
650   // If LHS and RHS are not related via constant offsets to the same base
651   // value, there is nothing we can do here.
652   if (LHS != RHS)
653     return nullptr;
654 
655   // Otherwise, the difference of LHS - RHS can be computed as:
656   //    LHS - RHS
657   //  = (LHSOffset + Base) - (RHSOffset + Base)
658   //  = LHSOffset - RHSOffset
659   return ConstantExpr::getSub(LHSOffset, RHSOffset);
660 }
661 
662 /// Given operands for a Sub, see if we can fold the result.
663 /// If not, this returns null.
664 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
665                               const Query &Q, unsigned MaxRecurse) {
666   if (Constant *CLHS = dyn_cast<Constant>(Op0))
667     if (Constant *CRHS = dyn_cast<Constant>(Op1))
668       return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
669 
670   // X - undef -> undef
671   // undef - X -> undef
672   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
673     return UndefValue::get(Op0->getType());
674 
675   // X - 0 -> X
676   if (match(Op1, m_Zero()))
677     return Op0;
678 
679   // X - X -> 0
680   if (Op0 == Op1)
681     return Constant::getNullValue(Op0->getType());
682 
683   // Is this a negation?
684   if (match(Op0, m_Zero())) {
685     // 0 - X -> 0 if the sub is NUW.
686     if (isNUW)
687       return Op0;
688 
689     unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
690     APInt KnownZero(BitWidth, 0);
691     APInt KnownOne(BitWidth, 0);
692     computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
693     if (KnownZero == ~APInt::getSignBit(BitWidth)) {
694       // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
695       // Op1 must be 0 because negating the minimum signed value is undefined.
696       if (isNSW)
697         return Op0;
698 
699       // 0 - X -> X if X is 0 or the minimum signed value.
700       return Op1;
701     }
702   }
703 
704   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
705   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
706   Value *X = nullptr, *Y = nullptr, *Z = Op1;
707   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
708     // See if "V === Y - Z" simplifies.
709     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
710       // It does!  Now see if "X + V" simplifies.
711       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
712         // It does, we successfully reassociated!
713         ++NumReassoc;
714         return W;
715       }
716     // See if "V === X - Z" simplifies.
717     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
718       // It does!  Now see if "Y + V" simplifies.
719       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
720         // It does, we successfully reassociated!
721         ++NumReassoc;
722         return W;
723       }
724   }
725 
726   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
727   // For example, X - (X + 1) -> -1
728   X = Op0;
729   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
730     // See if "V === X - Y" simplifies.
731     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
732       // It does!  Now see if "V - Z" simplifies.
733       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
734         // It does, we successfully reassociated!
735         ++NumReassoc;
736         return W;
737       }
738     // See if "V === X - Z" simplifies.
739     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
740       // It does!  Now see if "V - Y" simplifies.
741       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
742         // It does, we successfully reassociated!
743         ++NumReassoc;
744         return W;
745       }
746   }
747 
748   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
749   // For example, X - (X - Y) -> Y.
750   Z = Op0;
751   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
752     // See if "V === Z - X" simplifies.
753     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
754       // It does!  Now see if "V + Y" simplifies.
755       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
756         // It does, we successfully reassociated!
757         ++NumReassoc;
758         return W;
759       }
760 
761   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
762   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
763       match(Op1, m_Trunc(m_Value(Y))))
764     if (X->getType() == Y->getType())
765       // See if "V === X - Y" simplifies.
766       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
767         // It does!  Now see if "trunc V" simplifies.
768         if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
769                                         Q, MaxRecurse - 1))
770           // It does, return the simplified "trunc V".
771           return W;
772 
773   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
774   if (match(Op0, m_PtrToInt(m_Value(X))) &&
775       match(Op1, m_PtrToInt(m_Value(Y))))
776     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
777       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
778 
779   // i1 sub -> xor.
780   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
781     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
782       return V;
783 
784   // Threading Sub over selects and phi nodes is pointless, so don't bother.
785   // Threading over the select in "A - select(cond, B, C)" means evaluating
786   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
787   // only if B and C are equal.  If B and C are equal then (since we assume
788   // that operands have already been simplified) "select(cond, B, C)" should
789   // have been simplified to the common value of B and C already.  Analysing
790   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
791   // for threading over phi nodes.
792 
793   return nullptr;
794 }
795 
796 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
797                              const DataLayout &DL, const TargetLibraryInfo *TLI,
798                              const DominatorTree *DT, AssumptionCache *AC,
799                              const Instruction *CxtI) {
800   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
801                            RecursionLimit);
802 }
803 
804 /// Given operands for an FAdd, see if we can fold the result.  If not, this
805 /// returns null.
806 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
807                               const Query &Q, unsigned MaxRecurse) {
808   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
809     if (Constant *CRHS = dyn_cast<Constant>(Op1))
810       return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
811 
812     // Canonicalize the constant to the RHS.
813     std::swap(Op0, Op1);
814   }
815 
816   // fadd X, -0 ==> X
817   if (match(Op1, m_NegZero()))
818     return Op0;
819 
820   // fadd X, 0 ==> X, when we know X is not -0
821   if (match(Op1, m_Zero()) &&
822       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
823     return Op0;
824 
825   // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
826   //   where nnan and ninf have to occur at least once somewhere in this
827   //   expression
828   Value *SubOp = nullptr;
829   if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
830     SubOp = Op1;
831   else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
832     SubOp = Op0;
833   if (SubOp) {
834     Instruction *FSub = cast<Instruction>(SubOp);
835     if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
836         (FMF.noInfs() || FSub->hasNoInfs()))
837       return Constant::getNullValue(Op0->getType());
838   }
839 
840   return nullptr;
841 }
842 
843 /// Given operands for an FSub, see if we can fold the result.  If not, this
844 /// returns null.
845 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
846                               const Query &Q, unsigned MaxRecurse) {
847   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
848     if (Constant *CRHS = dyn_cast<Constant>(Op1))
849       return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
850   }
851 
852   // fsub X, 0 ==> X
853   if (match(Op1, m_Zero()))
854     return Op0;
855 
856   // fsub X, -0 ==> X, when we know X is not -0
857   if (match(Op1, m_NegZero()) &&
858       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
859     return Op0;
860 
861   // fsub -0.0, (fsub -0.0, X) ==> X
862   Value *X;
863   if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
864     return X;
865 
866   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
867   if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
868       match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
869     return X;
870 
871   // fsub nnan x, x ==> 0.0
872   if (FMF.noNaNs() && Op0 == Op1)
873     return Constant::getNullValue(Op0->getType());
874 
875   return nullptr;
876 }
877 
878 /// Given the operands for an FMul, see if we can fold the result
879 static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
880                                FastMathFlags FMF,
881                                const Query &Q,
882                                unsigned MaxRecurse) {
883  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
884     if (Constant *CRHS = dyn_cast<Constant>(Op1))
885       return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
886 
887     // Canonicalize the constant to the RHS.
888     std::swap(Op0, Op1);
889  }
890 
891  // fmul X, 1.0 ==> X
892  if (match(Op1, m_FPOne()))
893    return Op0;
894 
895  // fmul nnan nsz X, 0 ==> 0
896  if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
897    return Op1;
898 
899  return nullptr;
900 }
901 
902 /// Given operands for a Mul, see if we can fold the result.
903 /// If not, this returns null.
904 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
905                               unsigned MaxRecurse) {
906   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
907     if (Constant *CRHS = dyn_cast<Constant>(Op1))
908       return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
909 
910     // Canonicalize the constant to the RHS.
911     std::swap(Op0, Op1);
912   }
913 
914   // X * undef -> 0
915   if (match(Op1, m_Undef()))
916     return Constant::getNullValue(Op0->getType());
917 
918   // X * 0 -> 0
919   if (match(Op1, m_Zero()))
920     return Op1;
921 
922   // X * 1 -> X
923   if (match(Op1, m_One()))
924     return Op0;
925 
926   // (X / Y) * Y -> X if the division is exact.
927   Value *X = nullptr;
928   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
929       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
930     return X;
931 
932   // i1 mul -> and.
933   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
934     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
935       return V;
936 
937   // Try some generic simplifications for associative operations.
938   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
939                                           MaxRecurse))
940     return V;
941 
942   // Mul distributes over Add.  Try some generic simplifications based on this.
943   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
944                              Q, MaxRecurse))
945     return V;
946 
947   // If the operation is with the result of a select instruction, check whether
948   // operating on either branch of the select always yields the same value.
949   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
950     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
951                                          MaxRecurse))
952       return V;
953 
954   // If the operation is with the result of a phi instruction, check whether
955   // operating on all incoming values of the phi always yields the same value.
956   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
957     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
958                                       MaxRecurse))
959       return V;
960 
961   return nullptr;
962 }
963 
964 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
965                               const DataLayout &DL,
966                               const TargetLibraryInfo *TLI,
967                               const DominatorTree *DT, AssumptionCache *AC,
968                               const Instruction *CxtI) {
969   return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
970                             RecursionLimit);
971 }
972 
973 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
974                               const DataLayout &DL,
975                               const TargetLibraryInfo *TLI,
976                               const DominatorTree *DT, AssumptionCache *AC,
977                               const Instruction *CxtI) {
978   return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
979                             RecursionLimit);
980 }
981 
982 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
983                               const DataLayout &DL,
984                               const TargetLibraryInfo *TLI,
985                               const DominatorTree *DT, AssumptionCache *AC,
986                               const Instruction *CxtI) {
987   return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
988                             RecursionLimit);
989 }
990 
991 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
992                              const TargetLibraryInfo *TLI,
993                              const DominatorTree *DT, AssumptionCache *AC,
994                              const Instruction *CxtI) {
995   return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
996                            RecursionLimit);
997 }
998 
999 /// Given operands for an SDiv or UDiv, see if we can fold the result.
1000 /// If not, this returns null.
1001 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1002                           const Query &Q, unsigned MaxRecurse) {
1003   if (Constant *C0 = dyn_cast<Constant>(Op0))
1004     if (Constant *C1 = dyn_cast<Constant>(Op1))
1005       return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
1006 
1007   bool isSigned = Opcode == Instruction::SDiv;
1008 
1009   // X / undef -> undef
1010   if (match(Op1, m_Undef()))
1011     return Op1;
1012 
1013   // X / 0 -> undef, we don't need to preserve faults!
1014   if (match(Op1, m_Zero()))
1015     return UndefValue::get(Op1->getType());
1016 
1017   // undef / X -> 0
1018   if (match(Op0, m_Undef()))
1019     return Constant::getNullValue(Op0->getType());
1020 
1021   // 0 / X -> 0, we don't need to preserve faults!
1022   if (match(Op0, m_Zero()))
1023     return Op0;
1024 
1025   // X / 1 -> X
1026   if (match(Op1, m_One()))
1027     return Op0;
1028 
1029   if (Op0->getType()->isIntegerTy(1))
1030     // It can't be division by zero, hence it must be division by one.
1031     return Op0;
1032 
1033   // X / X -> 1
1034   if (Op0 == Op1)
1035     return ConstantInt::get(Op0->getType(), 1);
1036 
1037   // (X * Y) / Y -> X if the multiplication does not overflow.
1038   Value *X = nullptr, *Y = nullptr;
1039   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1040     if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1041     OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1042     // If the Mul knows it does not overflow, then we are good to go.
1043     if ((isSigned && Mul->hasNoSignedWrap()) ||
1044         (!isSigned && Mul->hasNoUnsignedWrap()))
1045       return X;
1046     // If X has the form X = A / Y then X * Y cannot overflow.
1047     if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1048       if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1049         return X;
1050   }
1051 
1052   // (X rem Y) / Y -> 0
1053   if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1054       (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1055     return Constant::getNullValue(Op0->getType());
1056 
1057   // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1058   ConstantInt *C1, *C2;
1059   if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1060       match(Op1, m_ConstantInt(C2))) {
1061     bool Overflow;
1062     C1->getValue().umul_ov(C2->getValue(), Overflow);
1063     if (Overflow)
1064       return Constant::getNullValue(Op0->getType());
1065   }
1066 
1067   // If the operation is with the result of a select instruction, check whether
1068   // operating on either branch of the select always yields the same value.
1069   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1070     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1071       return V;
1072 
1073   // If the operation is with the result of a phi instruction, check whether
1074   // operating on all incoming values of the phi always yields the same value.
1075   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1076     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1077       return V;
1078 
1079   return nullptr;
1080 }
1081 
1082 /// Given operands for an SDiv, see if we can fold the result.
1083 /// If not, this returns null.
1084 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1085                                unsigned MaxRecurse) {
1086   if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1087     return V;
1088 
1089   return nullptr;
1090 }
1091 
1092 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
1093                               const TargetLibraryInfo *TLI,
1094                               const DominatorTree *DT, AssumptionCache *AC,
1095                               const Instruction *CxtI) {
1096   return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1097                             RecursionLimit);
1098 }
1099 
1100 /// Given operands for a UDiv, see if we can fold the result.
1101 /// If not, this returns null.
1102 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1103                                unsigned MaxRecurse) {
1104   if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1105     return V;
1106 
1107   return nullptr;
1108 }
1109 
1110 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
1111                               const TargetLibraryInfo *TLI,
1112                               const DominatorTree *DT, AssumptionCache *AC,
1113                               const Instruction *CxtI) {
1114   return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1115                             RecursionLimit);
1116 }
1117 
1118 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1119                                const Query &Q, unsigned) {
1120   // undef / X -> undef    (the undef could be a snan).
1121   if (match(Op0, m_Undef()))
1122     return Op0;
1123 
1124   // X / undef -> undef
1125   if (match(Op1, m_Undef()))
1126     return Op1;
1127 
1128   // 0 / X -> 0
1129   // Requires that NaNs are off (X could be zero) and signed zeroes are
1130   // ignored (X could be positive or negative, so the output sign is unknown).
1131   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1132     return Op0;
1133 
1134   if (FMF.noNaNs()) {
1135     // X / X -> 1.0 is legal when NaNs are ignored.
1136     if (Op0 == Op1)
1137       return ConstantFP::get(Op0->getType(), 1.0);
1138 
1139     // -X /  X -> -1.0 and
1140     //  X / -X -> -1.0 are legal when NaNs are ignored.
1141     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1142     if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1143          BinaryOperator::getFNegArgument(Op0) == Op1) ||
1144         (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1145          BinaryOperator::getFNegArgument(Op1) == Op0))
1146       return ConstantFP::get(Op0->getType(), -1.0);
1147   }
1148 
1149   return nullptr;
1150 }
1151 
1152 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1153                               const DataLayout &DL,
1154                               const TargetLibraryInfo *TLI,
1155                               const DominatorTree *DT, AssumptionCache *AC,
1156                               const Instruction *CxtI) {
1157   return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
1158                             RecursionLimit);
1159 }
1160 
1161 /// Given operands for an SRem or URem, see if we can fold the result.
1162 /// If not, this returns null.
1163 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1164                           const Query &Q, unsigned MaxRecurse) {
1165   if (Constant *C0 = dyn_cast<Constant>(Op0))
1166     if (Constant *C1 = dyn_cast<Constant>(Op1))
1167       return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
1168 
1169   // X % undef -> undef
1170   if (match(Op1, m_Undef()))
1171     return Op1;
1172 
1173   // undef % X -> 0
1174   if (match(Op0, m_Undef()))
1175     return Constant::getNullValue(Op0->getType());
1176 
1177   // 0 % X -> 0, we don't need to preserve faults!
1178   if (match(Op0, m_Zero()))
1179     return Op0;
1180 
1181   // X % 0 -> undef, we don't need to preserve faults!
1182   if (match(Op1, m_Zero()))
1183     return UndefValue::get(Op0->getType());
1184 
1185   // X % 1 -> 0
1186   if (match(Op1, m_One()))
1187     return Constant::getNullValue(Op0->getType());
1188 
1189   if (Op0->getType()->isIntegerTy(1))
1190     // It can't be remainder by zero, hence it must be remainder by one.
1191     return Constant::getNullValue(Op0->getType());
1192 
1193   // X % X -> 0
1194   if (Op0 == Op1)
1195     return Constant::getNullValue(Op0->getType());
1196 
1197   // (X % Y) % Y -> X % Y
1198   if ((Opcode == Instruction::SRem &&
1199        match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1200       (Opcode == Instruction::URem &&
1201        match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1202     return Op0;
1203 
1204   // If the operation is with the result of a select instruction, check whether
1205   // operating on either branch of the select always yields the same value.
1206   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1207     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1208       return V;
1209 
1210   // If the operation is with the result of a phi instruction, check whether
1211   // operating on all incoming values of the phi always yields the same value.
1212   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1213     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1214       return V;
1215 
1216   return nullptr;
1217 }
1218 
1219 /// Given operands for an SRem, see if we can fold the result.
1220 /// If not, this returns null.
1221 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1222                                unsigned MaxRecurse) {
1223   if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1224     return V;
1225 
1226   return nullptr;
1227 }
1228 
1229 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
1230                               const TargetLibraryInfo *TLI,
1231                               const DominatorTree *DT, AssumptionCache *AC,
1232                               const Instruction *CxtI) {
1233   return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1234                             RecursionLimit);
1235 }
1236 
1237 /// Given operands for a URem, see if we can fold the result.
1238 /// If not, this returns null.
1239 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1240                                unsigned MaxRecurse) {
1241   if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1242     return V;
1243 
1244   return nullptr;
1245 }
1246 
1247 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
1248                               const TargetLibraryInfo *TLI,
1249                               const DominatorTree *DT, AssumptionCache *AC,
1250                               const Instruction *CxtI) {
1251   return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1252                             RecursionLimit);
1253 }
1254 
1255 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1256                                const Query &, unsigned) {
1257   // undef % X -> undef    (the undef could be a snan).
1258   if (match(Op0, m_Undef()))
1259     return Op0;
1260 
1261   // X % undef -> undef
1262   if (match(Op1, m_Undef()))
1263     return Op1;
1264 
1265   // 0 % X -> 0
1266   // Requires that NaNs are off (X could be zero) and signed zeroes are
1267   // ignored (X could be positive or negative, so the output sign is unknown).
1268   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1269     return Op0;
1270 
1271   return nullptr;
1272 }
1273 
1274 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1275                               const DataLayout &DL,
1276                               const TargetLibraryInfo *TLI,
1277                               const DominatorTree *DT, AssumptionCache *AC,
1278                               const Instruction *CxtI) {
1279   return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
1280                             RecursionLimit);
1281 }
1282 
1283 /// Returns true if a shift by \c Amount always yields undef.
1284 static bool isUndefShift(Value *Amount) {
1285   Constant *C = dyn_cast<Constant>(Amount);
1286   if (!C)
1287     return false;
1288 
1289   // X shift by undef -> undef because it may shift by the bitwidth.
1290   if (isa<UndefValue>(C))
1291     return true;
1292 
1293   // Shifting by the bitwidth or more is undefined.
1294   if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1295     if (CI->getValue().getLimitedValue() >=
1296         CI->getType()->getScalarSizeInBits())
1297       return true;
1298 
1299   // If all lanes of a vector shift are undefined the whole shift is.
1300   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1301     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1302       if (!isUndefShift(C->getAggregateElement(I)))
1303         return false;
1304     return true;
1305   }
1306 
1307   return false;
1308 }
1309 
1310 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1311 /// If not, this returns null.
1312 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1313                             const Query &Q, unsigned MaxRecurse) {
1314   if (Constant *C0 = dyn_cast<Constant>(Op0))
1315     if (Constant *C1 = dyn_cast<Constant>(Op1))
1316       return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
1317 
1318   // 0 shift by X -> 0
1319   if (match(Op0, m_Zero()))
1320     return Op0;
1321 
1322   // X shift by 0 -> X
1323   if (match(Op1, m_Zero()))
1324     return Op0;
1325 
1326   // Fold undefined shifts.
1327   if (isUndefShift(Op1))
1328     return UndefValue::get(Op0->getType());
1329 
1330   // If the operation is with the result of a select instruction, check whether
1331   // operating on either branch of the select always yields the same value.
1332   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1333     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1334       return V;
1335 
1336   // If the operation is with the result of a phi instruction, check whether
1337   // operating on all incoming values of the phi always yields the same value.
1338   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1339     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1340       return V;
1341 
1342   // If any bits in the shift amount make that value greater than or equal to
1343   // the number of bits in the type, the shift is undefined.
1344   unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1345   APInt KnownZero(BitWidth, 0);
1346   APInt KnownOne(BitWidth, 0);
1347   computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1348   if (KnownOne.getLimitedValue() >= BitWidth)
1349     return UndefValue::get(Op0->getType());
1350 
1351   // If all valid bits in the shift amount are known zero, the first operand is
1352   // unchanged.
1353   unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1354   APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1355   if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1356     return Op0;
1357 
1358   return nullptr;
1359 }
1360 
1361 /// \brief Given operands for an Shl, LShr or AShr, see if we can
1362 /// fold the result.  If not, this returns null.
1363 static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1364                                  bool isExact, const Query &Q,
1365                                  unsigned MaxRecurse) {
1366   if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1367     return V;
1368 
1369   // X >> X -> 0
1370   if (Op0 == Op1)
1371     return Constant::getNullValue(Op0->getType());
1372 
1373   // undef >> X -> 0
1374   // undef >> X -> undef (if it's exact)
1375   if (match(Op0, m_Undef()))
1376     return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1377 
1378   // The low bit cannot be shifted out of an exact shift if it is set.
1379   if (isExact) {
1380     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1381     APInt Op0KnownZero(BitWidth, 0);
1382     APInt Op0KnownOne(BitWidth, 0);
1383     computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1384                      Q.CxtI, Q.DT);
1385     if (Op0KnownOne[0])
1386       return Op0;
1387   }
1388 
1389   return nullptr;
1390 }
1391 
1392 /// Given operands for an Shl, see if we can fold the result.
1393 /// If not, this returns null.
1394 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1395                               const Query &Q, unsigned MaxRecurse) {
1396   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1397     return V;
1398 
1399   // undef << X -> 0
1400   // undef << X -> undef if (if it's NSW/NUW)
1401   if (match(Op0, m_Undef()))
1402     return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1403 
1404   // (X >> A) << A -> X
1405   Value *X;
1406   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1407     return X;
1408   return nullptr;
1409 }
1410 
1411 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1412                              const DataLayout &DL, const TargetLibraryInfo *TLI,
1413                              const DominatorTree *DT, AssumptionCache *AC,
1414                              const Instruction *CxtI) {
1415   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
1416                            RecursionLimit);
1417 }
1418 
1419 /// Given operands for an LShr, see if we can fold the result.
1420 /// If not, this returns null.
1421 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1422                                const Query &Q, unsigned MaxRecurse) {
1423   if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1424                                     MaxRecurse))
1425       return V;
1426 
1427   // (X << A) >> A -> X
1428   Value *X;
1429   if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1430     return X;
1431 
1432   return nullptr;
1433 }
1434 
1435 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1436                               const DataLayout &DL,
1437                               const TargetLibraryInfo *TLI,
1438                               const DominatorTree *DT, AssumptionCache *AC,
1439                               const Instruction *CxtI) {
1440   return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
1441                             RecursionLimit);
1442 }
1443 
1444 /// Given operands for an AShr, see if we can fold the result.
1445 /// If not, this returns null.
1446 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1447                                const Query &Q, unsigned MaxRecurse) {
1448   if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1449                                     MaxRecurse))
1450     return V;
1451 
1452   // all ones >>a X -> all ones
1453   if (match(Op0, m_AllOnes()))
1454     return Op0;
1455 
1456   // (X << A) >> A -> X
1457   Value *X;
1458   if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1459     return X;
1460 
1461   // Arithmetic shifting an all-sign-bit value is a no-op.
1462   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1463   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1464     return Op0;
1465 
1466   return nullptr;
1467 }
1468 
1469 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1470                               const DataLayout &DL,
1471                               const TargetLibraryInfo *TLI,
1472                               const DominatorTree *DT, AssumptionCache *AC,
1473                               const Instruction *CxtI) {
1474   return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
1475                             RecursionLimit);
1476 }
1477 
1478 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1479                                          ICmpInst *UnsignedICmp, bool IsAnd) {
1480   Value *X, *Y;
1481 
1482   ICmpInst::Predicate EqPred;
1483   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1484       !ICmpInst::isEquality(EqPred))
1485     return nullptr;
1486 
1487   ICmpInst::Predicate UnsignedPred;
1488   if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1489       ICmpInst::isUnsigned(UnsignedPred))
1490     ;
1491   else if (match(UnsignedICmp,
1492                  m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1493            ICmpInst::isUnsigned(UnsignedPred))
1494     UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1495   else
1496     return nullptr;
1497 
1498   // X < Y && Y != 0  -->  X < Y
1499   // X < Y || Y != 0  -->  Y != 0
1500   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1501     return IsAnd ? UnsignedICmp : ZeroICmp;
1502 
1503   // X >= Y || Y != 0  -->  true
1504   // X >= Y || Y == 0  -->  X >= Y
1505   if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1506     if (EqPred == ICmpInst::ICMP_NE)
1507       return getTrue(UnsignedICmp->getType());
1508     return UnsignedICmp;
1509   }
1510 
1511   // X < Y && Y == 0  -->  false
1512   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1513       IsAnd)
1514     return getFalse(UnsignedICmp->getType());
1515 
1516   return nullptr;
1517 }
1518 
1519 static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1520   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1521     return X;
1522 
1523   // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
1524   Type *ITy = Op0->getType();
1525   ICmpInst::Predicate Pred0, Pred1;
1526   const APInt *C0, *C1;
1527   Value *V;
1528   if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1529       match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1530     // Make a constant range that's the intersection of the two icmp ranges.
1531     // If the intersection is empty, we know that the result is false.
1532     auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1533     auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1534     if (Range0.intersectWith(Range1).isEmptySet())
1535       return getFalse(ITy);
1536   }
1537 
1538   // (icmp (add V, C0), C1) & (icmp V, C0)
1539   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1540     return nullptr;
1541 
1542   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1543     return nullptr;
1544 
1545   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1546   if (AddInst->getOperand(1) != Op1->getOperand(1))
1547     return nullptr;
1548 
1549   bool isNSW = AddInst->hasNoSignedWrap();
1550   bool isNUW = AddInst->hasNoUnsignedWrap();
1551 
1552   const APInt Delta = *C1 - *C0;
1553   if (C0->isStrictlyPositive()) {
1554     if (Delta == 2) {
1555       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1556         return getFalse(ITy);
1557       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1558         return getFalse(ITy);
1559     }
1560     if (Delta == 1) {
1561       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1562         return getFalse(ITy);
1563       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1564         return getFalse(ITy);
1565     }
1566   }
1567   if (C0->getBoolValue() && isNUW) {
1568     if (Delta == 2)
1569       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1570         return getFalse(ITy);
1571     if (Delta == 1)
1572       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1573         return getFalse(ITy);
1574   }
1575 
1576   return nullptr;
1577 }
1578 
1579 /// Given operands for an And, see if we can fold the result.
1580 /// If not, this returns null.
1581 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1582                               unsigned MaxRecurse) {
1583   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1584     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1585       return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
1586 
1587     // Canonicalize the constant to the RHS.
1588     std::swap(Op0, Op1);
1589   }
1590 
1591   // X & undef -> 0
1592   if (match(Op1, m_Undef()))
1593     return Constant::getNullValue(Op0->getType());
1594 
1595   // X & X = X
1596   if (Op0 == Op1)
1597     return Op0;
1598 
1599   // X & 0 = 0
1600   if (match(Op1, m_Zero()))
1601     return Op1;
1602 
1603   // X & -1 = X
1604   if (match(Op1, m_AllOnes()))
1605     return Op0;
1606 
1607   // A & ~A  =  ~A & A  =  0
1608   if (match(Op0, m_Not(m_Specific(Op1))) ||
1609       match(Op1, m_Not(m_Specific(Op0))))
1610     return Constant::getNullValue(Op0->getType());
1611 
1612   // (A | ?) & A = A
1613   Value *A = nullptr, *B = nullptr;
1614   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1615       (A == Op1 || B == Op1))
1616     return Op1;
1617 
1618   // A & (A | ?) = A
1619   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1620       (A == Op0 || B == Op0))
1621     return Op0;
1622 
1623   // A & (-A) = A if A is a power of two or zero.
1624   if (match(Op0, m_Neg(m_Specific(Op1))) ||
1625       match(Op1, m_Neg(m_Specific(Op0)))) {
1626     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1627                                Q.DT))
1628       return Op0;
1629     if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1630                                Q.DT))
1631       return Op1;
1632   }
1633 
1634   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1635     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1636       if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1637         return V;
1638       if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1639         return V;
1640     }
1641   }
1642 
1643   // The compares may be hidden behind casts. Look through those and try the
1644   // same folds as above.
1645   auto *Cast0 = dyn_cast<CastInst>(Op0);
1646   auto *Cast1 = dyn_cast<CastInst>(Op1);
1647   if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1648       Cast0->getSrcTy() == Cast1->getSrcTy()) {
1649     auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1650     auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1651     if (Cmp0 && Cmp1) {
1652       Instruction::CastOps CastOpc = Cast0->getOpcode();
1653       Type *ResultType = Cast0->getType();
1654       if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1655         return ConstantExpr::getCast(CastOpc, V, ResultType);
1656       if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1657         return ConstantExpr::getCast(CastOpc, V, ResultType);
1658     }
1659   }
1660 
1661   // Try some generic simplifications for associative operations.
1662   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1663                                           MaxRecurse))
1664     return V;
1665 
1666   // And distributes over Or.  Try some generic simplifications based on this.
1667   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1668                              Q, MaxRecurse))
1669     return V;
1670 
1671   // And distributes over Xor.  Try some generic simplifications based on this.
1672   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1673                              Q, MaxRecurse))
1674     return V;
1675 
1676   // If the operation is with the result of a select instruction, check whether
1677   // operating on either branch of the select always yields the same value.
1678   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1679     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1680                                          MaxRecurse))
1681       return V;
1682 
1683   // If the operation is with the result of a phi instruction, check whether
1684   // operating on all incoming values of the phi always yields the same value.
1685   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1686     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1687                                       MaxRecurse))
1688       return V;
1689 
1690   return nullptr;
1691 }
1692 
1693 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
1694                              const TargetLibraryInfo *TLI,
1695                              const DominatorTree *DT, AssumptionCache *AC,
1696                              const Instruction *CxtI) {
1697   return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1698                            RecursionLimit);
1699 }
1700 
1701 /// Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1702 /// contains all possible values.
1703 static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1704   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1705     return X;
1706 
1707   // (icmp (add V, C0), C1) | (icmp V, C0)
1708   ICmpInst::Predicate Pred0, Pred1;
1709   const APInt *C0, *C1;
1710   Value *V;
1711   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1712     return nullptr;
1713 
1714   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1715     return nullptr;
1716 
1717   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1718   if (AddInst->getOperand(1) != Op1->getOperand(1))
1719     return nullptr;
1720 
1721   Type *ITy = Op0->getType();
1722   bool isNSW = AddInst->hasNoSignedWrap();
1723   bool isNUW = AddInst->hasNoUnsignedWrap();
1724 
1725   const APInt Delta = *C1 - *C0;
1726   if (C0->isStrictlyPositive()) {
1727     if (Delta == 2) {
1728       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1729         return getTrue(ITy);
1730       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1731         return getTrue(ITy);
1732     }
1733     if (Delta == 1) {
1734       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1735         return getTrue(ITy);
1736       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1737         return getTrue(ITy);
1738     }
1739   }
1740   if (C0->getBoolValue() && isNUW) {
1741     if (Delta == 2)
1742       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1743         return getTrue(ITy);
1744     if (Delta == 1)
1745       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1746         return getTrue(ITy);
1747   }
1748 
1749   return nullptr;
1750 }
1751 
1752 /// Given operands for an Or, see if we can fold the result.
1753 /// If not, this returns null.
1754 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1755                              unsigned MaxRecurse) {
1756   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1757     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1758       return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
1759 
1760     // Canonicalize the constant to the RHS.
1761     std::swap(Op0, Op1);
1762   }
1763 
1764   // X | undef -> -1
1765   if (match(Op1, m_Undef()))
1766     return Constant::getAllOnesValue(Op0->getType());
1767 
1768   // X | X = X
1769   if (Op0 == Op1)
1770     return Op0;
1771 
1772   // X | 0 = X
1773   if (match(Op1, m_Zero()))
1774     return Op0;
1775 
1776   // X | -1 = -1
1777   if (match(Op1, m_AllOnes()))
1778     return Op1;
1779 
1780   // A | ~A  =  ~A | A  =  -1
1781   if (match(Op0, m_Not(m_Specific(Op1))) ||
1782       match(Op1, m_Not(m_Specific(Op0))))
1783     return Constant::getAllOnesValue(Op0->getType());
1784 
1785   // (A & ?) | A = A
1786   Value *A = nullptr, *B = nullptr;
1787   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1788       (A == Op1 || B == Op1))
1789     return Op1;
1790 
1791   // A | (A & ?) = A
1792   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1793       (A == Op0 || B == Op0))
1794     return Op0;
1795 
1796   // ~(A & ?) | A = -1
1797   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1798       (A == Op1 || B == Op1))
1799     return Constant::getAllOnesValue(Op1->getType());
1800 
1801   // A | ~(A & ?) = -1
1802   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1803       (A == Op0 || B == Op0))
1804     return Constant::getAllOnesValue(Op0->getType());
1805 
1806   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1807     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1808       if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1809         return V;
1810       if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1811         return V;
1812     }
1813   }
1814 
1815   // Try some generic simplifications for associative operations.
1816   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1817                                           MaxRecurse))
1818     return V;
1819 
1820   // Or distributes over And.  Try some generic simplifications based on this.
1821   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1822                              MaxRecurse))
1823     return V;
1824 
1825   // If the operation is with the result of a select instruction, check whether
1826   // operating on either branch of the select always yields the same value.
1827   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1828     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1829                                          MaxRecurse))
1830       return V;
1831 
1832   // (A & C)|(B & D)
1833   Value *C = nullptr, *D = nullptr;
1834   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1835       match(Op1, m_And(m_Value(B), m_Value(D)))) {
1836     ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1837     ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1838     if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1839       // (A & C1)|(B & C2)
1840       // If we have: ((V + N) & C1) | (V & C2)
1841       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1842       // replace with V+N.
1843       Value *V1, *V2;
1844       if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1845           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1846         // Add commutes, try both ways.
1847         if (V1 == B &&
1848             MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1849           return A;
1850         if (V2 == B &&
1851             MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1852           return A;
1853       }
1854       // Or commutes, try both ways.
1855       if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1856           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1857         // Add commutes, try both ways.
1858         if (V1 == A &&
1859             MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1860           return B;
1861         if (V2 == A &&
1862             MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1863           return B;
1864       }
1865     }
1866   }
1867 
1868   // If the operation is with the result of a phi instruction, check whether
1869   // operating on all incoming values of the phi always yields the same value.
1870   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1871     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1872       return V;
1873 
1874   return nullptr;
1875 }
1876 
1877 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
1878                             const TargetLibraryInfo *TLI,
1879                             const DominatorTree *DT, AssumptionCache *AC,
1880                             const Instruction *CxtI) {
1881   return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1882                           RecursionLimit);
1883 }
1884 
1885 /// Given operands for a Xor, see if we can fold the result.
1886 /// If not, this returns null.
1887 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1888                               unsigned MaxRecurse) {
1889   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1890     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1891       return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
1892 
1893     // Canonicalize the constant to the RHS.
1894     std::swap(Op0, Op1);
1895   }
1896 
1897   // A ^ undef -> undef
1898   if (match(Op1, m_Undef()))
1899     return Op1;
1900 
1901   // A ^ 0 = A
1902   if (match(Op1, m_Zero()))
1903     return Op0;
1904 
1905   // A ^ A = 0
1906   if (Op0 == Op1)
1907     return Constant::getNullValue(Op0->getType());
1908 
1909   // A ^ ~A  =  ~A ^ A  =  -1
1910   if (match(Op0, m_Not(m_Specific(Op1))) ||
1911       match(Op1, m_Not(m_Specific(Op0))))
1912     return Constant::getAllOnesValue(Op0->getType());
1913 
1914   // Try some generic simplifications for associative operations.
1915   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1916                                           MaxRecurse))
1917     return V;
1918 
1919   // Threading Xor over selects and phi nodes is pointless, so don't bother.
1920   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1921   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1922   // only if B and C are equal.  If B and C are equal then (since we assume
1923   // that operands have already been simplified) "select(cond, B, C)" should
1924   // have been simplified to the common value of B and C already.  Analysing
1925   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1926   // for threading over phi nodes.
1927 
1928   return nullptr;
1929 }
1930 
1931 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
1932                              const TargetLibraryInfo *TLI,
1933                              const DominatorTree *DT, AssumptionCache *AC,
1934                              const Instruction *CxtI) {
1935   return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1936                            RecursionLimit);
1937 }
1938 
1939 static Type *GetCompareTy(Value *Op) {
1940   return CmpInst::makeCmpResultType(Op->getType());
1941 }
1942 
1943 /// Rummage around inside V looking for something equivalent to the comparison
1944 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
1945 /// Helper function for analyzing max/min idioms.
1946 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1947                                          Value *LHS, Value *RHS) {
1948   SelectInst *SI = dyn_cast<SelectInst>(V);
1949   if (!SI)
1950     return nullptr;
1951   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1952   if (!Cmp)
1953     return nullptr;
1954   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1955   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1956     return Cmp;
1957   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1958       LHS == CmpRHS && RHS == CmpLHS)
1959     return Cmp;
1960   return nullptr;
1961 }
1962 
1963 // A significant optimization not implemented here is assuming that alloca
1964 // addresses are not equal to incoming argument values. They don't *alias*,
1965 // as we say, but that doesn't mean they aren't equal, so we take a
1966 // conservative approach.
1967 //
1968 // This is inspired in part by C++11 5.10p1:
1969 //   "Two pointers of the same type compare equal if and only if they are both
1970 //    null, both point to the same function, or both represent the same
1971 //    address."
1972 //
1973 // This is pretty permissive.
1974 //
1975 // It's also partly due to C11 6.5.9p6:
1976 //   "Two pointers compare equal if and only if both are null pointers, both are
1977 //    pointers to the same object (including a pointer to an object and a
1978 //    subobject at its beginning) or function, both are pointers to one past the
1979 //    last element of the same array object, or one is a pointer to one past the
1980 //    end of one array object and the other is a pointer to the start of a
1981 //    different array object that happens to immediately follow the first array
1982 //    object in the address space.)
1983 //
1984 // C11's version is more restrictive, however there's no reason why an argument
1985 // couldn't be a one-past-the-end value for a stack object in the caller and be
1986 // equal to the beginning of a stack object in the callee.
1987 //
1988 // If the C and C++ standards are ever made sufficiently restrictive in this
1989 // area, it may be possible to update LLVM's semantics accordingly and reinstate
1990 // this optimization.
1991 static Constant *
1992 computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
1993                    const DominatorTree *DT, CmpInst::Predicate Pred,
1994                    const Instruction *CxtI, Value *LHS, Value *RHS) {
1995   // First, skip past any trivial no-ops.
1996   LHS = LHS->stripPointerCasts();
1997   RHS = RHS->stripPointerCasts();
1998 
1999   // A non-null pointer is not equal to a null pointer.
2000   if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
2001       (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2002     return ConstantInt::get(GetCompareTy(LHS),
2003                             !CmpInst::isTrueWhenEqual(Pred));
2004 
2005   // We can only fold certain predicates on pointer comparisons.
2006   switch (Pred) {
2007   default:
2008     return nullptr;
2009 
2010     // Equality comaprisons are easy to fold.
2011   case CmpInst::ICMP_EQ:
2012   case CmpInst::ICMP_NE:
2013     break;
2014 
2015     // We can only handle unsigned relational comparisons because 'inbounds' on
2016     // a GEP only protects against unsigned wrapping.
2017   case CmpInst::ICMP_UGT:
2018   case CmpInst::ICMP_UGE:
2019   case CmpInst::ICMP_ULT:
2020   case CmpInst::ICMP_ULE:
2021     // However, we have to switch them to their signed variants to handle
2022     // negative indices from the base pointer.
2023     Pred = ICmpInst::getSignedPredicate(Pred);
2024     break;
2025   }
2026 
2027   // Strip off any constant offsets so that we can reason about them.
2028   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2029   // here and compare base addresses like AliasAnalysis does, however there are
2030   // numerous hazards. AliasAnalysis and its utilities rely on special rules
2031   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2032   // doesn't need to guarantee pointer inequality when it says NoAlias.
2033   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2034   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
2035 
2036   // If LHS and RHS are related via constant offsets to the same base
2037   // value, we can replace it with an icmp which just compares the offsets.
2038   if (LHS == RHS)
2039     return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
2040 
2041   // Various optimizations for (in)equality comparisons.
2042   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2043     // Different non-empty allocations that exist at the same time have
2044     // different addresses (if the program can tell). Global variables always
2045     // exist, so they always exist during the lifetime of each other and all
2046     // allocas. Two different allocas usually have different addresses...
2047     //
2048     // However, if there's an @llvm.stackrestore dynamically in between two
2049     // allocas, they may have the same address. It's tempting to reduce the
2050     // scope of the problem by only looking at *static* allocas here. That would
2051     // cover the majority of allocas while significantly reducing the likelihood
2052     // of having an @llvm.stackrestore pop up in the middle. However, it's not
2053     // actually impossible for an @llvm.stackrestore to pop up in the middle of
2054     // an entry block. Also, if we have a block that's not attached to a
2055     // function, we can't tell if it's "static" under the current definition.
2056     // Theoretically, this problem could be fixed by creating a new kind of
2057     // instruction kind specifically for static allocas. Such a new instruction
2058     // could be required to be at the top of the entry block, thus preventing it
2059     // from being subject to a @llvm.stackrestore. Instcombine could even
2060     // convert regular allocas into these special allocas. It'd be nifty.
2061     // However, until then, this problem remains open.
2062     //
2063     // So, we'll assume that two non-empty allocas have different addresses
2064     // for now.
2065     //
2066     // With all that, if the offsets are within the bounds of their allocations
2067     // (and not one-past-the-end! so we can't use inbounds!), and their
2068     // allocations aren't the same, the pointers are not equal.
2069     //
2070     // Note that it's not necessary to check for LHS being a global variable
2071     // address, due to canonicalization and constant folding.
2072     if (isa<AllocaInst>(LHS) &&
2073         (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
2074       ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2075       ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
2076       uint64_t LHSSize, RHSSize;
2077       if (LHSOffsetCI && RHSOffsetCI &&
2078           getObjectSize(LHS, LHSSize, DL, TLI) &&
2079           getObjectSize(RHS, RHSSize, DL, TLI)) {
2080         const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2081         const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
2082         if (!LHSOffsetValue.isNegative() &&
2083             !RHSOffsetValue.isNegative() &&
2084             LHSOffsetValue.ult(LHSSize) &&
2085             RHSOffsetValue.ult(RHSSize)) {
2086           return ConstantInt::get(GetCompareTy(LHS),
2087                                   !CmpInst::isTrueWhenEqual(Pred));
2088         }
2089       }
2090 
2091       // Repeat the above check but this time without depending on DataLayout
2092       // or being able to compute a precise size.
2093       if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2094           !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2095           LHSOffset->isNullValue() &&
2096           RHSOffset->isNullValue())
2097         return ConstantInt::get(GetCompareTy(LHS),
2098                                 !CmpInst::isTrueWhenEqual(Pred));
2099     }
2100 
2101     // Even if an non-inbounds GEP occurs along the path we can still optimize
2102     // equality comparisons concerning the result. We avoid walking the whole
2103     // chain again by starting where the last calls to
2104     // stripAndComputeConstantOffsets left off and accumulate the offsets.
2105     Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2106     Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
2107     if (LHS == RHS)
2108       return ConstantExpr::getICmp(Pred,
2109                                    ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2110                                    ConstantExpr::getAdd(RHSOffset, RHSNoBound));
2111 
2112     // If one side of the equality comparison must come from a noalias call
2113     // (meaning a system memory allocation function), and the other side must
2114     // come from a pointer that cannot overlap with dynamically-allocated
2115     // memory within the lifetime of the current function (allocas, byval
2116     // arguments, globals), then determine the comparison result here.
2117     SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2118     GetUnderlyingObjects(LHS, LHSUObjs, DL);
2119     GetUnderlyingObjects(RHS, RHSUObjs, DL);
2120 
2121     // Is the set of underlying objects all noalias calls?
2122     auto IsNAC = [](ArrayRef<Value *> Objects) {
2123       return all_of(Objects, isNoAliasCall);
2124     };
2125 
2126     // Is the set of underlying objects all things which must be disjoint from
2127     // noalias calls. For allocas, we consider only static ones (dynamic
2128     // allocas might be transformed into calls to malloc not simultaneously
2129     // live with the compared-to allocation). For globals, we exclude symbols
2130     // that might be resolve lazily to symbols in another dynamically-loaded
2131     // library (and, thus, could be malloc'ed by the implementation).
2132     auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2133       return all_of(Objects, [](Value *V) {
2134         if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2135           return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2136         if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2137           return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2138                   GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2139                  !GV->isThreadLocal();
2140         if (const Argument *A = dyn_cast<Argument>(V))
2141           return A->hasByValAttr();
2142         return false;
2143       });
2144     };
2145 
2146     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2147         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2148         return ConstantInt::get(GetCompareTy(LHS),
2149                                 !CmpInst::isTrueWhenEqual(Pred));
2150 
2151     // Fold comparisons for non-escaping pointer even if the allocation call
2152     // cannot be elided. We cannot fold malloc comparison to null. Also, the
2153     // dynamic allocation call could be either of the operands.
2154     Value *MI = nullptr;
2155     if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
2156       MI = LHS;
2157     else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
2158       MI = RHS;
2159     // FIXME: We should also fold the compare when the pointer escapes, but the
2160     // compare dominates the pointer escape
2161     if (MI && !PointerMayBeCaptured(MI, true, true))
2162       return ConstantInt::get(GetCompareTy(LHS),
2163                               CmpInst::isFalseWhenEqual(Pred));
2164   }
2165 
2166   // Otherwise, fail.
2167   return nullptr;
2168 }
2169 
2170 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2171                                        Value *RHS) {
2172   const APInt *C;
2173   if (!match(RHS, m_APInt(C)))
2174     return nullptr;
2175 
2176   // Rule out tautological comparisons (eg., ult 0 or uge 0).
2177   ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
2178   if (RHS_CR.isEmptySet())
2179     return ConstantInt::getFalse(GetCompareTy(RHS));
2180   if (RHS_CR.isFullSet())
2181     return ConstantInt::getTrue(GetCompareTy(RHS));
2182 
2183   // Many binary operators with constant RHS have easy to compute constant
2184   // range.  Use them to check whether the comparison is a tautology.
2185   unsigned Width = C->getBitWidth();
2186   APInt Lower = APInt(Width, 0);
2187   APInt Upper = APInt(Width, 0);
2188   const APInt *C2;
2189   if (match(LHS, m_URem(m_Value(), m_APInt(C2)))) {
2190     // 'urem x, C2' produces [0, C2).
2191     Upper = *C2;
2192   } else if (match(LHS, m_SRem(m_Value(), m_APInt(C2)))) {
2193     // 'srem x, C2' produces (-|C2|, |C2|).
2194     Upper = C2->abs();
2195     Lower = (-Upper) + 1;
2196   } else if (match(LHS, m_UDiv(m_APInt(C2), m_Value()))) {
2197     // 'udiv C2, x' produces [0, C2].
2198     Upper = *C2 + 1;
2199   } else if (match(LHS, m_UDiv(m_Value(), m_APInt(C2)))) {
2200     // 'udiv x, C2' produces [0, UINT_MAX / C2].
2201     APInt NegOne = APInt::getAllOnesValue(Width);
2202     if (*C2 != 0)
2203       Upper = NegOne.udiv(*C2) + 1;
2204   } else if (match(LHS, m_SDiv(m_APInt(C2), m_Value()))) {
2205     if (C2->isMinSignedValue()) {
2206       // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2207       Lower = *C2;
2208       Upper = Lower.lshr(1) + 1;
2209     } else {
2210       // 'sdiv C2, x' produces [-|C2|, |C2|].
2211       Upper = C2->abs() + 1;
2212       Lower = (-Upper) + 1;
2213     }
2214   } else if (match(LHS, m_SDiv(m_Value(), m_APInt(C2)))) {
2215     APInt IntMin = APInt::getSignedMinValue(Width);
2216     APInt IntMax = APInt::getSignedMaxValue(Width);
2217     if (C2->isAllOnesValue()) {
2218       // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2219       //    where C2 != -1 and C2 != 0 and C2 != 1
2220       Lower = IntMin + 1;
2221       Upper = IntMax + 1;
2222     } else if (C2->countLeadingZeros() < Width - 1) {
2223       // 'sdiv x, C2' produces [INT_MIN / C2, INT_MAX / C2]
2224       //    where C2 != -1 and C2 != 0 and C2 != 1
2225       Lower = IntMin.sdiv(*C2);
2226       Upper = IntMax.sdiv(*C2);
2227       if (Lower.sgt(Upper))
2228         std::swap(Lower, Upper);
2229       Upper = Upper + 1;
2230       assert(Upper != Lower && "Upper part of range has wrapped!");
2231     }
2232   } else if (match(LHS, m_NUWShl(m_APInt(C2), m_Value()))) {
2233     // 'shl nuw C2, x' produces [C2, C2 << CLZ(C2)]
2234     Lower = *C2;
2235     Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2236   } else if (match(LHS, m_NSWShl(m_APInt(C2), m_Value()))) {
2237     if (C2->isNegative()) {
2238       // 'shl nsw C2, x' produces [C2 << CLO(C2)-1, C2]
2239       unsigned ShiftAmount = C2->countLeadingOnes() - 1;
2240       Lower = C2->shl(ShiftAmount);
2241       Upper = *C2 + 1;
2242     } else {
2243       // 'shl nsw C2, x' produces [C2, C2 << CLZ(C2)-1]
2244       unsigned ShiftAmount = C2->countLeadingZeros() - 1;
2245       Lower = *C2;
2246       Upper = C2->shl(ShiftAmount) + 1;
2247     }
2248   } else if (match(LHS, m_LShr(m_Value(), m_APInt(C2)))) {
2249     // 'lshr x, C2' produces [0, UINT_MAX >> C2].
2250     APInt NegOne = APInt::getAllOnesValue(Width);
2251     if (C2->ult(Width))
2252       Upper = NegOne.lshr(*C2) + 1;
2253   } else if (match(LHS, m_LShr(m_APInt(C2), m_Value()))) {
2254     // 'lshr C2, x' produces [C2 >> (Width-1), C2].
2255     unsigned ShiftAmount = Width - 1;
2256     if (*C2 != 0 && cast<BinaryOperator>(LHS)->isExact())
2257       ShiftAmount = C2->countTrailingZeros();
2258     Lower = C2->lshr(ShiftAmount);
2259     Upper = *C2 + 1;
2260   } else if (match(LHS, m_AShr(m_Value(), m_APInt(C2)))) {
2261     // 'ashr x, C2' produces [INT_MIN >> C2, INT_MAX >> C2].
2262     APInt IntMin = APInt::getSignedMinValue(Width);
2263     APInt IntMax = APInt::getSignedMaxValue(Width);
2264     if (C2->ult(Width)) {
2265       Lower = IntMin.ashr(*C2);
2266       Upper = IntMax.ashr(*C2) + 1;
2267     }
2268   } else if (match(LHS, m_AShr(m_APInt(C2), m_Value()))) {
2269     unsigned ShiftAmount = Width - 1;
2270     if (*C2 != 0 && cast<BinaryOperator>(LHS)->isExact())
2271       ShiftAmount = C2->countTrailingZeros();
2272     if (C2->isNegative()) {
2273       // 'ashr C2, x' produces [C2, C2 >> (Width-1)]
2274       Lower = *C2;
2275       Upper = C2->ashr(ShiftAmount) + 1;
2276     } else {
2277       // 'ashr C2, x' produces [C2 >> (Width-1), C2]
2278       Lower = C2->ashr(ShiftAmount);
2279       Upper = *C2 + 1;
2280     }
2281   } else if (match(LHS, m_Or(m_Value(), m_APInt(C2)))) {
2282     // 'or x, C2' produces [C2, UINT_MAX].
2283     Lower = *C2;
2284   } else if (match(LHS, m_And(m_Value(), m_APInt(C2)))) {
2285     // 'and x, C2' produces [0, C2].
2286     Upper = *C2 + 1;
2287   } else if (match(LHS, m_NUWAdd(m_Value(), m_APInt(C2)))) {
2288     // 'add nuw x, C2' produces [C2, UINT_MAX].
2289     Lower = *C2;
2290   }
2291 
2292   ConstantRange LHS_CR =
2293       Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2294 
2295   if (auto *I = dyn_cast<Instruction>(LHS))
2296     if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2297       LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2298 
2299   if (!LHS_CR.isFullSet()) {
2300     if (RHS_CR.contains(LHS_CR))
2301       return ConstantInt::getTrue(GetCompareTy(RHS));
2302     if (RHS_CR.inverse().contains(LHS_CR))
2303       return ConstantInt::getFalse(GetCompareTy(RHS));
2304   }
2305 
2306   return nullptr;
2307 }
2308 
2309 /// Given operands for an ICmpInst, see if we can fold the result.
2310 /// If not, this returns null.
2311 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2312                                const Query &Q, unsigned MaxRecurse) {
2313   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2314   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
2315 
2316   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2317     if (Constant *CRHS = dyn_cast<Constant>(RHS))
2318       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
2319 
2320     // If we have a constant, make sure it is on the RHS.
2321     std::swap(LHS, RHS);
2322     Pred = CmpInst::getSwappedPredicate(Pred);
2323   }
2324 
2325   Type *ITy = GetCompareTy(LHS); // The return type.
2326   Type *OpTy = LHS->getType();   // The operand type.
2327 
2328   // icmp X, X -> true/false
2329   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
2330   // because X could be 0.
2331   if (LHS == RHS || isa<UndefValue>(RHS))
2332     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
2333 
2334   // Special case logic when the operands have i1 type.
2335   if (OpTy->getScalarType()->isIntegerTy(1)) {
2336     switch (Pred) {
2337     default: break;
2338     case ICmpInst::ICMP_EQ:
2339       // X == 1 -> X
2340       if (match(RHS, m_One()))
2341         return LHS;
2342       break;
2343     case ICmpInst::ICMP_NE:
2344       // X != 0 -> X
2345       if (match(RHS, m_Zero()))
2346         return LHS;
2347       break;
2348     case ICmpInst::ICMP_UGT:
2349       // X >u 0 -> X
2350       if (match(RHS, m_Zero()))
2351         return LHS;
2352       break;
2353     case ICmpInst::ICMP_UGE: {
2354       // X >=u 1 -> X
2355       if (match(RHS, m_One()))
2356         return LHS;
2357       if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2358         return getTrue(ITy);
2359       break;
2360     }
2361     case ICmpInst::ICMP_SGE: {
2362       /// For signed comparison, the values for an i1 are 0 and -1
2363       /// respectively. This maps into a truth table of:
2364       /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
2365       ///  0  |  0  |  1 (0 >= 0)   |  1
2366       ///  0  |  1  |  1 (0 >= -1)  |  1
2367       ///  1  |  0  |  0 (-1 >= 0)  |  0
2368       ///  1  |  1  |  1 (-1 >= -1) |  1
2369       if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2370         return getTrue(ITy);
2371       break;
2372     }
2373     case ICmpInst::ICMP_SLT:
2374       // X <s 0 -> X
2375       if (match(RHS, m_Zero()))
2376         return LHS;
2377       break;
2378     case ICmpInst::ICMP_SLE:
2379       // X <=s -1 -> X
2380       if (match(RHS, m_One()))
2381         return LHS;
2382       break;
2383     case ICmpInst::ICMP_ULE: {
2384       if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2385         return getTrue(ITy);
2386       break;
2387     }
2388     }
2389   }
2390 
2391   // If we are comparing with zero then try hard since this is a common case.
2392   if (match(RHS, m_Zero())) {
2393     bool LHSKnownNonNegative, LHSKnownNegative;
2394     switch (Pred) {
2395     default: llvm_unreachable("Unknown ICmp predicate!");
2396     case ICmpInst::ICMP_ULT:
2397       return getFalse(ITy);
2398     case ICmpInst::ICMP_UGE:
2399       return getTrue(ITy);
2400     case ICmpInst::ICMP_EQ:
2401     case ICmpInst::ICMP_ULE:
2402       if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2403         return getFalse(ITy);
2404       break;
2405     case ICmpInst::ICMP_NE:
2406     case ICmpInst::ICMP_UGT:
2407       if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2408         return getTrue(ITy);
2409       break;
2410     case ICmpInst::ICMP_SLT:
2411       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2412                      Q.CxtI, Q.DT);
2413       if (LHSKnownNegative)
2414         return getTrue(ITy);
2415       if (LHSKnownNonNegative)
2416         return getFalse(ITy);
2417       break;
2418     case ICmpInst::ICMP_SLE:
2419       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2420                      Q.CxtI, Q.DT);
2421       if (LHSKnownNegative)
2422         return getTrue(ITy);
2423       if (LHSKnownNonNegative &&
2424           isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2425         return getFalse(ITy);
2426       break;
2427     case ICmpInst::ICMP_SGE:
2428       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2429                      Q.CxtI, Q.DT);
2430       if (LHSKnownNegative)
2431         return getFalse(ITy);
2432       if (LHSKnownNonNegative)
2433         return getTrue(ITy);
2434       break;
2435     case ICmpInst::ICMP_SGT:
2436       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2437                      Q.CxtI, Q.DT);
2438       if (LHSKnownNegative)
2439         return getFalse(ITy);
2440       if (LHSKnownNonNegative &&
2441           isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2442         return getTrue(ITy);
2443       break;
2444     }
2445   }
2446 
2447   if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
2448     return V;
2449 
2450   // If both operands have range metadata, use the metadata
2451   // to simplify the comparison.
2452   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
2453     auto RHS_Instr = dyn_cast<Instruction>(RHS);
2454     auto LHS_Instr = dyn_cast<Instruction>(LHS);
2455 
2456     if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
2457         LHS_Instr->getMetadata(LLVMContext::MD_range)) {
2458       auto RHS_CR = getConstantRangeFromMetadata(
2459           *RHS_Instr->getMetadata(LLVMContext::MD_range));
2460       auto LHS_CR = getConstantRangeFromMetadata(
2461           *LHS_Instr->getMetadata(LLVMContext::MD_range));
2462 
2463       auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
2464       if (Satisfied_CR.contains(LHS_CR))
2465         return ConstantInt::getTrue(RHS->getContext());
2466 
2467       auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
2468                 CmpInst::getInversePredicate(Pred), RHS_CR);
2469       if (InversedSatisfied_CR.contains(LHS_CR))
2470         return ConstantInt::getFalse(RHS->getContext());
2471     }
2472   }
2473 
2474   // Compare of cast, for example (zext X) != 0 -> X != 0
2475   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2476     Instruction *LI = cast<CastInst>(LHS);
2477     Value *SrcOp = LI->getOperand(0);
2478     Type *SrcTy = SrcOp->getType();
2479     Type *DstTy = LI->getType();
2480 
2481     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2482     // if the integer type is the same size as the pointer type.
2483     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
2484         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
2485       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2486         // Transfer the cast to the constant.
2487         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2488                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
2489                                         Q, MaxRecurse-1))
2490           return V;
2491       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2492         if (RI->getOperand(0)->getType() == SrcTy)
2493           // Compare without the cast.
2494           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2495                                           Q, MaxRecurse-1))
2496             return V;
2497       }
2498     }
2499 
2500     if (isa<ZExtInst>(LHS)) {
2501       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2502       // same type.
2503       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2504         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2505           // Compare X and Y.  Note that signed predicates become unsigned.
2506           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2507                                           SrcOp, RI->getOperand(0), Q,
2508                                           MaxRecurse-1))
2509             return V;
2510       }
2511       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2512       // too.  If not, then try to deduce the result of the comparison.
2513       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2514         // Compute the constant that would happen if we truncated to SrcTy then
2515         // reextended to DstTy.
2516         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2517         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2518 
2519         // If the re-extended constant didn't change then this is effectively
2520         // also a case of comparing two zero-extended values.
2521         if (RExt == CI && MaxRecurse)
2522           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2523                                         SrcOp, Trunc, Q, MaxRecurse-1))
2524             return V;
2525 
2526         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2527         // there.  Use this to work out the result of the comparison.
2528         if (RExt != CI) {
2529           switch (Pred) {
2530           default: llvm_unreachable("Unknown ICmp predicate!");
2531           // LHS <u RHS.
2532           case ICmpInst::ICMP_EQ:
2533           case ICmpInst::ICMP_UGT:
2534           case ICmpInst::ICMP_UGE:
2535             return ConstantInt::getFalse(CI->getContext());
2536 
2537           case ICmpInst::ICMP_NE:
2538           case ICmpInst::ICMP_ULT:
2539           case ICmpInst::ICMP_ULE:
2540             return ConstantInt::getTrue(CI->getContext());
2541 
2542           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
2543           // is non-negative then LHS <s RHS.
2544           case ICmpInst::ICMP_SGT:
2545           case ICmpInst::ICMP_SGE:
2546             return CI->getValue().isNegative() ?
2547               ConstantInt::getTrue(CI->getContext()) :
2548               ConstantInt::getFalse(CI->getContext());
2549 
2550           case ICmpInst::ICMP_SLT:
2551           case ICmpInst::ICMP_SLE:
2552             return CI->getValue().isNegative() ?
2553               ConstantInt::getFalse(CI->getContext()) :
2554               ConstantInt::getTrue(CI->getContext());
2555           }
2556         }
2557       }
2558     }
2559 
2560     if (isa<SExtInst>(LHS)) {
2561       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2562       // same type.
2563       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2564         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2565           // Compare X and Y.  Note that the predicate does not change.
2566           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2567                                           Q, MaxRecurse-1))
2568             return V;
2569       }
2570       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2571       // too.  If not, then try to deduce the result of the comparison.
2572       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2573         // Compute the constant that would happen if we truncated to SrcTy then
2574         // reextended to DstTy.
2575         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2576         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2577 
2578         // If the re-extended constant didn't change then this is effectively
2579         // also a case of comparing two sign-extended values.
2580         if (RExt == CI && MaxRecurse)
2581           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
2582             return V;
2583 
2584         // Otherwise the upper bits of LHS are all equal, while RHS has varying
2585         // bits there.  Use this to work out the result of the comparison.
2586         if (RExt != CI) {
2587           switch (Pred) {
2588           default: llvm_unreachable("Unknown ICmp predicate!");
2589           case ICmpInst::ICMP_EQ:
2590             return ConstantInt::getFalse(CI->getContext());
2591           case ICmpInst::ICMP_NE:
2592             return ConstantInt::getTrue(CI->getContext());
2593 
2594           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
2595           // LHS >s RHS.
2596           case ICmpInst::ICMP_SGT:
2597           case ICmpInst::ICMP_SGE:
2598             return CI->getValue().isNegative() ?
2599               ConstantInt::getTrue(CI->getContext()) :
2600               ConstantInt::getFalse(CI->getContext());
2601           case ICmpInst::ICMP_SLT:
2602           case ICmpInst::ICMP_SLE:
2603             return CI->getValue().isNegative() ?
2604               ConstantInt::getFalse(CI->getContext()) :
2605               ConstantInt::getTrue(CI->getContext());
2606 
2607           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
2608           // LHS >u RHS.
2609           case ICmpInst::ICMP_UGT:
2610           case ICmpInst::ICMP_UGE:
2611             // Comparison is true iff the LHS <s 0.
2612             if (MaxRecurse)
2613               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2614                                               Constant::getNullValue(SrcTy),
2615                                               Q, MaxRecurse-1))
2616                 return V;
2617             break;
2618           case ICmpInst::ICMP_ULT:
2619           case ICmpInst::ICMP_ULE:
2620             // Comparison is true iff the LHS >=s 0.
2621             if (MaxRecurse)
2622               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2623                                               Constant::getNullValue(SrcTy),
2624                                               Q, MaxRecurse-1))
2625                 return V;
2626             break;
2627           }
2628         }
2629       }
2630     }
2631   }
2632 
2633   // icmp eq|ne X, Y -> false|true if X != Y
2634   if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2635       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
2636     LLVMContext &Ctx = LHS->getType()->getContext();
2637     return Pred == ICmpInst::ICMP_NE ?
2638       ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
2639   }
2640 
2641   // Special logic for binary operators.
2642   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2643   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2644   if (MaxRecurse && (LBO || RBO)) {
2645     // Analyze the case when either LHS or RHS is an add instruction.
2646     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2647     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2648     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2649     if (LBO && LBO->getOpcode() == Instruction::Add) {
2650       A = LBO->getOperand(0); B = LBO->getOperand(1);
2651       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2652         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2653         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2654     }
2655     if (RBO && RBO->getOpcode() == Instruction::Add) {
2656       C = RBO->getOperand(0); D = RBO->getOperand(1);
2657       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2658         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2659         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2660     }
2661 
2662     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2663     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2664       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2665                                       Constant::getNullValue(RHS->getType()),
2666                                       Q, MaxRecurse-1))
2667         return V;
2668 
2669     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2670     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2671       if (Value *V = SimplifyICmpInst(Pred,
2672                                       Constant::getNullValue(LHS->getType()),
2673                                       C == LHS ? D : C, Q, MaxRecurse-1))
2674         return V;
2675 
2676     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2677     if (A && C && (A == C || A == D || B == C || B == D) &&
2678         NoLHSWrapProblem && NoRHSWrapProblem) {
2679       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2680       Value *Y, *Z;
2681       if (A == C) {
2682         // C + B == C + D  ->  B == D
2683         Y = B;
2684         Z = D;
2685       } else if (A == D) {
2686         // D + B == C + D  ->  B == C
2687         Y = B;
2688         Z = C;
2689       } else if (B == C) {
2690         // A + C == C + D  ->  A == D
2691         Y = A;
2692         Z = D;
2693       } else {
2694         assert(B == D);
2695         // A + D == C + D  ->  A == C
2696         Y = A;
2697         Z = C;
2698       }
2699       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2700         return V;
2701     }
2702   }
2703 
2704   {
2705     Value *Y = nullptr;
2706     // icmp pred (or X, Y), X
2707     if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2708       if (Pred == ICmpInst::ICMP_ULT)
2709         return getFalse(ITy);
2710       if (Pred == ICmpInst::ICMP_UGE)
2711         return getTrue(ITy);
2712 
2713       if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2714         bool RHSKnownNonNegative, RHSKnownNegative;
2715         bool YKnownNonNegative, YKnownNegative;
2716         ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
2717                        Q.AC, Q.CxtI, Q.DT);
2718         ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2719                        Q.CxtI, Q.DT);
2720         if (RHSKnownNonNegative && YKnownNegative)
2721           return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2722         if (RHSKnownNegative || YKnownNonNegative)
2723           return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2724       }
2725     }
2726     // icmp pred X, (or X, Y)
2727     if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2728       if (Pred == ICmpInst::ICMP_ULE)
2729         return getTrue(ITy);
2730       if (Pred == ICmpInst::ICMP_UGT)
2731         return getFalse(ITy);
2732 
2733       if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2734         bool LHSKnownNonNegative, LHSKnownNegative;
2735         bool YKnownNonNegative, YKnownNegative;
2736         ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
2737                        Q.AC, Q.CxtI, Q.DT);
2738         ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2739                        Q.CxtI, Q.DT);
2740         if (LHSKnownNonNegative && YKnownNegative)
2741           return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2742         if (LHSKnownNegative || YKnownNonNegative)
2743           return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2744       }
2745     }
2746   }
2747 
2748   // icmp pred (and X, Y), X
2749   if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2750                                     m_And(m_Specific(RHS), m_Value())))) {
2751     if (Pred == ICmpInst::ICMP_UGT)
2752       return getFalse(ITy);
2753     if (Pred == ICmpInst::ICMP_ULE)
2754       return getTrue(ITy);
2755   }
2756   // icmp pred X, (and X, Y)
2757   if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2758                                     m_And(m_Specific(LHS), m_Value())))) {
2759     if (Pred == ICmpInst::ICMP_UGE)
2760       return getTrue(ITy);
2761     if (Pred == ICmpInst::ICMP_ULT)
2762       return getFalse(ITy);
2763   }
2764 
2765   // 0 - (zext X) pred C
2766   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2767     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2768       if (RHSC->getValue().isStrictlyPositive()) {
2769         if (Pred == ICmpInst::ICMP_SLT)
2770           return ConstantInt::getTrue(RHSC->getContext());
2771         if (Pred == ICmpInst::ICMP_SGE)
2772           return ConstantInt::getFalse(RHSC->getContext());
2773         if (Pred == ICmpInst::ICMP_EQ)
2774           return ConstantInt::getFalse(RHSC->getContext());
2775         if (Pred == ICmpInst::ICMP_NE)
2776           return ConstantInt::getTrue(RHSC->getContext());
2777       }
2778       if (RHSC->getValue().isNonNegative()) {
2779         if (Pred == ICmpInst::ICMP_SLE)
2780           return ConstantInt::getTrue(RHSC->getContext());
2781         if (Pred == ICmpInst::ICMP_SGT)
2782           return ConstantInt::getFalse(RHSC->getContext());
2783       }
2784     }
2785   }
2786 
2787   // icmp pred (urem X, Y), Y
2788   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2789     bool KnownNonNegative, KnownNegative;
2790     switch (Pred) {
2791     default:
2792       break;
2793     case ICmpInst::ICMP_SGT:
2794     case ICmpInst::ICMP_SGE:
2795       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2796                      Q.CxtI, Q.DT);
2797       if (!KnownNonNegative)
2798         break;
2799       LLVM_FALLTHROUGH;
2800     case ICmpInst::ICMP_EQ:
2801     case ICmpInst::ICMP_UGT:
2802     case ICmpInst::ICMP_UGE:
2803       return getFalse(ITy);
2804     case ICmpInst::ICMP_SLT:
2805     case ICmpInst::ICMP_SLE:
2806       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2807                      Q.CxtI, Q.DT);
2808       if (!KnownNonNegative)
2809         break;
2810       LLVM_FALLTHROUGH;
2811     case ICmpInst::ICMP_NE:
2812     case ICmpInst::ICMP_ULT:
2813     case ICmpInst::ICMP_ULE:
2814       return getTrue(ITy);
2815     }
2816   }
2817 
2818   // icmp pred X, (urem Y, X)
2819   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2820     bool KnownNonNegative, KnownNegative;
2821     switch (Pred) {
2822     default:
2823       break;
2824     case ICmpInst::ICMP_SGT:
2825     case ICmpInst::ICMP_SGE:
2826       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2827                      Q.CxtI, Q.DT);
2828       if (!KnownNonNegative)
2829         break;
2830       LLVM_FALLTHROUGH;
2831     case ICmpInst::ICMP_NE:
2832     case ICmpInst::ICMP_UGT:
2833     case ICmpInst::ICMP_UGE:
2834       return getTrue(ITy);
2835     case ICmpInst::ICMP_SLT:
2836     case ICmpInst::ICMP_SLE:
2837       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2838                      Q.CxtI, Q.DT);
2839       if (!KnownNonNegative)
2840         break;
2841       LLVM_FALLTHROUGH;
2842     case ICmpInst::ICMP_EQ:
2843     case ICmpInst::ICMP_ULT:
2844     case ICmpInst::ICMP_ULE:
2845       return getFalse(ITy);
2846     }
2847   }
2848 
2849   // x >> y <=u x
2850   // x udiv y <=u x.
2851   if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2852               match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2853     // icmp pred (X op Y), X
2854     if (Pred == ICmpInst::ICMP_UGT)
2855       return getFalse(ITy);
2856     if (Pred == ICmpInst::ICMP_ULE)
2857       return getTrue(ITy);
2858   }
2859 
2860   // handle:
2861   //   CI2 << X == CI
2862   //   CI2 << X != CI
2863   //
2864   //   where CI2 is a power of 2 and CI isn't
2865   if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2866     const APInt *CI2Val, *CIVal = &CI->getValue();
2867     if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2868         CI2Val->isPowerOf2()) {
2869       if (!CIVal->isPowerOf2()) {
2870         // CI2 << X can equal zero in some circumstances,
2871         // this simplification is unsafe if CI is zero.
2872         //
2873         // We know it is safe if:
2874         // - The shift is nsw, we can't shift out the one bit.
2875         // - The shift is nuw, we can't shift out the one bit.
2876         // - CI2 is one
2877         // - CI isn't zero
2878         if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2879             *CI2Val == 1 || !CI->isZero()) {
2880           if (Pred == ICmpInst::ICMP_EQ)
2881             return ConstantInt::getFalse(RHS->getContext());
2882           if (Pred == ICmpInst::ICMP_NE)
2883             return ConstantInt::getTrue(RHS->getContext());
2884         }
2885       }
2886       if (CIVal->isSignBit() && *CI2Val == 1) {
2887         if (Pred == ICmpInst::ICMP_UGT)
2888           return ConstantInt::getFalse(RHS->getContext());
2889         if (Pred == ICmpInst::ICMP_ULE)
2890           return ConstantInt::getTrue(RHS->getContext());
2891       }
2892     }
2893   }
2894 
2895   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2896       LBO->getOperand(1) == RBO->getOperand(1)) {
2897     switch (LBO->getOpcode()) {
2898     default: break;
2899     case Instruction::UDiv:
2900     case Instruction::LShr:
2901       if (ICmpInst::isSigned(Pred))
2902         break;
2903       LLVM_FALLTHROUGH;
2904     case Instruction::SDiv:
2905     case Instruction::AShr:
2906       if (!LBO->isExact() || !RBO->isExact())
2907         break;
2908       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2909                                       RBO->getOperand(0), Q, MaxRecurse-1))
2910         return V;
2911       break;
2912     case Instruction::Shl: {
2913       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2914       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2915       if (!NUW && !NSW)
2916         break;
2917       if (!NSW && ICmpInst::isSigned(Pred))
2918         break;
2919       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2920                                       RBO->getOperand(0), Q, MaxRecurse-1))
2921         return V;
2922       break;
2923     }
2924     }
2925   }
2926 
2927   // Simplify comparisons involving max/min.
2928   Value *A, *B;
2929   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2930   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2931 
2932   // Signed variants on "max(a,b)>=a -> true".
2933   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2934     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2935     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2936     // We analyze this as smax(A, B) pred A.
2937     P = Pred;
2938   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2939              (A == LHS || B == LHS)) {
2940     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2941     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2942     // We analyze this as smax(A, B) swapped-pred A.
2943     P = CmpInst::getSwappedPredicate(Pred);
2944   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2945              (A == RHS || B == RHS)) {
2946     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2947     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2948     // We analyze this as smax(-A, -B) swapped-pred -A.
2949     // Note that we do not need to actually form -A or -B thanks to EqP.
2950     P = CmpInst::getSwappedPredicate(Pred);
2951   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2952              (A == LHS || B == LHS)) {
2953     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2954     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2955     // We analyze this as smax(-A, -B) pred -A.
2956     // Note that we do not need to actually form -A or -B thanks to EqP.
2957     P = Pred;
2958   }
2959   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2960     // Cases correspond to "max(A, B) p A".
2961     switch (P) {
2962     default:
2963       break;
2964     case CmpInst::ICMP_EQ:
2965     case CmpInst::ICMP_SLE:
2966       // Equivalent to "A EqP B".  This may be the same as the condition tested
2967       // in the max/min; if so, we can just return that.
2968       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2969         return V;
2970       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2971         return V;
2972       // Otherwise, see if "A EqP B" simplifies.
2973       if (MaxRecurse)
2974         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2975           return V;
2976       break;
2977     case CmpInst::ICMP_NE:
2978     case CmpInst::ICMP_SGT: {
2979       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2980       // Equivalent to "A InvEqP B".  This may be the same as the condition
2981       // tested in the max/min; if so, we can just return that.
2982       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2983         return V;
2984       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2985         return V;
2986       // Otherwise, see if "A InvEqP B" simplifies.
2987       if (MaxRecurse)
2988         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2989           return V;
2990       break;
2991     }
2992     case CmpInst::ICMP_SGE:
2993       // Always true.
2994       return getTrue(ITy);
2995     case CmpInst::ICMP_SLT:
2996       // Always false.
2997       return getFalse(ITy);
2998     }
2999   }
3000 
3001   // Unsigned variants on "max(a,b)>=a -> true".
3002   P = CmpInst::BAD_ICMP_PREDICATE;
3003   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3004     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
3005     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3006     // We analyze this as umax(A, B) pred A.
3007     P = Pred;
3008   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3009              (A == LHS || B == LHS)) {
3010     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
3011     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3012     // We analyze this as umax(A, B) swapped-pred A.
3013     P = CmpInst::getSwappedPredicate(Pred);
3014   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3015              (A == RHS || B == RHS)) {
3016     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
3017     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3018     // We analyze this as umax(-A, -B) swapped-pred -A.
3019     // Note that we do not need to actually form -A or -B thanks to EqP.
3020     P = CmpInst::getSwappedPredicate(Pred);
3021   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3022              (A == LHS || B == LHS)) {
3023     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
3024     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3025     // We analyze this as umax(-A, -B) pred -A.
3026     // Note that we do not need to actually form -A or -B thanks to EqP.
3027     P = Pred;
3028   }
3029   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3030     // Cases correspond to "max(A, B) p A".
3031     switch (P) {
3032     default:
3033       break;
3034     case CmpInst::ICMP_EQ:
3035     case CmpInst::ICMP_ULE:
3036       // Equivalent to "A EqP B".  This may be the same as the condition tested
3037       // in the max/min; if so, we can just return that.
3038       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3039         return V;
3040       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3041         return V;
3042       // Otherwise, see if "A EqP B" simplifies.
3043       if (MaxRecurse)
3044         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
3045           return V;
3046       break;
3047     case CmpInst::ICMP_NE:
3048     case CmpInst::ICMP_UGT: {
3049       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3050       // Equivalent to "A InvEqP B".  This may be the same as the condition
3051       // tested in the max/min; if so, we can just return that.
3052       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3053         return V;
3054       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3055         return V;
3056       // Otherwise, see if "A InvEqP B" simplifies.
3057       if (MaxRecurse)
3058         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
3059           return V;
3060       break;
3061     }
3062     case CmpInst::ICMP_UGE:
3063       // Always true.
3064       return getTrue(ITy);
3065     case CmpInst::ICMP_ULT:
3066       // Always false.
3067       return getFalse(ITy);
3068     }
3069   }
3070 
3071   // Variants on "max(x,y) >= min(x,z)".
3072   Value *C, *D;
3073   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3074       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3075       (A == C || A == D || B == C || B == D)) {
3076     // max(x, ?) pred min(x, ?).
3077     if (Pred == CmpInst::ICMP_SGE)
3078       // Always true.
3079       return getTrue(ITy);
3080     if (Pred == CmpInst::ICMP_SLT)
3081       // Always false.
3082       return getFalse(ITy);
3083   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3084              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3085              (A == C || A == D || B == C || B == D)) {
3086     // min(x, ?) pred max(x, ?).
3087     if (Pred == CmpInst::ICMP_SLE)
3088       // Always true.
3089       return getTrue(ITy);
3090     if (Pred == CmpInst::ICMP_SGT)
3091       // Always false.
3092       return getFalse(ITy);
3093   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3094              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3095              (A == C || A == D || B == C || B == D)) {
3096     // max(x, ?) pred min(x, ?).
3097     if (Pred == CmpInst::ICMP_UGE)
3098       // Always true.
3099       return getTrue(ITy);
3100     if (Pred == CmpInst::ICMP_ULT)
3101       // Always false.
3102       return getFalse(ITy);
3103   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3104              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3105              (A == C || A == D || B == C || B == D)) {
3106     // min(x, ?) pred max(x, ?).
3107     if (Pred == CmpInst::ICMP_ULE)
3108       // Always true.
3109       return getTrue(ITy);
3110     if (Pred == CmpInst::ICMP_UGT)
3111       // Always false.
3112       return getFalse(ITy);
3113   }
3114 
3115   // Simplify comparisons of related pointers using a powerful, recursive
3116   // GEP-walk when we have target data available..
3117   if (LHS->getType()->isPointerTy())
3118     if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
3119       return C;
3120   if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3121     if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3122       if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3123               Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3124           Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3125               Q.DL.getTypeSizeInBits(CRHS->getType()))
3126         if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI,
3127                                          CLHS->getPointerOperand(),
3128                                          CRHS->getPointerOperand()))
3129           return C;
3130 
3131   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3132     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3133       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3134           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3135           (ICmpInst::isEquality(Pred) ||
3136            (GLHS->isInBounds() && GRHS->isInBounds() &&
3137             Pred == ICmpInst::getSignedPredicate(Pred)))) {
3138         // The bases are equal and the indices are constant.  Build a constant
3139         // expression GEP with the same indices and a null base pointer to see
3140         // what constant folding can make out of it.
3141         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3142         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
3143         Constant *NewLHS = ConstantExpr::getGetElementPtr(
3144             GLHS->getSourceElementType(), Null, IndicesLHS);
3145 
3146         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3147         Constant *NewRHS = ConstantExpr::getGetElementPtr(
3148             GLHS->getSourceElementType(), Null, IndicesRHS);
3149         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3150       }
3151     }
3152   }
3153 
3154   // If a bit is known to be zero for A and known to be one for B,
3155   // then A and B cannot be equal.
3156   if (ICmpInst::isEquality(Pred)) {
3157     const APInt *RHSVal;
3158     if (match(RHS, m_APInt(RHSVal))) {
3159       unsigned BitWidth = RHSVal->getBitWidth();
3160       APInt LHSKnownZero(BitWidth, 0);
3161       APInt LHSKnownOne(BitWidth, 0);
3162       computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
3163                        Q.CxtI, Q.DT);
3164       if (((LHSKnownZero & *RHSVal) != 0) || ((LHSKnownOne & ~(*RHSVal)) != 0))
3165         return Pred == ICmpInst::ICMP_EQ ? ConstantInt::getFalse(ITy)
3166                                          : ConstantInt::getTrue(ITy);
3167     }
3168   }
3169 
3170   // If the comparison is with the result of a select instruction, check whether
3171   // comparing with either branch of the select always yields the same value.
3172   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3173     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3174       return V;
3175 
3176   // If the comparison is with the result of a phi instruction, check whether
3177   // doing the compare with each incoming phi value yields a common result.
3178   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3179     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3180       return V;
3181 
3182   return nullptr;
3183 }
3184 
3185 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3186                               const DataLayout &DL,
3187                               const TargetLibraryInfo *TLI,
3188                               const DominatorTree *DT, AssumptionCache *AC,
3189                               const Instruction *CxtI) {
3190   return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3191                             RecursionLimit);
3192 }
3193 
3194 /// Given operands for an FCmpInst, see if we can fold the result.
3195 /// If not, this returns null.
3196 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3197                                FastMathFlags FMF, const Query &Q,
3198                                unsigned MaxRecurse) {
3199   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3200   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3201 
3202   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3203     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3204       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3205 
3206     // If we have a constant, make sure it is on the RHS.
3207     std::swap(LHS, RHS);
3208     Pred = CmpInst::getSwappedPredicate(Pred);
3209   }
3210 
3211   // Fold trivial predicates.
3212   Type *RetTy = GetCompareTy(LHS);
3213   if (Pred == FCmpInst::FCMP_FALSE)
3214     return getFalse(RetTy);
3215   if (Pred == FCmpInst::FCMP_TRUE)
3216     return getTrue(RetTy);
3217 
3218   // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3219   if (FMF.noNaNs()) {
3220     if (Pred == FCmpInst::FCMP_UNO)
3221       return getFalse(RetTy);
3222     if (Pred == FCmpInst::FCMP_ORD)
3223       return getTrue(RetTy);
3224   }
3225 
3226   // fcmp pred x, undef  and  fcmp pred undef, x
3227   // fold to true if unordered, false if ordered
3228   if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3229     // Choosing NaN for the undef will always make unordered comparison succeed
3230     // and ordered comparison fail.
3231     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3232   }
3233 
3234   // fcmp x,x -> true/false.  Not all compares are foldable.
3235   if (LHS == RHS) {
3236     if (CmpInst::isTrueWhenEqual(Pred))
3237       return getTrue(RetTy);
3238     if (CmpInst::isFalseWhenEqual(Pred))
3239       return getFalse(RetTy);
3240   }
3241 
3242   // Handle fcmp with constant RHS
3243   const ConstantFP *CFP = nullptr;
3244   if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3245     if (RHS->getType()->isVectorTy())
3246       CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3247     else
3248       CFP = dyn_cast<ConstantFP>(RHSC);
3249   }
3250   if (CFP) {
3251     // If the constant is a nan, see if we can fold the comparison based on it.
3252     if (CFP->getValueAPF().isNaN()) {
3253       if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
3254         return getFalse(RetTy);
3255       assert(FCmpInst::isUnordered(Pred) &&
3256              "Comparison must be either ordered or unordered!");
3257       // True if unordered.
3258       return getTrue(RetTy);
3259     }
3260     // Check whether the constant is an infinity.
3261     if (CFP->getValueAPF().isInfinity()) {
3262       if (CFP->getValueAPF().isNegative()) {
3263         switch (Pred) {
3264         case FCmpInst::FCMP_OLT:
3265           // No value is ordered and less than negative infinity.
3266           return getFalse(RetTy);
3267         case FCmpInst::FCMP_UGE:
3268           // All values are unordered with or at least negative infinity.
3269           return getTrue(RetTy);
3270         default:
3271           break;
3272         }
3273       } else {
3274         switch (Pred) {
3275         case FCmpInst::FCMP_OGT:
3276           // No value is ordered and greater than infinity.
3277           return getFalse(RetTy);
3278         case FCmpInst::FCMP_ULE:
3279           // All values are unordered with and at most infinity.
3280           return getTrue(RetTy);
3281         default:
3282           break;
3283         }
3284       }
3285     }
3286     if (CFP->getValueAPF().isZero()) {
3287       switch (Pred) {
3288       case FCmpInst::FCMP_UGE:
3289         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3290           return getTrue(RetTy);
3291         break;
3292       case FCmpInst::FCMP_OLT:
3293         // X < 0
3294         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3295           return getFalse(RetTy);
3296         break;
3297       default:
3298         break;
3299       }
3300     }
3301   }
3302 
3303   // If the comparison is with the result of a select instruction, check whether
3304   // comparing with either branch of the select always yields the same value.
3305   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3306     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3307       return V;
3308 
3309   // If the comparison is with the result of a phi instruction, check whether
3310   // doing the compare with each incoming phi value yields a common result.
3311   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3312     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3313       return V;
3314 
3315   return nullptr;
3316 }
3317 
3318 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3319                               FastMathFlags FMF, const DataLayout &DL,
3320                               const TargetLibraryInfo *TLI,
3321                               const DominatorTree *DT, AssumptionCache *AC,
3322                               const Instruction *CxtI) {
3323   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
3324                             Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3325 }
3326 
3327 /// See if V simplifies when its operand Op is replaced with RepOp.
3328 static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3329                                            const Query &Q,
3330                                            unsigned MaxRecurse) {
3331   // Trivial replacement.
3332   if (V == Op)
3333     return RepOp;
3334 
3335   auto *I = dyn_cast<Instruction>(V);
3336   if (!I)
3337     return nullptr;
3338 
3339   // If this is a binary operator, try to simplify it with the replaced op.
3340   if (auto *B = dyn_cast<BinaryOperator>(I)) {
3341     // Consider:
3342     //   %cmp = icmp eq i32 %x, 2147483647
3343     //   %add = add nsw i32 %x, 1
3344     //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
3345     //
3346     // We can't replace %sel with %add unless we strip away the flags.
3347     if (isa<OverflowingBinaryOperator>(B))
3348       if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3349         return nullptr;
3350     if (isa<PossiblyExactOperator>(B))
3351       if (B->isExact())
3352         return nullptr;
3353 
3354     if (MaxRecurse) {
3355       if (B->getOperand(0) == Op)
3356         return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3357                              MaxRecurse - 1);
3358       if (B->getOperand(1) == Op)
3359         return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3360                              MaxRecurse - 1);
3361     }
3362   }
3363 
3364   // Same for CmpInsts.
3365   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3366     if (MaxRecurse) {
3367       if (C->getOperand(0) == Op)
3368         return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3369                                MaxRecurse - 1);
3370       if (C->getOperand(1) == Op)
3371         return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3372                                MaxRecurse - 1);
3373     }
3374   }
3375 
3376   // TODO: We could hand off more cases to instsimplify here.
3377 
3378   // If all operands are constant after substituting Op for RepOp then we can
3379   // constant fold the instruction.
3380   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3381     // Build a list of all constant operands.
3382     SmallVector<Constant *, 8> ConstOps;
3383     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3384       if (I->getOperand(i) == Op)
3385         ConstOps.push_back(CRepOp);
3386       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3387         ConstOps.push_back(COp);
3388       else
3389         break;
3390     }
3391 
3392     // All operands were constants, fold it.
3393     if (ConstOps.size() == I->getNumOperands()) {
3394       if (CmpInst *C = dyn_cast<CmpInst>(I))
3395         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3396                                                ConstOps[1], Q.DL, Q.TLI);
3397 
3398       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3399         if (!LI->isVolatile())
3400           return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
3401 
3402       return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
3403     }
3404   }
3405 
3406   return nullptr;
3407 }
3408 
3409 /// Try to simplify a select instruction when its condition operand is an
3410 /// integer comparison where one operand of the compare is a constant.
3411 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3412                                     const APInt *Y, bool TrueWhenUnset) {
3413   const APInt *C;
3414 
3415   // (X & Y) == 0 ? X & ~Y : X  --> X
3416   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
3417   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3418       *Y == ~*C)
3419     return TrueWhenUnset ? FalseVal : TrueVal;
3420 
3421   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
3422   // (X & Y) != 0 ? X : X & ~Y  --> X
3423   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3424       *Y == ~*C)
3425     return TrueWhenUnset ? FalseVal : TrueVal;
3426 
3427   if (Y->isPowerOf2()) {
3428     // (X & Y) == 0 ? X | Y : X  --> X | Y
3429     // (X & Y) != 0 ? X | Y : X  --> X
3430     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3431         *Y == *C)
3432       return TrueWhenUnset ? TrueVal : FalseVal;
3433 
3434     // (X & Y) == 0 ? X : X | Y  --> X
3435     // (X & Y) != 0 ? X : X | Y  --> X | Y
3436     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3437         *Y == *C)
3438       return TrueWhenUnset ? TrueVal : FalseVal;
3439   }
3440 
3441   return nullptr;
3442 }
3443 
3444 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
3445 /// eq/ne.
3446 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *TrueVal,
3447                                            Value *FalseVal,
3448                                            bool TrueWhenUnset) {
3449   unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
3450   if (!BitWidth)
3451     return nullptr;
3452 
3453   APInt MinSignedValue;
3454   Value *X;
3455   if (match(CmpLHS, m_Trunc(m_Value(X))) && (X == TrueVal || X == FalseVal)) {
3456     // icmp slt (trunc X), 0  <--> icmp ne (and X, C), 0
3457     // icmp sgt (trunc X), -1 <--> icmp eq (and X, C), 0
3458     unsigned DestSize = CmpLHS->getType()->getScalarSizeInBits();
3459     MinSignedValue = APInt::getSignedMinValue(DestSize).zext(BitWidth);
3460   } else {
3461     // icmp slt X, 0  <--> icmp ne (and X, C), 0
3462     // icmp sgt X, -1 <--> icmp eq (and X, C), 0
3463     X = CmpLHS;
3464     MinSignedValue = APInt::getSignedMinValue(BitWidth);
3465   }
3466 
3467   if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, &MinSignedValue,
3468                                        TrueWhenUnset))
3469     return V;
3470 
3471   return nullptr;
3472 }
3473 
3474 /// Try to simplify a select instruction when its condition operand is an
3475 /// integer comparison.
3476 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3477                                          Value *FalseVal, const Query &Q,
3478                                          unsigned MaxRecurse) {
3479   ICmpInst::Predicate Pred;
3480   Value *CmpLHS, *CmpRHS;
3481   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3482     return nullptr;
3483 
3484   // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3485   // decomposeBitTestICmp() might help.
3486   if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3487     Value *X;
3488     const APInt *Y;
3489     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3490       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3491                                            Pred == ICmpInst::ICMP_EQ))
3492         return V;
3493   } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
3494     // Comparing signed-less-than 0 checks if the sign bit is set.
3495     if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3496                                                 false))
3497       return V;
3498   } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
3499     // Comparing signed-greater-than -1 checks if the sign bit is not set.
3500     if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3501                                                 true))
3502       return V;
3503   }
3504 
3505   if (CondVal->hasOneUse()) {
3506     const APInt *C;
3507     if (match(CmpRHS, m_APInt(C))) {
3508       // X < MIN ? T : F  -->  F
3509       if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3510         return FalseVal;
3511       // X < MIN ? T : F  -->  F
3512       if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3513         return FalseVal;
3514       // X > MAX ? T : F  -->  F
3515       if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3516         return FalseVal;
3517       // X > MAX ? T : F  -->  F
3518       if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3519         return FalseVal;
3520     }
3521   }
3522 
3523   // If we have an equality comparison, then we know the value in one of the
3524   // arms of the select. See if substituting this value into the arm and
3525   // simplifying the result yields the same value as the other arm.
3526   if (Pred == ICmpInst::ICMP_EQ) {
3527     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3528             TrueVal ||
3529         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3530             TrueVal)
3531       return FalseVal;
3532     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3533             FalseVal ||
3534         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3535             FalseVal)
3536       return FalseVal;
3537   } else if (Pred == ICmpInst::ICMP_NE) {
3538     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3539             FalseVal ||
3540         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3541             FalseVal)
3542       return TrueVal;
3543     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3544             TrueVal ||
3545         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3546             TrueVal)
3547       return TrueVal;
3548   }
3549 
3550   return nullptr;
3551 }
3552 
3553 /// Given operands for a SelectInst, see if we can fold the result.
3554 /// If not, this returns null.
3555 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3556                                  Value *FalseVal, const Query &Q,
3557                                  unsigned MaxRecurse) {
3558   // select true, X, Y  -> X
3559   // select false, X, Y -> Y
3560   if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3561     if (CB->isAllOnesValue())
3562       return TrueVal;
3563     if (CB->isNullValue())
3564       return FalseVal;
3565   }
3566 
3567   // select C, X, X -> X
3568   if (TrueVal == FalseVal)
3569     return TrueVal;
3570 
3571   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
3572     if (isa<Constant>(TrueVal))
3573       return TrueVal;
3574     return FalseVal;
3575   }
3576   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
3577     return FalseVal;
3578   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
3579     return TrueVal;
3580 
3581   if (Value *V =
3582           simplifySelectWithICmpCond(CondVal, TrueVal, FalseVal, Q, MaxRecurse))
3583     return V;
3584 
3585   return nullptr;
3586 }
3587 
3588 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3589                                 const DataLayout &DL,
3590                                 const TargetLibraryInfo *TLI,
3591                                 const DominatorTree *DT, AssumptionCache *AC,
3592                                 const Instruction *CxtI) {
3593   return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
3594                               Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3595 }
3596 
3597 /// Given operands for an GetElementPtrInst, see if we can fold the result.
3598 /// If not, this returns null.
3599 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3600                               const Query &Q, unsigned) {
3601   // The type of the GEP pointer operand.
3602   unsigned AS =
3603       cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
3604 
3605   // getelementptr P -> P.
3606   if (Ops.size() == 1)
3607     return Ops[0];
3608 
3609   // Compute the (pointer) type returned by the GEP instruction.
3610   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
3611   Type *GEPTy = PointerType::get(LastType, AS);
3612   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3613     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3614 
3615   if (isa<UndefValue>(Ops[0]))
3616     return UndefValue::get(GEPTy);
3617 
3618   if (Ops.size() == 2) {
3619     // getelementptr P, 0 -> P.
3620     if (match(Ops[1], m_Zero()))
3621       return Ops[0];
3622 
3623     Type *Ty = SrcTy;
3624     if (Ty->isSized()) {
3625       Value *P;
3626       uint64_t C;
3627       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
3628       // getelementptr P, N -> P if P points to a type of zero size.
3629       if (TyAllocSize == 0)
3630         return Ops[0];
3631 
3632       // The following transforms are only safe if the ptrtoint cast
3633       // doesn't truncate the pointers.
3634       if (Ops[1]->getType()->getScalarSizeInBits() ==
3635           Q.DL.getPointerSizeInBits(AS)) {
3636         auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3637           if (match(P, m_Zero()))
3638             return Constant::getNullValue(GEPTy);
3639           Value *Temp;
3640           if (match(P, m_PtrToInt(m_Value(Temp))))
3641             if (Temp->getType() == GEPTy)
3642               return Temp;
3643           return nullptr;
3644         };
3645 
3646         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3647         if (TyAllocSize == 1 &&
3648             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3649           if (Value *R = PtrToIntOrZero(P))
3650             return R;
3651 
3652         // getelementptr V, (ashr (sub P, V), C) -> Q
3653         // if P points to a type of size 1 << C.
3654         if (match(Ops[1],
3655                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3656                          m_ConstantInt(C))) &&
3657             TyAllocSize == 1ULL << C)
3658           if (Value *R = PtrToIntOrZero(P))
3659             return R;
3660 
3661         // getelementptr V, (sdiv (sub P, V), C) -> Q
3662         // if P points to a type of size C.
3663         if (match(Ops[1],
3664                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3665                          m_SpecificInt(TyAllocSize))))
3666           if (Value *R = PtrToIntOrZero(P))
3667             return R;
3668       }
3669     }
3670   }
3671 
3672   if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3673       all_of(Ops.slice(1).drop_back(1),
3674              [](Value *Idx) { return match(Idx, m_Zero()); })) {
3675     unsigned PtrWidth =
3676         Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3677     if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3678       APInt BasePtrOffset(PtrWidth, 0);
3679       Value *StrippedBasePtr =
3680           Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3681                                                             BasePtrOffset);
3682 
3683       // gep (gep V, C), (sub 0, V) -> C
3684       if (match(Ops.back(),
3685                 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3686         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3687         return ConstantExpr::getIntToPtr(CI, GEPTy);
3688       }
3689       // gep (gep V, C), (xor V, -1) -> C-1
3690       if (match(Ops.back(),
3691                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3692         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3693         return ConstantExpr::getIntToPtr(CI, GEPTy);
3694       }
3695     }
3696   }
3697 
3698   // Check to see if this is constant foldable.
3699   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3700     if (!isa<Constant>(Ops[i]))
3701       return nullptr;
3702 
3703   return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3704                                         Ops.slice(1));
3705 }
3706 
3707 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3708                              const DataLayout &DL,
3709                              const TargetLibraryInfo *TLI,
3710                              const DominatorTree *DT, AssumptionCache *AC,
3711                              const Instruction *CxtI) {
3712   return ::SimplifyGEPInst(SrcTy, Ops,
3713                            Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3714 }
3715 
3716 /// Given operands for an InsertValueInst, see if we can fold the result.
3717 /// If not, this returns null.
3718 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3719                                       ArrayRef<unsigned> Idxs, const Query &Q,
3720                                       unsigned) {
3721   if (Constant *CAgg = dyn_cast<Constant>(Agg))
3722     if (Constant *CVal = dyn_cast<Constant>(Val))
3723       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3724 
3725   // insertvalue x, undef, n -> x
3726   if (match(Val, m_Undef()))
3727     return Agg;
3728 
3729   // insertvalue x, (extractvalue y, n), n
3730   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
3731     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3732         EV->getIndices() == Idxs) {
3733       // insertvalue undef, (extractvalue y, n), n -> y
3734       if (match(Agg, m_Undef()))
3735         return EV->getAggregateOperand();
3736 
3737       // insertvalue y, (extractvalue y, n), n -> y
3738       if (Agg == EV->getAggregateOperand())
3739         return Agg;
3740     }
3741 
3742   return nullptr;
3743 }
3744 
3745 Value *llvm::SimplifyInsertValueInst(
3746     Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
3747     const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
3748     const Instruction *CxtI) {
3749   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
3750                                    RecursionLimit);
3751 }
3752 
3753 /// Given operands for an ExtractValueInst, see if we can fold the result.
3754 /// If not, this returns null.
3755 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3756                                        const Query &, unsigned) {
3757   if (auto *CAgg = dyn_cast<Constant>(Agg))
3758     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3759 
3760   // extractvalue x, (insertvalue y, elt, n), n -> elt
3761   unsigned NumIdxs = Idxs.size();
3762   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3763        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3764     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3765     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3766     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3767     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3768         Idxs.slice(0, NumCommonIdxs)) {
3769       if (NumIdxs == NumInsertValueIdxs)
3770         return IVI->getInsertedValueOperand();
3771       break;
3772     }
3773   }
3774 
3775   return nullptr;
3776 }
3777 
3778 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3779                                       const DataLayout &DL,
3780                                       const TargetLibraryInfo *TLI,
3781                                       const DominatorTree *DT,
3782                                       AssumptionCache *AC,
3783                                       const Instruction *CxtI) {
3784   return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
3785                                     RecursionLimit);
3786 }
3787 
3788 /// Given operands for an ExtractElementInst, see if we can fold the result.
3789 /// If not, this returns null.
3790 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3791                                          unsigned) {
3792   if (auto *CVec = dyn_cast<Constant>(Vec)) {
3793     if (auto *CIdx = dyn_cast<Constant>(Idx))
3794       return ConstantFoldExtractElementInstruction(CVec, CIdx);
3795 
3796     // The index is not relevant if our vector is a splat.
3797     if (auto *Splat = CVec->getSplatValue())
3798       return Splat;
3799 
3800     if (isa<UndefValue>(Vec))
3801       return UndefValue::get(Vec->getType()->getVectorElementType());
3802   }
3803 
3804   // If extracting a specified index from the vector, see if we can recursively
3805   // find a previously computed scalar that was inserted into the vector.
3806   if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3807     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
3808       return Elt;
3809 
3810   return nullptr;
3811 }
3812 
3813 Value *llvm::SimplifyExtractElementInst(
3814     Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
3815     const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
3816   return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
3817                                       RecursionLimit);
3818 }
3819 
3820 /// See if we can fold the given phi. If not, returns null.
3821 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
3822   // If all of the PHI's incoming values are the same then replace the PHI node
3823   // with the common value.
3824   Value *CommonValue = nullptr;
3825   bool HasUndefInput = false;
3826   for (Value *Incoming : PN->incoming_values()) {
3827     // If the incoming value is the phi node itself, it can safely be skipped.
3828     if (Incoming == PN) continue;
3829     if (isa<UndefValue>(Incoming)) {
3830       // Remember that we saw an undef value, but otherwise ignore them.
3831       HasUndefInput = true;
3832       continue;
3833     }
3834     if (CommonValue && Incoming != CommonValue)
3835       return nullptr;  // Not the same, bail out.
3836     CommonValue = Incoming;
3837   }
3838 
3839   // If CommonValue is null then all of the incoming values were either undef or
3840   // equal to the phi node itself.
3841   if (!CommonValue)
3842     return UndefValue::get(PN->getType());
3843 
3844   // If we have a PHI node like phi(X, undef, X), where X is defined by some
3845   // instruction, we cannot return X as the result of the PHI node unless it
3846   // dominates the PHI block.
3847   if (HasUndefInput)
3848     return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
3849 
3850   return CommonValue;
3851 }
3852 
3853 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
3854                                Type *Ty, const Query &Q, unsigned MaxRecurse) {
3855   if (auto *C = dyn_cast<Constant>(Op))
3856     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
3857 
3858   if (auto *CI = dyn_cast<CastInst>(Op)) {
3859     auto *Src = CI->getOperand(0);
3860     Type *SrcTy = Src->getType();
3861     Type *MidTy = CI->getType();
3862     Type *DstTy = Ty;
3863     if (Src->getType() == Ty) {
3864       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
3865       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
3866       Type *SrcIntPtrTy =
3867           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
3868       Type *MidIntPtrTy =
3869           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
3870       Type *DstIntPtrTy =
3871           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
3872       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
3873                                          SrcIntPtrTy, MidIntPtrTy,
3874                                          DstIntPtrTy) == Instruction::BitCast)
3875         return Src;
3876     }
3877   }
3878 
3879   // bitcast x -> x
3880   if (CastOpc == Instruction::BitCast)
3881     if (Op->getType() == Ty)
3882       return Op;
3883 
3884   return nullptr;
3885 }
3886 
3887 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
3888                               const DataLayout &DL,
3889                               const TargetLibraryInfo *TLI,
3890                               const DominatorTree *DT, AssumptionCache *AC,
3891                               const Instruction *CxtI) {
3892   return ::SimplifyCastInst(CastOpc, Op, Ty, Query(DL, TLI, DT, AC, CxtI),
3893                             RecursionLimit);
3894 }
3895 
3896 //=== Helper functions for higher up the class hierarchy.
3897 
3898 /// Given operands for a BinaryOperator, see if we can fold the result.
3899 /// If not, this returns null.
3900 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3901                             const Query &Q, unsigned MaxRecurse) {
3902   switch (Opcode) {
3903   case Instruction::Add:
3904     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3905                            Q, MaxRecurse);
3906   case Instruction::FAdd:
3907     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3908 
3909   case Instruction::Sub:
3910     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3911                            Q, MaxRecurse);
3912   case Instruction::FSub:
3913     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3914 
3915   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
3916   case Instruction::FMul:
3917     return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3918   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3919   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
3920   case Instruction::FDiv:
3921       return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3922   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3923   case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
3924   case Instruction::FRem:
3925       return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3926   case Instruction::Shl:
3927     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3928                            Q, MaxRecurse);
3929   case Instruction::LShr:
3930     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3931   case Instruction::AShr:
3932     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3933   case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3934   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3935   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
3936   default:
3937     if (Constant *CLHS = dyn_cast<Constant>(LHS))
3938       if (Constant *CRHS = dyn_cast<Constant>(RHS))
3939         return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
3940 
3941     // If the operation is associative, try some generic simplifications.
3942     if (Instruction::isAssociative(Opcode))
3943       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
3944         return V;
3945 
3946     // If the operation is with the result of a select instruction check whether
3947     // operating on either branch of the select always yields the same value.
3948     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3949       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
3950         return V;
3951 
3952     // If the operation is with the result of a phi instruction, check whether
3953     // operating on all incoming values of the phi always yields the same value.
3954     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3955       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
3956         return V;
3957 
3958     return nullptr;
3959   }
3960 }
3961 
3962 /// Given operands for a BinaryOperator, see if we can fold the result.
3963 /// If not, this returns null.
3964 /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
3965 /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
3966 static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3967                               const FastMathFlags &FMF, const Query &Q,
3968                               unsigned MaxRecurse) {
3969   switch (Opcode) {
3970   case Instruction::FAdd:
3971     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
3972   case Instruction::FSub:
3973     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
3974   case Instruction::FMul:
3975     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
3976   default:
3977     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
3978   }
3979 }
3980 
3981 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3982                            const DataLayout &DL, const TargetLibraryInfo *TLI,
3983                            const DominatorTree *DT, AssumptionCache *AC,
3984                            const Instruction *CxtI) {
3985   return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3986                          RecursionLimit);
3987 }
3988 
3989 Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3990                              const FastMathFlags &FMF, const DataLayout &DL,
3991                              const TargetLibraryInfo *TLI,
3992                              const DominatorTree *DT, AssumptionCache *AC,
3993                              const Instruction *CxtI) {
3994   return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
3995                            RecursionLimit);
3996 }
3997 
3998 /// Given operands for a CmpInst, see if we can fold the result.
3999 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4000                               const Query &Q, unsigned MaxRecurse) {
4001   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
4002     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
4003   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4004 }
4005 
4006 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4007                              const DataLayout &DL, const TargetLibraryInfo *TLI,
4008                              const DominatorTree *DT, AssumptionCache *AC,
4009                              const Instruction *CxtI) {
4010   return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
4011                            RecursionLimit);
4012 }
4013 
4014 static bool IsIdempotent(Intrinsic::ID ID) {
4015   switch (ID) {
4016   default: return false;
4017 
4018   // Unary idempotent: f(f(x)) = f(x)
4019   case Intrinsic::fabs:
4020   case Intrinsic::floor:
4021   case Intrinsic::ceil:
4022   case Intrinsic::trunc:
4023   case Intrinsic::rint:
4024   case Intrinsic::nearbyint:
4025   case Intrinsic::round:
4026     return true;
4027   }
4028 }
4029 
4030 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4031                                    const DataLayout &DL) {
4032   GlobalValue *PtrSym;
4033   APInt PtrOffset;
4034   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4035     return nullptr;
4036 
4037   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4038   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4039   Type *Int32PtrTy = Int32Ty->getPointerTo();
4040   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4041 
4042   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4043   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4044     return nullptr;
4045 
4046   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4047   if (OffsetInt % 4 != 0)
4048     return nullptr;
4049 
4050   Constant *C = ConstantExpr::getGetElementPtr(
4051       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4052       ConstantInt::get(Int64Ty, OffsetInt / 4));
4053   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4054   if (!Loaded)
4055     return nullptr;
4056 
4057   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4058   if (!LoadedCE)
4059     return nullptr;
4060 
4061   if (LoadedCE->getOpcode() == Instruction::Trunc) {
4062     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4063     if (!LoadedCE)
4064       return nullptr;
4065   }
4066 
4067   if (LoadedCE->getOpcode() != Instruction::Sub)
4068     return nullptr;
4069 
4070   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4071   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4072     return nullptr;
4073   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4074 
4075   Constant *LoadedRHS = LoadedCE->getOperand(1);
4076   GlobalValue *LoadedRHSSym;
4077   APInt LoadedRHSOffset;
4078   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4079                                   DL) ||
4080       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4081     return nullptr;
4082 
4083   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4084 }
4085 
4086 static bool maskIsAllZeroOrUndef(Value *Mask) {
4087   auto *ConstMask = dyn_cast<Constant>(Mask);
4088   if (!ConstMask)
4089     return false;
4090   if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4091     return true;
4092   for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4093        ++I) {
4094     if (auto *MaskElt = ConstMask->getAggregateElement(I))
4095       if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4096         continue;
4097     return false;
4098   }
4099   return true;
4100 }
4101 
4102 template <typename IterTy>
4103 static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
4104                                 const Query &Q, unsigned MaxRecurse) {
4105   Intrinsic::ID IID = F->getIntrinsicID();
4106   unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
4107   Type *ReturnType = F->getReturnType();
4108 
4109   // Binary Ops
4110   if (NumOperands == 2) {
4111     Value *LHS = *ArgBegin;
4112     Value *RHS = *(ArgBegin + 1);
4113     if (IID == Intrinsic::usub_with_overflow ||
4114         IID == Intrinsic::ssub_with_overflow) {
4115       // X - X -> { 0, false }
4116       if (LHS == RHS)
4117         return Constant::getNullValue(ReturnType);
4118 
4119       // X - undef -> undef
4120       // undef - X -> undef
4121       if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4122         return UndefValue::get(ReturnType);
4123     }
4124 
4125     if (IID == Intrinsic::uadd_with_overflow ||
4126         IID == Intrinsic::sadd_with_overflow) {
4127       // X + undef -> undef
4128       if (isa<UndefValue>(RHS))
4129         return UndefValue::get(ReturnType);
4130     }
4131 
4132     if (IID == Intrinsic::umul_with_overflow ||
4133         IID == Intrinsic::smul_with_overflow) {
4134       // X * 0 -> { 0, false }
4135       if (match(RHS, m_Zero()))
4136         return Constant::getNullValue(ReturnType);
4137 
4138       // X * undef -> { 0, false }
4139       if (match(RHS, m_Undef()))
4140         return Constant::getNullValue(ReturnType);
4141     }
4142 
4143     if (IID == Intrinsic::load_relative && isa<Constant>(LHS) &&
4144         isa<Constant>(RHS))
4145       return SimplifyRelativeLoad(cast<Constant>(LHS), cast<Constant>(RHS),
4146                                   Q.DL);
4147   }
4148 
4149   // Simplify calls to llvm.masked.load.*
4150   if (IID == Intrinsic::masked_load) {
4151     Value *MaskArg = ArgBegin[2];
4152     Value *PassthruArg = ArgBegin[3];
4153     // If the mask is all zeros or undef, the "passthru" argument is the result.
4154     if (maskIsAllZeroOrUndef(MaskArg))
4155       return PassthruArg;
4156   }
4157 
4158   // Perform idempotent optimizations
4159   if (!IsIdempotent(IID))
4160     return nullptr;
4161 
4162   // Unary Ops
4163   if (NumOperands == 1)
4164     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
4165       if (II->getIntrinsicID() == IID)
4166         return II;
4167 
4168   return nullptr;
4169 }
4170 
4171 template <typename IterTy>
4172 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
4173                            const Query &Q, unsigned MaxRecurse) {
4174   Type *Ty = V->getType();
4175   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4176     Ty = PTy->getElementType();
4177   FunctionType *FTy = cast<FunctionType>(Ty);
4178 
4179   // call undef -> undef
4180   // call null -> undef
4181   if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
4182     return UndefValue::get(FTy->getReturnType());
4183 
4184   Function *F = dyn_cast<Function>(V);
4185   if (!F)
4186     return nullptr;
4187 
4188   if (F->isIntrinsic())
4189     if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
4190       return Ret;
4191 
4192   if (!canConstantFoldCallTo(F))
4193     return nullptr;
4194 
4195   SmallVector<Constant *, 4> ConstantArgs;
4196   ConstantArgs.reserve(ArgEnd - ArgBegin);
4197   for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4198     Constant *C = dyn_cast<Constant>(*I);
4199     if (!C)
4200       return nullptr;
4201     ConstantArgs.push_back(C);
4202   }
4203 
4204   return ConstantFoldCall(F, ConstantArgs, Q.TLI);
4205 }
4206 
4207 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
4208                           User::op_iterator ArgEnd, const DataLayout &DL,
4209                           const TargetLibraryInfo *TLI, const DominatorTree *DT,
4210                           AssumptionCache *AC, const Instruction *CxtI) {
4211   return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
4212                         RecursionLimit);
4213 }
4214 
4215 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
4216                           const DataLayout &DL, const TargetLibraryInfo *TLI,
4217                           const DominatorTree *DT, AssumptionCache *AC,
4218                           const Instruction *CxtI) {
4219   return ::SimplifyCall(V, Args.begin(), Args.end(),
4220                         Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
4221 }
4222 
4223 /// See if we can compute a simplified version of this instruction.
4224 /// If not, this returns null.
4225 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
4226                                  const TargetLibraryInfo *TLI,
4227                                  const DominatorTree *DT, AssumptionCache *AC) {
4228   Value *Result;
4229 
4230   switch (I->getOpcode()) {
4231   default:
4232     Result = ConstantFoldInstruction(I, DL, TLI);
4233     break;
4234   case Instruction::FAdd:
4235     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
4236                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4237     break;
4238   case Instruction::Add:
4239     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4240                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4241                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4242                              TLI, DT, AC, I);
4243     break;
4244   case Instruction::FSub:
4245     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
4246                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4247     break;
4248   case Instruction::Sub:
4249     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4250                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4251                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4252                              TLI, DT, AC, I);
4253     break;
4254   case Instruction::FMul:
4255     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
4256                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4257     break;
4258   case Instruction::Mul:
4259     Result =
4260         SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4261     break;
4262   case Instruction::SDiv:
4263     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4264                               AC, I);
4265     break;
4266   case Instruction::UDiv:
4267     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4268                               AC, I);
4269     break;
4270   case Instruction::FDiv:
4271     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
4272                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4273     break;
4274   case Instruction::SRem:
4275     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4276                               AC, I);
4277     break;
4278   case Instruction::URem:
4279     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4280                               AC, I);
4281     break;
4282   case Instruction::FRem:
4283     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
4284                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4285     break;
4286   case Instruction::Shl:
4287     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4288                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4289                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4290                              TLI, DT, AC, I);
4291     break;
4292   case Instruction::LShr:
4293     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
4294                               cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4295                               AC, I);
4296     break;
4297   case Instruction::AShr:
4298     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
4299                               cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4300                               AC, I);
4301     break;
4302   case Instruction::And:
4303     Result =
4304         SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4305     break;
4306   case Instruction::Or:
4307     Result =
4308         SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4309     break;
4310   case Instruction::Xor:
4311     Result =
4312         SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4313     break;
4314   case Instruction::ICmp:
4315     Result =
4316         SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
4317                          I->getOperand(1), DL, TLI, DT, AC, I);
4318     break;
4319   case Instruction::FCmp:
4320     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4321                               I->getOperand(0), I->getOperand(1),
4322                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4323     break;
4324   case Instruction::Select:
4325     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
4326                                 I->getOperand(2), DL, TLI, DT, AC, I);
4327     break;
4328   case Instruction::GetElementPtr: {
4329     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
4330     Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
4331                              Ops, DL, TLI, DT, AC, I);
4332     break;
4333   }
4334   case Instruction::InsertValue: {
4335     InsertValueInst *IV = cast<InsertValueInst>(I);
4336     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4337                                      IV->getInsertedValueOperand(),
4338                                      IV->getIndices(), DL, TLI, DT, AC, I);
4339     break;
4340   }
4341   case Instruction::ExtractValue: {
4342     auto *EVI = cast<ExtractValueInst>(I);
4343     Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
4344                                       EVI->getIndices(), DL, TLI, DT, AC, I);
4345     break;
4346   }
4347   case Instruction::ExtractElement: {
4348     auto *EEI = cast<ExtractElementInst>(I);
4349     Result = SimplifyExtractElementInst(
4350         EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
4351     break;
4352   }
4353   case Instruction::PHI:
4354     Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
4355     break;
4356   case Instruction::Call: {
4357     CallSite CS(cast<CallInst>(I));
4358     Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
4359                           TLI, DT, AC, I);
4360     break;
4361   }
4362 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4363 #include "llvm/IR/Instruction.def"
4364 #undef HANDLE_CAST_INST
4365     Result = SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(),
4366                               DL, TLI, DT, AC, I);
4367     break;
4368   }
4369 
4370   // In general, it is possible for computeKnownBits to determine all bits in a
4371   // value even when the operands are not all constants.
4372   if (!Result && I->getType()->isIntegerTy()) {
4373     unsigned BitWidth = I->getType()->getScalarSizeInBits();
4374     APInt KnownZero(BitWidth, 0);
4375     APInt KnownOne(BitWidth, 0);
4376     computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT);
4377     if ((KnownZero | KnownOne).isAllOnesValue())
4378       Result = ConstantInt::get(I->getContext(), KnownOne);
4379   }
4380 
4381   /// If called on unreachable code, the above logic may report that the
4382   /// instruction simplified to itself.  Make life easier for users by
4383   /// detecting that case here, returning a safe value instead.
4384   return Result == I ? UndefValue::get(I->getType()) : Result;
4385 }
4386 
4387 /// \brief Implementation of recursive simplification through an instruction's
4388 /// uses.
4389 ///
4390 /// This is the common implementation of the recursive simplification routines.
4391 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4392 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4393 /// instructions to process and attempt to simplify it using
4394 /// InstructionSimplify.
4395 ///
4396 /// This routine returns 'true' only when *it* simplifies something. The passed
4397 /// in simplified value does not count toward this.
4398 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
4399                                               const TargetLibraryInfo *TLI,
4400                                               const DominatorTree *DT,
4401                                               AssumptionCache *AC) {
4402   bool Simplified = false;
4403   SmallSetVector<Instruction *, 8> Worklist;
4404   const DataLayout &DL = I->getModule()->getDataLayout();
4405 
4406   // If we have an explicit value to collapse to, do that round of the
4407   // simplification loop by hand initially.
4408   if (SimpleV) {
4409     for (User *U : I->users())
4410       if (U != I)
4411         Worklist.insert(cast<Instruction>(U));
4412 
4413     // Replace the instruction with its simplified value.
4414     I->replaceAllUsesWith(SimpleV);
4415 
4416     // Gracefully handle edge cases where the instruction is not wired into any
4417     // parent block.
4418     if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4419         !I->mayHaveSideEffects())
4420       I->eraseFromParent();
4421   } else {
4422     Worklist.insert(I);
4423   }
4424 
4425   // Note that we must test the size on each iteration, the worklist can grow.
4426   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4427     I = Worklist[Idx];
4428 
4429     // See if this instruction simplifies.
4430     SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
4431     if (!SimpleV)
4432       continue;
4433 
4434     Simplified = true;
4435 
4436     // Stash away all the uses of the old instruction so we can check them for
4437     // recursive simplifications after a RAUW. This is cheaper than checking all
4438     // uses of To on the recursive step in most cases.
4439     for (User *U : I->users())
4440       Worklist.insert(cast<Instruction>(U));
4441 
4442     // Replace the instruction with its simplified value.
4443     I->replaceAllUsesWith(SimpleV);
4444 
4445     // Gracefully handle edge cases where the instruction is not wired into any
4446     // parent block.
4447     if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4448         !I->mayHaveSideEffects())
4449       I->eraseFromParent();
4450   }
4451   return Simplified;
4452 }
4453 
4454 bool llvm::recursivelySimplifyInstruction(Instruction *I,
4455                                           const TargetLibraryInfo *TLI,
4456                                           const DominatorTree *DT,
4457                                           AssumptionCache *AC) {
4458   return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
4459 }
4460 
4461 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
4462                                          const TargetLibraryInfo *TLI,
4463                                          const DominatorTree *DT,
4464                                          AssumptionCache *AC) {
4465   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4466   assert(SimpleV && "Must provide a simplified value.");
4467   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
4468 }
4469