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