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