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