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   // If any bits in the shift amount make that value greater than or equal to
1319   // the number of bits in the type, the shift is undefined.
1320   unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1321   APInt KnownZero(BitWidth, 0);
1322   APInt KnownOne(BitWidth, 0);
1323   computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1324   if (KnownOne.getLimitedValue() >= BitWidth)
1325     return UndefValue::get(Op0->getType());
1326 
1327   // If all valid bits in the shift amount are known zero, the first operand is
1328   // unchanged.
1329   unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1330   APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1331   if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1332     return Op0;
1333 
1334   return nullptr;
1335 }
1336 
1337 /// \brief Given operands for an Shl, LShr or AShr, see if we can
1338 /// fold the result.  If not, this returns null.
1339 static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1340                                  bool isExact, const Query &Q,
1341                                  unsigned MaxRecurse) {
1342   if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1343     return V;
1344 
1345   // X >> X -> 0
1346   if (Op0 == Op1)
1347     return Constant::getNullValue(Op0->getType());
1348 
1349   // undef >> X -> 0
1350   // undef >> X -> undef (if it's exact)
1351   if (match(Op0, m_Undef()))
1352     return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1353 
1354   // The low bit cannot be shifted out of an exact shift if it is set.
1355   if (isExact) {
1356     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1357     APInt Op0KnownZero(BitWidth, 0);
1358     APInt Op0KnownOne(BitWidth, 0);
1359     computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1360                      Q.CxtI, Q.DT);
1361     if (Op0KnownOne[0])
1362       return Op0;
1363   }
1364 
1365   return nullptr;
1366 }
1367 
1368 /// Given operands for an Shl, see if we can fold the result.
1369 /// If not, this returns null.
1370 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1371                               const Query &Q, unsigned MaxRecurse) {
1372   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1373     return V;
1374 
1375   // undef << X -> 0
1376   // undef << X -> undef if (if it's NSW/NUW)
1377   if (match(Op0, m_Undef()))
1378     return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1379 
1380   // (X >> A) << A -> X
1381   Value *X;
1382   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1383     return X;
1384   return nullptr;
1385 }
1386 
1387 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1388                              const DataLayout &DL, const TargetLibraryInfo *TLI,
1389                              const DominatorTree *DT, AssumptionCache *AC,
1390                              const Instruction *CxtI) {
1391   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
1392                            RecursionLimit);
1393 }
1394 
1395 /// Given operands for an LShr, see if we can fold the result.
1396 /// If not, this returns null.
1397 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1398                                const Query &Q, unsigned MaxRecurse) {
1399   if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1400                                     MaxRecurse))
1401       return V;
1402 
1403   // (X << A) >> A -> X
1404   Value *X;
1405   if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1406     return X;
1407 
1408   return nullptr;
1409 }
1410 
1411 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1412                               const DataLayout &DL,
1413                               const TargetLibraryInfo *TLI,
1414                               const DominatorTree *DT, AssumptionCache *AC,
1415                               const Instruction *CxtI) {
1416   return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
1417                             RecursionLimit);
1418 }
1419 
1420 /// Given operands for an AShr, see if we can fold the result.
1421 /// If not, this returns null.
1422 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1423                                const Query &Q, unsigned MaxRecurse) {
1424   if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1425                                     MaxRecurse))
1426     return V;
1427 
1428   // all ones >>a X -> all ones
1429   if (match(Op0, m_AllOnes()))
1430     return Op0;
1431 
1432   // (X << A) >> A -> X
1433   Value *X;
1434   if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1435     return X;
1436 
1437   // Arithmetic shifting an all-sign-bit value is a no-op.
1438   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1439   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1440     return Op0;
1441 
1442   return nullptr;
1443 }
1444 
1445 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1446                               const DataLayout &DL,
1447                               const TargetLibraryInfo *TLI,
1448                               const DominatorTree *DT, AssumptionCache *AC,
1449                               const Instruction *CxtI) {
1450   return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
1451                             RecursionLimit);
1452 }
1453 
1454 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1455                                          ICmpInst *UnsignedICmp, bool IsAnd) {
1456   Value *X, *Y;
1457 
1458   ICmpInst::Predicate EqPred;
1459   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1460       !ICmpInst::isEquality(EqPred))
1461     return nullptr;
1462 
1463   ICmpInst::Predicate UnsignedPred;
1464   if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1465       ICmpInst::isUnsigned(UnsignedPred))
1466     ;
1467   else if (match(UnsignedICmp,
1468                  m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1469            ICmpInst::isUnsigned(UnsignedPred))
1470     UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1471   else
1472     return nullptr;
1473 
1474   // X < Y && Y != 0  -->  X < Y
1475   // X < Y || Y != 0  -->  Y != 0
1476   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1477     return IsAnd ? UnsignedICmp : ZeroICmp;
1478 
1479   // X >= Y || Y != 0  -->  true
1480   // X >= Y || Y == 0  -->  X >= Y
1481   if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1482     if (EqPred == ICmpInst::ICMP_NE)
1483       return getTrue(UnsignedICmp->getType());
1484     return UnsignedICmp;
1485   }
1486 
1487   // X < Y && Y == 0  -->  false
1488   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1489       IsAnd)
1490     return getFalse(UnsignedICmp->getType());
1491 
1492   return nullptr;
1493 }
1494 
1495 /// Simplify (and (icmp ...) (icmp ...)) to true when we can tell that the range
1496 /// of possible values cannot be satisfied.
1497 static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1498   ICmpInst::Predicate Pred0, Pred1;
1499   ConstantInt *CI1, *CI2;
1500   Value *V;
1501 
1502   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1503     return X;
1504 
1505   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1506                          m_ConstantInt(CI2))))
1507    return nullptr;
1508 
1509   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1510     return nullptr;
1511 
1512   Type *ITy = Op0->getType();
1513 
1514   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1515   bool isNSW = AddInst->hasNoSignedWrap();
1516   bool isNUW = AddInst->hasNoUnsignedWrap();
1517 
1518   const APInt &CI1V = CI1->getValue();
1519   const APInt &CI2V = CI2->getValue();
1520   const APInt Delta = CI2V - CI1V;
1521   if (CI1V.isStrictlyPositive()) {
1522     if (Delta == 2) {
1523       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1524         return getFalse(ITy);
1525       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1526         return getFalse(ITy);
1527     }
1528     if (Delta == 1) {
1529       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1530         return getFalse(ITy);
1531       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1532         return getFalse(ITy);
1533     }
1534   }
1535   if (CI1V.getBoolValue() && isNUW) {
1536     if (Delta == 2)
1537       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1538         return getFalse(ITy);
1539     if (Delta == 1)
1540       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1541         return getFalse(ITy);
1542   }
1543 
1544   return nullptr;
1545 }
1546 
1547 /// Given operands for an And, see if we can fold the result.
1548 /// If not, this returns null.
1549 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1550                               unsigned MaxRecurse) {
1551   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1552     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1553       return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
1554 
1555     // Canonicalize the constant to the RHS.
1556     std::swap(Op0, Op1);
1557   }
1558 
1559   // X & undef -> 0
1560   if (match(Op1, m_Undef()))
1561     return Constant::getNullValue(Op0->getType());
1562 
1563   // X & X = X
1564   if (Op0 == Op1)
1565     return Op0;
1566 
1567   // X & 0 = 0
1568   if (match(Op1, m_Zero()))
1569     return Op1;
1570 
1571   // X & -1 = X
1572   if (match(Op1, m_AllOnes()))
1573     return Op0;
1574 
1575   // A & ~A  =  ~A & A  =  0
1576   if (match(Op0, m_Not(m_Specific(Op1))) ||
1577       match(Op1, m_Not(m_Specific(Op0))))
1578     return Constant::getNullValue(Op0->getType());
1579 
1580   // (A | ?) & A = A
1581   Value *A = nullptr, *B = nullptr;
1582   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1583       (A == Op1 || B == Op1))
1584     return Op1;
1585 
1586   // A & (A | ?) = A
1587   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1588       (A == Op0 || B == Op0))
1589     return Op0;
1590 
1591   // A & (-A) = A if A is a power of two or zero.
1592   if (match(Op0, m_Neg(m_Specific(Op1))) ||
1593       match(Op1, m_Neg(m_Specific(Op0)))) {
1594     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1595                                Q.DT))
1596       return Op0;
1597     if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1598                                Q.DT))
1599       return Op1;
1600   }
1601 
1602   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1603     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1604       if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1605         return V;
1606       if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1607         return V;
1608     }
1609   }
1610 
1611   // Try some generic simplifications for associative operations.
1612   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1613                                           MaxRecurse))
1614     return V;
1615 
1616   // And distributes over Or.  Try some generic simplifications based on this.
1617   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1618                              Q, MaxRecurse))
1619     return V;
1620 
1621   // And distributes over Xor.  Try some generic simplifications based on this.
1622   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1623                              Q, MaxRecurse))
1624     return V;
1625 
1626   // If the operation is with the result of a select instruction, check whether
1627   // operating on either branch of the select always yields the same value.
1628   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1629     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1630                                          MaxRecurse))
1631       return V;
1632 
1633   // If the operation is with the result of a phi instruction, check whether
1634   // operating on all incoming values of the phi always yields the same value.
1635   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1636     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1637                                       MaxRecurse))
1638       return V;
1639 
1640   return nullptr;
1641 }
1642 
1643 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
1644                              const TargetLibraryInfo *TLI,
1645                              const DominatorTree *DT, AssumptionCache *AC,
1646                              const Instruction *CxtI) {
1647   return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1648                            RecursionLimit);
1649 }
1650 
1651 /// Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1652 /// contains all possible values.
1653 static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1654   ICmpInst::Predicate Pred0, Pred1;
1655   ConstantInt *CI1, *CI2;
1656   Value *V;
1657 
1658   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1659     return X;
1660 
1661   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1662                          m_ConstantInt(CI2))))
1663    return nullptr;
1664 
1665   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1666     return nullptr;
1667 
1668   Type *ITy = Op0->getType();
1669 
1670   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1671   bool isNSW = AddInst->hasNoSignedWrap();
1672   bool isNUW = AddInst->hasNoUnsignedWrap();
1673 
1674   const APInt &CI1V = CI1->getValue();
1675   const APInt &CI2V = CI2->getValue();
1676   const APInt Delta = CI2V - CI1V;
1677   if (CI1V.isStrictlyPositive()) {
1678     if (Delta == 2) {
1679       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1680         return getTrue(ITy);
1681       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1682         return getTrue(ITy);
1683     }
1684     if (Delta == 1) {
1685       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1686         return getTrue(ITy);
1687       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1688         return getTrue(ITy);
1689     }
1690   }
1691   if (CI1V.getBoolValue() && isNUW) {
1692     if (Delta == 2)
1693       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1694         return getTrue(ITy);
1695     if (Delta == 1)
1696       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1697         return getTrue(ITy);
1698   }
1699 
1700   return nullptr;
1701 }
1702 
1703 /// Given operands for an Or, see if we can fold the result.
1704 /// If not, this returns null.
1705 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1706                              unsigned MaxRecurse) {
1707   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1708     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1709       return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
1710 
1711     // Canonicalize the constant to the RHS.
1712     std::swap(Op0, Op1);
1713   }
1714 
1715   // X | undef -> -1
1716   if (match(Op1, m_Undef()))
1717     return Constant::getAllOnesValue(Op0->getType());
1718 
1719   // X | X = X
1720   if (Op0 == Op1)
1721     return Op0;
1722 
1723   // X | 0 = X
1724   if (match(Op1, m_Zero()))
1725     return Op0;
1726 
1727   // X | -1 = -1
1728   if (match(Op1, m_AllOnes()))
1729     return Op1;
1730 
1731   // A | ~A  =  ~A | A  =  -1
1732   if (match(Op0, m_Not(m_Specific(Op1))) ||
1733       match(Op1, m_Not(m_Specific(Op0))))
1734     return Constant::getAllOnesValue(Op0->getType());
1735 
1736   // (A & ?) | A = A
1737   Value *A = nullptr, *B = nullptr;
1738   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1739       (A == Op1 || B == Op1))
1740     return Op1;
1741 
1742   // A | (A & ?) = A
1743   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1744       (A == Op0 || B == Op0))
1745     return Op0;
1746 
1747   // ~(A & ?) | A = -1
1748   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1749       (A == Op1 || B == Op1))
1750     return Constant::getAllOnesValue(Op1->getType());
1751 
1752   // A | ~(A & ?) = -1
1753   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1754       (A == Op0 || B == Op0))
1755     return Constant::getAllOnesValue(Op0->getType());
1756 
1757   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1758     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1759       if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1760         return V;
1761       if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1762         return V;
1763     }
1764   }
1765 
1766   // Try some generic simplifications for associative operations.
1767   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1768                                           MaxRecurse))
1769     return V;
1770 
1771   // Or distributes over And.  Try some generic simplifications based on this.
1772   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1773                              MaxRecurse))
1774     return V;
1775 
1776   // If the operation is with the result of a select instruction, check whether
1777   // operating on either branch of the select always yields the same value.
1778   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1779     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1780                                          MaxRecurse))
1781       return V;
1782 
1783   // (A & C)|(B & D)
1784   Value *C = nullptr, *D = nullptr;
1785   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1786       match(Op1, m_And(m_Value(B), m_Value(D)))) {
1787     ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1788     ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1789     if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1790       // (A & C1)|(B & C2)
1791       // If we have: ((V + N) & C1) | (V & C2)
1792       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1793       // replace with V+N.
1794       Value *V1, *V2;
1795       if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1796           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1797         // Add commutes, try both ways.
1798         if (V1 == B &&
1799             MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1800           return A;
1801         if (V2 == B &&
1802             MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1803           return A;
1804       }
1805       // Or commutes, try both ways.
1806       if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1807           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1808         // Add commutes, try both ways.
1809         if (V1 == A &&
1810             MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1811           return B;
1812         if (V2 == A &&
1813             MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1814           return B;
1815       }
1816     }
1817   }
1818 
1819   // If the operation is with the result of a phi instruction, check whether
1820   // operating on all incoming values of the phi always yields the same value.
1821   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1822     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1823       return V;
1824 
1825   return nullptr;
1826 }
1827 
1828 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
1829                             const TargetLibraryInfo *TLI,
1830                             const DominatorTree *DT, AssumptionCache *AC,
1831                             const Instruction *CxtI) {
1832   return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1833                           RecursionLimit);
1834 }
1835 
1836 /// Given operands for a Xor, see if we can fold the result.
1837 /// If not, this returns null.
1838 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1839                               unsigned MaxRecurse) {
1840   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1841     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1842       return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
1843 
1844     // Canonicalize the constant to the RHS.
1845     std::swap(Op0, Op1);
1846   }
1847 
1848   // A ^ undef -> undef
1849   if (match(Op1, m_Undef()))
1850     return Op1;
1851 
1852   // A ^ 0 = A
1853   if (match(Op1, m_Zero()))
1854     return Op0;
1855 
1856   // A ^ A = 0
1857   if (Op0 == Op1)
1858     return Constant::getNullValue(Op0->getType());
1859 
1860   // A ^ ~A  =  ~A ^ A  =  -1
1861   if (match(Op0, m_Not(m_Specific(Op1))) ||
1862       match(Op1, m_Not(m_Specific(Op0))))
1863     return Constant::getAllOnesValue(Op0->getType());
1864 
1865   // Try some generic simplifications for associative operations.
1866   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1867                                           MaxRecurse))
1868     return V;
1869 
1870   // Threading Xor over selects and phi nodes is pointless, so don't bother.
1871   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1872   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1873   // only if B and C are equal.  If B and C are equal then (since we assume
1874   // that operands have already been simplified) "select(cond, B, C)" should
1875   // have been simplified to the common value of B and C already.  Analysing
1876   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1877   // for threading over phi nodes.
1878 
1879   return nullptr;
1880 }
1881 
1882 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
1883                              const TargetLibraryInfo *TLI,
1884                              const DominatorTree *DT, AssumptionCache *AC,
1885                              const Instruction *CxtI) {
1886   return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1887                            RecursionLimit);
1888 }
1889 
1890 static Type *GetCompareTy(Value *Op) {
1891   return CmpInst::makeCmpResultType(Op->getType());
1892 }
1893 
1894 /// Rummage around inside V looking for something equivalent to the comparison
1895 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
1896 /// Helper function for analyzing max/min idioms.
1897 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1898                                          Value *LHS, Value *RHS) {
1899   SelectInst *SI = dyn_cast<SelectInst>(V);
1900   if (!SI)
1901     return nullptr;
1902   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1903   if (!Cmp)
1904     return nullptr;
1905   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1906   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1907     return Cmp;
1908   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1909       LHS == CmpRHS && RHS == CmpLHS)
1910     return Cmp;
1911   return nullptr;
1912 }
1913 
1914 // A significant optimization not implemented here is assuming that alloca
1915 // addresses are not equal to incoming argument values. They don't *alias*,
1916 // as we say, but that doesn't mean they aren't equal, so we take a
1917 // conservative approach.
1918 //
1919 // This is inspired in part by C++11 5.10p1:
1920 //   "Two pointers of the same type compare equal if and only if they are both
1921 //    null, both point to the same function, or both represent the same
1922 //    address."
1923 //
1924 // This is pretty permissive.
1925 //
1926 // It's also partly due to C11 6.5.9p6:
1927 //   "Two pointers compare equal if and only if both are null pointers, both are
1928 //    pointers to the same object (including a pointer to an object and a
1929 //    subobject at its beginning) or function, both are pointers to one past the
1930 //    last element of the same array object, or one is a pointer to one past the
1931 //    end of one array object and the other is a pointer to the start of a
1932 //    different array object that happens to immediately follow the first array
1933 //    object in the address space.)
1934 //
1935 // C11's version is more restrictive, however there's no reason why an argument
1936 // couldn't be a one-past-the-end value for a stack object in the caller and be
1937 // equal to the beginning of a stack object in the callee.
1938 //
1939 // If the C and C++ standards are ever made sufficiently restrictive in this
1940 // area, it may be possible to update LLVM's semantics accordingly and reinstate
1941 // this optimization.
1942 static Constant *
1943 computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
1944                    const DominatorTree *DT, CmpInst::Predicate Pred,
1945                    const Instruction *CxtI, Value *LHS, Value *RHS) {
1946   // First, skip past any trivial no-ops.
1947   LHS = LHS->stripPointerCasts();
1948   RHS = RHS->stripPointerCasts();
1949 
1950   // A non-null pointer is not equal to a null pointer.
1951   if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
1952       (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1953     return ConstantInt::get(GetCompareTy(LHS),
1954                             !CmpInst::isTrueWhenEqual(Pred));
1955 
1956   // We can only fold certain predicates on pointer comparisons.
1957   switch (Pred) {
1958   default:
1959     return nullptr;
1960 
1961     // Equality comaprisons are easy to fold.
1962   case CmpInst::ICMP_EQ:
1963   case CmpInst::ICMP_NE:
1964     break;
1965 
1966     // We can only handle unsigned relational comparisons because 'inbounds' on
1967     // a GEP only protects against unsigned wrapping.
1968   case CmpInst::ICMP_UGT:
1969   case CmpInst::ICMP_UGE:
1970   case CmpInst::ICMP_ULT:
1971   case CmpInst::ICMP_ULE:
1972     // However, we have to switch them to their signed variants to handle
1973     // negative indices from the base pointer.
1974     Pred = ICmpInst::getSignedPredicate(Pred);
1975     break;
1976   }
1977 
1978   // Strip off any constant offsets so that we can reason about them.
1979   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1980   // here and compare base addresses like AliasAnalysis does, however there are
1981   // numerous hazards. AliasAnalysis and its utilities rely on special rules
1982   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1983   // doesn't need to guarantee pointer inequality when it says NoAlias.
1984   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
1985   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
1986 
1987   // If LHS and RHS are related via constant offsets to the same base
1988   // value, we can replace it with an icmp which just compares the offsets.
1989   if (LHS == RHS)
1990     return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1991 
1992   // Various optimizations for (in)equality comparisons.
1993   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1994     // Different non-empty allocations that exist at the same time have
1995     // different addresses (if the program can tell). Global variables always
1996     // exist, so they always exist during the lifetime of each other and all
1997     // allocas. Two different allocas usually have different addresses...
1998     //
1999     // However, if there's an @llvm.stackrestore dynamically in between two
2000     // allocas, they may have the same address. It's tempting to reduce the
2001     // scope of the problem by only looking at *static* allocas here. That would
2002     // cover the majority of allocas while significantly reducing the likelihood
2003     // of having an @llvm.stackrestore pop up in the middle. However, it's not
2004     // actually impossible for an @llvm.stackrestore to pop up in the middle of
2005     // an entry block. Also, if we have a block that's not attached to a
2006     // function, we can't tell if it's "static" under the current definition.
2007     // Theoretically, this problem could be fixed by creating a new kind of
2008     // instruction kind specifically for static allocas. Such a new instruction
2009     // could be required to be at the top of the entry block, thus preventing it
2010     // from being subject to a @llvm.stackrestore. Instcombine could even
2011     // convert regular allocas into these special allocas. It'd be nifty.
2012     // However, until then, this problem remains open.
2013     //
2014     // So, we'll assume that two non-empty allocas have different addresses
2015     // for now.
2016     //
2017     // With all that, if the offsets are within the bounds of their allocations
2018     // (and not one-past-the-end! so we can't use inbounds!), and their
2019     // allocations aren't the same, the pointers are not equal.
2020     //
2021     // Note that it's not necessary to check for LHS being a global variable
2022     // address, due to canonicalization and constant folding.
2023     if (isa<AllocaInst>(LHS) &&
2024         (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
2025       ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2026       ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
2027       uint64_t LHSSize, RHSSize;
2028       if (LHSOffsetCI && RHSOffsetCI &&
2029           getObjectSize(LHS, LHSSize, DL, TLI) &&
2030           getObjectSize(RHS, RHSSize, DL, TLI)) {
2031         const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2032         const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
2033         if (!LHSOffsetValue.isNegative() &&
2034             !RHSOffsetValue.isNegative() &&
2035             LHSOffsetValue.ult(LHSSize) &&
2036             RHSOffsetValue.ult(RHSSize)) {
2037           return ConstantInt::get(GetCompareTy(LHS),
2038                                   !CmpInst::isTrueWhenEqual(Pred));
2039         }
2040       }
2041 
2042       // Repeat the above check but this time without depending on DataLayout
2043       // or being able to compute a precise size.
2044       if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2045           !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2046           LHSOffset->isNullValue() &&
2047           RHSOffset->isNullValue())
2048         return ConstantInt::get(GetCompareTy(LHS),
2049                                 !CmpInst::isTrueWhenEqual(Pred));
2050     }
2051 
2052     // Even if an non-inbounds GEP occurs along the path we can still optimize
2053     // equality comparisons concerning the result. We avoid walking the whole
2054     // chain again by starting where the last calls to
2055     // stripAndComputeConstantOffsets left off and accumulate the offsets.
2056     Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2057     Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
2058     if (LHS == RHS)
2059       return ConstantExpr::getICmp(Pred,
2060                                    ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2061                                    ConstantExpr::getAdd(RHSOffset, RHSNoBound));
2062 
2063     // If one side of the equality comparison must come from a noalias call
2064     // (meaning a system memory allocation function), and the other side must
2065     // come from a pointer that cannot overlap with dynamically-allocated
2066     // memory within the lifetime of the current function (allocas, byval
2067     // arguments, globals), then determine the comparison result here.
2068     SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2069     GetUnderlyingObjects(LHS, LHSUObjs, DL);
2070     GetUnderlyingObjects(RHS, RHSUObjs, DL);
2071 
2072     // Is the set of underlying objects all noalias calls?
2073     auto IsNAC = [](SmallVectorImpl<Value *> &Objects) {
2074       return std::all_of(Objects.begin(), Objects.end(), isNoAliasCall);
2075     };
2076 
2077     // Is the set of underlying objects all things which must be disjoint from
2078     // noalias calls. For allocas, we consider only static ones (dynamic
2079     // allocas might be transformed into calls to malloc not simultaneously
2080     // live with the compared-to allocation). For globals, we exclude symbols
2081     // that might be resolve lazily to symbols in another dynamically-loaded
2082     // library (and, thus, could be malloc'ed by the implementation).
2083     auto IsAllocDisjoint = [](SmallVectorImpl<Value *> &Objects) {
2084       return std::all_of(Objects.begin(), Objects.end(), [](Value *V) {
2085         if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2086           return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2087         if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2088           return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2089                   GV->hasProtectedVisibility() || GV->hasUnnamedAddr()) &&
2090                  !GV->isThreadLocal();
2091         if (const Argument *A = dyn_cast<Argument>(V))
2092           return A->hasByValAttr();
2093         return false;
2094       });
2095     };
2096 
2097     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2098         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2099         return ConstantInt::get(GetCompareTy(LHS),
2100                                 !CmpInst::isTrueWhenEqual(Pred));
2101 
2102     // Fold comparisons for non-escaping pointer even if the allocation call
2103     // cannot be elided. We cannot fold malloc comparison to null. Also, the
2104     // dynamic allocation call could be either of the operands.
2105     Value *MI = nullptr;
2106     if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT, TLI))
2107       MI = LHS;
2108     else if (isAllocLikeFn(RHS, TLI) &&
2109              llvm::isKnownNonNullAt(LHS, CxtI, DT, TLI))
2110       MI = RHS;
2111     // FIXME: We should also fold the compare when the pointer escapes, but the
2112     // compare dominates the pointer escape
2113     if (MI && !PointerMayBeCaptured(MI, true, true))
2114       return ConstantInt::get(GetCompareTy(LHS),
2115                               CmpInst::isFalseWhenEqual(Pred));
2116   }
2117 
2118   // Otherwise, fail.
2119   return nullptr;
2120 }
2121 
2122 /// Given operands for an ICmpInst, see if we can fold the result.
2123 /// If not, this returns null.
2124 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2125                                const Query &Q, unsigned MaxRecurse) {
2126   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2127   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
2128 
2129   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2130     if (Constant *CRHS = dyn_cast<Constant>(RHS))
2131       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
2132 
2133     // If we have a constant, make sure it is on the RHS.
2134     std::swap(LHS, RHS);
2135     Pred = CmpInst::getSwappedPredicate(Pred);
2136   }
2137 
2138   Type *ITy = GetCompareTy(LHS); // The return type.
2139   Type *OpTy = LHS->getType();   // The operand type.
2140 
2141   // icmp X, X -> true/false
2142   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
2143   // because X could be 0.
2144   if (LHS == RHS || isa<UndefValue>(RHS))
2145     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
2146 
2147   // Special case logic when the operands have i1 type.
2148   if (OpTy->getScalarType()->isIntegerTy(1)) {
2149     switch (Pred) {
2150     default: break;
2151     case ICmpInst::ICMP_EQ:
2152       // X == 1 -> X
2153       if (match(RHS, m_One()))
2154         return LHS;
2155       break;
2156     case ICmpInst::ICMP_NE:
2157       // X != 0 -> X
2158       if (match(RHS, m_Zero()))
2159         return LHS;
2160       break;
2161     case ICmpInst::ICMP_UGT:
2162       // X >u 0 -> X
2163       if (match(RHS, m_Zero()))
2164         return LHS;
2165       break;
2166     case ICmpInst::ICMP_UGE: {
2167       // X >=u 1 -> X
2168       if (match(RHS, m_One()))
2169         return LHS;
2170       if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2171         return getTrue(ITy);
2172       break;
2173     }
2174     case ICmpInst::ICMP_SGE: {
2175       /// For signed comparison, the values for an i1 are 0 and -1
2176       /// respectively. This maps into a truth table of:
2177       /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
2178       ///  0  |  0  |  1 (0 >= 0)   |  1
2179       ///  0  |  1  |  1 (0 >= -1)  |  1
2180       ///  1  |  0  |  0 (-1 >= 0)  |  0
2181       ///  1  |  1  |  1 (-1 >= -1) |  1
2182       if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2183         return getTrue(ITy);
2184       break;
2185     }
2186     case ICmpInst::ICMP_SLT:
2187       // X <s 0 -> X
2188       if (match(RHS, m_Zero()))
2189         return LHS;
2190       break;
2191     case ICmpInst::ICMP_SLE:
2192       // X <=s -1 -> X
2193       if (match(RHS, m_One()))
2194         return LHS;
2195       break;
2196     case ICmpInst::ICMP_ULE: {
2197       if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2198         return getTrue(ITy);
2199       break;
2200     }
2201     }
2202   }
2203 
2204   // If we are comparing with zero then try hard since this is a common case.
2205   if (match(RHS, m_Zero())) {
2206     bool LHSKnownNonNegative, LHSKnownNegative;
2207     switch (Pred) {
2208     default: llvm_unreachable("Unknown ICmp predicate!");
2209     case ICmpInst::ICMP_ULT:
2210       return getFalse(ITy);
2211     case ICmpInst::ICMP_UGE:
2212       return getTrue(ITy);
2213     case ICmpInst::ICMP_EQ:
2214     case ICmpInst::ICMP_ULE:
2215       if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2216         return getFalse(ITy);
2217       break;
2218     case ICmpInst::ICMP_NE:
2219     case ICmpInst::ICMP_UGT:
2220       if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2221         return getTrue(ITy);
2222       break;
2223     case ICmpInst::ICMP_SLT:
2224       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2225                      Q.CxtI, Q.DT);
2226       if (LHSKnownNegative)
2227         return getTrue(ITy);
2228       if (LHSKnownNonNegative)
2229         return getFalse(ITy);
2230       break;
2231     case ICmpInst::ICMP_SLE:
2232       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2233                      Q.CxtI, Q.DT);
2234       if (LHSKnownNegative)
2235         return getTrue(ITy);
2236       if (LHSKnownNonNegative &&
2237           isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2238         return getFalse(ITy);
2239       break;
2240     case ICmpInst::ICMP_SGE:
2241       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2242                      Q.CxtI, Q.DT);
2243       if (LHSKnownNegative)
2244         return getFalse(ITy);
2245       if (LHSKnownNonNegative)
2246         return getTrue(ITy);
2247       break;
2248     case ICmpInst::ICMP_SGT:
2249       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2250                      Q.CxtI, Q.DT);
2251       if (LHSKnownNegative)
2252         return getFalse(ITy);
2253       if (LHSKnownNonNegative &&
2254           isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2255         return getTrue(ITy);
2256       break;
2257     }
2258   }
2259 
2260   // See if we are doing a comparison with a constant integer.
2261   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2262     // Rule out tautological comparisons (eg., ult 0 or uge 0).
2263     ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
2264     if (RHS_CR.isEmptySet())
2265       return ConstantInt::getFalse(CI->getContext());
2266     if (RHS_CR.isFullSet())
2267       return ConstantInt::getTrue(CI->getContext());
2268 
2269     // Many binary operators with constant RHS have easy to compute constant
2270     // range.  Use them to check whether the comparison is a tautology.
2271     unsigned Width = CI->getBitWidth();
2272     APInt Lower = APInt(Width, 0);
2273     APInt Upper = APInt(Width, 0);
2274     ConstantInt *CI2;
2275     if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2276       // 'urem x, CI2' produces [0, CI2).
2277       Upper = CI2->getValue();
2278     } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2279       // 'srem x, CI2' produces (-|CI2|, |CI2|).
2280       Upper = CI2->getValue().abs();
2281       Lower = (-Upper) + 1;
2282     } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2283       // 'udiv CI2, x' produces [0, CI2].
2284       Upper = CI2->getValue() + 1;
2285     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2286       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2287       APInt NegOne = APInt::getAllOnesValue(Width);
2288       if (!CI2->isZero())
2289         Upper = NegOne.udiv(CI2->getValue()) + 1;
2290     } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
2291       if (CI2->isMinSignedValue()) {
2292         // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2293         Lower = CI2->getValue();
2294         Upper = Lower.lshr(1) + 1;
2295       } else {
2296         // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2297         Upper = CI2->getValue().abs() + 1;
2298         Lower = (-Upper) + 1;
2299       }
2300     } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
2301       APInt IntMin = APInt::getSignedMinValue(Width);
2302       APInt IntMax = APInt::getSignedMaxValue(Width);
2303       APInt Val = CI2->getValue();
2304       if (Val.isAllOnesValue()) {
2305         // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2306         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
2307         Lower = IntMin + 1;
2308         Upper = IntMax + 1;
2309       } else if (Val.countLeadingZeros() < Width - 1) {
2310         // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
2311         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
2312         Lower = IntMin.sdiv(Val);
2313         Upper = IntMax.sdiv(Val);
2314         if (Lower.sgt(Upper))
2315           std::swap(Lower, Upper);
2316         Upper = Upper + 1;
2317         assert(Upper != Lower && "Upper part of range has wrapped!");
2318       }
2319     } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
2320       // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
2321       Lower = CI2->getValue();
2322       Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2323     } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
2324       if (CI2->isNegative()) {
2325         // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
2326         unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
2327         Lower = CI2->getValue().shl(ShiftAmount);
2328         Upper = CI2->getValue() + 1;
2329       } else {
2330         // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
2331         unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
2332         Lower = CI2->getValue();
2333         Upper = CI2->getValue().shl(ShiftAmount) + 1;
2334       }
2335     } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2336       // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2337       APInt NegOne = APInt::getAllOnesValue(Width);
2338       if (CI2->getValue().ult(Width))
2339         Upper = NegOne.lshr(CI2->getValue()) + 1;
2340     } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2341       // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2342       unsigned ShiftAmount = Width - 1;
2343       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2344         ShiftAmount = CI2->getValue().countTrailingZeros();
2345       Lower = CI2->getValue().lshr(ShiftAmount);
2346       Upper = CI2->getValue() + 1;
2347     } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2348       // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2349       APInt IntMin = APInt::getSignedMinValue(Width);
2350       APInt IntMax = APInt::getSignedMaxValue(Width);
2351       if (CI2->getValue().ult(Width)) {
2352         Lower = IntMin.ashr(CI2->getValue());
2353         Upper = IntMax.ashr(CI2->getValue()) + 1;
2354       }
2355     } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2356       unsigned ShiftAmount = Width - 1;
2357       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2358         ShiftAmount = CI2->getValue().countTrailingZeros();
2359       if (CI2->isNegative()) {
2360         // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2361         Lower = CI2->getValue();
2362         Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2363       } else {
2364         // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2365         Lower = CI2->getValue().ashr(ShiftAmount);
2366         Upper = CI2->getValue() + 1;
2367       }
2368     } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2369       // 'or x, CI2' produces [CI2, UINT_MAX].
2370       Lower = CI2->getValue();
2371     } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2372       // 'and x, CI2' produces [0, CI2].
2373       Upper = CI2->getValue() + 1;
2374     } else if (match(LHS, m_NUWAdd(m_Value(), m_ConstantInt(CI2)))) {
2375       // 'add nuw x, CI2' produces [CI2, UINT_MAX].
2376       Lower = CI2->getValue();
2377     }
2378 
2379     ConstantRange LHS_CR = Lower != Upper ? ConstantRange(Lower, Upper)
2380                                           : ConstantRange(Width, true);
2381 
2382     if (auto *I = dyn_cast<Instruction>(LHS))
2383       if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2384         LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2385 
2386     if (!LHS_CR.isFullSet()) {
2387       if (RHS_CR.contains(LHS_CR))
2388         return ConstantInt::getTrue(RHS->getContext());
2389       if (RHS_CR.inverse().contains(LHS_CR))
2390         return ConstantInt::getFalse(RHS->getContext());
2391     }
2392   }
2393 
2394   // If both operands have range metadata, use the metadata
2395   // to simplify the comparison.
2396   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
2397     auto RHS_Instr = dyn_cast<Instruction>(RHS);
2398     auto LHS_Instr = dyn_cast<Instruction>(LHS);
2399 
2400     if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
2401         LHS_Instr->getMetadata(LLVMContext::MD_range)) {
2402       auto RHS_CR = getConstantRangeFromMetadata(
2403           *RHS_Instr->getMetadata(LLVMContext::MD_range));
2404       auto LHS_CR = getConstantRangeFromMetadata(
2405           *LHS_Instr->getMetadata(LLVMContext::MD_range));
2406 
2407       auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
2408       if (Satisfied_CR.contains(LHS_CR))
2409         return ConstantInt::getTrue(RHS->getContext());
2410 
2411       auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
2412                 CmpInst::getInversePredicate(Pred), RHS_CR);
2413       if (InversedSatisfied_CR.contains(LHS_CR))
2414         return ConstantInt::getFalse(RHS->getContext());
2415     }
2416   }
2417 
2418   // Compare of cast, for example (zext X) != 0 -> X != 0
2419   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2420     Instruction *LI = cast<CastInst>(LHS);
2421     Value *SrcOp = LI->getOperand(0);
2422     Type *SrcTy = SrcOp->getType();
2423     Type *DstTy = LI->getType();
2424 
2425     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2426     // if the integer type is the same size as the pointer type.
2427     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
2428         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
2429       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2430         // Transfer the cast to the constant.
2431         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2432                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
2433                                         Q, MaxRecurse-1))
2434           return V;
2435       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2436         if (RI->getOperand(0)->getType() == SrcTy)
2437           // Compare without the cast.
2438           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2439                                           Q, MaxRecurse-1))
2440             return V;
2441       }
2442     }
2443 
2444     if (isa<ZExtInst>(LHS)) {
2445       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2446       // same type.
2447       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2448         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2449           // Compare X and Y.  Note that signed predicates become unsigned.
2450           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2451                                           SrcOp, RI->getOperand(0), Q,
2452                                           MaxRecurse-1))
2453             return V;
2454       }
2455       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2456       // too.  If not, then try to deduce the result of the comparison.
2457       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2458         // Compute the constant that would happen if we truncated to SrcTy then
2459         // reextended to DstTy.
2460         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2461         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2462 
2463         // If the re-extended constant didn't change then this is effectively
2464         // also a case of comparing two zero-extended values.
2465         if (RExt == CI && MaxRecurse)
2466           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2467                                         SrcOp, Trunc, Q, MaxRecurse-1))
2468             return V;
2469 
2470         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2471         // there.  Use this to work out the result of the comparison.
2472         if (RExt != CI) {
2473           switch (Pred) {
2474           default: llvm_unreachable("Unknown ICmp predicate!");
2475           // LHS <u RHS.
2476           case ICmpInst::ICMP_EQ:
2477           case ICmpInst::ICMP_UGT:
2478           case ICmpInst::ICMP_UGE:
2479             return ConstantInt::getFalse(CI->getContext());
2480 
2481           case ICmpInst::ICMP_NE:
2482           case ICmpInst::ICMP_ULT:
2483           case ICmpInst::ICMP_ULE:
2484             return ConstantInt::getTrue(CI->getContext());
2485 
2486           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
2487           // is non-negative then LHS <s RHS.
2488           case ICmpInst::ICMP_SGT:
2489           case ICmpInst::ICMP_SGE:
2490             return CI->getValue().isNegative() ?
2491               ConstantInt::getTrue(CI->getContext()) :
2492               ConstantInt::getFalse(CI->getContext());
2493 
2494           case ICmpInst::ICMP_SLT:
2495           case ICmpInst::ICMP_SLE:
2496             return CI->getValue().isNegative() ?
2497               ConstantInt::getFalse(CI->getContext()) :
2498               ConstantInt::getTrue(CI->getContext());
2499           }
2500         }
2501       }
2502     }
2503 
2504     if (isa<SExtInst>(LHS)) {
2505       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2506       // same type.
2507       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2508         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2509           // Compare X and Y.  Note that the predicate does not change.
2510           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2511                                           Q, MaxRecurse-1))
2512             return V;
2513       }
2514       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2515       // too.  If not, then try to deduce the result of the comparison.
2516       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2517         // Compute the constant that would happen if we truncated to SrcTy then
2518         // reextended to DstTy.
2519         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2520         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2521 
2522         // If the re-extended constant didn't change then this is effectively
2523         // also a case of comparing two sign-extended values.
2524         if (RExt == CI && MaxRecurse)
2525           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
2526             return V;
2527 
2528         // Otherwise the upper bits of LHS are all equal, while RHS has varying
2529         // bits there.  Use this to work out the result of the comparison.
2530         if (RExt != CI) {
2531           switch (Pred) {
2532           default: llvm_unreachable("Unknown ICmp predicate!");
2533           case ICmpInst::ICMP_EQ:
2534             return ConstantInt::getFalse(CI->getContext());
2535           case ICmpInst::ICMP_NE:
2536             return ConstantInt::getTrue(CI->getContext());
2537 
2538           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
2539           // LHS >s RHS.
2540           case ICmpInst::ICMP_SGT:
2541           case ICmpInst::ICMP_SGE:
2542             return CI->getValue().isNegative() ?
2543               ConstantInt::getTrue(CI->getContext()) :
2544               ConstantInt::getFalse(CI->getContext());
2545           case ICmpInst::ICMP_SLT:
2546           case ICmpInst::ICMP_SLE:
2547             return CI->getValue().isNegative() ?
2548               ConstantInt::getFalse(CI->getContext()) :
2549               ConstantInt::getTrue(CI->getContext());
2550 
2551           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
2552           // LHS >u RHS.
2553           case ICmpInst::ICMP_UGT:
2554           case ICmpInst::ICMP_UGE:
2555             // Comparison is true iff the LHS <s 0.
2556             if (MaxRecurse)
2557               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2558                                               Constant::getNullValue(SrcTy),
2559                                               Q, MaxRecurse-1))
2560                 return V;
2561             break;
2562           case ICmpInst::ICMP_ULT:
2563           case ICmpInst::ICMP_ULE:
2564             // Comparison is true iff the LHS >=s 0.
2565             if (MaxRecurse)
2566               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2567                                               Constant::getNullValue(SrcTy),
2568                                               Q, MaxRecurse-1))
2569                 return V;
2570             break;
2571           }
2572         }
2573       }
2574     }
2575   }
2576 
2577   // icmp eq|ne X, Y -> false|true if X != Y
2578   if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2579       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
2580     LLVMContext &Ctx = LHS->getType()->getContext();
2581     return Pred == ICmpInst::ICMP_NE ?
2582       ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
2583   }
2584 
2585   // Special logic for binary operators.
2586   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2587   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2588   if (MaxRecurse && (LBO || RBO)) {
2589     // Analyze the case when either LHS or RHS is an add instruction.
2590     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2591     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2592     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2593     if (LBO && LBO->getOpcode() == Instruction::Add) {
2594       A = LBO->getOperand(0); B = LBO->getOperand(1);
2595       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2596         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2597         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2598     }
2599     if (RBO && RBO->getOpcode() == Instruction::Add) {
2600       C = RBO->getOperand(0); D = RBO->getOperand(1);
2601       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2602         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2603         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2604     }
2605 
2606     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2607     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2608       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2609                                       Constant::getNullValue(RHS->getType()),
2610                                       Q, MaxRecurse-1))
2611         return V;
2612 
2613     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2614     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2615       if (Value *V = SimplifyICmpInst(Pred,
2616                                       Constant::getNullValue(LHS->getType()),
2617                                       C == LHS ? D : C, Q, MaxRecurse-1))
2618         return V;
2619 
2620     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2621     if (A && C && (A == C || A == D || B == C || B == D) &&
2622         NoLHSWrapProblem && NoRHSWrapProblem) {
2623       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2624       Value *Y, *Z;
2625       if (A == C) {
2626         // C + B == C + D  ->  B == D
2627         Y = B;
2628         Z = D;
2629       } else if (A == D) {
2630         // D + B == C + D  ->  B == C
2631         Y = B;
2632         Z = C;
2633       } else if (B == C) {
2634         // A + C == C + D  ->  A == D
2635         Y = A;
2636         Z = D;
2637       } else {
2638         assert(B == D);
2639         // A + D == C + D  ->  A == C
2640         Y = A;
2641         Z = C;
2642       }
2643       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2644         return V;
2645     }
2646   }
2647 
2648   {
2649     Value *Y = nullptr;
2650     // icmp pred (or X, Y), X
2651     if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2652       if (Pred == ICmpInst::ICMP_ULT)
2653         return getFalse(ITy);
2654       if (Pred == ICmpInst::ICMP_UGE)
2655         return getTrue(ITy);
2656 
2657       if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2658         bool RHSKnownNonNegative, RHSKnownNegative;
2659         bool YKnownNonNegative, YKnownNegative;
2660         ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
2661                        Q.AC, Q.CxtI, Q.DT);
2662         ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2663                        Q.CxtI, Q.DT);
2664         if (RHSKnownNonNegative && YKnownNegative)
2665           return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2666         if (RHSKnownNegative || YKnownNonNegative)
2667           return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2668       }
2669     }
2670     // icmp pred X, (or X, Y)
2671     if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2672       if (Pred == ICmpInst::ICMP_ULE)
2673         return getTrue(ITy);
2674       if (Pred == ICmpInst::ICMP_UGT)
2675         return getFalse(ITy);
2676 
2677       if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2678         bool LHSKnownNonNegative, LHSKnownNegative;
2679         bool YKnownNonNegative, YKnownNegative;
2680         ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
2681                        Q.AC, Q.CxtI, Q.DT);
2682         ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2683                        Q.CxtI, Q.DT);
2684         if (LHSKnownNonNegative && YKnownNegative)
2685           return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2686         if (LHSKnownNegative || YKnownNonNegative)
2687           return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2688       }
2689     }
2690   }
2691 
2692   // icmp pred (and X, Y), X
2693   if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2694                                     m_And(m_Specific(RHS), m_Value())))) {
2695     if (Pred == ICmpInst::ICMP_UGT)
2696       return getFalse(ITy);
2697     if (Pred == ICmpInst::ICMP_ULE)
2698       return getTrue(ITy);
2699   }
2700   // icmp pred X, (and X, Y)
2701   if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2702                                     m_And(m_Specific(LHS), m_Value())))) {
2703     if (Pred == ICmpInst::ICMP_UGE)
2704       return getTrue(ITy);
2705     if (Pred == ICmpInst::ICMP_ULT)
2706       return getFalse(ITy);
2707   }
2708 
2709   // 0 - (zext X) pred C
2710   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2711     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2712       if (RHSC->getValue().isStrictlyPositive()) {
2713         if (Pred == ICmpInst::ICMP_SLT)
2714           return ConstantInt::getTrue(RHSC->getContext());
2715         if (Pred == ICmpInst::ICMP_SGE)
2716           return ConstantInt::getFalse(RHSC->getContext());
2717         if (Pred == ICmpInst::ICMP_EQ)
2718           return ConstantInt::getFalse(RHSC->getContext());
2719         if (Pred == ICmpInst::ICMP_NE)
2720           return ConstantInt::getTrue(RHSC->getContext());
2721       }
2722       if (RHSC->getValue().isNonNegative()) {
2723         if (Pred == ICmpInst::ICMP_SLE)
2724           return ConstantInt::getTrue(RHSC->getContext());
2725         if (Pred == ICmpInst::ICMP_SGT)
2726           return ConstantInt::getFalse(RHSC->getContext());
2727       }
2728     }
2729   }
2730 
2731   // icmp pred (urem X, Y), Y
2732   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2733     bool KnownNonNegative, KnownNegative;
2734     switch (Pred) {
2735     default:
2736       break;
2737     case ICmpInst::ICMP_SGT:
2738     case ICmpInst::ICMP_SGE:
2739       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2740                      Q.CxtI, Q.DT);
2741       if (!KnownNonNegative)
2742         break;
2743       // fall-through
2744     case ICmpInst::ICMP_EQ:
2745     case ICmpInst::ICMP_UGT:
2746     case ICmpInst::ICMP_UGE:
2747       return getFalse(ITy);
2748     case ICmpInst::ICMP_SLT:
2749     case ICmpInst::ICMP_SLE:
2750       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2751                      Q.CxtI, Q.DT);
2752       if (!KnownNonNegative)
2753         break;
2754       // fall-through
2755     case ICmpInst::ICMP_NE:
2756     case ICmpInst::ICMP_ULT:
2757     case ICmpInst::ICMP_ULE:
2758       return getTrue(ITy);
2759     }
2760   }
2761 
2762   // icmp pred X, (urem Y, X)
2763   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2764     bool KnownNonNegative, KnownNegative;
2765     switch (Pred) {
2766     default:
2767       break;
2768     case ICmpInst::ICMP_SGT:
2769     case ICmpInst::ICMP_SGE:
2770       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2771                      Q.CxtI, Q.DT);
2772       if (!KnownNonNegative)
2773         break;
2774       // fall-through
2775     case ICmpInst::ICMP_NE:
2776     case ICmpInst::ICMP_UGT:
2777     case ICmpInst::ICMP_UGE:
2778       return getTrue(ITy);
2779     case ICmpInst::ICMP_SLT:
2780     case ICmpInst::ICMP_SLE:
2781       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2782                      Q.CxtI, Q.DT);
2783       if (!KnownNonNegative)
2784         break;
2785       // fall-through
2786     case ICmpInst::ICMP_EQ:
2787     case ICmpInst::ICMP_ULT:
2788     case ICmpInst::ICMP_ULE:
2789       return getFalse(ITy);
2790     }
2791   }
2792 
2793   // x >> y <=u x
2794   // x udiv y <=u x.
2795   if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2796               match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2797     // icmp pred (X op Y), X
2798     if (Pred == ICmpInst::ICMP_UGT)
2799       return getFalse(ITy);
2800     if (Pred == ICmpInst::ICMP_ULE)
2801       return getTrue(ITy);
2802   }
2803 
2804   // handle:
2805   //   CI2 << X == CI
2806   //   CI2 << X != CI
2807   //
2808   //   where CI2 is a power of 2 and CI isn't
2809   if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2810     const APInt *CI2Val, *CIVal = &CI->getValue();
2811     if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2812         CI2Val->isPowerOf2()) {
2813       if (!CIVal->isPowerOf2()) {
2814         // CI2 << X can equal zero in some circumstances,
2815         // this simplification is unsafe if CI is zero.
2816         //
2817         // We know it is safe if:
2818         // - The shift is nsw, we can't shift out the one bit.
2819         // - The shift is nuw, we can't shift out the one bit.
2820         // - CI2 is one
2821         // - CI isn't zero
2822         if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2823             *CI2Val == 1 || !CI->isZero()) {
2824           if (Pred == ICmpInst::ICMP_EQ)
2825             return ConstantInt::getFalse(RHS->getContext());
2826           if (Pred == ICmpInst::ICMP_NE)
2827             return ConstantInt::getTrue(RHS->getContext());
2828         }
2829       }
2830       if (CIVal->isSignBit() && *CI2Val == 1) {
2831         if (Pred == ICmpInst::ICMP_UGT)
2832           return ConstantInt::getFalse(RHS->getContext());
2833         if (Pred == ICmpInst::ICMP_ULE)
2834           return ConstantInt::getTrue(RHS->getContext());
2835       }
2836     }
2837   }
2838 
2839   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2840       LBO->getOperand(1) == RBO->getOperand(1)) {
2841     switch (LBO->getOpcode()) {
2842     default: break;
2843     case Instruction::UDiv:
2844     case Instruction::LShr:
2845       if (ICmpInst::isSigned(Pred))
2846         break;
2847       // fall-through
2848     case Instruction::SDiv:
2849     case Instruction::AShr:
2850       if (!LBO->isExact() || !RBO->isExact())
2851         break;
2852       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2853                                       RBO->getOperand(0), Q, MaxRecurse-1))
2854         return V;
2855       break;
2856     case Instruction::Shl: {
2857       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2858       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2859       if (!NUW && !NSW)
2860         break;
2861       if (!NSW && ICmpInst::isSigned(Pred))
2862         break;
2863       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2864                                       RBO->getOperand(0), Q, MaxRecurse-1))
2865         return V;
2866       break;
2867     }
2868     }
2869   }
2870 
2871   // Simplify comparisons involving max/min.
2872   Value *A, *B;
2873   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2874   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2875 
2876   // Signed variants on "max(a,b)>=a -> true".
2877   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2878     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2879     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2880     // We analyze this as smax(A, B) pred A.
2881     P = Pred;
2882   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2883              (A == LHS || B == LHS)) {
2884     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2885     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2886     // We analyze this as smax(A, B) swapped-pred A.
2887     P = CmpInst::getSwappedPredicate(Pred);
2888   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2889              (A == RHS || B == RHS)) {
2890     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2891     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2892     // We analyze this as smax(-A, -B) swapped-pred -A.
2893     // Note that we do not need to actually form -A or -B thanks to EqP.
2894     P = CmpInst::getSwappedPredicate(Pred);
2895   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2896              (A == LHS || B == LHS)) {
2897     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2898     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2899     // We analyze this as smax(-A, -B) pred -A.
2900     // Note that we do not need to actually form -A or -B thanks to EqP.
2901     P = Pred;
2902   }
2903   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2904     // Cases correspond to "max(A, B) p A".
2905     switch (P) {
2906     default:
2907       break;
2908     case CmpInst::ICMP_EQ:
2909     case CmpInst::ICMP_SLE:
2910       // Equivalent to "A EqP B".  This may be the same as the condition tested
2911       // in the max/min; if so, we can just return that.
2912       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2913         return V;
2914       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2915         return V;
2916       // Otherwise, see if "A EqP B" simplifies.
2917       if (MaxRecurse)
2918         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2919           return V;
2920       break;
2921     case CmpInst::ICMP_NE:
2922     case CmpInst::ICMP_SGT: {
2923       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2924       // Equivalent to "A InvEqP B".  This may be the same as the condition
2925       // tested in the max/min; if so, we can just return that.
2926       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2927         return V;
2928       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2929         return V;
2930       // Otherwise, see if "A InvEqP B" simplifies.
2931       if (MaxRecurse)
2932         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2933           return V;
2934       break;
2935     }
2936     case CmpInst::ICMP_SGE:
2937       // Always true.
2938       return getTrue(ITy);
2939     case CmpInst::ICMP_SLT:
2940       // Always false.
2941       return getFalse(ITy);
2942     }
2943   }
2944 
2945   // Unsigned variants on "max(a,b)>=a -> true".
2946   P = CmpInst::BAD_ICMP_PREDICATE;
2947   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2948     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2949     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2950     // We analyze this as umax(A, B) pred A.
2951     P = Pred;
2952   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2953              (A == LHS || B == LHS)) {
2954     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2955     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2956     // We analyze this as umax(A, B) swapped-pred A.
2957     P = CmpInst::getSwappedPredicate(Pred);
2958   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2959              (A == RHS || B == RHS)) {
2960     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2961     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2962     // We analyze this as umax(-A, -B) swapped-pred -A.
2963     // Note that we do not need to actually form -A or -B thanks to EqP.
2964     P = CmpInst::getSwappedPredicate(Pred);
2965   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2966              (A == LHS || B == LHS)) {
2967     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2968     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2969     // We analyze this as umax(-A, -B) pred -A.
2970     // Note that we do not need to actually form -A or -B thanks to EqP.
2971     P = Pred;
2972   }
2973   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2974     // Cases correspond to "max(A, B) p A".
2975     switch (P) {
2976     default:
2977       break;
2978     case CmpInst::ICMP_EQ:
2979     case CmpInst::ICMP_ULE:
2980       // Equivalent to "A EqP B".  This may be the same as the condition tested
2981       // in the max/min; if so, we can just return that.
2982       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2983         return V;
2984       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2985         return V;
2986       // Otherwise, see if "A EqP B" simplifies.
2987       if (MaxRecurse)
2988         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2989           return V;
2990       break;
2991     case CmpInst::ICMP_NE:
2992     case CmpInst::ICMP_UGT: {
2993       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2994       // Equivalent to "A InvEqP B".  This may be the same as the condition
2995       // tested in the max/min; if so, we can just return that.
2996       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2997         return V;
2998       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2999         return V;
3000       // Otherwise, see if "A InvEqP B" simplifies.
3001       if (MaxRecurse)
3002         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
3003           return V;
3004       break;
3005     }
3006     case CmpInst::ICMP_UGE:
3007       // Always true.
3008       return getTrue(ITy);
3009     case CmpInst::ICMP_ULT:
3010       // Always false.
3011       return getFalse(ITy);
3012     }
3013   }
3014 
3015   // Variants on "max(x,y) >= min(x,z)".
3016   Value *C, *D;
3017   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3018       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3019       (A == C || A == D || B == C || B == D)) {
3020     // max(x, ?) pred min(x, ?).
3021     if (Pred == CmpInst::ICMP_SGE)
3022       // Always true.
3023       return getTrue(ITy);
3024     if (Pred == CmpInst::ICMP_SLT)
3025       // Always false.
3026       return getFalse(ITy);
3027   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3028              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3029              (A == C || A == D || B == C || B == D)) {
3030     // min(x, ?) pred max(x, ?).
3031     if (Pred == CmpInst::ICMP_SLE)
3032       // Always true.
3033       return getTrue(ITy);
3034     if (Pred == CmpInst::ICMP_SGT)
3035       // Always false.
3036       return getFalse(ITy);
3037   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3038              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3039              (A == C || A == D || B == C || B == D)) {
3040     // max(x, ?) pred min(x, ?).
3041     if (Pred == CmpInst::ICMP_UGE)
3042       // Always true.
3043       return getTrue(ITy);
3044     if (Pred == CmpInst::ICMP_ULT)
3045       // Always false.
3046       return getFalse(ITy);
3047   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3048              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3049              (A == C || A == D || B == C || B == D)) {
3050     // min(x, ?) pred max(x, ?).
3051     if (Pred == CmpInst::ICMP_ULE)
3052       // Always true.
3053       return getTrue(ITy);
3054     if (Pred == CmpInst::ICMP_UGT)
3055       // Always false.
3056       return getFalse(ITy);
3057   }
3058 
3059   // Simplify comparisons of related pointers using a powerful, recursive
3060   // GEP-walk when we have target data available..
3061   if (LHS->getType()->isPointerTy())
3062     if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
3063       return C;
3064 
3065   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3066     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3067       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3068           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3069           (ICmpInst::isEquality(Pred) ||
3070            (GLHS->isInBounds() && GRHS->isInBounds() &&
3071             Pred == ICmpInst::getSignedPredicate(Pred)))) {
3072         // The bases are equal and the indices are constant.  Build a constant
3073         // expression GEP with the same indices and a null base pointer to see
3074         // what constant folding can make out of it.
3075         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3076         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
3077         Constant *NewLHS = ConstantExpr::getGetElementPtr(
3078             GLHS->getSourceElementType(), Null, IndicesLHS);
3079 
3080         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3081         Constant *NewRHS = ConstantExpr::getGetElementPtr(
3082             GLHS->getSourceElementType(), Null, IndicesRHS);
3083         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3084       }
3085     }
3086   }
3087 
3088   // If a bit is known to be zero for A and known to be one for B,
3089   // then A and B cannot be equal.
3090   if (ICmpInst::isEquality(Pred)) {
3091     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3092       uint32_t BitWidth = CI->getBitWidth();
3093       APInt LHSKnownZero(BitWidth, 0);
3094       APInt LHSKnownOne(BitWidth, 0);
3095       computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
3096                        Q.CxtI, Q.DT);
3097       const APInt &RHSVal = CI->getValue();
3098       if (((LHSKnownZero & RHSVal) != 0) || ((LHSKnownOne & ~RHSVal) != 0))
3099         return Pred == ICmpInst::ICMP_EQ
3100                    ? ConstantInt::getFalse(CI->getContext())
3101                    : ConstantInt::getTrue(CI->getContext());
3102     }
3103   }
3104 
3105   // If the comparison is with the result of a select instruction, check whether
3106   // comparing with either branch of the select always yields the same value.
3107   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3108     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3109       return V;
3110 
3111   // If the comparison is with the result of a phi instruction, check whether
3112   // doing the compare with each incoming phi value yields a common result.
3113   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3114     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3115       return V;
3116 
3117   return nullptr;
3118 }
3119 
3120 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3121                               const DataLayout &DL,
3122                               const TargetLibraryInfo *TLI,
3123                               const DominatorTree *DT, AssumptionCache *AC,
3124                               const Instruction *CxtI) {
3125   return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3126                             RecursionLimit);
3127 }
3128 
3129 /// Given operands for an FCmpInst, see if we can fold the result.
3130 /// If not, this returns null.
3131 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3132                                FastMathFlags FMF, const Query &Q,
3133                                unsigned MaxRecurse) {
3134   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3135   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3136 
3137   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3138     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3139       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3140 
3141     // If we have a constant, make sure it is on the RHS.
3142     std::swap(LHS, RHS);
3143     Pred = CmpInst::getSwappedPredicate(Pred);
3144   }
3145 
3146   // Fold trivial predicates.
3147   if (Pred == FCmpInst::FCMP_FALSE)
3148     return ConstantInt::get(GetCompareTy(LHS), 0);
3149   if (Pred == FCmpInst::FCMP_TRUE)
3150     return ConstantInt::get(GetCompareTy(LHS), 1);
3151 
3152   // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3153   if (FMF.noNaNs()) {
3154     if (Pred == FCmpInst::FCMP_UNO)
3155       return ConstantInt::get(GetCompareTy(LHS), 0);
3156     if (Pred == FCmpInst::FCMP_ORD)
3157       return ConstantInt::get(GetCompareTy(LHS), 1);
3158   }
3159 
3160   // fcmp pred x, undef  and  fcmp pred undef, x
3161   // fold to true if unordered, false if ordered
3162   if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3163     // Choosing NaN for the undef will always make unordered comparison succeed
3164     // and ordered comparison fail.
3165     return ConstantInt::get(GetCompareTy(LHS), CmpInst::isUnordered(Pred));
3166   }
3167 
3168   // fcmp x,x -> true/false.  Not all compares are foldable.
3169   if (LHS == RHS) {
3170     if (CmpInst::isTrueWhenEqual(Pred))
3171       return ConstantInt::get(GetCompareTy(LHS), 1);
3172     if (CmpInst::isFalseWhenEqual(Pred))
3173       return ConstantInt::get(GetCompareTy(LHS), 0);
3174   }
3175 
3176   // Handle fcmp with constant RHS
3177   const ConstantFP *CFP = nullptr;
3178   if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3179     if (RHS->getType()->isVectorTy())
3180       CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3181     else
3182       CFP = dyn_cast<ConstantFP>(RHSC);
3183   }
3184   if (CFP) {
3185     // If the constant is a nan, see if we can fold the comparison based on it.
3186     if (CFP->getValueAPF().isNaN()) {
3187       if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
3188         return ConstantInt::getFalse(CFP->getContext());
3189       assert(FCmpInst::isUnordered(Pred) &&
3190              "Comparison must be either ordered or unordered!");
3191       // True if unordered.
3192       return ConstantInt::get(GetCompareTy(LHS), 1);
3193     }
3194     // Check whether the constant is an infinity.
3195     if (CFP->getValueAPF().isInfinity()) {
3196       if (CFP->getValueAPF().isNegative()) {
3197         switch (Pred) {
3198         case FCmpInst::FCMP_OLT:
3199           // No value is ordered and less than negative infinity.
3200           return ConstantInt::get(GetCompareTy(LHS), 0);
3201         case FCmpInst::FCMP_UGE:
3202           // All values are unordered with or at least negative infinity.
3203           return ConstantInt::get(GetCompareTy(LHS), 1);
3204         default:
3205           break;
3206         }
3207       } else {
3208         switch (Pred) {
3209         case FCmpInst::FCMP_OGT:
3210           // No value is ordered and greater than infinity.
3211           return ConstantInt::get(GetCompareTy(LHS), 0);
3212         case FCmpInst::FCMP_ULE:
3213           // All values are unordered with and at most infinity.
3214           return ConstantInt::get(GetCompareTy(LHS), 1);
3215         default:
3216           break;
3217         }
3218       }
3219     }
3220     if (CFP->getValueAPF().isZero()) {
3221       switch (Pred) {
3222       case FCmpInst::FCMP_UGE:
3223         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3224           return ConstantInt::get(GetCompareTy(LHS), 1);
3225         break;
3226       case FCmpInst::FCMP_OLT:
3227         // X < 0
3228         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3229           return ConstantInt::get(GetCompareTy(LHS), 0);
3230         break;
3231       default:
3232         break;
3233       }
3234     }
3235   }
3236 
3237   // If the comparison is with the result of a select instruction, check whether
3238   // comparing with either branch of the select always yields the same value.
3239   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3240     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3241       return V;
3242 
3243   // If the comparison is with the result of a phi instruction, check whether
3244   // doing the compare with each incoming phi value yields a common result.
3245   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3246     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3247       return V;
3248 
3249   return nullptr;
3250 }
3251 
3252 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3253                               FastMathFlags FMF, const DataLayout &DL,
3254                               const TargetLibraryInfo *TLI,
3255                               const DominatorTree *DT, AssumptionCache *AC,
3256                               const Instruction *CxtI) {
3257   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
3258                             Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3259 }
3260 
3261 /// See if V simplifies when its operand Op is replaced with RepOp.
3262 static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3263                                            const Query &Q,
3264                                            unsigned MaxRecurse) {
3265   // Trivial replacement.
3266   if (V == Op)
3267     return RepOp;
3268 
3269   auto *I = dyn_cast<Instruction>(V);
3270   if (!I)
3271     return nullptr;
3272 
3273   // If this is a binary operator, try to simplify it with the replaced op.
3274   if (auto *B = dyn_cast<BinaryOperator>(I)) {
3275     // Consider:
3276     //   %cmp = icmp eq i32 %x, 2147483647
3277     //   %add = add nsw i32 %x, 1
3278     //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
3279     //
3280     // We can't replace %sel with %add unless we strip away the flags.
3281     if (isa<OverflowingBinaryOperator>(B))
3282       if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3283         return nullptr;
3284     if (isa<PossiblyExactOperator>(B))
3285       if (B->isExact())
3286         return nullptr;
3287 
3288     if (MaxRecurse) {
3289       if (B->getOperand(0) == Op)
3290         return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3291                              MaxRecurse - 1);
3292       if (B->getOperand(1) == Op)
3293         return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3294                              MaxRecurse - 1);
3295     }
3296   }
3297 
3298   // Same for CmpInsts.
3299   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3300     if (MaxRecurse) {
3301       if (C->getOperand(0) == Op)
3302         return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3303                                MaxRecurse - 1);
3304       if (C->getOperand(1) == Op)
3305         return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3306                                MaxRecurse - 1);
3307     }
3308   }
3309 
3310   // TODO: We could hand off more cases to instsimplify here.
3311 
3312   // If all operands are constant after substituting Op for RepOp then we can
3313   // constant fold the instruction.
3314   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3315     // Build a list of all constant operands.
3316     SmallVector<Constant *, 8> ConstOps;
3317     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3318       if (I->getOperand(i) == Op)
3319         ConstOps.push_back(CRepOp);
3320       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3321         ConstOps.push_back(COp);
3322       else
3323         break;
3324     }
3325 
3326     // All operands were constants, fold it.
3327     if (ConstOps.size() == I->getNumOperands()) {
3328       if (CmpInst *C = dyn_cast<CmpInst>(I))
3329         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3330                                                ConstOps[1], Q.DL, Q.TLI);
3331 
3332       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3333         if (!LI->isVolatile())
3334           return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
3335 
3336       return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
3337     }
3338   }
3339 
3340   return nullptr;
3341 }
3342 
3343 /// Given operands for a SelectInst, see if we can fold the result.
3344 /// If not, this returns null.
3345 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3346                                  Value *FalseVal, const Query &Q,
3347                                  unsigned MaxRecurse) {
3348   // select true, X, Y  -> X
3349   // select false, X, Y -> Y
3350   if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3351     if (CB->isAllOnesValue())
3352       return TrueVal;
3353     if (CB->isNullValue())
3354       return FalseVal;
3355   }
3356 
3357   // select C, X, X -> X
3358   if (TrueVal == FalseVal)
3359     return TrueVal;
3360 
3361   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
3362     if (isa<Constant>(TrueVal))
3363       return TrueVal;
3364     return FalseVal;
3365   }
3366   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
3367     return FalseVal;
3368   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
3369     return TrueVal;
3370 
3371   if (const auto *ICI = dyn_cast<ICmpInst>(CondVal)) {
3372     unsigned BitWidth = Q.DL.getTypeSizeInBits(TrueVal->getType());
3373     ICmpInst::Predicate Pred = ICI->getPredicate();
3374     Value *CmpLHS = ICI->getOperand(0);
3375     Value *CmpRHS = ICI->getOperand(1);
3376     APInt MinSignedValue = APInt::getSignBit(BitWidth);
3377     Value *X;
3378     const APInt *Y;
3379     bool TrueWhenUnset;
3380     bool IsBitTest = false;
3381     if (ICmpInst::isEquality(Pred) &&
3382         match(CmpLHS, m_And(m_Value(X), m_APInt(Y))) &&
3383         match(CmpRHS, m_Zero())) {
3384       IsBitTest = true;
3385       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
3386     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
3387       X = CmpLHS;
3388       Y = &MinSignedValue;
3389       IsBitTest = true;
3390       TrueWhenUnset = false;
3391     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
3392       X = CmpLHS;
3393       Y = &MinSignedValue;
3394       IsBitTest = true;
3395       TrueWhenUnset = true;
3396     }
3397     if (IsBitTest) {
3398       const APInt *C;
3399       // (X & Y) == 0 ? X & ~Y : X  --> X
3400       // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
3401       if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3402           *Y == ~*C)
3403         return TrueWhenUnset ? FalseVal : TrueVal;
3404       // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
3405       // (X & Y) != 0 ? X : X & ~Y  --> X
3406       if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3407           *Y == ~*C)
3408         return TrueWhenUnset ? FalseVal : TrueVal;
3409 
3410       if (Y->isPowerOf2()) {
3411         // (X & Y) == 0 ? X | Y : X  --> X | Y
3412         // (X & Y) != 0 ? X | Y : X  --> X
3413         if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3414             *Y == *C)
3415           return TrueWhenUnset ? TrueVal : FalseVal;
3416         // (X & Y) == 0 ? X : X | Y  --> X
3417         // (X & Y) != 0 ? X : X | Y  --> X | Y
3418         if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3419             *Y == *C)
3420           return TrueWhenUnset ? TrueVal : FalseVal;
3421       }
3422     }
3423     if (ICI->hasOneUse()) {
3424       const APInt *C;
3425       if (match(CmpRHS, m_APInt(C))) {
3426         // X < MIN ? T : F  -->  F
3427         if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3428           return FalseVal;
3429         // X < MIN ? T : F  -->  F
3430         if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3431           return FalseVal;
3432         // X > MAX ? T : F  -->  F
3433         if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3434           return FalseVal;
3435         // X > MAX ? T : F  -->  F
3436         if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3437           return FalseVal;
3438       }
3439     }
3440 
3441     // If we have an equality comparison then we know the value in one of the
3442     // arms of the select. See if substituting this value into the arm and
3443     // simplifying the result yields the same value as the other arm.
3444     if (Pred == ICmpInst::ICMP_EQ) {
3445       if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3446               TrueVal ||
3447           SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3448               TrueVal)
3449         return FalseVal;
3450       if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3451               FalseVal ||
3452           SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3453               FalseVal)
3454         return FalseVal;
3455     } else if (Pred == ICmpInst::ICMP_NE) {
3456       if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3457               FalseVal ||
3458           SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3459               FalseVal)
3460         return TrueVal;
3461       if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3462               TrueVal ||
3463           SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3464               TrueVal)
3465         return TrueVal;
3466     }
3467   }
3468 
3469   return nullptr;
3470 }
3471 
3472 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3473                                 const DataLayout &DL,
3474                                 const TargetLibraryInfo *TLI,
3475                                 const DominatorTree *DT, AssumptionCache *AC,
3476                                 const Instruction *CxtI) {
3477   return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
3478                               Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3479 }
3480 
3481 /// Given operands for an GetElementPtrInst, see if we can fold the result.
3482 /// If not, this returns null.
3483 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3484                               const Query &Q, unsigned) {
3485   // The type of the GEP pointer operand.
3486   unsigned AS =
3487       cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
3488 
3489   // getelementptr P -> P.
3490   if (Ops.size() == 1)
3491     return Ops[0];
3492 
3493   // Compute the (pointer) type returned by the GEP instruction.
3494   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
3495   Type *GEPTy = PointerType::get(LastType, AS);
3496   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3497     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3498 
3499   if (isa<UndefValue>(Ops[0]))
3500     return UndefValue::get(GEPTy);
3501 
3502   if (Ops.size() == 2) {
3503     // getelementptr P, 0 -> P.
3504     if (match(Ops[1], m_Zero()))
3505       return Ops[0];
3506 
3507     Type *Ty = SrcTy;
3508     if (Ty->isSized()) {
3509       Value *P;
3510       uint64_t C;
3511       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
3512       // getelementptr P, N -> P if P points to a type of zero size.
3513       if (TyAllocSize == 0)
3514         return Ops[0];
3515 
3516       // The following transforms are only safe if the ptrtoint cast
3517       // doesn't truncate the pointers.
3518       if (Ops[1]->getType()->getScalarSizeInBits() ==
3519           Q.DL.getPointerSizeInBits(AS)) {
3520         auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3521           if (match(P, m_Zero()))
3522             return Constant::getNullValue(GEPTy);
3523           Value *Temp;
3524           if (match(P, m_PtrToInt(m_Value(Temp))))
3525             if (Temp->getType() == GEPTy)
3526               return Temp;
3527           return nullptr;
3528         };
3529 
3530         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3531         if (TyAllocSize == 1 &&
3532             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3533           if (Value *R = PtrToIntOrZero(P))
3534             return R;
3535 
3536         // getelementptr V, (ashr (sub P, V), C) -> Q
3537         // if P points to a type of size 1 << C.
3538         if (match(Ops[1],
3539                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3540                          m_ConstantInt(C))) &&
3541             TyAllocSize == 1ULL << C)
3542           if (Value *R = PtrToIntOrZero(P))
3543             return R;
3544 
3545         // getelementptr V, (sdiv (sub P, V), C) -> Q
3546         // if P points to a type of size C.
3547         if (match(Ops[1],
3548                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3549                          m_SpecificInt(TyAllocSize))))
3550           if (Value *R = PtrToIntOrZero(P))
3551             return R;
3552       }
3553     }
3554   }
3555 
3556   // Check to see if this is constant foldable.
3557   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3558     if (!isa<Constant>(Ops[i]))
3559       return nullptr;
3560 
3561   return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3562                                         Ops.slice(1));
3563 }
3564 
3565 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3566                              const DataLayout &DL,
3567                              const TargetLibraryInfo *TLI,
3568                              const DominatorTree *DT, AssumptionCache *AC,
3569                              const Instruction *CxtI) {
3570   return ::SimplifyGEPInst(SrcTy, Ops,
3571                            Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3572 }
3573 
3574 /// Given operands for an InsertValueInst, see if we can fold the result.
3575 /// If not, this returns null.
3576 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3577                                       ArrayRef<unsigned> Idxs, const Query &Q,
3578                                       unsigned) {
3579   if (Constant *CAgg = dyn_cast<Constant>(Agg))
3580     if (Constant *CVal = dyn_cast<Constant>(Val))
3581       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3582 
3583   // insertvalue x, undef, n -> x
3584   if (match(Val, m_Undef()))
3585     return Agg;
3586 
3587   // insertvalue x, (extractvalue y, n), n
3588   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
3589     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3590         EV->getIndices() == Idxs) {
3591       // insertvalue undef, (extractvalue y, n), n -> y
3592       if (match(Agg, m_Undef()))
3593         return EV->getAggregateOperand();
3594 
3595       // insertvalue y, (extractvalue y, n), n -> y
3596       if (Agg == EV->getAggregateOperand())
3597         return Agg;
3598     }
3599 
3600   return nullptr;
3601 }
3602 
3603 Value *llvm::SimplifyInsertValueInst(
3604     Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
3605     const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
3606     const Instruction *CxtI) {
3607   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
3608                                    RecursionLimit);
3609 }
3610 
3611 /// Given operands for an ExtractValueInst, see if we can fold the result.
3612 /// If not, this returns null.
3613 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3614                                        const Query &, unsigned) {
3615   if (auto *CAgg = dyn_cast<Constant>(Agg))
3616     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3617 
3618   // extractvalue x, (insertvalue y, elt, n), n -> elt
3619   unsigned NumIdxs = Idxs.size();
3620   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3621        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3622     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3623     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3624     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3625     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3626         Idxs.slice(0, NumCommonIdxs)) {
3627       if (NumIdxs == NumInsertValueIdxs)
3628         return IVI->getInsertedValueOperand();
3629       break;
3630     }
3631   }
3632 
3633   return nullptr;
3634 }
3635 
3636 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3637                                       const DataLayout &DL,
3638                                       const TargetLibraryInfo *TLI,
3639                                       const DominatorTree *DT,
3640                                       AssumptionCache *AC,
3641                                       const Instruction *CxtI) {
3642   return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
3643                                     RecursionLimit);
3644 }
3645 
3646 /// Given operands for an ExtractElementInst, see if we can fold the result.
3647 /// If not, this returns null.
3648 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3649                                          unsigned) {
3650   if (auto *CVec = dyn_cast<Constant>(Vec)) {
3651     if (auto *CIdx = dyn_cast<Constant>(Idx))
3652       return ConstantFoldExtractElementInstruction(CVec, CIdx);
3653 
3654     // The index is not relevant if our vector is a splat.
3655     if (auto *Splat = CVec->getSplatValue())
3656       return Splat;
3657 
3658     if (isa<UndefValue>(Vec))
3659       return UndefValue::get(Vec->getType()->getVectorElementType());
3660   }
3661 
3662   // If extracting a specified index from the vector, see if we can recursively
3663   // find a previously computed scalar that was inserted into the vector.
3664   if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3665     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
3666       return Elt;
3667 
3668   return nullptr;
3669 }
3670 
3671 Value *llvm::SimplifyExtractElementInst(
3672     Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
3673     const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
3674   return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
3675                                       RecursionLimit);
3676 }
3677 
3678 /// See if we can fold the given phi. If not, returns null.
3679 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
3680   // If all of the PHI's incoming values are the same then replace the PHI node
3681   // with the common value.
3682   Value *CommonValue = nullptr;
3683   bool HasUndefInput = false;
3684   for (Value *Incoming : PN->incoming_values()) {
3685     // If the incoming value is the phi node itself, it can safely be skipped.
3686     if (Incoming == PN) continue;
3687     if (isa<UndefValue>(Incoming)) {
3688       // Remember that we saw an undef value, but otherwise ignore them.
3689       HasUndefInput = true;
3690       continue;
3691     }
3692     if (CommonValue && Incoming != CommonValue)
3693       return nullptr;  // Not the same, bail out.
3694     CommonValue = Incoming;
3695   }
3696 
3697   // If CommonValue is null then all of the incoming values were either undef or
3698   // equal to the phi node itself.
3699   if (!CommonValue)
3700     return UndefValue::get(PN->getType());
3701 
3702   // If we have a PHI node like phi(X, undef, X), where X is defined by some
3703   // instruction, we cannot return X as the result of the PHI node unless it
3704   // dominates the PHI block.
3705   if (HasUndefInput)
3706     return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
3707 
3708   return CommonValue;
3709 }
3710 
3711 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
3712   if (Constant *C = dyn_cast<Constant>(Op))
3713     return ConstantFoldCastOperand(Instruction::Trunc, C, Ty, Q.DL);
3714 
3715   return nullptr;
3716 }
3717 
3718 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout &DL,
3719                                const TargetLibraryInfo *TLI,
3720                                const DominatorTree *DT, AssumptionCache *AC,
3721                                const Instruction *CxtI) {
3722   return ::SimplifyTruncInst(Op, Ty, Query(DL, TLI, DT, AC, CxtI),
3723                              RecursionLimit);
3724 }
3725 
3726 //=== Helper functions for higher up the class hierarchy.
3727 
3728 /// Given operands for a BinaryOperator, see if we can fold the result.
3729 /// If not, this returns null.
3730 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3731                             const Query &Q, unsigned MaxRecurse) {
3732   switch (Opcode) {
3733   case Instruction::Add:
3734     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3735                            Q, MaxRecurse);
3736   case Instruction::FAdd:
3737     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3738 
3739   case Instruction::Sub:
3740     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3741                            Q, MaxRecurse);
3742   case Instruction::FSub:
3743     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3744 
3745   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
3746   case Instruction::FMul:
3747     return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3748   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3749   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
3750   case Instruction::FDiv:
3751       return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3752   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3753   case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
3754   case Instruction::FRem:
3755       return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3756   case Instruction::Shl:
3757     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3758                            Q, MaxRecurse);
3759   case Instruction::LShr:
3760     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3761   case Instruction::AShr:
3762     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3763   case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3764   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3765   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
3766   default:
3767     if (Constant *CLHS = dyn_cast<Constant>(LHS))
3768       if (Constant *CRHS = dyn_cast<Constant>(RHS))
3769         return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
3770 
3771     // If the operation is associative, try some generic simplifications.
3772     if (Instruction::isAssociative(Opcode))
3773       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
3774         return V;
3775 
3776     // If the operation is with the result of a select instruction check whether
3777     // operating on either branch of the select always yields the same value.
3778     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3779       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
3780         return V;
3781 
3782     // If the operation is with the result of a phi instruction, check whether
3783     // operating on all incoming values of the phi always yields the same value.
3784     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3785       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
3786         return V;
3787 
3788     return nullptr;
3789   }
3790 }
3791 
3792 /// Given operands for a BinaryOperator, see if we can fold the result.
3793 /// If not, this returns null.
3794 /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
3795 /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
3796 static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3797                               const FastMathFlags &FMF, const Query &Q,
3798                               unsigned MaxRecurse) {
3799   switch (Opcode) {
3800   case Instruction::FAdd:
3801     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
3802   case Instruction::FSub:
3803     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
3804   case Instruction::FMul:
3805     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
3806   default:
3807     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
3808   }
3809 }
3810 
3811 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3812                            const DataLayout &DL, const TargetLibraryInfo *TLI,
3813                            const DominatorTree *DT, AssumptionCache *AC,
3814                            const Instruction *CxtI) {
3815   return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3816                          RecursionLimit);
3817 }
3818 
3819 Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3820                              const FastMathFlags &FMF, const DataLayout &DL,
3821                              const TargetLibraryInfo *TLI,
3822                              const DominatorTree *DT, AssumptionCache *AC,
3823                              const Instruction *CxtI) {
3824   return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
3825                            RecursionLimit);
3826 }
3827 
3828 /// Given operands for a CmpInst, see if we can fold the result.
3829 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3830                               const Query &Q, unsigned MaxRecurse) {
3831   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
3832     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3833   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3834 }
3835 
3836 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3837                              const DataLayout &DL, const TargetLibraryInfo *TLI,
3838                              const DominatorTree *DT, AssumptionCache *AC,
3839                              const Instruction *CxtI) {
3840   return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3841                            RecursionLimit);
3842 }
3843 
3844 static bool IsIdempotent(Intrinsic::ID ID) {
3845   switch (ID) {
3846   default: return false;
3847 
3848   // Unary idempotent: f(f(x)) = f(x)
3849   case Intrinsic::fabs:
3850   case Intrinsic::floor:
3851   case Intrinsic::ceil:
3852   case Intrinsic::trunc:
3853   case Intrinsic::rint:
3854   case Intrinsic::nearbyint:
3855   case Intrinsic::round:
3856     return true;
3857   }
3858 }
3859 
3860 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
3861                                    const DataLayout &DL) {
3862   GlobalValue *PtrSym;
3863   APInt PtrOffset;
3864   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
3865     return nullptr;
3866 
3867   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
3868   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
3869   Type *Int32PtrTy = Int32Ty->getPointerTo();
3870   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
3871 
3872   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
3873   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
3874     return nullptr;
3875 
3876   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
3877   if (OffsetInt % 4 != 0)
3878     return nullptr;
3879 
3880   Constant *C = ConstantExpr::getGetElementPtr(
3881       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
3882       ConstantInt::get(Int64Ty, OffsetInt / 4));
3883   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
3884   if (!Loaded)
3885     return nullptr;
3886 
3887   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
3888   if (!LoadedCE)
3889     return nullptr;
3890 
3891   if (LoadedCE->getOpcode() == Instruction::Trunc) {
3892     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3893     if (!LoadedCE)
3894       return nullptr;
3895   }
3896 
3897   if (LoadedCE->getOpcode() != Instruction::Sub)
3898     return nullptr;
3899 
3900   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3901   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
3902     return nullptr;
3903   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
3904 
3905   Constant *LoadedRHS = LoadedCE->getOperand(1);
3906   GlobalValue *LoadedRHSSym;
3907   APInt LoadedRHSOffset;
3908   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
3909                                   DL) ||
3910       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
3911     return nullptr;
3912 
3913   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
3914 }
3915 
3916 template <typename IterTy>
3917 static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
3918                                 const Query &Q, unsigned MaxRecurse) {
3919   Intrinsic::ID IID = F->getIntrinsicID();
3920   unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
3921   Type *ReturnType = F->getReturnType();
3922 
3923   // Binary Ops
3924   if (NumOperands == 2) {
3925     Value *LHS = *ArgBegin;
3926     Value *RHS = *(ArgBegin + 1);
3927     if (IID == Intrinsic::usub_with_overflow ||
3928         IID == Intrinsic::ssub_with_overflow) {
3929       // X - X -> { 0, false }
3930       if (LHS == RHS)
3931         return Constant::getNullValue(ReturnType);
3932 
3933       // X - undef -> undef
3934       // undef - X -> undef
3935       if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
3936         return UndefValue::get(ReturnType);
3937     }
3938 
3939     if (IID == Intrinsic::uadd_with_overflow ||
3940         IID == Intrinsic::sadd_with_overflow) {
3941       // X + undef -> undef
3942       if (isa<UndefValue>(RHS))
3943         return UndefValue::get(ReturnType);
3944     }
3945 
3946     if (IID == Intrinsic::umul_with_overflow ||
3947         IID == Intrinsic::smul_with_overflow) {
3948       // X * 0 -> { 0, false }
3949       if (match(RHS, m_Zero()))
3950         return Constant::getNullValue(ReturnType);
3951 
3952       // X * undef -> { 0, false }
3953       if (match(RHS, m_Undef()))
3954         return Constant::getNullValue(ReturnType);
3955     }
3956 
3957     if (IID == Intrinsic::load_relative && isa<Constant>(LHS) &&
3958         isa<Constant>(RHS))
3959       return SimplifyRelativeLoad(cast<Constant>(LHS), cast<Constant>(RHS),
3960                                   Q.DL);
3961   }
3962 
3963   // Perform idempotent optimizations
3964   if (!IsIdempotent(IID))
3965     return nullptr;
3966 
3967   // Unary Ops
3968   if (NumOperands == 1)
3969     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3970       if (II->getIntrinsicID() == IID)
3971         return II;
3972 
3973   return nullptr;
3974 }
3975 
3976 template <typename IterTy>
3977 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
3978                            const Query &Q, unsigned MaxRecurse) {
3979   Type *Ty = V->getType();
3980   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
3981     Ty = PTy->getElementType();
3982   FunctionType *FTy = cast<FunctionType>(Ty);
3983 
3984   // call undef -> undef
3985   if (isa<UndefValue>(V))
3986     return UndefValue::get(FTy->getReturnType());
3987 
3988   Function *F = dyn_cast<Function>(V);
3989   if (!F)
3990     return nullptr;
3991 
3992   if (F->isIntrinsic())
3993     if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
3994       return Ret;
3995 
3996   if (!canConstantFoldCallTo(F))
3997     return nullptr;
3998 
3999   SmallVector<Constant *, 4> ConstantArgs;
4000   ConstantArgs.reserve(ArgEnd - ArgBegin);
4001   for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4002     Constant *C = dyn_cast<Constant>(*I);
4003     if (!C)
4004       return nullptr;
4005     ConstantArgs.push_back(C);
4006   }
4007 
4008   return ConstantFoldCall(F, ConstantArgs, Q.TLI);
4009 }
4010 
4011 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
4012                           User::op_iterator ArgEnd, const DataLayout &DL,
4013                           const TargetLibraryInfo *TLI, const DominatorTree *DT,
4014                           AssumptionCache *AC, const Instruction *CxtI) {
4015   return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
4016                         RecursionLimit);
4017 }
4018 
4019 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
4020                           const DataLayout &DL, const TargetLibraryInfo *TLI,
4021                           const DominatorTree *DT, AssumptionCache *AC,
4022                           const Instruction *CxtI) {
4023   return ::SimplifyCall(V, Args.begin(), Args.end(),
4024                         Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
4025 }
4026 
4027 /// See if we can compute a simplified version of this instruction.
4028 /// If not, this returns null.
4029 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
4030                                  const TargetLibraryInfo *TLI,
4031                                  const DominatorTree *DT, AssumptionCache *AC) {
4032   Value *Result;
4033 
4034   switch (I->getOpcode()) {
4035   default:
4036     Result = ConstantFoldInstruction(I, DL, TLI);
4037     break;
4038   case Instruction::FAdd:
4039     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
4040                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4041     break;
4042   case Instruction::Add:
4043     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4044                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4045                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4046                              TLI, DT, AC, I);
4047     break;
4048   case Instruction::FSub:
4049     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
4050                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4051     break;
4052   case Instruction::Sub:
4053     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4054                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4055                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4056                              TLI, DT, AC, I);
4057     break;
4058   case Instruction::FMul:
4059     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
4060                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4061     break;
4062   case Instruction::Mul:
4063     Result =
4064         SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4065     break;
4066   case Instruction::SDiv:
4067     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4068                               AC, I);
4069     break;
4070   case Instruction::UDiv:
4071     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4072                               AC, I);
4073     break;
4074   case Instruction::FDiv:
4075     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
4076                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4077     break;
4078   case Instruction::SRem:
4079     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4080                               AC, I);
4081     break;
4082   case Instruction::URem:
4083     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4084                               AC, I);
4085     break;
4086   case Instruction::FRem:
4087     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
4088                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4089     break;
4090   case Instruction::Shl:
4091     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4092                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4093                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4094                              TLI, DT, AC, I);
4095     break;
4096   case Instruction::LShr:
4097     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
4098                               cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4099                               AC, I);
4100     break;
4101   case Instruction::AShr:
4102     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
4103                               cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4104                               AC, I);
4105     break;
4106   case Instruction::And:
4107     Result =
4108         SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4109     break;
4110   case Instruction::Or:
4111     Result =
4112         SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4113     break;
4114   case Instruction::Xor:
4115     Result =
4116         SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4117     break;
4118   case Instruction::ICmp:
4119     Result =
4120         SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
4121                          I->getOperand(1), DL, TLI, DT, AC, I);
4122     break;
4123   case Instruction::FCmp:
4124     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4125                               I->getOperand(0), I->getOperand(1),
4126                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4127     break;
4128   case Instruction::Select:
4129     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
4130                                 I->getOperand(2), DL, TLI, DT, AC, I);
4131     break;
4132   case Instruction::GetElementPtr: {
4133     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
4134     Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
4135                              Ops, DL, TLI, DT, AC, I);
4136     break;
4137   }
4138   case Instruction::InsertValue: {
4139     InsertValueInst *IV = cast<InsertValueInst>(I);
4140     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4141                                      IV->getInsertedValueOperand(),
4142                                      IV->getIndices(), DL, TLI, DT, AC, I);
4143     break;
4144   }
4145   case Instruction::ExtractValue: {
4146     auto *EVI = cast<ExtractValueInst>(I);
4147     Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
4148                                       EVI->getIndices(), DL, TLI, DT, AC, I);
4149     break;
4150   }
4151   case Instruction::ExtractElement: {
4152     auto *EEI = cast<ExtractElementInst>(I);
4153     Result = SimplifyExtractElementInst(
4154         EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
4155     break;
4156   }
4157   case Instruction::PHI:
4158     Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
4159     break;
4160   case Instruction::Call: {
4161     CallSite CS(cast<CallInst>(I));
4162     Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
4163                           TLI, DT, AC, I);
4164     break;
4165   }
4166   case Instruction::Trunc:
4167     Result =
4168         SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT, AC, I);
4169     break;
4170   }
4171 
4172   // In general, it is possible for computeKnownBits to determine all bits in a
4173   // value even when the operands are not all constants.
4174   if (!Result && I->getType()->isIntegerTy()) {
4175     unsigned BitWidth = I->getType()->getScalarSizeInBits();
4176     APInt KnownZero(BitWidth, 0);
4177     APInt KnownOne(BitWidth, 0);
4178     computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT);
4179     if ((KnownZero | KnownOne).isAllOnesValue())
4180       Result = ConstantInt::get(I->getContext(), KnownOne);
4181   }
4182 
4183   /// If called on unreachable code, the above logic may report that the
4184   /// instruction simplified to itself.  Make life easier for users by
4185   /// detecting that case here, returning a safe value instead.
4186   return Result == I ? UndefValue::get(I->getType()) : Result;
4187 }
4188 
4189 /// \brief Implementation of recursive simplification through an instruction's
4190 /// uses.
4191 ///
4192 /// This is the common implementation of the recursive simplification routines.
4193 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4194 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4195 /// instructions to process and attempt to simplify it using
4196 /// InstructionSimplify.
4197 ///
4198 /// This routine returns 'true' only when *it* simplifies something. The passed
4199 /// in simplified value does not count toward this.
4200 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
4201                                               const TargetLibraryInfo *TLI,
4202                                               const DominatorTree *DT,
4203                                               AssumptionCache *AC) {
4204   bool Simplified = false;
4205   SmallSetVector<Instruction *, 8> Worklist;
4206   const DataLayout &DL = I->getModule()->getDataLayout();
4207 
4208   // If we have an explicit value to collapse to, do that round of the
4209   // simplification loop by hand initially.
4210   if (SimpleV) {
4211     for (User *U : I->users())
4212       if (U != I)
4213         Worklist.insert(cast<Instruction>(U));
4214 
4215     // Replace the instruction with its simplified value.
4216     I->replaceAllUsesWith(SimpleV);
4217 
4218     // Gracefully handle edge cases where the instruction is not wired into any
4219     // parent block.
4220     if (I->getParent())
4221       I->eraseFromParent();
4222   } else {
4223     Worklist.insert(I);
4224   }
4225 
4226   // Note that we must test the size on each iteration, the worklist can grow.
4227   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4228     I = Worklist[Idx];
4229 
4230     // See if this instruction simplifies.
4231     SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
4232     if (!SimpleV)
4233       continue;
4234 
4235     Simplified = true;
4236 
4237     // Stash away all the uses of the old instruction so we can check them for
4238     // recursive simplifications after a RAUW. This is cheaper than checking all
4239     // uses of To on the recursive step in most cases.
4240     for (User *U : I->users())
4241       Worklist.insert(cast<Instruction>(U));
4242 
4243     // Replace the instruction with its simplified value.
4244     I->replaceAllUsesWith(SimpleV);
4245 
4246     // Gracefully handle edge cases where the instruction is not wired into any
4247     // parent block.
4248     if (I->getParent())
4249       I->eraseFromParent();
4250   }
4251   return Simplified;
4252 }
4253 
4254 bool llvm::recursivelySimplifyInstruction(Instruction *I,
4255                                           const TargetLibraryInfo *TLI,
4256                                           const DominatorTree *DT,
4257                                           AssumptionCache *AC) {
4258   return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
4259 }
4260 
4261 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
4262                                          const TargetLibraryInfo *TLI,
4263                                          const DominatorTree *DT,
4264                                          AssumptionCache *AC) {
4265   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4266   assert(SimpleV && "Must provide a simplified value.");
4267   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
4268 }
4269