LCOV - code coverage report
Current view: top level - lib/Analysis - InstructionSimplify.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 1830 1878 97.4 %
Date: 2018-06-17 00:07:59 Functions: 120 125 96.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13