LCOV - code coverage report
Current view: top level - lib/Analysis - InstructionSimplify.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 1839 1885 97.6 %
Date: 2018-07-13 00:08:38 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        2331 :   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        2261 :   return ConstantInt::getTrue(Ty);
      78             : }
      79             : 
      80             : /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
      81        7517 : 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        6703 :   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
      89             :     return true;
      90        8835 :   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
      91        2152 :     CRHS == LHS;
      92             : }
      93             : 
      94             : /// Does the given value dominate the specified phi node?
      95      122830 : 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       98036 :   if (!I->getParent() || !P->getParent() || !I->getFunction())
     105             :     return false;
     106             : 
     107             :   // If we have a DominatorTree then do a precise test.
     108       48488 :   if (DT)
     109       34669 :     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       27866 :   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      386930 : 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      386930 :   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      123424 :     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       26802 :       if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
     139        2114 :         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         695 :           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
     143         687 :                                      && L == B && R == A)) {
     144             :             ++NumExpand;
     145             :             return LHS;
     146             :           }
     147             :           // Otherwise return "L op' R" if it simplifies.
     148         687 :           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       75808 :     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       16737 :       if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
     162        1043 :         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          34 :           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
     166          34 :                                      && L == C && R == B)) {
     167             :             ++NumExpand;
     168             :             return RHS;
     169             :           }
     170             :           // Otherwise return "L op' R" if it simplifies.
     171          34 :           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     7725000 : 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     7725000 :   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     7874687 :   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      103649 :     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       75191 :       if (V == B) return LHS;
     207             :       // Otherwise return "A op V" if it simplifies.
     208       74869 :       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     7744441 :   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       26628 :     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          22 :       if (V == B) return RHS;
     226             :       // Otherwise return "V op C" if it simplifies.
     227           2 :       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     7867989 :   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      100315 :     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         201 :       if (V == A) return LHS;
     249             :       // Otherwise return "V op B" if it simplifies.
     250          91 :       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     7744284 :   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       26607 :     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         104 :       if (V == C) return RHS;
     268             :       // Otherwise return "B op V" if it simplifies.
     269          97 :       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        4142 : 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        4142 :   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        3866 :   if (SI == LHS) {
     302        3311 :     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
     303        3311 :     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
     304             :   } else {
     305         555 :     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
     306         555 :     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        3866 :   if (TV == FV)
     312             :     return TV;
     313             : 
     314             :   // If one branch simplified to undef, return the other one.
     315        4938 :   if (TV && isa<UndefValue>(TV))
     316             :     return FV;
     317        4396 :   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        2848 :   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        2826 :   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        2002 :     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
     332         459 :     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        7974 : 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        7974 :   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        1661 :     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        7891 :   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
     376        7891 :   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        7854 :   } 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        5413 :     if (!isSameCompare(Cond, Pred, TV, RHS))
     384             :       return nullptr;
     385           8 :     TCmp = getTrue(Cond->getType());
     386             :   }
     387             : 
     388             :   // Does "cmp FV, RHS" simplify?
     389        2486 :   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
     390        2486 :   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        2485 :   } 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        2104 :     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         394 :   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        1020 :   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         339 :   if (match(FCmp, m_Zero()))
     415         155 :     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       53215 : 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       53215 :   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       34546 :     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       11097 :     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       59013 :   for (Value *Incoming : PI->incoming_values()) {
     461             :     // If the incoming value is the phi node itself, it can safely be skipped.
     462       44214 :     if (Incoming == PI) continue;
     463       44214 :     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       44214 :     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       66485 : 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       66485 :   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        7351 :     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       65722 :   if (!valueDominatesPHI(RHS, PI, Q.DT))
     496             :     return nullptr;
     497             : 
     498             :   // Evaluate the BinOp on the incoming phi values.
     499             :   Value *CommonValue = nullptr;
     500      101577 :   for (Value *Incoming : PI->incoming_values()) {
     501             :     // If the incoming value is the phi node itself, it can safely be skipped.
     502       75938 :     if (Incoming == PI) continue;
     503       75933 :     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       75933 :     if (!V || (CommonValue && V != CommonValue))
     507             :       return nullptr;
     508             :     CommonValue = V;
     509             :   }
     510             : 
     511             :   return CommonValue;
     512             : }
     513             : 
     514     8176765 : static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
     515             :                                        Value *&Op0, Value *&Op1,
     516             :                                        const SimplifyQuery &Q) {
     517     8176765 :   if (auto *CLHS = dyn_cast<Constant>(Op0)) {
     518      353792 :     if (auto *CRHS = dyn_cast<Constant>(Op1))
     519      140326 :       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     7492058 : static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
     531             :                               const SimplifyQuery &Q, unsigned MaxRecurse) {
     532     7492058 :   if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
     533             :     return C;
     534             : 
     535             :   // X + undef -> undef
     536    14777480 :   if (match(Op1, m_Undef()))
     537             :     return Op1;
     538             : 
     539             :   // X + 0 -> X
     540     7388736 :   if (match(Op1, m_Zero()))
     541        6267 :     return Op0;
     542             : 
     543             :   // X + (Y - X) -> Y
     544             :   // (Y - X) + X -> Y
     545             :   // Eg: X + -X -> 0
     546     7382469 :   Value *Y = nullptr;
     547    29529875 :   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
     548    14764937 :       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
     549          70 :     return Y;
     550             : 
     551             :   // X + ~X -> -1   since   ~X = -X-1
     552     7382399 :   Type *Ty = Op0->getType();
     553    29529594 :   if (match(Op0, m_Not(m_Specific(Op1))) ||
     554    14764796 :       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    14866153 :   if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
     561     7382406 :       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     7432053 :   if (IsNUW && match(Op1, m_AllOnes()))
     566          29 :     return Op1; // Which is -1.
     567             : 
     568             :   /// i1 add -> xor.
     569    22029397 :   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    14764716 :   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
     575     7382358 :                                           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     7382232 :   return nullptr;
     588             : }
     589             : 
     590     4987697 : Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
     591             :                              const SimplifyQuery &Query) {
     592     4987697 :   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      944810 : static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
     606             :                                                 bool AllowNonInbounds = false) {
     607             :   assert(V->getType()->isPtrOrPtrVectorTy());
     608             : 
     609      944810 :   Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
     610      944810 :   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      944810 :   Visited.insert(V);
     616             :   do {
     617      979807 :     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
     618      120769 :       if ((!AllowNonInbounds && !GEP->isInBounds()) ||
     619       38445 :           !GEP->accumulateConstantOffset(DL, Offset))
     620             :         break;
     621       34871 :       V = GEP->getPointerOperand();
     622      493680 :     } 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      937755 :       if (auto CS = CallSite(V))
     630       26327 :         if (Value *RV = CS.getReturnedArgOperand()) {
     631           1 :           V = RV;
     632           1 :           continue;
     633             :         }
     634      937754 :       break;
     635             :     }
     636             :     assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
     637       34997 :   } while (Visited.insert(V).second);
     638             : 
     639      944810 :   Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
     640     1889620 :   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       19472 : static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
     649             :                                           Value *RHS) {
     650       19472 :   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
     651       19472 :   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       19472 :   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       91975 : static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
     668             :                               const SimplifyQuery &Q, unsigned MaxRecurse) {
     669       91975 :   if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
     670             :     return C;
     671             : 
     672             :   // X - undef -> undef
     673             :   // undef - X -> undef
     674      271661 :   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
     675           2 :     return UndefValue::get(Op0->getType());
     676             : 
     677             :   // X - 0 -> X
     678       90552 :   if (match(Op1, m_Zero()))
     679         487 :     return Op0;
     680             : 
     681             :   // X - X -> 0
     682       90065 :   if (Op0 == Op1)
     683         205 :     return Constant::getNullValue(Op0->getType());
     684             : 
     685             :   // Is this a negation?
     686       89860 :   if (match(Op0, m_Zero())) {
     687             :     // 0 - X -> 0 if the sub is NUW.
     688        6032 :     if (isNUW)
     689          20 :       return Constant::getNullValue(Op0->getType());
     690             : 
     691       12044 :     KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
     692        6025 :     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       89847 :   Value *X = nullptr, *Y = nullptr, *Z = Op1;
     706      179043 :   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
     707             :     // See if "V === Y - Z" simplifies.
     708        4358 :     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        4345 :     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       89807 :   X = Op0;
     728      178963 :   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
     729             :     // See if "V === X - Y" simplifies.
     730        1305 :     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        1259 :     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       89761 :   Z = Op0;
     750      178871 :   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      268961 :   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
     762       90114 :       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      292490 :   if (match(Op0, m_PtrToInt(m_Value(X))) &&
     774      112994 :       match(Op1, m_PtrToInt(m_Value(Y))))
     775       19472 :     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
     776          10 :       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
     777             : 
     778             :   // i1 sub -> xor.
     779      178825 :   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       56676 : Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
     796             :                              const SimplifyQuery &Q) {
     797       56676 :   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       77638 : static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
     803             :                               unsigned MaxRecurse) {
     804       77638 :   if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
     805             :     return C;
     806             : 
     807             :   // X * undef -> 0
     808             :   // X * 0 -> 0
     809       72404 :   if (match(Op1, m_CombineOr(m_Undef(), m_Zero())))
     810         946 :     return Constant::getNullValue(Op0->getType());
     811             : 
     812             :   // X * 1 -> X
     813      142916 :   if (match(Op1, m_One()))
     814        1354 :     return Op0;
     815             : 
     816             :   // (X / Y) * Y -> X if the division is exact.
     817       70104 :   Value *X = nullptr;
     818      280060 :   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
     819      139852 :       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
     820         358 :     return X;
     821             : 
     822             :   // i1 mul -> and.
     823      167112 :   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      139488 :   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
     829       69744 :                                           MaxRecurse))
     830             :     return V;
     831             : 
     832             :   // Mul distributes over Add. Try some generic simplifications based on this.
     833      139484 :   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
     834       69742 :                              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      138542 :   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
     840        2668 :     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
     841        1334 :                                          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      128885 :   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
     847       30392 :     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
     848       15196 :                                       MaxRecurse))
     849             :       return V;
     850             : 
     851             :   return nullptr;
     852             : }
     853             : 
     854       18780 : Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
     855       18780 :   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       28497 : static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) {
     861       28497 :   Type *Ty = Op0->getType();
     862             : 
     863             :   // X / undef -> undef
     864             :   // X % undef -> undef
     865       28497 :   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       28494 :   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       16571 :   if (Op1C && Ty->isVectorTy()) {
     878             :     unsigned NumElts = Ty->getVectorNumElements();
     879        2705 :     for (unsigned i = 0; i != NumElts; ++i) {
     880        1219 :       Constant *Elt = Op1C->getAggregateElement(i);
     881        2432 :       if (Elt && (Elt->isNullValue() || isa<UndefValue>(Elt)))
     882          16 :         return UndefValue::get(Ty);
     883             :     }
     884             :   }
     885             : 
     886             :   // undef / X -> 0
     887             :   // undef % X -> 0
     888       28413 :   if (match(Op0, m_Undef()))
     889           0 :     return Constant::getNullValue(Ty);
     890             : 
     891             :   // 0 / X -> 0
     892             :   // 0 % X -> 0
     893       28413 :   if (match(Op0, m_Zero()))
     894          53 :     return Constant::getNullValue(Op0->getType());
     895             : 
     896             :   // X / X -> 1
     897             :   // X % X -> 0
     898       28360 :   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             :   // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1.
     906             :   Value *X;
     907      113178 :   if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
     908       56722 :       (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
     909         110 :     return IsDiv ? Op0 : Constant::getNullValue(Ty);
     910             : 
     911             :   return nullptr;
     912             : }
     913             : 
     914             : /// Given a predicate and two operands, return true if the comparison is true.
     915             : /// This is a helper for div/rem simplification where we return some other value
     916             : /// when we can prove a relationship between the operands.
     917       27397 : static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
     918             :                        const SimplifyQuery &Q, unsigned MaxRecurse) {
     919       27397 :   Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
     920             :   Constant *C = dyn_cast_or_null<Constant>(V);
     921         605 :   return (C && C->isAllOnesValue());
     922             : }
     923             : 
     924             : /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
     925             : /// to simplify X % Y to X.
     926       28221 : static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
     927             :                       unsigned MaxRecurse, bool IsSigned) {
     928             :   // Recursion is always used, so bail out at once if we already hit the limit.
     929       28221 :   if (!MaxRecurse--)
     930             :     return false;
     931             : 
     932       28185 :   if (IsSigned) {
     933             :     // |X| / |Y| --> 0
     934             :     //
     935             :     // We require that 1 operand is a simple constant. That could be extended to
     936             :     // 2 variables if we computed the sign bit for each.
     937             :     //
     938             :     // Make sure that a constant is not the minimum signed value because taking
     939             :     // the abs() of that is undefined.
     940       11276 :     Type *Ty = X->getType();
     941             :     const APInt *C;
     942       33786 :     if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
     943             :       // Is the variable divisor magnitude always greater than the constant
     944             :       // dividend magnitude?
     945             :       // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
     946          84 :       Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
     947         168 :       Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
     948          84 :       if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
     949          42 :           isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
     950             :         return true;
     951             :     }
     952       22552 :     if (match(Y, m_APInt(C))) {
     953             :       // Special-case: we can't take the abs() of a minimum signed value. If
     954             :       // that's the divisor, then all we have to do is prove that the dividend
     955             :       // is also not the minimum signed value.
     956       10364 :       if (C->isMinSignedValue())
     957           9 :         return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
     958             : 
     959             :       // Is the variable dividend magnitude always less than the constant
     960             :       // divisor magnitude?
     961             :       // |X| < |C| --> X > -abs(C) and X < abs(C)
     962       20710 :       Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
     963       41420 :       Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
     964       10395 :       if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
     965          40 :           isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
     966             :         return true;
     967             :     }
     968             :     return false;
     969             :   }
     970             : 
     971             :   // IsSigned == false.
     972             :   // Is the dividend unsigned less than the divisor?
     973       16909 :   return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
     974             : }
     975             : 
     976             : /// These are simplifications common to SDiv and UDiv.
     977       19381 : static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
     978             :                           const SimplifyQuery &Q, unsigned MaxRecurse) {
     979       19381 :   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
     980             :     return C;
     981             : 
     982       19151 :   if (Value *V = simplifyDivRem(Op0, Op1, true))
     983             :     return V;
     984             : 
     985       18966 :   bool IsSigned = Opcode == Instruction::SDiv;
     986             : 
     987             :   // (X * Y) / Y -> X if the multiplication does not overflow.
     988             :   Value *X;
     989       37932 :   if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
     990          28 :     auto *Mul = cast<OverflowingBinaryOperator>(Op0);
     991             :     // If the Mul does not overflow, then we are good to go.
     992          52 :     if ((IsSigned && Mul->hasNoSignedWrap()) ||
     993           4 :         (!IsSigned && Mul->hasNoUnsignedWrap()))
     994           4 :       return X;
     995             :     // If X has the form X = A / Y, then X * Y cannot overflow.
     996          70 :     if ((IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
     997          24 :         (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1)))))
     998           4 :       return X;
     999             :   }
    1000             : 
    1001             :   // (X rem Y) / Y -> 0
    1002       48129 :   if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
    1003       36446 :       (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
    1004           2 :     return Constant::getNullValue(Op0->getType());
    1005             : 
    1006             :   // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
    1007             :   ConstantInt *C1, *C2;
    1008       46656 :   if (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
    1009           8 :       match(Op1, m_ConstantInt(C2))) {
    1010             :     bool Overflow;
    1011           6 :     (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
    1012           2 :     if (Overflow)
    1013           1 :       return Constant::getNullValue(Op0->getType());
    1014             :   }
    1015             : 
    1016             :   // If the operation is with the result of a select instruction, check whether
    1017             :   // operating on either branch of the select always yields the same value.
    1018       37897 :   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
    1019          42 :     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
    1020             :       return V;
    1021             : 
    1022             :   // If the operation is with the result of a phi instruction, check whether
    1023             :   // operating on all incoming values of the phi always yields the same value.
    1024       36978 :   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
    1025        1904 :     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
    1026             :       return V;
    1027             : 
    1028       18954 :   if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
    1029          17 :     return Constant::getNullValue(Op0->getType());
    1030             : 
    1031             :   return nullptr;
    1032             : }
    1033             : 
    1034             : /// These are simplifications common to SRem and URem.
    1035        9707 : static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
    1036             :                           const SimplifyQuery &Q, unsigned MaxRecurse) {
    1037        9707 :   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
    1038             :     return C;
    1039             : 
    1040        9346 :   if (Value *V = simplifyDivRem(Op0, Op1, false))
    1041             :     return V;
    1042             : 
    1043             :   // (X % Y) % Y -> X % Y
    1044        1102 :   if ((Opcode == Instruction::SRem &&
    1045       27824 :        match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
    1046        8173 :       (Opcode == Instruction::URem &&
    1047       17448 :        match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
    1048           2 :     return Op0;
    1049             : 
    1050             :   // (X << Y) % X -> 0
    1051        1101 :   if ((Opcode == Instruction::SRem &&
    1052       27817 :        match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
    1053        8172 :       (Opcode == Instruction::URem &&
    1054       17445 :        match(Op0, m_NUWShl(m_Specific(Op1), m_Value()))))
    1055           4 :     return Constant::getNullValue(Op0->getType());
    1056             : 
    1057             :   // If the operation is with the result of a select instruction, check whether
    1058             :   // operating on either branch of the select always yields the same value.
    1059       18503 :   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
    1060          99 :     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
    1061             :       return V;
    1062             : 
    1063             :   // If the operation is with the result of a phi instruction, check whether
    1064             :   // operating on all incoming values of the phi always yields the same value.
    1065       17460 :   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
    1066        1355 :     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
    1067             :       return V;
    1068             : 
    1069             :   // If X / Y == 0, then X % Y == X.
    1070        9267 :   if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
    1071          14 :     return Op0;
    1072             : 
    1073             :   return nullptr;
    1074             : }
    1075             : 
    1076             : /// Given operands for an SDiv, see if we can fold the result.
    1077             : /// If not, this returns null.
    1078        3421 : static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
    1079             :                                unsigned MaxRecurse) {
    1080       10351 :   return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse);
    1081             : }
    1082             : 
    1083        6930 : Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
    1084        6930 :   return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit);
    1085             : }
    1086             : 
    1087             : /// Given operands for a UDiv, see if we can fold the result.
    1088             : /// If not, this returns null.
    1089        4066 : static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
    1090             :                                unsigned MaxRecurse) {
    1091        9030 :   return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse);
    1092             : }
    1093             : 
    1094        4964 : Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
    1095        4964 :   return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit);
    1096             : }
    1097             : 
    1098             : /// Given operands for an SRem, see if we can fold the result.
    1099             : /// If not, this returns null.
    1100        1193 : static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
    1101             :                                unsigned MaxRecurse) {
    1102             :   // If the divisor is 0, the result is undefined, so assume the divisor is -1.
    1103             :   // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
    1104             :   Value *X;
    1105        3583 :   if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
    1106           2 :     return ConstantInt::getNullValue(Op0->getType());
    1107             : 
    1108        1191 :   return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
    1109             : }
    1110             : 
    1111         909 : Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
    1112         909 :   return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit);
    1113             : }
    1114             : 
    1115             : /// Given operands for a URem, see if we can fold the result.
    1116             : /// If not, this returns null.
    1117        2910 : static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
    1118             :                                unsigned MaxRecurse) {
    1119        8516 :   return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
    1120             : }
    1121             : 
    1122        5606 : Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
    1123        5606 :   return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit);
    1124             : }
    1125             : 
    1126             : /// Returns true if a shift by \c Amount always yields undef.
    1127      130814 : static bool isUndefShift(Value *Amount) {
    1128             :   Constant *C = dyn_cast<Constant>(Amount);
    1129             :   if (!C)
    1130             :     return false;
    1131             : 
    1132             :   // X shift by undef -> undef because it may shift by the bitwidth.
    1133      108651 :   if (isa<UndefValue>(C))
    1134             :     return true;
    1135             : 
    1136             :   // Shifting by the bitwidth or more is undefined.
    1137             :   if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
    1138      106391 :     if (CI->getValue().getLimitedValue() >=
    1139      106391 :         CI->getType()->getScalarSizeInBits())
    1140             :       return true;
    1141             : 
    1142             :   // If all lanes of a vector shift are undefined the whole shift is.
    1143      108574 :   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
    1144        4446 :     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
    1145        2219 :       if (!isUndefShift(C->getAggregateElement(I)))
    1146             :         return false;
    1147             :     return true;
    1148             :   }
    1149             : 
    1150             :   return false;
    1151             : }
    1152             : 
    1153             : /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
    1154             : /// If not, this returns null.
    1155      137732 : static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
    1156             :                             Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse) {
    1157      137732 :   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
    1158             :     return C;
    1159             : 
    1160             :   // 0 shift by X -> 0
    1161      257490 :   if (match(Op0, m_Zero()))
    1162          24 :     return Constant::getNullValue(Op0->getType());
    1163             : 
    1164             :   // X shift by 0 -> X
    1165             :   // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
    1166             :   // would be poison.
    1167             :   Value *X;
    1168      386043 :   if (match(Op1, m_Zero()) ||
    1169      257230 :       (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
    1170         126 :     return Op0;
    1171             : 
    1172             :   // Fold undefined shifts.
    1173      128595 :   if (isUndefShift(Op1))
    1174          20 :     return UndefValue::get(Op0->getType());
    1175             : 
    1176             :   // If the operation is with the result of a select instruction, check whether
    1177             :   // operating on either branch of the select always yields the same value.
    1178      255436 :   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
    1179        1780 :     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
    1180             :       return V;
    1181             : 
    1182             :   // If the operation is with the result of a phi instruction, check whether
    1183             :   // operating on all incoming values of the phi always yields the same value.
    1184      247327 :   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
    1185       10051 :     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
    1186             :       return V;
    1187             : 
    1188             :   // If any bits in the shift amount make that value greater than or equal to
    1189             :   // the number of bits in the type, the shift is undefined.
    1190      257148 :   KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
    1191      128574 :   if (Known.One.getLimitedValue() >= Known.getBitWidth())
    1192           4 :     return UndefValue::get(Op0->getType());
    1193             : 
    1194             :   // If all valid bits in the shift amount are known zero, the first operand is
    1195             :   // unchanged.
    1196             :   unsigned NumValidShiftBits = Log2_32_Ceil(Known.getBitWidth());
    1197      128570 :   if (Known.countMinTrailingZeros() >= NumValidShiftBits)
    1198           6 :     return Op0;
    1199             : 
    1200             :   return nullptr;
    1201             : }
    1202             : 
    1203             : /// Given operands for an Shl, LShr or AShr, see if we can
    1204             : /// fold the result.  If not, this returns null.
    1205       70074 : static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
    1206             :                                  Value *Op1, bool isExact, const SimplifyQuery &Q,
    1207             :                                  unsigned MaxRecurse) {
    1208       70074 :   if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
    1209             :     return V;
    1210             : 
    1211             :   // X >> X -> 0
    1212       68421 :   if (Op0 == Op1)
    1213           3 :     return Constant::getNullValue(Op0->getType());
    1214             : 
    1215             :   // undef >> X -> 0
    1216             :   // undef >> X -> undef (if it's exact)
    1217       68418 :   if (match(Op0, m_Undef()))
    1218           3 :     return isExact ? Op0 : Constant::getNullValue(Op0->getType());
    1219             : 
    1220             :   // The low bit cannot be shifted out of an exact shift if it is set.
    1221       68415 :   if (isExact) {
    1222       37596 :     KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
    1223       18800 :     if (Op0Known.One[0])
    1224           4 :       return Op0;
    1225             :   }
    1226             : 
    1227             :   return nullptr;
    1228             : }
    1229             : 
    1230             : /// Given operands for an Shl, see if we can fold the result.
    1231             : /// If not, this returns null.
    1232       67658 : static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
    1233             :                               const SimplifyQuery &Q, unsigned MaxRecurse) {
    1234       67658 :   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
    1235             :     return V;
    1236             : 
    1237             :   // undef << X -> 0
    1238             :   // undef << X -> undef if (if it's NSW/NUW)
    1239       60143 :   if (match(Op0, m_Undef()))
    1240           4 :     return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
    1241             : 
    1242             :   // (X >> A) << A -> X
    1243             :   Value *X;
    1244      120278 :   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
    1245          30 :     return X;
    1246             : 
    1247             :   // shl nuw i8 C, %x  ->  C  iff C has sign bit set.
    1248       63273 :   if (isNUW && match(Op0, m_Negative()))
    1249             :     return Op0;
    1250             :   // NOTE: could use computeKnownBits() / LazyValueInfo,
    1251             :   // but the cost-benefit analysis suggests it isn't worth it.
    1252             : 
    1253             :   return nullptr;
    1254             : }
    1255             : 
    1256       40021 : Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
    1257             :                              const SimplifyQuery &Q) {
    1258       40021 :   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
    1259             : }
    1260             : 
    1261             : /// Given operands for an LShr, see if we can fold the result.
    1262             : /// If not, this returns null.
    1263       41028 : static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
    1264             :                                const SimplifyQuery &Q, unsigned MaxRecurse) {
    1265       82056 :   if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
    1266       41028 :                                     MaxRecurse))
    1267             :       return V;
    1268             : 
    1269             :   // (X << A) >> A -> X
    1270             :   Value *X;
    1271       79130 :   if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
    1272           9 :     return X;
    1273             : 
    1274             :   return nullptr;
    1275             : }
    1276             : 
    1277       29629 : Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
    1278             :                               const SimplifyQuery &Q) {
    1279       29629 :   return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
    1280             : }
    1281             : 
    1282             : /// Given operands for an AShr, see if we can fold the result.
    1283             : /// If not, this returns null.
    1284       29046 : static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
    1285             :                                const SimplifyQuery &Q, unsigned MaxRecurse) {
    1286       58092 :   if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
    1287       29046 :                                     MaxRecurse))
    1288             :     return V;
    1289             : 
    1290             :   // all ones >>a X -> -1
    1291             :   // Do not return Op0 because it may contain undef elements if it's a vector.
    1292       28846 :   if (match(Op0, m_AllOnes()))
    1293           8 :     return Constant::getAllOnesValue(Op0->getType());
    1294             : 
    1295             :   // (X << A) >> A -> X
    1296             :   Value *X;
    1297       57676 :   if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
    1298           3 :     return X;
    1299             : 
    1300             :   // Arithmetic shifting an all-sign-bit value is a no-op.
    1301       28835 :   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
    1302       28835 :   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
    1303             :     return Op0;
    1304             : 
    1305       28828 :   return nullptr;
    1306             : }
    1307             : 
    1308       20181 : Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
    1309             :                               const SimplifyQuery &Q) {
    1310       20181 :   return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
    1311             : }
    1312             : 
    1313             : /// Commuted variants are assumed to be handled by calling this function again
    1314             : /// with the parameters swapped.
    1315       20017 : static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
    1316             :                                          ICmpInst *UnsignedICmp, bool IsAnd) {
    1317             :   Value *X, *Y;
    1318             : 
    1319             :   ICmpInst::Predicate EqPred;
    1320       26761 :   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
    1321        6744 :       !ICmpInst::isEquality(EqPred))
    1322             :     return nullptr;
    1323             : 
    1324             :   ICmpInst::Predicate UnsignedPred;
    1325        6663 :   if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
    1326          10 :       ICmpInst::isUnsigned(UnsignedPred))
    1327             :     ;
    1328             :   else if (match(UnsignedICmp,
    1329        7375 :                  m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
    1330         729 :            ICmpInst::isUnsigned(UnsignedPred))
    1331          17 :     UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
    1332             :   else
    1333             :     return nullptr;
    1334             : 
    1335             :   // X < Y && Y != 0  -->  X < Y
    1336             :   // X < Y || Y != 0  -->  Y != 0
    1337          24 :   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
    1338           4 :     return IsAnd ? UnsignedICmp : ZeroICmp;
    1339             : 
    1340             :   // X >= Y || Y != 0  -->  true
    1341             :   // X >= Y || Y == 0  -->  X >= Y
    1342          20 :   if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
    1343           5 :     if (EqPred == ICmpInst::ICMP_NE)
    1344           6 :       return getTrue(UnsignedICmp->getType());
    1345             :     return UnsignedICmp;
    1346             :   }
    1347             : 
    1348             :   // X < Y && Y == 0  -->  false
    1349          15 :   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
    1350             :       IsAnd)
    1351           8 :     return getFalse(UnsignedICmp->getType());
    1352             : 
    1353             :   return nullptr;
    1354             : }
    1355             : 
    1356             : /// Commuted variants are assumed to be handled by calling this function again
    1357             : /// with the parameters swapped.
    1358        5584 : static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
    1359             :   ICmpInst::Predicate Pred0, Pred1;
    1360             :   Value *A ,*B;
    1361             :   if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
    1362             :       !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
    1363             :     return nullptr;
    1364             : 
    1365             :   // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
    1366             :   // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
    1367             :   // can eliminate Op1 from this 'and'.
    1368         184 :   if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
    1369             :     return Op0;
    1370             : 
    1371             :   // Check for any combination of predicates that are guaranteed to be disjoint.
    1372         273 :   if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
    1373           9 :       (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
    1374         162 :       (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
    1375          13 :       (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
    1376          78 :     return getFalse(Op0->getType());
    1377             : 
    1378             :   return nullptr;
    1379             : }
    1380             : 
    1381             : /// Commuted variants are assumed to be handled by calling this function again
    1382             : /// with the parameters swapped.
    1383       14235 : static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
    1384             :   ICmpInst::Predicate Pred0, Pred1;
    1385             :   Value *A ,*B;
    1386             :   if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
    1387             :       !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
    1388             :     return nullptr;
    1389             : 
    1390             :   // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
    1391             :   // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
    1392             :   // can eliminate Op0 from this 'or'.
    1393         303 :   if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
    1394             :     return Op1;
    1395             : 
    1396             :   // Check for any combination of predicates that cover the entire range of
    1397             :   // possibilities.
    1398         381 :   if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
    1399          12 :       (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
    1400         216 :       (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
    1401          13 :       (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
    1402          74 :     return getTrue(Op0->getType());
    1403             : 
    1404             :   return nullptr;
    1405             : }
    1406             : 
    1407             : /// Test if a pair of compares with a shared operand and 2 constants has an
    1408             : /// empty set intersection, full set union, or if one compare is a superset of
    1409             : /// the other.
    1410        9785 : static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
    1411             :                                                 bool IsAnd) {
    1412             :   // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
    1413        9785 :   if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
    1414             :     return nullptr;
    1415             : 
    1416             :   const APInt *C0, *C1;
    1417        8273 :   if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
    1418        3099 :       !match(Cmp1->getOperand(1), m_APInt(C1)))
    1419             :     return nullptr;
    1420             : 
    1421        1509 :   auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
    1422        1509 :   auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
    1423             : 
    1424             :   // For and-of-compares, check if the intersection is empty:
    1425             :   // (icmp X, C0) && (icmp X, C1) --> empty set --> false
    1426         503 :   if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
    1427          92 :     return getFalse(Cmp0->getType());
    1428             : 
    1429             :   // For or-of-compares, check if the union is full:
    1430             :   // (icmp X, C0) || (icmp X, C1) --> full set --> true
    1431         457 :   if (!IsAnd && Range0.unionWith(Range1).isFullSet())
    1432          86 :     return getTrue(Cmp0->getType());
    1433             : 
    1434             :   // Is one range a superset of the other?
    1435             :   // If this is and-of-compares, take the smaller set:
    1436             :   // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
    1437             :   // If this is or-of-compares, take the larger set:
    1438             :   // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
    1439         414 :   if (Range0.contains(Range1))
    1440          99 :     return IsAnd ? Cmp1 : Cmp0;
    1441         315 :   if (Range1.contains(Range0))
    1442          90 :     return IsAnd ? Cmp0 : Cmp1;
    1443             : 
    1444             :   return nullptr;
    1445             : }
    1446             : 
    1447        9507 : static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
    1448             :                                            bool IsAnd) {
    1449             :   ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
    1450        3721 :   if (!match(Cmp0->getOperand(1), m_Zero()) ||
    1451       11940 :       !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
    1452             :     return nullptr;
    1453             : 
    1454         707 :   if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
    1455             :     return nullptr;
    1456             : 
    1457             :   // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
    1458             :   Value *X = Cmp0->getOperand(0);
    1459             :   Value *Y = Cmp1->getOperand(0);
    1460             : 
    1461             :   // If one of the compares is a masked version of a (not) null check, then
    1462             :   // that compare implies the other, so we eliminate the other. Optionally, look
    1463             :   // through a pointer-to-int cast to match a null check of a pointer type.
    1464             : 
    1465             :   // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
    1466             :   // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
    1467             :   // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
    1468             :   // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
    1469        2455 :   if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
    1470        1225 :       match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
    1471             :     return Cmp1;
    1472             : 
    1473             :   // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
    1474             :   // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
    1475             :   // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
    1476             :   // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
    1477        2419 :   if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
    1478        1207 :       match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
    1479             :     return Cmp0;
    1480             : 
    1481             :   return nullptr;
    1482             : }
    1483             : 
    1484        5172 : static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1) {
    1485             :   // (icmp (add V, C0), C1) & (icmp V, C0)
    1486             :   ICmpInst::Predicate Pred0, Pred1;
    1487             :   const APInt *C0, *C1;
    1488             :   Value *V;
    1489        5172 :   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
    1490             :     return nullptr;
    1491             : 
    1492         124 :   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
    1493             :     return nullptr;
    1494             : 
    1495             :   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
    1496          12 :   if (AddInst->getOperand(1) != Op1->getOperand(1))
    1497             :     return nullptr;
    1498             : 
    1499          12 :   Type *ITy = Op0->getType();
    1500          12 :   bool isNSW = AddInst->hasNoSignedWrap();
    1501          12 :   bool isNUW = AddInst->hasNoUnsignedWrap();
    1502             : 
    1503          24 :   const APInt Delta = *C1 - *C0;
    1504          12 :   if (C0->isStrictlyPositive()) {
    1505          12 :     if (Delta == 2) {
    1506           6 :       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
    1507           2 :         return getFalse(ITy);
    1508           4 :       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
    1509           2 :         return getFalse(ITy);
    1510             :     }
    1511           8 :     if (Delta == 1) {
    1512           6 :       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
    1513           2 :         return getFalse(ITy);
    1514           4 :       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
    1515           2 :         return getFalse(ITy);
    1516             :     }
    1517             :   }
    1518           4 :   if (C0->getBoolValue() && isNUW) {
    1519           4 :     if (Delta == 2)
    1520           2 :       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
    1521           2 :         return getFalse(ITy);
    1522           2 :     if (Delta == 1)
    1523           2 :       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
    1524           2 :         return getFalse(ITy);
    1525             :   }
    1526             : 
    1527             :   return nullptr;
    1528             : }
    1529             : 
    1530        2826 : static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
    1531        2826 :   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
    1532             :     return X;
    1533        2824 :   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true))
    1534             :     return X;
    1535             : 
    1536        2820 :   if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
    1537             :     return X;
    1538        2764 :   if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0))
    1539             :     return X;
    1540             : 
    1541        2745 :   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
    1542             :     return X;
    1543             : 
    1544        2600 :   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
    1545             :     return X;
    1546             : 
    1547        2592 :   if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1))
    1548             :     return X;
    1549        2580 :   if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0))
    1550             :     return X;
    1551             : 
    1552        2580 :   return nullptr;
    1553             : }
    1554             : 
    1555       13782 : static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1) {
    1556             :   // (icmp (add V, C0), C1) | (icmp V, C0)
    1557             :   ICmpInst::Predicate Pred0, Pred1;
    1558             :   const APInt *C0, *C1;
    1559             :   Value *V;
    1560       13782 :   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
    1561             :     return nullptr;
    1562             : 
    1563          39 :   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
    1564             :     return nullptr;
    1565             : 
    1566             :   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
    1567          13 :   if (AddInst->getOperand(1) != Op1->getOperand(1))
    1568             :     return nullptr;
    1569             : 
    1570          12 :   Type *ITy = Op0->getType();
    1571          12 :   bool isNSW = AddInst->hasNoSignedWrap();
    1572          12 :   bool isNUW = AddInst->hasNoUnsignedWrap();
    1573             : 
    1574          24 :   const APInt Delta = *C1 - *C0;
    1575          12 :   if (C0->isStrictlyPositive()) {
    1576          12 :     if (Delta == 2) {
    1577           6 :       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
    1578           2 :         return getTrue(ITy);
    1579           4 :       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
    1580           2 :         return getTrue(ITy);
    1581             :     }
    1582           8 :     if (Delta == 1) {
    1583           6 :       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
    1584           2 :         return getTrue(ITy);
    1585           4 :       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
    1586           2 :         return getTrue(ITy);
    1587             :     }
    1588             :   }
    1589           4 :   if (C0->getBoolValue() && isNUW) {
    1590           4 :     if (Delta == 2)
    1591           2 :       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
    1592           2 :         return getTrue(ITy);
    1593           2 :     if (Delta == 1)
    1594           2 :       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
    1595           2 :         return getTrue(ITy);
    1596             :   }
    1597             : 
    1598             :   return nullptr;
    1599             : }
    1600             : 
    1601        7184 : static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
    1602        7184 :   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
    1603             :     return X;
    1604        7183 :   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false))
    1605             :     return X;
    1606             : 
    1607        7177 :   if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
    1608             :     return X;
    1609        7058 :   if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0))
    1610             :     return X;
    1611             : 
    1612        7040 :   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
    1613             :     return X;
    1614             : 
    1615        6907 :   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
    1616             :     return X;
    1617             : 
    1618        6897 :   if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1))
    1619             :     return X;
    1620        6885 :   if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0))
    1621             :     return X;
    1622             : 
    1623        6885 :   return nullptr;
    1624             : }
    1625             : 
    1626        1319 : static Value *simplifyAndOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) {
    1627             :   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
    1628             :   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
    1629        1319 :   if (LHS0->getType() != RHS0->getType())
    1630             :     return nullptr;
    1631             : 
    1632             :   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
    1633        2617 :   if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
    1634        1633 :       (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
    1635             :     // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
    1636             :     // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
    1637             :     // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
    1638             :     // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
    1639             :     // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
    1640             :     // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
    1641             :     // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
    1642             :     // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
    1643          56 :     if ((isKnownNeverNaN(LHS0) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
    1644          42 :         (isKnownNeverNaN(LHS1) && (LHS0 == RHS0 || LHS0 == RHS1)))
    1645             :       return RHS;
    1646             : 
    1647             :     // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
    1648             :     // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
    1649             :     // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
    1650             :     // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
    1651             :     // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
    1652             :     // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
    1653             :     // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
    1654             :     // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
    1655          40 :     if ((isKnownNeverNaN(RHS0) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
    1656          34 :         (isKnownNeverNaN(RHS1) && (RHS0 == LHS0 || RHS0 == LHS1)))
    1657             :       return LHS;
    1658             :   }
    1659             : 
    1660             :   return nullptr;
    1661             : }
    1662             : 
    1663      210787 : static Value *simplifyAndOrOfCmps(Value *Op0, Value *Op1, bool IsAnd) {
    1664             :   // Look through casts of the 'and' operands to find compares.
    1665             :   auto *Cast0 = dyn_cast<CastInst>(Op0);
    1666             :   auto *Cast1 = dyn_cast<CastInst>(Op1);
    1667      212772 :   if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
    1668             :       Cast0->getSrcTy() == Cast1->getSrcTy()) {
    1669             :     Op0 = Cast0->getOperand(0);
    1670             :     Op1 = Cast1->getOperand(0);
    1671             :   }
    1672             : 
    1673             :   Value *V = nullptr;
    1674             :   auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
    1675             :   auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
    1676      210787 :   if (ICmp0 && ICmp1)
    1677       10010 :     V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1) :
    1678             :                 simplifyOrOfICmps(ICmp0, ICmp1);
    1679             : 
    1680             :   auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
    1681             :   auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
    1682      210787 :   if (FCmp0 && FCmp1)
    1683        1319 :     V = simplifyAndOrOfFCmps(FCmp0, FCmp1, IsAnd);
    1684             : 
    1685      210787 :   if (!V)
    1686             :     return nullptr;
    1687         561 :   if (!Cast0)
    1688             :     return V;
    1689             : 
    1690             :   // If we looked through casts, we can only handle a constant simplification
    1691             :   // because we are not allowed to create a cast instruction here.
    1692             :   if (auto *C = dyn_cast<Constant>(V))
    1693          16 :     return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
    1694             : 
    1695             :   return nullptr;
    1696             : }
    1697             : 
    1698             : /// Given operands for an And, see if we can fold the result.
    1699             : /// If not, this returns null.
    1700      127171 : static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
    1701             :                               unsigned MaxRecurse) {
    1702      127171 :   if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
    1703             :     return C;
    1704             : 
    1705             :   // X & undef -> 0
    1706      234248 :   if (match(Op1, m_Undef()))
    1707           2 :     return Constant::getNullValue(Op0->getType());
    1708             : 
    1709             :   // X & X = X
    1710      117122 :   if (Op0 == Op1)
    1711             :     return Op0;
    1712             : 
    1713             :   // X & 0 = 0
    1714      117062 :   if (match(Op1, m_Zero()))
    1715        1379 :     return Constant::getNullValue(Op0->getType());
    1716             : 
    1717             :   // X & -1 = X
    1718      231366 :   if (match(Op1, m_AllOnes()))
    1719        5224 :     return Op0;
    1720             : 
    1721             :   // A & ~A  =  ~A & A  =  0
    1722      441801 :   if (match(Op0, m_Not(m_Specific(Op1))) ||
    1723      220883 :       match(Op1, m_Not(m_Specific(Op0))))
    1724          58 :     return Constant::getNullValue(Op0->getType());
    1725             : 
    1726             :   // (A | ?) & A = A
    1727      220802 :   if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
    1728             :     return Op1;
    1729             : 
    1730             :   // A & (A | ?) = A
    1731      220732 :   if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
    1732             :     return Op0;
    1733             : 
    1734             :   // A mask that only clears known zeros of a shifted value is a no-op.
    1735             :   Value *X;
    1736             :   const APInt *Mask;
    1737             :   const APInt *ShAmt;
    1738      220626 :   if (match(Op1, m_APInt(Mask))) {
    1739             :     // If all bits in the inverted and shifted mask are clear:
    1740             :     // and (shl X, ShAmt), Mask --> shl X, ShAmt
    1741      198826 :     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
    1742      266372 :         (~(*Mask)).lshr(*ShAmt).isNullValue())
    1743          30 :       return Op0;
    1744             : 
    1745             :     // If all bits in the inverted and shifted mask are clear:
    1746             :     // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
    1747      203228 :     if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
    1748      275236 :         (~(*Mask)).shl(*ShAmt).isNullValue())
    1749          32 :       return Op0;
    1750             :   }
    1751             : 
    1752             :   // A & (-A) = A if A is a power of two or zero.
    1753      441004 :   if (match(Op0, m_Neg(m_Specific(Op1))) ||
    1754      220502 :       match(Op1, m_Neg(m_Specific(Op0)))) {
    1755          10 :     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
    1756          10 :                                Q.DT))
    1757           2 :       return Op0;
    1758           8 :     if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
    1759           8 :                                Q.DT))
    1760           0 :       return Op1;
    1761             :   }
    1762             : 
    1763      110249 :   if (Value *V = simplifyAndOrOfCmps(Op0, Op1, true))
    1764             :     return V;
    1765             : 
    1766             :   // Try some generic simplifications for associative operations.
    1767      219990 :   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
    1768      109995 :                                           MaxRecurse))
    1769             :     return V;
    1770             : 
    1771             :   // And distributes over Or.  Try some generic simplifications based on this.
    1772      217828 :   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
    1773      108914 :                              Q, MaxRecurse))
    1774             :     return V;
    1775             : 
    1776             :   // And distributes over Xor.  Try some generic simplifications based on this.
    1777      216542 :   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
    1778      108271 :                              Q, MaxRecurse))
    1779             :     return V;
    1780             : 
    1781             :   // If the operation is with the result of a select instruction, check whether
    1782             :   // operating on either branch of the select always yields the same value.
    1783      215927 :   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
    1784        1240 :     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
    1785         620 :                                          MaxRecurse))
    1786             :       return V;
    1787             : 
    1788             :   // If the operation is with the result of a phi instruction, check whether
    1789             :   // operating on all incoming values of the phi always yields the same value.
    1790      202936 :   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
    1791       30852 :     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
    1792       15426 :                                       MaxRecurse))
    1793             :       return V;
    1794             : 
    1795             :   return nullptr;
    1796             : }
    1797             : 
    1798       65546 : Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
    1799       65546 :   return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit);
    1800             : }
    1801             : 
    1802             : /// Given operands for an Or, see if we can fold the result.
    1803             : /// If not, this returns null.
    1804      110472 : static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
    1805             :                              unsigned MaxRecurse) {
    1806      110472 :   if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
    1807             :     return C;
    1808             : 
    1809             :   // X | undef -> -1
    1810             :   // X | -1 = -1
    1811             :   // Do not return Op1 because it may contain undef elements if it's a vector.
    1812      413321 :   if (match(Op1, m_Undef()) || match(Op1, m_AllOnes()))
    1813          49 :     return Constant::getAllOnesValue(Op0->getType());
    1814             : 
    1815             :   // X | X = X
    1816             :   // X | 0 = X
    1817      206481 :   if (Op0 == Op1 || match(Op1, m_Zero()))
    1818         515 :     return Op0;
    1819             : 
    1820             :   // A | ~A  =  ~A | A  =  -1
    1821      411027 :   if (match(Op0, m_Not(m_Specific(Op1))) ||
    1822      205467 :       match(Op1, m_Not(m_Specific(Op0))))
    1823        2043 :     return Constant::getAllOnesValue(Op0->getType());
    1824             : 
    1825             :   // (A & ?) | A = A
    1826      201474 :   if (match(Op0, m_c_And(m_Specific(Op1), m_Value())))
    1827             :     return Op1;
    1828             : 
    1829             :   // A | (A & ?) = A
    1830      201382 :   if (match(Op1, m_c_And(m_Specific(Op0), m_Value())))
    1831             :     return Op0;
    1832             : 
    1833             :   // ~(A & ?) | A = -1
    1834      100556 :   if (match(Op0, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
    1835           2 :     return Constant::getAllOnesValue(Op1->getType());
    1836             : 
    1837             :   // A | ~(A & ?) = -1
    1838      201108 :   if (match(Op1, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
    1839           0 :     return Constant::getAllOnesValue(Op0->getType());
    1840             : 
    1841             :   Value *A, *B;
    1842             :   // (A & ~B) | (A ^ B) -> (A ^ B)
    1843             :   // (~B & A) | (A ^ B) -> (A ^ B)
    1844             :   // (A & ~B) | (B ^ A) -> (B ^ A)
    1845             :   // (~B & A) | (B ^ A) -> (B ^ A)
    1846      305022 :   if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
    1847      110632 :       (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
    1848      107270 :        match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
    1849           4 :     return Op1;
    1850             : 
    1851             :   // Commute the 'or' operands.
    1852             :   // (A ^ B) | (A & ~B) -> (A ^ B)
    1853             :   // (A ^ B) | (~B & A) -> (A ^ B)
    1854             :   // (B ^ A) | (A & ~B) -> (B ^ A)
    1855             :   // (B ^ A) | (~B & A) -> (B ^ A)
    1856      302422 :   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
    1857      102864 :       (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
    1858      102090 :        match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
    1859           4 :     return Op0;
    1860             : 
    1861             :   // (A & B) | (~A ^ B) -> (~A ^ B)
    1862             :   // (B & A) | (~A ^ B) -> (~A ^ B)
    1863             :   // (A & B) | (B ^ ~A) -> (B ^ ~A)
    1864             :   // (B & A) | (B ^ ~A) -> (B ^ ~A)
    1865      321192 :   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
    1866      159206 :       (match(Op1, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
    1867      139650 :        match(Op1, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
    1868           4 :     return Op1;
    1869             : 
    1870             :   // (~A ^ B) | (A & B) -> (~A ^ B)
    1871             :   // (~A ^ B) | (B & A) -> (~A ^ B)
    1872             :   // (B ^ ~A) | (A & B) -> (B ^ ~A)
    1873             :   // (B ^ ~A) | (B & A) -> (B ^ ~A)
    1874      311615 :   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
    1875      130507 :       (match(Op0, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
    1876      120516 :        match(Op0, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
    1877           4 :     return Op0;
    1878             : 
    1879      100538 :   if (Value *V = simplifyAndOrOfCmps(Op0, Op1, false))
    1880             :     return V;
    1881             : 
    1882             :   // Try some generic simplifications for associative operations.
    1883      200462 :   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
    1884      100231 :                                           MaxRecurse))
    1885             :     return V;
    1886             : 
    1887             :   // Or distributes over And.  Try some generic simplifications based on this.
    1888      200006 :   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
    1889      100003 :                              MaxRecurse))
    1890             :     return V;
    1891             : 
    1892             :   // If the operation is with the result of a select instruction, check whether
    1893             :   // operating on either branch of the select always yields the same value.
    1894      199780 :   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
    1895         534 :     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
    1896         267 :                                          MaxRecurse))
    1897             :       return V;
    1898             : 
    1899             :   // (A & C1)|(B & C2)
    1900             :   const APInt *C1, *C2;
    1901      314022 :   if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
    1902      114016 :       match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
    1903        7436 :     if (*C1 == ~*C2) {
    1904             :       // (A & C1)|(B & C2)
    1905             :       // If we have: ((V + N) & C1) | (V & C2)
    1906             :       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
    1907             :       // replace with V+N.
    1908             :       Value *N;
    1909         339 :       if (C2->isMask() && // C2 == 0+1+
    1910         335 :           match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
    1911             :         // Add commutes, try both ways.
    1912           4 :         if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
    1913          11 :           return A;
    1914             :       }
    1915             :       // Or commutes, try both ways.
    1916         293 :       if (C1->isMask() &&
    1917         290 :           match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
    1918             :         // Add commutes, try both ways.
    1919           3 :         if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
    1920           3 :           return B;
    1921             :       }
    1922             :     }
    1923             :   }
    1924             : 
    1925             :   // If the operation is with the result of a phi instruction, check whether
    1926             :   // operating on all incoming values of the phi always yields the same value.
    1927      195390 :   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
    1928        9283 :     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
    1929             :       return V;
    1930             : 
    1931             :   return nullptr;
    1932             : }
    1933             : 
    1934       35502 : Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
    1935       35502 :   return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit);
    1936             : }
    1937             : 
    1938             : /// Given operands for a Xor, see if we can fold the result.
    1939             : /// If not, this returns null.
    1940       67852 : static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
    1941             :                               unsigned MaxRecurse) {
    1942       67852 :   if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
    1943             :     return C;
    1944             : 
    1945             :   // A ^ undef -> undef
    1946      129640 :   if (match(Op1, m_Undef()))
    1947             :     return Op1;
    1948             : 
    1949             :   // A ^ 0 = A
    1950       64820 :   if (match(Op1, m_Zero()))
    1951        2122 :     return Op0;
    1952             : 
    1953             :   // A ^ A = 0
    1954       62698 :   if (Op0 == Op1)
    1955          21 :     return Constant::getNullValue(Op0->getType());
    1956             : 
    1957             :   // A ^ ~A  =  ~A ^ A  =  -1
    1958      250708 :   if (match(Op0, m_Not(m_Specific(Op1))) ||
    1959      125354 :       match(Op1, m_Not(m_Specific(Op0))))
    1960           5 :     return Constant::getAllOnesValue(Op0->getType());
    1961             : 
    1962             :   // Try some generic simplifications for associative operations.
    1963      125344 :   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
    1964       62672 :                                           MaxRecurse))
    1965             :     return V;
    1966             : 
    1967             :   // Threading Xor over selects and phi nodes is pointless, so don't bother.
    1968             :   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
    1969             :   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
    1970             :   // only if B and C are equal.  If B and C are equal then (since we assume
    1971             :   // that operands have already been simplified) "select(cond, B, C)" should
    1972             :   // have been simplified to the common value of B and C already.  Analysing
    1973             :   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
    1974             :   // for threading over phi nodes.
    1975             : 
    1976       60633 :   return nullptr;
    1977             : }
    1978             : 
    1979       38792 : Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
    1980       38792 :   return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit);
    1981             : }
    1982             : 
    1983             : 
    1984             : static Type *GetCompareTy(Value *Op) {
    1985     3761582 :   return CmpInst::makeCmpResultType(Op->getType());
    1986             : }
    1987             : 
    1988             : /// Rummage around inside V looking for something equivalent to the comparison
    1989             : /// "LHS Pred RHS". Return such a value if found, otherwise return null.
    1990             : /// Helper function for analyzing max/min idioms.
    1991         353 : static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
    1992             :                                          Value *LHS, Value *RHS) {
    1993             :   SelectInst *SI = dyn_cast<SelectInst>(V);
    1994             :   if (!SI)
    1995             :     return nullptr;
    1996             :   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
    1997             :   if (!Cmp)
    1998             :     return nullptr;
    1999             :   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
    2000         182 :   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
    2001             :     return Cmp;
    2002         170 :   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
    2003         170 :       LHS == CmpRHS && RHS == CmpLHS)
    2004             :     return Cmp;
    2005             :   return nullptr;
    2006             : }
    2007             : 
    2008             : // A significant optimization not implemented here is assuming that alloca
    2009             : // addresses are not equal to incoming argument values. They don't *alias*,
    2010             : // as we say, but that doesn't mean they aren't equal, so we take a
    2011             : // conservative approach.
    2012             : //
    2013             : // This is inspired in part by C++11 5.10p1:
    2014             : //   "Two pointers of the same type compare equal if and only if they are both
    2015             : //    null, both point to the same function, or both represent the same
    2016             : //    address."
    2017             : //
    2018             : // This is pretty permissive.
    2019             : //
    2020             : // It's also partly due to C11 6.5.9p6:
    2021             : //   "Two pointers compare equal if and only if both are null pointers, both are
    2022             : //    pointers to the same object (including a pointer to an object and a
    2023             : //    subobject at its beginning) or function, both are pointers to one past the
    2024             : //    last element of the same array object, or one is a pointer to one past the
    2025             : //    end of one array object and the other is a pointer to the start of a
    2026             : //    different array object that happens to immediately follow the first array
    2027             : //    object in the address space.)
    2028             : //
    2029             : // C11's version is more restrictive, however there's no reason why an argument
    2030             : // couldn't be a one-past-the-end value for a stack object in the caller and be
    2031             : // equal to the beginning of a stack object in the callee.
    2032             : //
    2033             : // If the C and C++ standards are ever made sufficiently restrictive in this
    2034             : // area, it may be possible to update LLVM's semantics accordingly and reinstate
    2035             : // this optimization.
    2036             : static Constant *
    2037      229565 : computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
    2038             :                    const DominatorTree *DT, CmpInst::Predicate Pred,
    2039             :                    AssumptionCache *AC, const Instruction *CxtI,
    2040             :                    Value *LHS, Value *RHS) {
    2041             :   // First, skip past any trivial no-ops.
    2042      459130 :   LHS = LHS->stripPointerCasts();
    2043      459130 :   RHS = RHS->stripPointerCasts();
    2044             : 
    2045             :   // A non-null pointer is not equal to a null pointer.
    2046      239147 :   if (llvm::isKnownNonZero(LHS, DL) && isa<ConstantPointerNull>(RHS) &&
    2047         629 :       (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
    2048         629 :     return ConstantInt::get(GetCompareTy(LHS),
    2049        1258 :                             !CmpInst::isTrueWhenEqual(Pred));
    2050             : 
    2051             :   // We can only fold certain predicates on pointer comparisons.
    2052      228936 :   switch (Pred) {
    2053             :   default:
    2054             :     return nullptr;
    2055             : 
    2056             :     // Equality comaprisons are easy to fold.
    2057             :   case CmpInst::ICMP_EQ:
    2058             :   case CmpInst::ICMP_NE:
    2059             :     break;
    2060             : 
    2061             :     // We can only handle unsigned relational comparisons because 'inbounds' on
    2062             :     // a GEP only protects against unsigned wrapping.
    2063        4776 :   case CmpInst::ICMP_UGT:
    2064             :   case CmpInst::ICMP_UGE:
    2065             :   case CmpInst::ICMP_ULT:
    2066             :   case CmpInst::ICMP_ULE:
    2067             :     // However, we have to switch them to their signed variants to handle
    2068             :     // negative indices from the base pointer.
    2069        4776 :     Pred = ICmpInst::getSignedPredicate(Pred);
    2070             :     break;
    2071             :   }
    2072             : 
    2073             :   // Strip off any constant offsets so that we can reason about them.
    2074             :   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
    2075             :   // here and compare base addresses like AliasAnalysis does, however there are
    2076             :   // numerous hazards. AliasAnalysis and its utilities rely on special rules
    2077             :   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
    2078             :   // doesn't need to guarantee pointer inequality when it says NoAlias.
    2079      228922 :   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
    2080      228922 :   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
    2081             : 
    2082             :   // If LHS and RHS are related via constant offsets to the same base
    2083             :   // value, we can replace it with an icmp which just compares the offsets.
    2084      228922 :   if (LHS == RHS)
    2085         128 :     return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
    2086             : 
    2087             :   // Various optimizations for (in)equality comparisons.
    2088      228794 :   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
    2089             :     // Different non-empty allocations that exist at the same time have
    2090             :     // different addresses (if the program can tell). Global variables always
    2091             :     // exist, so they always exist during the lifetime of each other and all
    2092             :     // allocas. Two different allocas usually have different addresses...
    2093             :     //
    2094             :     // However, if there's an @llvm.stackrestore dynamically in between two
    2095             :     // allocas, they may have the same address. It's tempting to reduce the
    2096             :     // scope of the problem by only looking at *static* allocas here. That would
    2097             :     // cover the majority of allocas while significantly reducing the likelihood
    2098             :     // of having an @llvm.stackrestore pop up in the middle. However, it's not
    2099             :     // actually impossible for an @llvm.stackrestore to pop up in the middle of
    2100             :     // an entry block. Also, if we have a block that's not attached to a
    2101             :     // function, we can't tell if it's "static" under the current definition.
    2102             :     // Theoretically, this problem could be fixed by creating a new kind of
    2103             :     // instruction kind specifically for static allocas. Such a new instruction
    2104             :     // could be required to be at the top of the entry block, thus preventing it
    2105             :     // from being subject to a @llvm.stackrestore. Instcombine could even
    2106             :     // convert regular allocas into these special allocas. It'd be nifty.
    2107             :     // However, until then, this problem remains open.
    2108             :     //
    2109             :     // So, we'll assume that two non-empty allocas have different addresses
    2110             :     // for now.
    2111             :     //
    2112             :     // With all that, if the offsets are within the bounds of their allocations
    2113             :     // (and not one-past-the-end! so we can't use inbounds!), and their
    2114             :     // allocations aren't the same, the pointers are not equal.
    2115             :     //
    2116             :     // Note that it's not necessary to check for LHS being a global variable
    2117             :     // address, due to canonicalization and constant folding.
    2118             :     if (isa<AllocaInst>(LHS) &&
    2119          65 :         (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
    2120             :       ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
    2121             :       ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
    2122             :       uint64_t LHSSize, RHSSize;
    2123          16 :       ObjectSizeOpts Opts;
    2124          16 :       Opts.NullIsUnknownSize =
    2125          32 :           NullPointerIsDefined(cast<AllocaInst>(LHS)->getFunction());
    2126          32 :       if (LHSOffsetCI && RHSOffsetCI &&
    2127          32 :           getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
    2128          16 :           getObjectSize(RHS, RHSSize, DL, TLI, Opts)) {
    2129             :         const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
    2130             :         const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
    2131          32 :         if (!LHSOffsetValue.isNegative() &&
    2132          32 :             !RHSOffsetValue.isNegative() &&
    2133          48 :             LHSOffsetValue.ult(LHSSize) &&
    2134          16 :             RHSOffsetValue.ult(RHSSize)) {
    2135          16 :           return ConstantInt::get(GetCompareTy(LHS),
    2136          48 :                                   !CmpInst::isTrueWhenEqual(Pred));
    2137             :         }
    2138             :       }
    2139             : 
    2140             :       // Repeat the above check but this time without depending on DataLayout
    2141             :       // or being able to compute a precise size.
    2142           0 :       if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
    2143           0 :           !cast<PointerType>(RHS->getType())->isEmptyTy() &&
    2144           0 :           LHSOffset->isNullValue() &&
    2145           0 :           RHSOffset->isNullValue())
    2146           0 :         return ConstantInt::get(GetCompareTy(LHS),
    2147           0 :                                 !CmpInst::isTrueWhenEqual(Pred));
    2148             :     }
    2149             : 
    2150             :     // Even if an non-inbounds GEP occurs along the path we can still optimize
    2151             :     // equality comparisons concerning the result. We avoid walking the whole
    2152             :     // chain again by starting where the last calls to
    2153             :     // stripAndComputeConstantOffsets left off and accumulate the offsets.
    2154      224011 :     Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
    2155      224011 :     Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
    2156      224011 :     if (LHS == RHS)
    2157          43 :       return ConstantExpr::getICmp(Pred,
    2158             :                                    ConstantExpr::getAdd(LHSOffset, LHSNoBound),
    2159          43 :                                    ConstantExpr::getAdd(RHSOffset, RHSNoBound));
    2160             : 
    2161             :     // If one side of the equality comparison must come from a noalias call
    2162             :     // (meaning a system memory allocation function), and the other side must
    2163             :     // come from a pointer that cannot overlap with dynamically-allocated
    2164             :     // memory within the lifetime of the current function (allocas, byval
    2165             :     // arguments, globals), then determine the comparison result here.
    2166             :     SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
    2167      223968 :     GetUnderlyingObjects(LHS, LHSUObjs, DL);
    2168      223968 :     GetUnderlyingObjects(RHS, RHSUObjs, DL);
    2169             : 
    2170             :     // Is the set of underlying objects all noalias calls?
    2171             :     auto IsNAC = [](ArrayRef<Value *> Objects) {
    2172             :       return all_of(Objects, isNoAliasCall);
    2173             :     };
    2174             : 
    2175             :     // Is the set of underlying objects all things which must be disjoint from
    2176             :     // noalias calls. For allocas, we consider only static ones (dynamic
    2177             :     // allocas might be transformed into calls to malloc not simultaneously
    2178             :     // live with the compared-to allocation). For globals, we exclude symbols
    2179             :     // that might be resolve lazily to symbols in another dynamically-loaded
    2180             :     // library (and, thus, could be malloc'ed by the implementation).
    2181             :     auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
    2182         553 :       return all_of(Objects, [](Value *V) {
    2183             :         if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
    2184           9 :           return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
    2185             :         if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
    2186           7 :           return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
    2187          11 :                   GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
    2188             :                  !GV->isThreadLocal();
    2189             :         if (const Argument *A = dyn_cast<Argument>(V))
    2190           2 :           return A->hasByValAttr();
    2191             :         return false;
    2192             :       });
    2193             :     };
    2194             : 
    2195      448302 :     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
    2196         178 :         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
    2197           8 :         return ConstantInt::get(GetCompareTy(LHS),
    2198          16 :                                 !CmpInst::isTrueWhenEqual(Pred));
    2199             : 
    2200             :     // Fold comparisons for non-escaping pointer even if the allocation call
    2201             :     // cannot be elided. We cannot fold malloc comparison to null. Also, the
    2202             :     // dynamic allocation call could be either of the operands.
    2203             :     Value *MI = nullptr;
    2204      224040 :     if (isAllocLikeFn(LHS, TLI) &&
    2205          80 :         llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
    2206           1 :       MI = LHS;
    2207      224021 :     else if (isAllocLikeFn(RHS, TLI) &&
    2208          62 :              llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
    2209           8 :       MI = RHS;
    2210             :     // FIXME: We should also fold the compare when the pointer escapes, but the
    2211             :     // compare dominates the pointer escape
    2212           9 :     if (MI && !PointerMayBeCaptured(MI, true, true))
    2213           2 :       return ConstantInt::get(GetCompareTy(LHS),
    2214           4 :                               CmpInst::isFalseWhenEqual(Pred));
    2215             :   }
    2216             : 
    2217             :   // Otherwise, fail.
    2218             :   return nullptr;
    2219             : }
    2220             : 
    2221             : /// Fold an icmp when its operands have i1 scalar type.
    2222      688307 : static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
    2223             :                                   Value *RHS, const SimplifyQuery &Q) {
    2224             :   Type *ITy = GetCompareTy(LHS); // The return type.
    2225      688307 :   Type *OpTy = LHS->getType();   // The operand type.
    2226      688307 :   if (!OpTy->isIntOrIntVectorTy(1))
    2227             :     return nullptr;
    2228             : 
    2229             :   // A boolean compared to true/false can be simplified in 14 out of the 20
    2230             :   // (10 predicates * 2 constants) possible combinations. Cases not handled here
    2231             :   // require a 'not' of the LHS, so those must be transformed in InstCombine.
    2232        4376 :   if (match(RHS, m_Zero())) {
    2233             :     switch (Pred) {
    2234             :     case CmpInst::ICMP_NE:  // X !=  0 -> X
    2235             :     case CmpInst::ICMP_UGT: // X >u  0 -> X
    2236             :     case CmpInst::ICMP_SLT: // X <s  0 -> X
    2237             :       return LHS;
    2238             : 
    2239             :     case CmpInst::ICMP_ULT: // X <u  0 -> false
    2240             :     case CmpInst::ICMP_SGT: // X >s  0 -> false
    2241             :       return getFalse(ITy);
    2242             : 
    2243             :     case CmpInst::ICMP_UGE: // X >=u 0 -> true
    2244             :     case CmpInst::ICMP_SLE: // X <=s 0 -> true
    2245             :       return getTrue(ITy);
    2246             : 
    2247             :     default: break;
    2248             :     }
    2249         632 :   } else if (match(RHS, m_One())) {
    2250             :     switch (Pred) {
    2251             :     case CmpInst::ICMP_EQ:  // X ==   1 -> X
    2252             :     case CmpInst::ICMP_UGE: // X >=u  1 -> X
    2253             :     case CmpInst::ICMP_SLE: // X <=s -1 -> X
    2254             :       return LHS;
    2255             : 
    2256             :     case CmpInst::ICMP_UGT: // X >u   1 -> false
    2257             :     case CmpInst::ICMP_SLT: // X <s  -1 -> false
    2258             :       return getFalse(ITy);
    2259             : 
    2260             :     case CmpInst::ICMP_ULE: // X <=u  1 -> true
    2261             :     case CmpInst::ICMP_SGE: // X >=s -1 -> true
    2262             :       return getTrue(ITy);
    2263             : 
    2264             :     default: break;
    2265             :     }
    2266             :   }
    2267             : 
    2268         697 :   switch (Pred) {
    2269             :   default:
    2270             :     break;
    2271          21 :   case ICmpInst::ICMP_UGE:
    2272          42 :     if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
    2273             :       return getTrue(ITy);
    2274             :     break;
    2275          23 :   case ICmpInst::ICMP_SGE:
    2276             :     /// For signed comparison, the values for an i1 are 0 and -1
    2277             :     /// respectively. This maps into a truth table of:
    2278             :     /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
    2279             :     ///  0  |  0  |  1 (0 >= 0)   |  1
    2280             :     ///  0  |  1  |  1 (0 >= -1)  |  1
    2281             :     ///  1  |  0  |  0 (-1 >= 0)  |  0
    2282             :     ///  1  |  1  |  1 (-1 >= -1) |  1
    2283          46 :     if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
    2284             :       return getTrue(ITy);
    2285             :     break;
    2286          37 :   case ICmpInst::ICMP_ULE:
    2287          74 :     if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
    2288             :       return getTrue(ITy);
    2289             :     break;
    2290             :   }
    2291             : 
    2292             :   return nullptr;
    2293             : }
    2294             : 
    2295             : /// Try hard to fold icmp with zero RHS because this is a common case.
    2296      684618 : static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
    2297             :                                    Value *RHS, const SimplifyQuery &Q) {
    2298      684618 :   if (!match(RHS, m_Zero()))
    2299             :     return nullptr;
    2300             : 
    2301             :   Type *ITy = GetCompareTy(LHS); // The return type.
    2302      341875 :   switch (Pred) {
    2303           0 :   default:
    2304           0 :     llvm_unreachable("Unknown ICmp predicate!");
    2305             :   case ICmpInst::ICMP_ULT:
    2306         109 :     return getFalse(ITy);
    2307             :   case ICmpInst::ICMP_UGE:
    2308         205 :     return getTrue(ITy);
    2309      143186 :   case ICmpInst::ICMP_EQ:
    2310             :   case ICmpInst::ICMP_ULE:
    2311      143186 :     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
    2312        1086 :       return getFalse(ITy);
    2313             :     break;
    2314      187550 :   case ICmpInst::ICMP_NE:
    2315             :   case ICmpInst::ICMP_UGT:
    2316      187550 :     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
    2317        1758 :       return getTrue(ITy);
    2318             :     break;
    2319        3109 :   case ICmpInst::ICMP_SLT: {
    2320        3109 :     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
    2321        3109 :     if (LHSKnown.isNegative())
    2322          22 :       return getTrue(ITy);
    2323        3106 :     if (LHSKnown.isNonNegative())
    2324          16 :       return getFalse(ITy);
    2325        3090 :     break;
    2326             :   }
    2327          59 :   case ICmpInst::ICMP_SLE: {
    2328          59 :     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
    2329          59 :     if (LHSKnown.isNegative())
    2330           0 :       return getTrue(ITy);
    2331          62 :     if (LHSKnown.isNonNegative() &&
    2332           3 :         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
    2333           0 :       return getFalse(ITy);
    2334          59 :     break;
    2335             :   }
    2336         281 :   case ICmpInst::ICMP_SGE: {
    2337         281 :     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
    2338         281 :     if (LHSKnown.isNegative())
    2339           3 :       return getFalse(ITy);
    2340         281 :     if (LHSKnown.isNonNegative())
    2341           3 :       return getTrue(ITy);
    2342         278 :     break;
    2343             :   }
    2344        7376 :   case ICmpInst::ICMP_SGT: {
    2345        7376 :     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
    2346        7376 :     if (LHSKnown.isNegative())
    2347          16 :       return getFalse(ITy);
    2348        7534 :     if (LHSKnown.isNonNegative() &&
    2349         159 :         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
    2350          14 :       return getTrue(ITy);
    2351        7361 :     break;
    2352             :   }
    2353             :   }
    2354             : 
    2355             :   return nullptr;
    2356             : }
    2357             : 
    2358             : /// Many binary operators with a constant operand have an easy-to-compute
    2359             : /// range of outputs. This can be used to fold a comparison to always true or
    2360             : /// always false.
    2361       93235 : static void setLimitsForBinOp(BinaryOperator &BO, APInt &Lower, APInt &Upper) {
    2362       93235 :   unsigned Width = Lower.getBitWidth();
    2363             :   const APInt *C;
    2364       93235 :   switch (BO.getOpcode()) {
    2365             :   case Instruction::Add:
    2366      123041 :     if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
    2367             :       // FIXME: If we have both nuw and nsw, we should reduce the range further.
    2368       37661 :       if (BO.hasNoUnsignedWrap()) {
    2369             :         // 'add nuw x, C' produces [C, UINT_MAX].
    2370       17074 :         Lower = *C;
    2371       20587 :       } else if (BO.hasNoSignedWrap()) {
    2372       10936 :         if (C->isNegative()) {
    2373             :           // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
    2374        8452 :           Lower = APInt::getSignedMinValue(Width);
    2375       12678 :           Upper = APInt::getSignedMaxValue(Width) + *C + 1;
    2376             :         } else {
    2377             :           // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
    2378        2484 :           Lower = APInt::getSignedMinValue(Width) + *C;
    2379        2484 :           Upper = APInt::getSignedMaxValue(Width) + 1;
    2380             :         }
    2381             :       }
    2382             :     }
    2383             :     break;
    2384             : 
    2385             :   case Instruction::And:
    2386       40688 :     if (match(BO.getOperand(1), m_APInt(C)))
    2387             :       // 'and x, C' produces [0, C].
    2388       25112 :       Upper = *C + 1;
    2389             :     break;
    2390             : 
    2391             :   case Instruction::Or:
    2392        1532 :     if (match(BO.getOperand(1), m_APInt(C)))
    2393             :       // 'or x, C' produces [C, UINT_MAX].
    2394         450 :       Lower = *C;
    2395             :     break;
    2396             : 
    2397             :   case Instruction::AShr:
    2398        6893 :     if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
    2399             :       // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
    2400        6795 :       Lower = APInt::getSignedMinValue(Width).ashr(*C);
    2401        6795 :       Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
    2402          98 :     } else if (match(BO.getOperand(0), m_APInt(C))) {
    2403          36 :       unsigned ShiftAmount = Width - 1;
    2404          72 :       if (!C->isNullValue() && BO.isExact())
    2405          16 :         ShiftAmount = C->countTrailingZeros();
    2406          72 :       if (C->isNegative()) {
    2407             :         // 'ashr C, x' produces [C, C >> (Width-1)]
    2408          35 :         Lower = *C;
    2409          70 :         Upper = C->ashr(ShiftAmount) + 1;
    2410             :       } else {
    2411             :         // 'ashr C, x' produces [C >> (Width-1), C]
    2412           2 :         Lower = C->ashr(ShiftAmount);
    2413           2 :         Upper = *C + 1;
    2414             :       }
    2415             :     }
    2416             :     break;
    2417             : 
    2418             :   case Instruction::LShr:
    2419        5750 :     if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
    2420             :       // 'lshr x, C' produces [0, UINT_MAX >> C].
    2421        5538 :       Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
    2422         212 :     } else if (match(BO.getOperand(0), m_APInt(C))) {
    2423             :       // 'lshr C, x' produces [C >> (Width-1), C].
    2424          97 :       unsigned ShiftAmount = Width - 1;
    2425         194 :       if (!C->isNullValue() && BO.isExact())
    2426          16 :         ShiftAmount = C->countTrailingZeros();
    2427         194 :       Lower = C->lshr(ShiftAmount);
    2428         194 :       Upper = *C + 1;
    2429             :     }
    2430             :     break;
    2431             : 
    2432             :   case Instruction::Shl:
    2433        4396 :     if (match(BO.getOperand(0), m_APInt(C))) {
    2434          52 :       if (BO.hasNoUnsignedWrap()) {
    2435             :         // 'shl nuw C, x' produces [C, C << CLZ(C)]
    2436           3 :         Lower = *C;
    2437           6 :         Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
    2438          49 :       } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
    2439          16 :         if (C->isNegative()) {
    2440             :           // 'shl nsw C, x' produces [C << CLO(C)-1, C]
    2441           6 :           unsigned ShiftAmount = C->countLeadingOnes() - 1;
    2442          12 :           Lower = C->shl(ShiftAmount);
    2443          12 :           Upper = *C + 1;
    2444             :         } else {
    2445             :           // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
    2446           2 :           unsigned ShiftAmount = C->countLeadingZeros() - 1;
    2447           2 :           Lower = *C;
    2448           4 :           Upper = C->shl(ShiftAmount) + 1;
    2449             :         }
    2450             :       }
    2451             :     }
    2452             :     break;
    2453             : 
    2454             :   case Instruction::SDiv:
    2455        1776 :     if (match(BO.getOperand(1), m_APInt(C))) {
    2456         885 :       APInt IntMin = APInt::getSignedMinValue(Width);
    2457         885 :       APInt IntMax = APInt::getSignedMaxValue(Width);
    2458        1770 :       if (C->isAllOnesValue()) {
    2459             :         // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
    2460             :         //    where C != -1 and C != 0 and C != 1
    2461           2 :         Lower = IntMin + 1;
    2462           2 :         Upper = IntMax + 1;
    2463         883 :       } else if (C->countLeadingZeros() < Width - 1) {
    2464             :         // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
    2465             :         //    where C != -1 and C != 0 and C != 1
    2466        1766 :         Lower = IntMin.sdiv(*C);
    2467        1766 :         Upper = IntMax.sdiv(*C);
    2468         883 :         if (Lower.sgt(Upper))
    2469             :           std::swap(Lower, Upper);
    2470         883 :         Upper = Upper + 1;
    2471             :         assert(Upper != Lower && "Upper part of range has wrapped!");
    2472             :       }
    2473           6 :     } else if (match(BO.getOperand(0), m_APInt(C))) {
    2474           3 :       if (C->isMinSignedValue()) {
    2475             :         // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
    2476           1 :         Lower = *C;
    2477           2 :         Upper = Lower.lshr(1) + 1;
    2478             :       } else {
    2479             :         // 'sdiv C, x' produces [-|C|, |C|].
    2480           4 :         Upper = C->abs() + 1;
    2481           4 :         Lower = (-Upper) + 1;
    2482             :       }
    2483             :     }
    2484             :     break;
    2485             : 
    2486             :   case Instruction::UDiv:
    2487        3866 :     if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
    2488             :       // 'udiv x, C' produces [0, UINT_MAX / C].
    2489         228 :       Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
    2490        3562 :     } else if (match(BO.getOperand(0), m_APInt(C))) {
    2491             :       // 'udiv C, x' produces [0, C].
    2492        3242 :       Upper = *C + 1;
    2493             :     }
    2494             :     break;
    2495             : 
    2496             :   case Instruction::SRem:
    2497         400 :     if (match(BO.getOperand(1), m_APInt(C))) {
    2498             :       // 'srem x, C' produces (-|C|, |C|).
    2499         324 :       Upper = C->abs();
    2500         324 :       Lower = (-Upper) + 1;
    2501             :     }
    2502             :     break;
    2503             : 
    2504             :   case Instruction::URem:
    2505        2232 :     if (match(BO.getOperand(1), m_APInt(C)))
    2506             :       // 'urem x, C' produces [0, C).
    2507         283 :       Upper = *C;
    2508             :     break;
    2509             : 
    2510             :   default:
    2511             :     break;
    2512             :   }
    2513       93235 : }
    2514             : 
    2515      681423 : static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
    2516             :                                        Value *RHS) {
    2517             :   Type *ITy = GetCompareTy(RHS); // The return type.
    2518             : 
    2519             :   Value *X;
    2520             :   // Sign-bit checks can be optimized to true/false after unsigned
    2521             :   // floating-point casts:
    2522             :   // icmp slt (bitcast (uitofp X)),  0 --> false
    2523             :   // icmp sgt (bitcast (uitofp X)), -1 --> true
    2524     1362846 :   if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
    2525          45 :     if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
    2526           9 :       return ConstantInt::getFalse(ITy);
    2527          36 :     if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
    2528           9 :       return ConstantInt::getTrue(ITy);
    2529             :   }
    2530             : 
    2531             :   const APInt *C;
    2532     1362810 :   if (!match(RHS, m_APInt(C)))
    2533             :     return nullptr;
    2534             : 
    2535             :   // Rule out tautological comparisons (eg., ult 0 or uge 0).
    2536      657226 :   ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
    2537      328613 :   if (RHS_CR.isEmptySet())
    2538         376 :     return ConstantInt::getFalse(ITy);
    2539      328237 :   if (RHS_CR.isFullSet())
    2540           5 :     return ConstantInt::getTrue(ITy);
    2541             : 
    2542             :   // Find the range of possible values for binary operators.
    2543      328232 :   unsigned Width = C->getBitWidth();
    2544             :   APInt Lower = APInt(Width, 0);
    2545             :   APInt Upper = APInt(Width, 0);
    2546             :   if (auto *BO = dyn_cast<BinaryOperator>(LHS))
    2547       93235 :     setLimitsForBinOp(*BO, Lower, Upper);
    2548             : 
    2549             :   ConstantRange LHS_CR =
    2550     1641160 :       Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
    2551             : 
    2552             :   if (auto *I = dyn_cast<Instruction>(LHS))
    2553      239661 :     if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
    2554       40962 :       LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
    2555             : 
    2556      328232 :   if (!LHS_CR.isFullSet()) {
    2557       83793 :     if (RHS_CR.contains(LHS_CR))
    2558         287 :       return ConstantInt::getTrue(ITy);
    2559       83506 :     if (RHS_CR.inverse().contains(LHS_CR))
    2560         410 :       return ConstantInt::getFalse(ITy);
    2561             :   }
    2562             : 
    2563             :   return nullptr;
    2564             : }
    2565             : 
    2566             : /// TODO: A large part of this logic is duplicated in InstCombine's
    2567             : /// foldICmpBinOp(). We should be able to share that and avoid the code
    2568             : /// duplication.
    2569      676016 : static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
    2570             :                                     Value *RHS, const SimplifyQuery &Q,
    2571             :                                     unsigned MaxRecurse) {
    2572             :   Type *ITy = GetCompareTy(LHS); // The return type.
    2573             : 
    2574             :   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
    2575             :   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
    2576      676016 :   if (MaxRecurse && (LBO || RBO)) {
    2577             :     // Analyze the case when either LHS or RHS is an add instruction.
    2578             :     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
    2579             :     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
    2580             :     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
    2581      259544 :     if (LBO && LBO->getOpcode() == Instruction::Add) {
    2582             :       A = LBO->getOperand(0);
    2583             :       B = LBO->getOperand(1);
    2584             :       NoLHSWrapProblem =
    2585       39898 :           ICmpInst::isEquality(Pred) ||
    2586      113788 :           (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
    2587       32046 :           (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
    2588             :     }
    2589      157477 :     if (RBO && RBO->getOpcode() == Instruction::Add) {
    2590             :       C = RBO->getOperand(0);
    2591             :       D = RBO->getOperand(1);
    2592             :       NoRHSWrapProblem =
    2593        2472 :           ICmpInst::isEquality(Pred) ||
    2594       12839 :           (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
    2595        2184 :           (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
    2596             :     }
    2597             : 
    2598             :     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
    2599      136109 :     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
    2600        3252 :       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
    2601        1084 :                                       Constant::getNullValue(RHS->getType()), Q,
    2602        1084 :                                       MaxRecurse - 1))
    2603             :         return V;
    2604             : 
    2605             :     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
    2606      136104 :     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
    2607           2 :       if (Value *V =
    2608           2 :               SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
    2609           2 :                                C == LHS ? D : C, Q, MaxRecurse - 1))
    2610             :         return V;
    2611             : 
    2612             :     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
    2613      136102 :     if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
    2614             :         NoRHSWrapProblem) {
    2615             :       // Determine Y and Z in the form icmp (X+Y), (X+Z).
    2616             :       Value *Y, *Z;
    2617          14 :       if (A == C) {
    2618             :         // C + B == C + D  ->  B == D
    2619             :         Y = B;
    2620             :         Z = D;
    2621          10 :       } else if (A == D) {
    2622             :         // D + B == C + D  ->  B == C
    2623             :         Y = B;
    2624             :         Z = C;
    2625           8 :       } else if (B == C) {
    2626             :         // A + C == C + D  ->  A == D
    2627             :         Y = A;
    2628             :         Z = D;
    2629             :       } else {
    2630             :         assert(B == D);
    2631             :         // A + D == C + D  ->  A == C
    2632             :         Y = A;
    2633             :         Z = C;
    2634             :       }
    2635          14 :       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
    2636             :         return V;
    2637             :     }
    2638             :   }
    2639             : 
    2640             :   {
    2641      676003 :     Value *Y = nullptr;
    2642             :     // icmp pred (or X, Y), X
    2643      800235 :     if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
    2644         968 :       if (Pred == ICmpInst::ICMP_ULT)
    2645           1 :         return getFalse(ITy);
    2646         967 :       if (Pred == ICmpInst::ICMP_UGE)
    2647           1 :         return getTrue(ITy);
    2648             : 
    2649         966 :       if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
    2650         200 :         KnownBits RHSKnown = computeKnownBits(RHS, 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 (RHSKnown.isNonNegative() && YKnown.isNegative())
    2653          14 :           return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
    2654         202 :         if (RHSKnown.isNegative() || YKnown.isNonNegative())
    2655          10 :           return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
    2656             :       }
    2657             :     }
    2658             :     // icmp pred X, (or X, Y)
    2659      697344 :     if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
    2660         108 :       if (Pred == ICmpInst::ICMP_ULE)
    2661           1 :         return getTrue(ITy);
    2662         107 :       if (Pred == ICmpInst::ICMP_UGT)
    2663           1 :         return getFalse(ITy);
    2664             : 
    2665         106 :       if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
    2666         200 :         KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
    2667         200 :         KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
    2668         152 :         if (LHSKnown.isNonNegative() && YKnown.isNegative())
    2669          14 :           return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
    2670         202 :         if (LHSKnown.isNegative() || YKnown.isNonNegative())
    2671          10 :           return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
    2672             :       }
    2673             :     }
    2674             :   }
    2675             : 
    2676             :   // icmp pred (and X, Y), X
    2677      924391 :   if (LBO && match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
    2678        2329 :     if (Pred == ICmpInst::ICMP_UGT)
    2679           1 :       return getFalse(ITy);
    2680        2328 :     if (Pred == ICmpInst::ICMP_ULE)
    2681           1 :       return getTrue(ITy);
    2682             :   }
    2683             :   // icmp pred X, (and X, Y)
    2684      697314 :   if (RBO && match(RBO, m_c_And(m_Value(), m_Specific(LHS)))) {
    2685         348 :     if (Pred == ICmpInst::ICMP_UGE)
    2686           1 :       return getTrue(ITy);
    2687         347 :     if (Pred == ICmpInst::ICMP_ULT)
    2688           1 :       return getFalse(ITy);
    2689             :   }
    2690             : 
    2691             :   // 0 - (zext X) pred C
    2692     1208627 :   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
    2693             :     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
    2694           6 :       if (RHSC->getValue().isStrictlyPositive()) {
    2695           4 :         if (Pred == ICmpInst::ICMP_SLT)
    2696           1 :           return ConstantInt::getTrue(RHSC->getContext());
    2697           3 :         if (Pred == ICmpInst::ICMP_SGE)
    2698           1 :           return ConstantInt::getFalse(RHSC->getContext());
    2699           2 :         if (Pred == ICmpInst::ICMP_EQ)
    2700           1 :           return ConstantInt::getFalse(RHSC->getContext());
    2701           1 :         if (Pred == ICmpInst::ICMP_NE)
    2702           1 :           return ConstantInt::getTrue(RHSC->getContext());
    2703             :       }
    2704           2 :       if (RHSC->getValue().isNonNegative()) {
    2705           2 :         if (Pred == ICmpInst::ICMP_SLE)
    2706           1 :           return ConstantInt::getTrue(RHSC->getContext());
    2707           1 :         if (Pred == ICmpInst::ICMP_SGT)
    2708           1 :           return ConstantInt::getFalse(RHSC->getContext());
    2709             :       }
    2710             :     }
    2711             :   }
    2712             : 
    2713             :   // icmp pred (urem X, Y), Y
    2714      800165 :   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
    2715          32 :     switch (Pred) {
    2716             :     default:
    2717             :       break;
    2718           1 :     case ICmpInst::ICMP_SGT:
    2719             :     case ICmpInst::ICMP_SGE: {
    2720           1 :       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
    2721           1 :       if (!Known.isNonNegative())
    2722             :         break;
    2723             :       LLVM_FALLTHROUGH;
    2724             :     }
    2725             :     case ICmpInst::ICMP_EQ:
    2726             :     case ICmpInst::ICMP_UGT:
    2727             :     case ICmpInst::ICMP_UGE:
    2728          10 :       return getFalse(ITy);
    2729           1 :     case ICmpInst::ICMP_SLT:
    2730             :     case ICmpInst::ICMP_SLE: {
    2731           1 :       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
    2732           1 :       if (!Known.isNonNegative())
    2733             :         break;
    2734             :       LLVM_FALLTHROUGH;
    2735             :     }
    2736             :     case ICmpInst::ICMP_NE:
    2737             :     case ICmpInst::ICMP_ULT:
    2738             :     case ICmpInst::ICMP_ULE:
    2739          20 :       return getTrue(ITy);
    2740             :     }
    2741             :   }
    2742             : 
    2743             :   // icmp pred X, (urem Y, X)
    2744      697274 :   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
    2745         181 :     switch (Pred) {
    2746             :     default:
    2747             :       break;
    2748           0 :     case ICmpInst::ICMP_SGT:
    2749             :     case ICmpInst::ICMP_SGE: {
    2750           0 :       KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
    2751           0 :       if (!Known.isNonNegative())
    2752             :         break;
    2753             :       LLVM_FALLTHROUGH;
    2754             :     }
    2755             :     case ICmpInst::ICMP_NE:
    2756             :     case ICmpInst::ICMP_UGT:
    2757             :     case ICmpInst::ICMP_UGE:
    2758           1 :       return getTrue(ITy);
    2759           0 :     case ICmpInst::ICMP_SLT:
    2760             :     case ICmpInst::ICMP_SLE: {
    2761           0 :       KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
    2762           0 :       if (!Known.isNonNegative())
    2763             :         break;
    2764             :       LLVM_FALLTHROUGH;
    2765             :     }
    2766             :     case ICmpInst::ICMP_EQ:
    2767             :     case ICmpInst::ICMP_ULT:
    2768             :     case ICmpInst::ICMP_ULE:
    2769         180 :       return getFalse(ITy);
    2770             :     }
    2771             :   }
    2772             : 
    2773             :   // x >> y <=u x
    2774             :   // x udiv y <=u x.
    2775     1599842 :   if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
    2776      799918 :               match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
    2777             :     // icmp pred (X op Y), X
    2778          10 :     if (Pred == ICmpInst::ICMP_UGT)
    2779           2 :       return getFalse(ITy);
    2780           8 :     if (Pred == ICmpInst::ICMP_ULE)
    2781           2 :       return getTrue(ITy);
    2782             :   }
    2783             : 
    2784             :   // x >=u x >> y
    2785             :   // x >=u x udiv y.
    2786     1393814 :   if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
    2787      696906 :               match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
    2788             :     // icmp pred X, (X op Y)
    2789           4 :     if (Pred == ICmpInst::ICMP_ULT)
    2790           2 :       return getFalse(ITy);
    2791           2 :     if (Pred == ICmpInst::ICMP_UGE)
    2792           2 :       return getTrue(ITy);
    2793             :   }
    2794             : 
    2795             :   // handle:
    2796             :   //   CI2 << X == CI
    2797             :   //   CI2 << X != CI
    2798             :   //
    2799             :   //   where CI2 is a power of 2 and CI isn't
    2800             :   if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
    2801             :     const APInt *CI2Val, *CIVal = &CI->getValue();
    2802      412701 :     if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
    2803          28 :         CI2Val->isPowerOf2()) {
    2804          22 :       if (!CIVal->isPowerOf2()) {
    2805             :         // CI2 << X can equal zero in some circumstances,
    2806             :         // this simplification is unsafe if CI is zero.
    2807             :         //
    2808             :         // We know it is safe if:
    2809             :         // - The shift is nsw, we can't shift out the one bit.
    2810             :         // - The shift is nuw, we can't shift out the one bit.
    2811             :         // - CI2 is one
    2812             :         // - CI isn't zero
    2813          38 :         if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
    2814          26 :             CI2Val->isOneValue() || !CI->isZero()) {
    2815          12 :           if (Pred == ICmpInst::ICMP_EQ)
    2816           7 :             return ConstantInt::getFalse(RHS->getContext());
    2817          10 :           if (Pred == ICmpInst::ICMP_NE)
    2818           1 :             return ConstantInt::getTrue(RHS->getContext());
    2819             :         }
    2820             :       }
    2821          23 :       if (CIVal->isSignMask() && CI2Val->isOneValue()) {
    2822           4 :         if (Pred == ICmpInst::ICMP_UGT)
    2823           1 :           return ConstantInt::getFalse(RHS->getContext());
    2824           3 :         if (Pred == ICmpInst::ICMP_ULE)
    2825           1 :           return ConstantInt::getTrue(RHS->getContext());
    2826             :       }
    2827             :     }
    2828             :   }
    2829             : 
    2830      686944 :   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
    2831             :       LBO->getOperand(1) == RBO->getOperand(1)) {
    2832         957 :     switch (LBO->getOpcode()) {
    2833             :     default:
    2834             :       break;
    2835         364 :     case Instruction::UDiv:
    2836             :     case Instruction::LShr:
    2837         364 :       if (ICmpInst::isSigned(Pred) || !LBO->isExact() || !RBO->isExact())
    2838             :         break;
    2839           2 :       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
    2840           1 :                                       RBO->getOperand(0), Q, MaxRecurse - 1))
    2841           0 :           return V;
    2842             :       break;
    2843             :     case Instruction::SDiv:
    2844         148 :       if (!ICmpInst::isEquality(Pred) || !LBO->isExact() || !RBO->isExact())
    2845             :         break;
    2846           4 :       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
    2847           2 :                                       RBO->getOperand(0), Q, MaxRecurse - 1))
    2848           1 :         return V;
    2849             :       break;
    2850         158 :     case Instruction::AShr:
    2851         158 :       if (!LBO->isExact() || !RBO->isExact())
    2852             :         break;
    2853         314 :       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
    2854         157 :                                       RBO->getOperand(0), Q, MaxRecurse - 1))
    2855         157 :         return V;
    2856             :       break;
    2857           3 :     case Instruction::Shl: {
    2858           3 :       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
    2859           3 :       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
    2860           3 :       if (!NUW && !NSW)
    2861             :         break;
    2862           0 :       if (!NSW && ICmpInst::isSigned(Pred))
    2863             :         break;
    2864           0 :       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
    2865           0 :                                       RBO->getOperand(0), Q, MaxRecurse - 1))
    2866             :         return V;
    2867             :       break;
    2868             :     }
    2869             :     }
    2870             :   }
    2871             :   return nullptr;
    2872             : }
    2873             : 
    2874             : /// Simplify integer comparisons where at least one operand of the compare
    2875             : /// matches an integer min/max idiom.
    2876      675739 : static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
    2877             :                                      Value *RHS, const SimplifyQuery &Q,
    2878             :                                      unsigned MaxRecurse) {
    2879             :   Type *ITy = GetCompareTy(LHS); // The return type.
    2880             :   Value *A, *B;
    2881             :   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
    2882             :   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
    2883             : 
    2884             :   // Signed variants on "max(a,b)>=a -> true".
    2885     1351478 :   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
    2886         104 :     if (A != RHS)
    2887             :       std::swap(A, B);       // smax(A, B) pred A.
    2888             :     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
    2889             :     // We analyze this as smax(A, B) pred A.
    2890             :     P = Pred;
    2891     2027012 :   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
    2892         225 :              (A == LHS || B == LHS)) {
    2893          11 :     if (A != LHS)
    2894             :       std::swap(A, B);       // A pred smax(A, B).
    2895             :     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
    2896             :     // We analyze this as smax(A, B) swapped-pred A.
    2897          11 :     P = CmpInst::getSwappedPredicate(Pred);
    2898     2027270 :   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
    2899         806 :              (A == RHS || B == RHS)) {
    2900          19 :     if (A != RHS)
    2901             :       std::swap(A, B);       // smin(A, B) pred A.
    2902             :     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
    2903             :     // We analyze this as smax(-A, -B) swapped-pred -A.
    2904             :     // Note that we do not need to actually form -A or -B thanks to EqP.
    2905          19 :     P = CmpInst::getSwappedPredicate(Pred);
    2906     2027378 :   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
    2907        1212 :              (A == LHS || B == LHS)) {
    2908          68 :     if (A != LHS)
    2909             :       std::swap(A, B);       // A pred smin(A, B).
    2910             :     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
    2911             :     // We analyze this as smax(-A, -B) pred -A.
    2912             :     // Note that we do not need to actually form -A or -B thanks to EqP.
    2913             :     P = Pred;
    2914             :   }
    2915         202 :   if (P != CmpInst::BAD_ICMP_PREDICATE) {
    2916             :     // Cases correspond to "max(A, B) p A".
    2917         202 :     switch (P) {
    2918             :     default:
    2919             :       break;
    2920          18 :     case CmpInst::ICMP_EQ:
    2921             :     case CmpInst::ICMP_SLE:
    2922             :       // Equivalent to "A EqP B".  This may be the same as the condition tested
    2923             :       // in the max/min; if so, we can just return that.
    2924          18 :       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
    2925          17 :         return V;
    2926          17 :       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
    2927          16 :         return V;
    2928             :       // Otherwise, see if "A EqP B" simplifies.
    2929          16 :       if (MaxRecurse)
    2930          16 :         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
    2931             :           return V;
    2932             :       break;
    2933          74 :     case CmpInst::ICMP_NE:
    2934             :     case CmpInst::ICMP_SGT: {
    2935          74 :       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
    2936             :       // Equivalent to "A InvEqP B".  This may be the same as the condition
    2937             :       // tested in the max/min; if so, we can just return that.
    2938          74 :       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
    2939             :         return V;
    2940          69 :       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
    2941             :         return V;
    2942             :       // Otherwise, see if "A InvEqP B" simplifies.
    2943          47 :       if (MaxRecurse)
    2944          47 :         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
    2945             :           return V;
    2946             :       break;
    2947             :     }
    2948             :     case CmpInst::ICMP_SGE:
    2949             :       // Always true.
    2950           8 :       return getTrue(ITy);
    2951             :     case CmpInst::ICMP_SLT:
    2952             :       // Always false.
    2953         102 :       return getFalse(ITy);
    2954             :     }
    2955             :   }
    2956             : 
    2957             :   // Unsigned variants on "max(a,b)>=a -> true".
    2958             :   P = CmpInst::BAD_ICMP_PREDICATE;
    2959     1351204 :   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
    2960         126 :     if (A != RHS)
    2961             :       std::swap(A, B);       // umax(A, B) pred A.
    2962             :     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
    2963             :     // We analyze this as umax(A, B) pred A.
    2964             :     P = Pred;
    2965     2026524 :   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
    2966         219 :              (A == LHS || B == LHS)) {
    2967          15 :     if (A != LHS)
    2968             :       std::swap(A, B);       // A pred umax(A, B).
    2969             :     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
    2970             :     // We analyze this as umax(A, B) swapped-pred A.
    2971          15 :     P = CmpInst::getSwappedPredicate(Pred);
    2972     2028025 :   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
    2973        3302 :              (A == RHS || B == RHS)) {
    2974          11 :     if (A != RHS)
    2975             :       std::swap(A, B);       // umin(A, B) pred A.
    2976             :     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
    2977             :     // We analyze this as umax(-A, -B) swapped-pred -A.
    2978             :     // Note that we do not need to actually form -A or -B thanks to EqP.
    2979          11 :     P = CmpInst::getSwappedPredicate(Pred);
    2980     2027241 :   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
    2981        1878 :              (A == LHS || B == LHS)) {
    2982          65 :     if (A != LHS)
    2983             :       std::swap(A, B);       // A pred umin(A, B).
    2984             :     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
    2985             :     // We analyze this as umax(-A, -B) pred -A.
    2986             :     // Note that we do not need to actually form -A or -B thanks to EqP.
    2987             :     P = Pred;
    2988             :   }
    2989         217 :   if (P != CmpInst::BAD_ICMP_PREDICATE) {
    2990             :     // Cases correspond to "max(A, B) p A".
    2991         217 :     switch (P) {
    2992             :     default:
    2993             :       break;
    2994          19 :     case CmpInst::ICMP_EQ:
    2995             :     case CmpInst::ICMP_ULE:
    2996             :       // Equivalent to "A EqP B".  This may be the same as the condition tested
    2997             :       // in the max/min; if so, we can just return that.
    2998          19 :       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
    2999          18 :         return V;
    3000          18 :       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
    3001          17 :         return V;
    3002             :       // Otherwise, see if "A EqP B" simplifies.
    3003          17 :       if (MaxRecurse)
    3004          17 :         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
    3005             :           return V;
    3006             :       break;
    3007          71 :     case CmpInst::ICMP_NE:
    3008             :     case CmpInst::ICMP_UGT: {
    3009          71 :       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
    3010             :       // Equivalent to "A InvEqP B".  This may be the same as the condition
    3011             :       // tested in the max/min; if so, we can just return that.
    3012          71 :       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
    3013             :         return V;
    3014          67 :       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
    3015             :         return V;
    3016             :       // Otherwise, see if "A InvEqP B" simplifies.
    3017          45 :       if (MaxRecurse)
    3018          45 :         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
    3019             :           return V;
    3020             :       break;
    3021             :     }
    3022             :     case CmpInst::ICMP_UGE:
    3023             :       // Always true.
    3024           4 :       return getTrue(ITy);
    3025             :     case CmpInst::ICMP_ULT:
    3026             :       // Always false.
    3027         123 :       return getFalse(ITy);
    3028             :     }
    3029             :   }
    3030             : 
    3031             :   // Variants on "max(x,y) >= min(x,z)".
    3032             :   Value *C, *D;
    3033     1351352 :   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
    3034     1350890 :       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
    3035          38 :       (A == C || A == D || B == C || B == D)) {
    3036             :     // max(x, ?) pred min(x, ?).
    3037          38 :     if (Pred == CmpInst::ICMP_SGE)
    3038             :       // Always true.
    3039           1 :       return getTrue(ITy);
    3040          37 :     if (Pred == CmpInst::ICMP_SLT)
    3041             :       // Always false.
    3042           1 :       return getFalse(ITy);
    3043     1351209 :   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
    3044     1351209 :              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
    3045           2 :              (A == C || A == D || B == C || B == D)) {
    3046             :     // min(x, ?) pred max(x, ?).
    3047           2 :     if (Pred == CmpInst::ICMP_SLE)
    3048             :       // Always true.
    3049           1 :       return getTrue(ITy);
    3050           1 :     if (Pred == CmpInst::ICMP_SGT)
    3051             :       // Always false.
    3052           1 :       return getFalse(ITy);
    3053     1351271 :   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
    3054     1351271 :              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
    3055          38 :              (A == C || A == D || B == C || B == D)) {
    3056             :     // max(x, ?) pred min(x, ?).
    3057          38 :     if (Pred == CmpInst::ICMP_UGE)
    3058             :       // Always true.
    3059           1 :       return getTrue(ITy);
    3060          37 :     if (Pred == CmpInst::ICMP_ULT)
    3061             :       // Always false.
    3062           1 :       return getFalse(ITy);
    3063     1352384 :   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
    3064     1352384 :              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
    3065           2 :              (A == C || A == D || B == C || B == D)) {
    3066             :     // min(x, ?) pred max(x, ?).
    3067           2 :     if (Pred == CmpInst::ICMP_ULE)
    3068             :       // Always true.
    3069           1 :       return getTrue(ITy);
    3070           1 :     if (Pred == CmpInst::ICMP_UGT)
    3071             :       // Always false.
    3072           1 :       return getFalse(ITy);
    3073             :   }
    3074             : 
    3075             :   return nullptr;
    3076             : }
    3077             : 
    3078             : /// Given operands for an ICmpInst, see if we can fold the result.
    3079             : /// If not, this returns null.
    3080      734514 : static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
    3081             :                                const SimplifyQuery &Q, unsigned MaxRecurse) {
    3082             :   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
    3083             :   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
    3084             : 
    3085             :   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
    3086             :     if (Constant *CRHS = dyn_cast<Constant>(RHS))
    3087       45189 :       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
    3088             : 
    3089             :     // If we have a constant, make sure it is on the RHS.
    3090             :     std::swap(LHS, RHS);
    3091        8095 :     Pred = CmpInst::getSwappedPredicate(Pred);
    3092             :   }
    3093             : 
    3094             :   Type *ITy = GetCompareTy(LHS); // The return type.
    3095             : 
    3096             :   // icmp X, X -> true/false
    3097             :   // icmp X, undef -> true/false because undef could be X.
    3098     1377656 :   if (LHS == RHS || isa<UndefValue>(RHS))
    3099        1018 :     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
    3100             : 
    3101      688307 :   if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
    3102             :     return V;
    3103             : 
    3104      684618 :   if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
    3105             :     return V;
    3106             : 
    3107      681423 :   if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
    3108             :     return V;
    3109             : 
    3110             :   // If both operands have range metadata, use the metadata
    3111             :   // to simplify the comparison.
    3112      818667 :   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
    3113             :     auto RHS_Instr = cast<Instruction>(RHS);
    3114             :     auto LHS_Instr = cast<Instruction>(LHS);
    3115             : 
    3116      113450 :     if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
    3117             :         LHS_Instr->getMetadata(LLVMContext::MD_range)) {
    3118             :       auto RHS_CR = getConstantRangeFromMetadata(
    3119        1272 :           *RHS_Instr->getMetadata(LLVMContext::MD_range));
    3120             :       auto LHS_CR = getConstantRangeFromMetadata(
    3121        1272 :           *LHS_Instr->getMetadata(LLVMContext::MD_range));
    3122             : 
    3123        1272 :       auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
    3124         637 :       if (Satisfied_CR.contains(LHS_CR))
    3125           3 :         return ConstantInt::getTrue(RHS->getContext());
    3126             : 
    3127             :       auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
    3128        1271 :                 CmpInst::getInversePredicate(Pred), RHS_CR);
    3129         636 :       if (InversedSatisfied_CR.contains(LHS_CR))
    3130           1 :         return ConstantInt::getFalse(RHS->getContext());
    3131             :     }
    3132             :   }
    3133             : 
    3134             :   // Compare of cast, for example (zext X) != 0 -> X != 0
    3135       20888 :   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
    3136             :     Instruction *LI = cast<CastInst>(LHS);
    3137       18917 :     Value *SrcOp = LI->getOperand(0);
    3138       18917 :     Type *SrcTy = SrcOp->getType();
    3139       18917 :     Type *DstTy = LI->getType();
    3140             : 
    3141             :     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
    3142             :     // if the integer type is the same size as the pointer type.
    3143       19307 :     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
    3144         390 :         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
    3145             :       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
    3146             :         // Transfer the cast to the constant.
    3147         268 :         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
    3148         134 :                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
    3149         134 :                                         Q, MaxRecurse-1))
    3150             :           return V;
    3151             :       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
    3152         198 :         if (RI->getOperand(0)->getType() == SrcTy)
    3153             :           // Compare without the cast.
    3154         316 :           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
    3155         158 :                                           Q, MaxRecurse-1))
    3156             :             return V;
    3157             :       }
    3158             :     }
    3159             : 
    3160             :     if (isa<ZExtInst>(LHS)) {
    3161             :       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
    3162             :       // same type.
    3163             :       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
    3164        1480 :         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
    3165             :           // Compare X and Y.  Note that signed predicates become unsigned.
    3166        1422 :           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
    3167             :                                           SrcOp, RI->getOperand(0), Q,
    3168         711 :                                           MaxRecurse-1))
    3169             :             return V;
    3170             :       }
    3171             :       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
    3172             :       // too.  If not, then try to deduce the result of the comparison.
    3173             :       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
    3174             :         // Compute the constant that would happen if we truncated to SrcTy then
    3175             :         // reextended to DstTy.
    3176        9705 :         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
    3177        9705 :         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
    3178             : 
    3179             :         // If the re-extended constant didn't change then this is effectively
    3180             :         // also a case of comparing two zero-extended values.
    3181        9705 :         if (RExt == CI && MaxRecurse)
    3182       18974 :           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
    3183        9487 :                                         SrcOp, Trunc, Q, MaxRecurse-1))
    3184             :             return V;
    3185             : 
    3186             :         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
    3187             :         // there.  Use this to work out the result of the comparison.
    3188        6105 :         if (RExt != CI) {
    3189          93 :           switch (Pred) {
    3190           0 :           default: llvm_unreachable("Unknown ICmp predicate!");
    3191             :           // LHS <u RHS.
    3192          57 :           case ICmpInst::ICMP_EQ:
    3193             :           case ICmpInst::ICMP_UGT:
    3194             :           case ICmpInst::ICMP_UGE:
    3195          57 :             return ConstantInt::getFalse(CI->getContext());
    3196             : 
    3197          15 :           case ICmpInst::ICMP_NE:
    3198             :           case ICmpInst::ICMP_ULT:
    3199             :           case ICmpInst::ICMP_ULE:
    3200          15 :             return ConstantInt::getTrue(CI->getContext());
    3201             : 
    3202             :           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
    3203             :           // is non-negative then LHS <s RHS.
    3204             :           case ICmpInst::ICMP_SGT:
    3205             :           case ICmpInst::ICMP_SGE:
    3206          12 :             return CI->getValue().isNegative() ?
    3207          10 :               ConstantInt::getTrue(CI->getContext()) :
    3208          22 :               ConstantInt::getFalse(CI->getContext());
    3209             : 
    3210             :           case ICmpInst::ICMP_SLT:
    3211             :           case ICmpInst::ICMP_SLE:
    3212           9 :             return CI->getValue().isNegative() ?
    3213           3 :               ConstantInt::getFalse(CI->getContext()) :
    3214          12 :               ConstantInt::getTrue(CI->getContext());
    3215             :           }
    3216             :         }
    3217             :       }
    3218             :     }
    3219             : 
    3220             :     if (isa<SExtInst>(LHS)) {
    3221             :       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
    3222             :       // same type.
    3223             :       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
    3224         312 :         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
    3225             :           // Compare X and Y.  Note that the predicate does not change.
    3226         306 :           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
    3227         153 :                                           Q, MaxRecurse-1))
    3228             :             return V;
    3229             :       }
    3230             :       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
    3231             :       // too.  If not, then try to deduce the result of the comparison.
    3232             :       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
    3233             :         // Compute the constant that would happen if we truncated to SrcTy then
    3234             :         // reextended to DstTy.
    3235         854 :         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
    3236         854 :         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
    3237             : 
    3238             :         // If the re-extended constant didn't change then this is effectively
    3239             :         // also a case of comparing two sign-extended values.
    3240         854 :         if (RExt == CI && MaxRecurse)
    3241         821 :           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
    3242             :             return V;
    3243             : 
    3244             :         // Otherwise the upper bits of LHS are all equal, while RHS has varying
    3245             :         // bits there.  Use this to work out the result of the comparison.
    3246         775 :         if (RExt != CI) {
    3247          33 :           switch (Pred) {
    3248           0 :           default: llvm_unreachable("Unknown ICmp predicate!");
    3249           5 :           case ICmpInst::ICMP_EQ:
    3250           5 :             return ConstantInt::getFalse(CI->getContext());
    3251           8 :           case ICmpInst::ICMP_NE:
    3252           8 :             return ConstantInt::getTrue(CI->getContext());
    3253             : 
    3254             :           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
    3255             :           // LHS >s RHS.
    3256             :           case ICmpInst::ICMP_SGT:
    3257             :           case ICmpInst::ICMP_SGE:
    3258           8 :             return CI->getValue().isNegative() ?
    3259           7 :               ConstantInt::getTrue(CI->getContext()) :
    3260          15 :               ConstantInt::getFalse(CI->getContext());
    3261             :           case ICmpInst::ICMP_SLT:
    3262             :           case ICmpInst::ICMP_SLE:
    3263           8 :             return CI->getValue().isNegative() ?
    3264           1 :               ConstantInt::getFalse(CI->getContext()) :
    3265           9 :               ConstantInt::getTrue(CI->getContext());
    3266             : 
    3267             :           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
    3268             :           // LHS >u RHS.
    3269           3 :           case ICmpInst::ICMP_UGT:
    3270             :           case ICmpInst::ICMP_UGE:
    3271             :             // Comparison is true iff the LHS <s 0.
    3272           3 :             if (MaxRecurse)
    3273           6 :               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
    3274           3 :                                               Constant::getNullValue(SrcTy),
    3275           3 :                                               Q, MaxRecurse-1))
    3276             :                 return V;
    3277             :             break;
    3278           1 :           case ICmpInst::ICMP_ULT:
    3279             :           case ICmpInst::ICMP_ULE:
    3280             :             // Comparison is true iff the LHS >=s 0.
    3281           1 :             if (MaxRecurse)
    3282           2 :               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
    3283           1 :                                               Constant::getNullValue(SrcTy),
    3284           1 :                                               Q, MaxRecurse-1))
    3285             :                 return V;
    3286             :             break;
    3287             :           }
    3288             :         }
    3289             :       }
    3290             :     }
    3291             :   }
    3292             : 
    3293             :   // icmp eq|ne X, Y -> false|true if X != Y
    3294     1161923 :   if (ICmpInst::isEquality(Pred) &&
    3295      485404 :       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
    3296         503 :     return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
    3297             :   }
    3298             : 
    3299      676016 :   if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
    3300             :     return V;
    3301             : 
    3302      675739 :   if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
    3303             :     return V;
    3304             : 
    3305             :   // Simplify comparisons of related pointers using a powerful, recursive
    3306             :   // GEP-walk when we have target data available..
    3307     1350874 :   if (LHS->getType()->isPointerTy())
    3308      458720 :     if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI, LHS,
    3309      229360 :                                      RHS))
    3310             :       return C;
    3311             :   if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
    3312             :     if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
    3313         498 :       if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
    3314         454 :               Q.DL.getTypeSizeInBits(CLHS->getType()) &&
    3315         410 :           Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
    3316         205 :               Q.DL.getTypeSizeInBits(CRHS->getType()))
    3317         410 :         if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
    3318             :                                          CLHS->getPointerOperand(),
    3319         205 :                                          CRHS->getPointerOperand()))
    3320             :           return C;
    3321             : 
    3322             :   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
    3323             :     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
    3324          48 :       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
    3325         739 :           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
    3326          10 :           (ICmpInst::isEquality(Pred) ||
    3327          18 :            (GLHS->isInBounds() && GRHS->isInBounds() &&
    3328           4 :             Pred == ICmpInst::getSignedPredicate(Pred)))) {
    3329             :         // The bases are equal and the indices are constant.  Build a constant
    3330             :         // expression GEP with the same indices and a null base pointer to see
    3331             :         // what constant folding can make out of it.
    3332           4 :         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
    3333             :         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
    3334           8 :         Constant *NewLHS = ConstantExpr::getGetElementPtr(
    3335           4 :             GLHS->getSourceElementType(), Null, IndicesLHS);
    3336             : 
    3337             :         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
    3338           8 :         Constant *NewRHS = ConstantExpr::getGetElementPtr(
    3339           4 :             GLHS->getSourceElementType(), Null, IndicesRHS);
    3340           4 :         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
    3341             :       }
    3342             :     }
    3343             :   }
    3344             : 
    3345             :   // If the comparison is with the result of a select instruction, check whether
    3346             :   // comparing with either branch of the select always yields the same value.
    3347             :   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
    3348        7743 :     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
    3349             :       return V;
    3350             : 
    3351             :   // If the comparison is with the result of a phi instruction, check whether
    3352             :   // doing the compare with each incoming phi value yields a common result.
    3353             :   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
    3354       66357 :     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
    3355             :       return V;
    3356             : 
    3357             :   return nullptr;
    3358             : }
    3359             : 
    3360      599885 : Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
    3361             :                               const SimplifyQuery &Q) {
    3362      599885 :   return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
    3363             : }
    3364             : 
    3365             : /// Given operands for an FCmpInst, see if we can fold the result.
    3366             : /// If not, this returns null.
    3367        8391 : static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
    3368             :                                FastMathFlags FMF, const SimplifyQuery &Q,
    3369             :                                unsigned MaxRecurse) {
    3370             :   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
    3371             :   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
    3372             : 
    3373             :   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
    3374             :     if (Constant *CRHS = dyn_cast<Constant>(RHS))
    3375         149 :       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
    3376             : 
    3377             :     // If we have a constant, make sure it is on the RHS.
    3378             :     std::swap(LHS, RHS);
    3379         258 :     Pred = CmpInst::getSwappedPredicate(Pred);
    3380             :   }
    3381             : 
    3382             :   // Fold trivial predicates.
    3383             :   Type *RetTy = GetCompareTy(LHS);
    3384        8242 :   if (Pred == FCmpInst::FCMP_FALSE)
    3385          35 :     return getFalse(RetTy);
    3386        8207 :   if (Pred == FCmpInst::FCMP_TRUE)
    3387          35 :     return getTrue(RetTy);
    3388             : 
    3389             :   // UNO/ORD predicates can be trivially folded if NaNs are ignored.
    3390        8172 :   if (FMF.noNaNs()) {
    3391         544 :     if (Pred == FCmpInst::FCMP_UNO)
    3392           9 :       return getFalse(RetTy);
    3393         535 :     if (Pred == FCmpInst::FCMP_ORD)
    3394           1 :       return getTrue(RetTy);
    3395             :   }
    3396             : 
    3397             :   // NaN is unordered; NaN is not ordered.
    3398             :   assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
    3399             :          "Comparison must be either ordered or unordered");
    3400        8162 :   if (match(RHS, m_NaN()))
    3401          15 :     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
    3402             : 
    3403             :   // fcmp pred x, undef  and  fcmp pred undef, x
    3404             :   // fold to true if unordered, false if ordered
    3405       16294 :   if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
    3406             :     // Choosing NaN for the undef will always make unordered comparison succeed
    3407             :     // and ordered comparison fail.
    3408          14 :     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
    3409             :   }
    3410             : 
    3411             :   // fcmp x,x -> true/false.  Not all compares are foldable.
    3412        8133 :   if (LHS == RHS) {
    3413         140 :     if (CmpInst::isTrueWhenEqual(Pred))
    3414           2 :       return getTrue(RetTy);
    3415         138 :     if (CmpInst::isFalseWhenEqual(Pred))
    3416           7 :       return getFalse(RetTy);
    3417             :   }
    3418             : 
    3419             :   // Handle fcmp with constant RHS.
    3420             :   const APFloat *C;
    3421       16248 :   if (match(RHS, m_APFloat(C))) {
    3422             :     // Check whether the constant is an infinity.
    3423        7222 :     if (C->isInfinity()) {
    3424         176 :       if (C->isNegative()) {
    3425          67 :         switch (Pred) {
    3426             :         case FCmpInst::FCMP_OLT:
    3427             :           // No value is ordered and less than negative infinity.
    3428           1 :           return getFalse(RetTy);
    3429             :         case FCmpInst::FCMP_UGE:
    3430             :           // All values are unordered with or at least negative infinity.
    3431           1 :           return getTrue(RetTy);
    3432             :         default:
    3433             :           break;
    3434             :         }
    3435             :       } else {
    3436         109 :         switch (Pred) {
    3437             :         case FCmpInst::FCMP_OGT:
    3438             :           // No value is ordered and greater than infinity.
    3439           1 :           return getFalse(RetTy);
    3440             :         case FCmpInst::FCMP_ULE:
    3441             :           // All values are unordered with and at most infinity.
    3442           3 :           return getTrue(RetTy);
    3443             :         default:
    3444             :           break;
    3445             :         }
    3446             :       }
    3447             :     }
    3448        3605 :     if (C->isZero()) {
    3449        1954 :       switch (Pred) {
    3450          24 :       case FCmpInst::FCMP_UGE:
    3451          24 :         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
    3452           6 :           return getTrue(RetTy);
    3453             :         break;
    3454         171 :       case FCmpInst::FCMP_OLT:
    3455             :         // X < 0
    3456         171 :         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
    3457           6 :           return getFalse(RetTy);
    3458             :         break;
    3459             :       default:
    3460             :         break;
    3461             :       }
    3462        1651 :     } else if (C->isNegative()) {
    3463             :       assert(!C->isNaN() && "Unexpected NaN constant!");
    3464             :       // TODO: We can catch more cases by using a range check rather than
    3465             :       //       relying on CannotBeOrderedLessThanZero.
    3466             :       switch (Pred) {
    3467          26 :       case FCmpInst::FCMP_UGE:
    3468             :       case FCmpInst::FCMP_UGT:
    3469             :       case FCmpInst::FCMP_UNE:
    3470             :         // (X >= 0) implies (X > C) when (C < 0)
    3471          26 :         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
    3472           5 :           return getTrue(RetTy);
    3473             :         break;
    3474          73 :       case FCmpInst::FCMP_OEQ:
    3475             :       case FCmpInst::FCMP_OLE:
    3476             :       case FCmpInst::FCMP_OLT:
    3477             :         // (X >= 0) implies !(X < C) when (C < 0)
    3478          73 :         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
    3479           6 :           return getFalse(RetTy);
    3480             :         break;
    3481             :       default:
    3482             :         break;
    3483             :       }
    3484             :     }
    3485             :   }
    3486             : 
    3487             :   // If the comparison is with the result of a select instruction, check whether
    3488             :   // comparing with either branch of the select always yields the same value.
    3489             :   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
    3490         231 :     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
    3491             :       return V;
    3492             : 
    3493             :   // If the comparison is with the result of a phi instruction, check whether
    3494             :   // doing the compare with each incoming phi value yields a common result.
    3495             :   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
    3496         128 :     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
    3497             :       return V;
    3498             : 
    3499             :   return nullptr;
    3500             : }
    3501             : 
    3502        7986 : Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
    3503             :                               FastMathFlags FMF, const SimplifyQuery &Q) {
    3504        7986 :   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
    3505             : }
    3506             : 
    3507             : /// See if V simplifies when its operand Op is replaced with RepOp.
    3508     1232495 : static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
    3509             :                                            const SimplifyQuery &Q,
    3510             :                                            unsigned MaxRecurse) {
    3511             :   // Trivial replacement.
    3512     1232495 :   if (V == Op)
    3513        4877 :     return RepOp;
    3514             : 
    3515             :   // We cannot replace a constant, and shouldn't even try.
    3516     1227618 :   if (isa<Constant>(Op))
    3517             :     return nullptr;
    3518             : 
    3519             :   auto *I = dyn_cast<Instruction>(V);
    3520             :   if (!I)
    3521             :     return nullptr;
    3522             : 
    3523             :   // If this is a binary operator, try to simplify it with the replaced op.
    3524             :   if (auto *B = dyn_cast<BinaryOperator>(I)) {
    3525             :     // Consider:
    3526             :     //   %cmp = icmp eq i32 %x, 2147483647
    3527             :     //   %add = add nsw i32 %x, 1
    3528             :     //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
    3529             :     //
    3530             :     // We can't replace %sel with %add unless we strip away the flags.
    3531             :     if (isa<OverflowingBinaryOperator>(B))
    3532        2488 :       if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
    3533             :         return nullptr;
    3534             :     if (isa<PossiblyExactOperator>(B))
    3535         339 :       if (B->isExact())
    3536             :         return nullptr;
    3537             : 
    3538        2758 :     if (MaxRecurse) {
    3539        2758 :       if (B->getOperand(0) == Op)
    3540         622 :         return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
    3541         311 :                              MaxRecurse - 1);
    3542        2447 :       if (B->getOperand(1) == Op)
    3543           3 :         return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
    3544           3 :                              MaxRecurse - 1);
    3545             :     }
    3546             :   }
    3547             : 
    3548             :   // Same for CmpInsts.
    3549             :   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
    3550          44 :     if (MaxRecurse) {
    3551          44 :       if (C->getOperand(0) == Op)
    3552          10 :         return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
    3553           5 :                                MaxRecurse - 1);
    3554          39 :       if (C->getOperand(1) == Op)
    3555           0 :         return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
    3556           0 :                                MaxRecurse - 1);
    3557             :     }
    3558             :   }
    3559             : 
    3560             :   // Same for GEPs.
    3561             :   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
    3562        2700 :     if (MaxRecurse) {
    3563        8100 :       SmallVector<Value *, 8> NewOps(GEP->getNumOperands());
    3564        2700 :       transform(GEP->operands(), NewOps.begin(),
    3565        5468 :                 [&](Value *V) { return V == Op ? RepOp : V; });
    3566        5400 :       return SimplifyGEPInst(GEP->getSourceElementType(), NewOps, Q,
    3567        2700 :                              MaxRecurse - 1);
    3568             :     }
    3569             :   }
    3570             : 
    3571             :   // TODO: We could hand off more cases to instsimplify here.
    3572             : 
    3573             :   // If all operands are constant after substituting Op for RepOp then we can
    3574             :   // constant fold the instruction.
    3575       18212 :   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
    3576             :     // Build a list of all constant operands.
    3577             :     SmallVector<Constant *, 8> ConstOps;
    3578       11032 :     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
    3579       17752 :       if (I->getOperand(i) == Op)
    3580         212 :         ConstOps.push_back(CRepOp);
    3581        8664 :       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
    3582        1510 :         ConstOps.push_back(COp);
    3583             :       else
    3584             :         break;
    3585             :     }
    3586             : 
    3587             :     // All operands were constants, fold it.
    3588        7588 :     if (ConstOps.size() == I->getNumOperands()) {
    3589             :       if (CmpInst *C = dyn_cast<CmpInst>(I))
    3590           0 :         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
    3591           0 :                                                ConstOps[1], Q.DL, Q.TLI);
    3592             : 
    3593             :       if (LoadInst *LI = dyn_cast<LoadInst>(I))
    3594         205 :         if (!LI->isVolatile())
    3595         193 :           return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
    3596             : 
    3597         482 :       return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
    3598             :     }
    3599             :   }
    3600             : 
    3601        8672 :   return nullptr;
    3602             : }
    3603             : 
    3604             : /// Try to simplify a select instruction when its condition operand is an
    3605             : /// integer comparison where one operand of the compare is a constant.
    3606       22590 : static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
    3607             :                                     const APInt *Y, bool TrueWhenUnset) {
    3608             :   const APInt *C;
    3609             : 
    3610             :   // (X & Y) == 0 ? X & ~Y : X  --> X
    3611             :   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
    3612       45736 :   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
    3613       67781 :       *Y == ~*C)
    3614          11 :     return TrueWhenUnset ? FalseVal : TrueVal;
    3615             : 
    3616             :   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
    3617             :   // (X & Y) != 0 ? X : X & ~Y  --> X
    3618       46511 :   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
    3619       67748 :       *Y == ~*C)
    3620          11 :     return TrueWhenUnset ? FalseVal : TrueVal;
    3621             : 
    3622       22568 :   if (Y->isPowerOf2()) {
    3623             :     // (X & Y) == 0 ? X | Y : X  --> X | Y
    3624             :     // (X & Y) != 0 ? X | Y : X  --> X
    3625       12033 :     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
    3626           8 :         *Y == *C)
    3627           8 :       return TrueWhenUnset ? TrueVal : FalseVal;
    3628             : 
    3629             :     // (X & Y) == 0 ? X : X | Y  --> X
    3630             :     // (X & Y) != 0 ? X : X | Y  --> X | Y
    3631        6126 :     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
    3632           7 :         *Y == *C)
    3633           7 :       return TrueWhenUnset ? TrueVal : FalseVal;
    3634             :   }
    3635             : 
    3636             :   return nullptr;
    3637             : }
    3638             : 
    3639             : /// An alternative way to test if a bit is set or not uses sgt/slt instead of
    3640             : /// eq/ne.
    3641      399389 : static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
    3642             :                                            ICmpInst::Predicate Pred,
    3643             :                                            Value *TrueVal, Value *FalseVal) {
    3644             :   Value *X;
    3645             :   APInt Mask;
    3646      399389 :   if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
    3647             :     return nullptr;
    3648             : 
    3649       19244 :   return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
    3650       19244 :                                Pred == ICmpInst::ICMP_EQ);
    3651             : }
    3652             : 
    3653             : /// Try to simplify a select instruction when its condition operand is an
    3654             : /// integer comparison.
    3655      483857 : static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
    3656             :                                          Value *FalseVal, const SimplifyQuery &Q,
    3657             :                                          unsigned MaxRecurse) {
    3658             :   ICmpInst::Predicate Pred;
    3659             :   Value *CmpLHS, *CmpRHS;
    3660             :   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
    3661             :     return nullptr;
    3662             : 
    3663      707565 :   if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
    3664             :     Value *X;
    3665             :     const APInt *Y;
    3666      465560 :     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
    3667        6692 :       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
    3668        3346 :                                            Pred == ICmpInst::ICMP_EQ))
    3669          12 :         return V;
    3670             :   }
    3671             : 
    3672             :   // Check for other compares that behave like bit test.
    3673      798778 :   if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
    3674      399389 :                                               TrueVal, FalseVal))
    3675             :     return V;
    3676             : 
    3677             :   // If we have an equality comparison, then we know the value in one of the
    3678             :   // arms of the select. See if substituting this value into the arm and
    3679             :   // simplifying the result yields the same value as the other arm.
    3680      399364 :   if (Pred == ICmpInst::ICMP_EQ) {
    3681      129505 :     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
    3682      258982 :             TrueVal ||
    3683      129477 :         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
    3684             :             TrueVal)
    3685             :       return FalseVal;
    3686      129475 :     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
    3687      258948 :             FalseVal ||
    3688      129473 :         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
    3689             :             FalseVal)
    3690             :       return FalseVal;
    3691      269859 :   } else if (Pred == ICmpInst::ICMP_NE) {
    3692      178647 :     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
    3693      357287 :             FalseVal ||
    3694      178640 :         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
    3695             :             FalseVal)
    3696             :       return TrueVal;
    3697      178639 :     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
    3698      357278 :             TrueVal ||
    3699      178639 :         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
    3700             :             TrueVal)
    3701             :       return TrueVal;
    3702             :   }
    3703             : 
    3704             :   return nullptr;
    3705             : }
    3706             : 
    3707             : /// Given operands for a SelectInst, see if we can fold the result.
    3708             : /// If not, this returns null.
    3709      487999 : static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
    3710             :                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
    3711             :   if (auto *CondC = dyn_cast<Constant>(Cond)) {
    3712             :     if (auto *TrueC = dyn_cast<Constant>(TrueVal))
    3713             :       if (auto *FalseC = dyn_cast<Constant>(FalseVal))
    3714        3667 :         return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
    3715             : 
    3716             :     // select undef, X, Y -> X or Y
    3717         466 :     if (isa<UndefValue>(CondC))
    3718          49 :       return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
    3719             : 
    3720             :     // TODO: Vector constants with undef elements don't simplify.
    3721             : 
    3722             :     // select true, X, Y  -> X
    3723         417 :     if (CondC->isAllOnesValue())
    3724             :       return TrueVal;
    3725             :     // select false, X, Y -> Y
    3726         381 :     if (CondC->isNullValue())
    3727             :       return FalseVal;
    3728             :   }
    3729             : 
    3730             :   // select ?, X, X -> X
    3731      483898 :   if (TrueVal == FalseVal)
    3732             :     return TrueVal;
    3733             : 
    3734      483878 :   if (isa<UndefValue>(TrueVal))   // select ?, undef, X -> X
    3735             :     return FalseVal;
    3736      483862 :   if (isa<UndefValue>(FalseVal))   // select ?, X, undef -> X
    3737             :     return TrueVal;
    3738             : 
    3739      483857 :   if (Value *V =
    3740      483857 :           simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
    3741             :     return V;
    3742             : 
    3743      483780 :   return nullptr;
    3744             : }
    3745             : 
    3746      487999 : Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
    3747             :                                 const SimplifyQuery &Q) {
    3748      487999 :   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
    3749             : }
    3750             : 
    3751             : /// Given operands for an GetElementPtrInst, see if we can fold the result.
    3752             : /// If not, this returns null.
    3753     1683452 : static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
    3754             :                               const SimplifyQuery &Q, unsigned) {
    3755             :   // The type of the GEP pointer operand.
    3756             :   unsigned AS =
    3757     1683452 :       cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
    3758             : 
    3759             :   // getelementptr P -> P.
    3760     1683452 :   if (Ops.size() == 1)
    3761             :     return Ops[0];
    3762             : 
    3763             :   // Compute the (pointer) type returned by the GEP instruction.
    3764     1683378 :   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
    3765     1683378 :   Type *GEPTy = PointerType::get(LastType, AS);
    3766     1683378 :   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
    3767        2097 :     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
    3768     1681281 :   else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
    3769         843 :     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
    3770             : 
    3771     3366756 :   if (isa<UndefValue>(Ops[0]))
    3772        2021 :     return UndefValue::get(GEPTy);
    3773             : 
    3774     1681357 :   if (Ops.size() == 2) {
    3775             :     // getelementptr P, 0 -> P.
    3776      500022 :     if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy)
    3777             :       return Ops[0];
    3778             : 
    3779             :     Type *Ty = SrcTy;
    3780      245610 :     if (Ty->isSized()) {
    3781             :       Value *P;
    3782             :       uint64_t C;
    3783      245610 :       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
    3784             :       // getelementptr P, N -> P if P points to a type of zero size.
    3785      245610 :       if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy)
    3786          20 :         return Ops[0];
    3787             : 
    3788             :       // The following transforms are only safe if the ptrtoint cast
    3789             :       // doesn't truncate the pointers.
    3790      491216 :       if (Ops[1]->getType()->getScalarSizeInBits() ==
    3791      245608 :           Q.DL.getIndexSizeInBits(AS)) {
    3792          40 :         auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
    3793          20 :           if (match(P, m_Zero()))
    3794           3 :             return Constant::getNullValue(GEPTy);
    3795             :           Value *Temp;
    3796          34 :           if (match(P, m_PtrToInt(m_Value(Temp))))
    3797          34 :             if (Temp->getType() == GEPTy)
    3798             :               return Temp;
    3799             :           return nullptr;
    3800      232594 :         };
    3801             : 
    3802             :         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
    3803      329804 :         if (TyAllocSize == 1 &&
    3804      329801 :             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
    3805           3 :           if (Value *R = PtrToIntOrZero(P))
    3806          18 :             return R;
    3807             : 
    3808             :         // getelementptr V, (ashr (sub P, V), C) -> Q
    3809             :         // if P points to a type of size 1 << C.
    3810      232592 :         if (match(Ops[1],
    3811      465171 :                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
    3812      232605 :                          m_ConstantInt(C))) &&
    3813          13 :             TyAllocSize == 1ULL << C)
    3814          13 :           if (Value *R = PtrToIntOrZero(P))
    3815             :             return R;
    3816             : 
    3817             :         // getelementptr V, (sdiv (sub P, V), C) -> Q
    3818             :         // if P points to a type of size C.
    3819      465158 :         if (match(Ops[1],
    3820      465158 :                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
    3821             :                          m_SpecificInt(TyAllocSize))))
    3822           4 :           if (Value *R = PtrToIntOrZero(P))
    3823             :             return R;
    3824             :       }
    3825             :     }
    3826             :   }
    3827             : 
    3828     1923753 :   if (Q.DL.getTypeAllocSize(LastType) == 1 &&
    3829             :       all_of(Ops.slice(1).drop_back(1),
    3830             :              [](Value *Idx) { return match(Idx, m_Zero()); })) {
    3831             :     unsigned IdxWidth =
    3832      232220 :         Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
    3833      464440 :     if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) {
    3834             :       APInt BasePtrOffset(IdxWidth, 0);
    3835             :       Value *StrippedBasePtr =
    3836      162029 :           Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
    3837             :                                                             BasePtrOffset);
    3838             : 
    3839             :       // gep (gep V, C), (sub 0, V) -> C
    3840      324058 :       if (match(Ops.back(),
    3841      324058 :                 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
    3842           3 :         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
    3843           3 :         return ConstantExpr::getIntToPtr(CI, GEPTy);
    3844             :       }
    3845             :       // gep (gep V, C), (xor V, -1) -> C-1
    3846      324052 :       if (match(Ops.back(),
    3847      324052 :                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
    3848           3 :         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
    3849           1 :         return ConstantExpr::getIntToPtr(CI, GEPTy);
    3850             :       }
    3851             :     }
    3852             :   }
    3853             : 
    3854             :   // Check to see if this is constant foldable.
    3855     1676932 :   if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); }))
    3856             :     return nullptr;
    3857             : 
    3858       12824 :   auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
    3859        6412 :                                             Ops.slice(1));
    3860        6412 :   if (auto *CEFolded = ConstantFoldConstant(CE, Q.DL))
    3861             :     return CEFolded;
    3862             :   return CE;
    3863             : }
    3864             : 
    3865     1680752 : Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
    3866             :                              const SimplifyQuery &Q) {
    3867     1680752 :   return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
    3868             : }
    3869             : 
    3870             : /// Given operands for an InsertValueInst, see if we can fold the result.
    3871             : /// If not, this returns null.
    3872       21815 : static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
    3873             :                                       ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
    3874             :                                       unsigned) {
    3875             :   if (Constant *CAgg = dyn_cast<Constant>(Agg))
    3876             :     if (Constant *CVal = dyn_cast<Constant>(Val))
    3877         138 :       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
    3878             : 
    3879             :   // insertvalue x, undef, n -> x
    3880       21677 :   if (match(Val, m_Undef()))
    3881             :     return Agg;
    3882             : 
    3883             :   // insertvalue x, (extractvalue y, n), n
    3884             :   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
    3885        6865 :     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
    3886             :         EV->getIndices() == Idxs) {
    3887             :       // insertvalue undef, (extractvalue y, n), n -> y
    3888        3405 :       if (match(Agg, m_Undef()))
    3889             :         return EV->getAggregateOperand();
    3890             : 
    3891             :       // insertvalue y, (extractvalue y, n), n -> y
    3892        1719 :       if (Agg == EV->getAggregateOperand())
    3893             :         return Agg;
    3894             :     }
    3895             : 
    3896             :   return nullptr;
    3897             : }
    3898             : 
    3899       21815 : Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
    3900             :                                      ArrayRef<unsigned> Idxs,
    3901             :                                      const SimplifyQuery &Q) {
    3902       21815 :   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
    3903             : }
    3904             : 
    3905       28804 : Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
    3906             :                                        const SimplifyQuery &Q) {
    3907             :   // Try to constant fold.
    3908             :   auto *VecC = dyn_cast<Constant>(Vec);
    3909             :   auto *ValC = dyn_cast<Constant>(Val);
    3910             :   auto *IdxC = dyn_cast<Constant>(Idx);
    3911       28804 :   if (VecC && ValC && IdxC)
    3912         447 :     return ConstantFoldInsertElementInstruction(VecC, ValC, IdxC);
    3913             : 
    3914             :   // Fold into undef if index is out of bounds.
    3915             :   if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
    3916       27188 :     uint64_t NumElements = cast<VectorType>(Vec->getType())->getNumElements();
    3917       27188 :     if (CI->uge(NumElements))
    3918           9 :       return UndefValue::get(Vec->getType());
    3919             :   }
    3920             : 
    3921             :   // If index is undef, it might be out of bounds (see above case)
    3922       28348 :   if (isa<UndefValue>(Idx))
    3923          14 :     return UndefValue::get(Vec->getType());
    3924             : 
    3925             :   return nullptr;
    3926             : }
    3927             : 
    3928             : /// Given operands for an ExtractValueInst, see if we can fold the result.
    3929             : /// If not, this returns null.
    3930      681859 : static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
    3931             :                                        const SimplifyQuery &, unsigned) {
    3932             :   if (auto *CAgg = dyn_cast<Constant>(Agg))
    3933          10 :     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
    3934             : 
    3935             :   // extractvalue x, (insertvalue y, elt, n), n -> elt
    3936      681849 :   unsigned NumIdxs = Idxs.size();
    3937      682119 :   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
    3938             :        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
    3939             :     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
    3940         727 :     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
    3941         727 :     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
    3942        1454 :     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
    3943             :         Idxs.slice(0, NumCommonIdxs)) {
    3944         426 :       if (NumIdxs == NumInsertValueIdxs)
    3945         420 :         return IVI->getInsertedValueOperand();
    3946           6 :       break;
    3947             :     }
    3948             :   }
    3949             : 
    3950             :   return nullptr;
    3951             : }
    3952             : 
    3953      681859 : Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
    3954             :                                       const SimplifyQuery &Q) {
    3955      681859 :   return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
    3956             : }
    3957             : 
    3958             : /// Given operands for an ExtractElementInst, see if we can fold the result.
    3959             : /// If not, this returns null.
    3960       21630 : static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &,
    3961             :                                          unsigned) {
    3962             :   if (auto *CVec = dyn_cast<Constant>(Vec)) {
    3963             :     if (auto *CIdx = dyn_cast<Constant>(Idx))
    3964          26 :       return ConstantFoldExtractElementInstruction(CVec, CIdx);
    3965             : 
    3966             :     // The index is not relevant if our vector is a splat.
    3967         282 :     if (auto *Splat = CVec->getSplatValue())
    3968             :       return Splat;
    3969             : 
    3970         282 :     if (isa<UndefValue>(Vec))
    3971           2 :       return UndefValue::get(Vec->getType()->getVectorElementType());
    3972             :   }
    3973             : 
    3974             :   // If extracting a specified index from the vector, see if we can recursively
    3975             :   // find a previously computed scalar that was inserted into the vector.
    3976             :   if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
    3977       40564 :     if (IdxC->getValue().uge(Vec->getType()->getVectorNumElements()))
    3978             :       // definitely out of bounds, thus undefined result
    3979          10 :       return UndefValue::get(Vec->getType()->getVectorElementType());
    3980       20277 :     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
    3981             :       return Elt;
    3982             :   }
    3983             : 
    3984             :   // An undef extract index can be arbitrarily chosen to be an out-of-range
    3985             :   // index value, which would result in the instruction being undef.
    3986       21349 :   if (isa<UndefValue>(Idx))
    3987          12 :     return UndefValue::get(Vec->getType()->getVectorElementType());
    3988             : 
    3989             :   return nullptr;
    3990             : }
    3991             : 
    3992       21630 : Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
    3993             :                                         const SimplifyQuery &Q) {
    3994       21630 :   return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
    3995             : }
    3996             : 
    3997             : /// See if we can fold the given phi. If not, returns null.
    3998     2124319 : static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
    3999             :   // If all of the PHI's incoming values are the same then replace the PHI node
    4000             :   // with the common value.
    4001             :   Value *CommonValue = nullptr;
    4002             :   bool HasUndefInput = false;
    4003     6442479 :   for (Value *Incoming : PN->incoming_values()) {
    4004             :     // If the incoming value is the phi node itself, it can safely be skipped.
    4005     4247371 :     if (Incoming == PN) continue;
    4006     4246842 :     if (isa<UndefValue>(Incoming)) {
    4007             :       // Remember that we saw an undef value, but otherwise ignore them.
    4008             :       HasUndefInput = true;
    4009             :       continue;
    4010             :     }
    4011     4234645 :     if (CommonValue && Incoming != CommonValue)
    4012             :       return nullptr;  // Not the same, bail out.
    4013             :     CommonValue = Incoming;
    4014             :   }
    4015             : 
    4016             :   // If CommonValue is null then all of the incoming values were either undef or
    4017             :   // equal to the phi node itself.
    4018       36028 :   if (!CommonValue)
    4019          79 :     return UndefValue::get(PN->getType());
    4020             : 
    4021             :   // If we have a PHI node like phi(X, undef, X), where X is defined by some
    4022             :   // instruction, we cannot return X as the result of the PHI node unless it
    4023             :   // dominates the PHI block.
    4024       35949 :   if (HasUndefInput)
    4025       11465 :     return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
    4026             : 
    4027             :   return CommonValue;
    4028             : }
    4029             : 
    4030      779579 : static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
    4031             :                                Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
    4032             :   if (auto *C = dyn_cast<Constant>(Op))
    4033        5584 :     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
    4034             : 
    4035             :   if (auto *CI = dyn_cast<CastInst>(Op)) {
    4036             :     auto *Src = CI->getOperand(0);
    4037       20796 :     Type *SrcTy = Src->getType();
    4038       20796 :     Type *MidTy = CI->getType();
    4039             :     Type *DstTy = Ty;
    4040       20796 :     if (Src->getType() == Ty) {
    4041             :       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
    4042             :       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
    4043             :       Type *SrcIntPtrTy =
    4044       12503 :           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
    4045             :       Type *MidIntPtrTy =
    4046       12503 :           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
    4047             :       Type *DstIntPtrTy =
    4048       12503 :           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
    4049       12503 :       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
    4050             :                                          SrcIntPtrTy, MidIntPtrTy,
    4051             :                                          DstIntPtrTy) == Instruction::BitCast)
    4052             :         return Src;
    4053             :     }
    4054             :   }
    4055             : 
    4056             :   // bitcast x -> x
    4057      762377 :   if (CastOpc == Instruction::BitCast)
    4058      290612 :     if (Op->getType() == Ty)
    4059             :       return Op;
    4060             : 
    4061             :   return nullptr;
    4062             : }
    4063             : 
    4064      779578 : Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
    4065             :                               const SimplifyQuery &Q) {
    4066      779578 :   return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
    4067             : }
    4068             : 
    4069             : /// For the given destination element of a shuffle, peek through shuffles to
    4070             : /// match a root vector source operand that contains that element in the same
    4071             : /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
    4072       19730 : static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
    4073             :                                    int MaskVal, Value *RootVec,
    4074             :                                    unsigned MaxRecurse) {
    4075       20375 :   if (!MaxRecurse--)
    4076             :     return nullptr;
    4077             : 
    4078             :   // Bail out if any mask value is undefined. That kind of shuffle may be
    4079             :   // simplified further based on demanded bits or other folds.
    4080       20371 :   if (MaskVal == -1)
    4081             :     return nullptr;
    4082             : 
    4083             :   // The mask value chooses which source operand we need to look at next.
    4084       40730 :   int InVecNumElts = Op0->getType()->getVectorNumElements();
    4085             :   int RootElt = MaskVal;
    4086             :   Value *SourceOp = Op0;
    4087       20365 :   if (MaskVal >= InVecNumElts) {
    4088        2754 :     RootElt = MaskVal - InVecNumElts;
    4089             :     SourceOp = Op1;
    4090             :   }
    4091             : 
    4092             :   // If the source operand is a shuffle itself, look through it to find the
    4093             :   // matching root vector.
    4094             :   if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
    4095         645 :     return foldIdentityShuffles(
    4096             :         DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
    4097         645 :         SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
    4098             :   }
    4099             : 
    4100             :   // TODO: Look through bitcasts? What if the bitcast changes the vector element
    4101             :   // size?
    4102             : 
    4103             :   // The source operand is not a shuffle. Initialize the root vector value for
    4104             :   // this shuffle if that has not been done yet.
    4105       19720 :   if (!RootVec)
    4106             :     RootVec = SourceOp;
    4107             : 
    4108             :   // Give up as soon as a source operand does not match the existing root value.
    4109       19720 :   if (RootVec != SourceOp)
    4110             :     return nullptr;
    4111             : 
    4112             :   // The element must be coming from the same lane in the source vector
    4113             :   // (although it may have crossed lanes in intermediate shuffles).
    4114       17627 :   if (RootElt != DestElt)
    4115             :     return nullptr;
    4116             : 
    4117       11855 :   return RootVec;
    4118             : }
    4119             : 
    4120       12158 : static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
    4121             :                                         Type *RetTy, const SimplifyQuery &Q,
    4122             :                                         unsigned MaxRecurse) {
    4123       12158 :   if (isa<UndefValue>(Mask))
    4124           9 :     return UndefValue::get(RetTy);
    4125             : 
    4126       12149 :   Type *InVecTy = Op0->getType();
    4127       12149 :   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
    4128             :   unsigned InVecNumElts = InVecTy->getVectorNumElements();
    4129             : 
    4130             :   SmallVector<int, 32> Indices;
    4131       12149 :   ShuffleVectorInst::getShuffleMask(Mask, Indices);
    4132             :   assert(MaskNumElts == Indices.size() &&
    4133             :          "Size of Indices not same as number of mask elements?");
    4134             : 
    4135             :   // Canonicalization: If mask does not select elements from an input vector,
    4136             :   // replace that input vector with undef.
    4137             :   bool MaskSelects0 = false, MaskSelects1 = false;
    4138      174603 :   for (unsigned i = 0; i != MaskNumElts; ++i) {
    4139      162454 :     if (Indices[i] == -1)
    4140             :       continue;
    4141       77172 :     if ((unsigned)Indices[i] < InVecNumElts)
    4142             :       MaskSelects0 = true;
    4143             :     else
    4144             :       MaskSelects1 = true;
    4145             :   }
    4146       12149 :   if (!MaskSelects0)
    4147         247 :     Op0 = UndefValue::get(InVecTy);
    4148       12149 :   if (!MaskSelects1)
    4149        7159 :     Op1 = UndefValue::get(InVecTy);
    4150             : 
    4151             :   auto *Op0Const = dyn_cast<Constant>(Op0);
    4152             :   auto *Op1Const = dyn_cast<Constant>(Op1);
    4153             : 
    4154             :   // If all operands are constant, constant fold the shuffle.
    4155       12149 :   if (Op0Const && Op1Const)
    4156         109 :     return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
    4157             : 
    4158             :   // Canonicalization: if only one input vector is constant, it shall be the
    4159             :   // second one.
    4160       12040 :   if (Op0Const && !Op1Const) {
    4161             :     std::swap(Op0, Op1);
    4162             :     ShuffleVectorInst::commuteShuffleMask(Indices, InVecNumElts);
    4163             :   }
    4164             : 
    4165             :   // A shuffle of a splat is always the splat itself. Legal if the shuffle's
    4166             :   // value type is same as the input vectors' type.
    4167             :   if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
    4168         332 :     if (isa<UndefValue>(Op1) && RetTy == InVecTy &&
    4169          86 :         OpShuf->getMask()->getSplatValue())
    4170             :       return Op0;
    4171             : 
    4172             :   // Don't fold a shuffle with undef mask elements. This may get folded in a
    4173             :   // better way using demanded bits or other analysis.
    4174             :   // TODO: Should we allow this?
    4175       24070 :   if (find(Indices, -1) != Indices.end())
    4176             :     return nullptr;
    4177             : 
    4178             :   // Check if every element of this shuffle can be mapped back to the
    4179             :   // corresponding element of a single root vector. If so, we don't need this
    4180             :   // shuffle. This handles simple identity shuffles as well as chains of
    4181             :   // shuffles that may widen/narrow and/or move elements across lanes and back.
    4182             :   Value *RootVec = nullptr;
    4183       29748 :   for (unsigned i = 0; i != MaskNumElts; ++i) {
    4184             :     // Note that recursion is limited for each vector element, so if any element
    4185             :     // exceeds the limit, this will fail to simplify.
    4186       19730 :     RootVec =
    4187       39460 :         foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
    4188             : 
    4189             :     // We can't replace a widening/narrowing shuffle with one of its operands.
    4190       19730 :     if (!RootVec || RootVec->getType() != RetTy)
    4191             :       return nullptr;
    4192             :   }
    4193             :   return RootVec;
    4194             : }
    4195             : 
    4196             : /// Given operands for a ShuffleVectorInst, fold the result or return null.
    4197       12158 : Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
    4198             :                                        Type *RetTy, const SimplifyQuery &Q) {
    4199       12158 :   return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
    4200             : }
    4201             : 
    4202          98 : static Constant *propagateNaN(Constant *In) {
    4203             :   // If the input is a vector with undef elements, just return a default NaN.
    4204          98 :   if (!In->isNaN())
    4205           1 :     return ConstantFP::getNaN(In->getType());
    4206             : 
    4207             :   // Propagate the existing NaN constant when possible.
    4208             :   // TODO: Should we quiet a signaling NaN?
    4209             :   return In;
    4210             : }
    4211             : 
    4212       42211 : static Constant *simplifyFPBinop(Value *Op0, Value *Op1) {
    4213       84416 :   if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
    4214         224 :     return ConstantFP::getNaN(Op0->getType());
    4215             : 
    4216       41987 :   if (match(Op0, m_NaN()))
    4217          14 :     return propagateNaN(cast<Constant>(Op0));
    4218       41973 :   if (match(Op1, m_NaN()))
    4219          84 :     return propagateNaN(cast<Constant>(Op1));
    4220             : 
    4221             :   return nullptr;
    4222             : }
    4223             : 
    4224             : /// Given operands for an FAdd, see if we can fold the result.  If not, this
    4225             : /// returns null.
    4226       14795 : static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
    4227             :                                const SimplifyQuery &Q, unsigned MaxRecurse) {
    4228       14795 :   if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
    4229             :     return C;
    4230             : 
    4231       14619 :   if (Constant *C = simplifyFPBinop(Op0, Op1))
    4232             :     return C;
    4233             : 
    4234             :   // fadd X, -0 ==> X
    4235       29188 :   if (match(Op1, m_NegZeroFP()))
    4236           6 :     return Op0;
    4237             : 
    4238             :   // fadd X, 0 ==> X, when we know X is not -0
    4239       44060 :   if (match(Op1, m_PosZeroFP()) &&
    4240         262 :       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
    4241          39 :     return Op0;
    4242             : 
    4243             :   // With nnan: (+/-0.0 - X) + X --> 0.0 (and commuted variant)
    4244             :   // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
    4245             :   // Negative zeros are allowed because we always end up with positive zero:
    4246             :   // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
    4247             :   // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
    4248             :   // X =  0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
    4249             :   // X =  0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
    4250       32269 :   if (FMF.noNaNs() && (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
    4251       16133 :                        match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0)))))
    4252           6 :     return ConstantFP::getNullValue(Op0->getType());
    4253             : 
    4254             :   return nullptr;
    4255             : }
    4256             : 
    4257             : /// Given operands for an FSub, see if we can fold the result.  If not, this
    4258             : /// returns null.
    4259        8657 : static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
    4260             :                                const SimplifyQuery &Q, unsigned MaxRecurse) {
    4261        8657 :   if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
    4262             :     return C;
    4263             : 
    4264        8514 :   if (Constant *C = simplifyFPBinop(Op0, Op1))
    4265             :     return C;
    4266             : 
    4267             :   // fsub X, +0 ==> X
    4268       16730 :   if (match(Op1, m_PosZeroFP()))
    4269           8 :     return Op0;
    4270             : 
    4271             :   // fsub X, -0 ==> X, when we know X is not -0
    4272       25072 :   if (match(Op1, m_NegZeroFP()) &&
    4273           0 :       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
    4274           1 :     return Op0;
    4275             : 
    4276             :   // fsub -0.0, (fsub -0.0, X) ==> X
    4277             :   Value *X;
    4278       29075 :   if (match(Op0, m_NegZeroFP()) &&
    4279       12363 :       match(Op1, m_FSub(m_NegZeroFP(), m_Value(X))))
    4280          31 :     return X;
    4281             : 
    4282             :   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
    4283       18437 :   if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
    4284        8632 :       match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))))
    4285           3 :     return X;
    4286             : 
    4287             :   // fsub nnan x, x ==> 0.0
    4288        8990 :   if (FMF.noNaNs() && Op0 == Op1)
    4289           1 :     return Constant::getNullValue(Op0->getType());
    4290             : 
    4291             :   return nullptr;
    4292             : }
    4293             : 
    4294             : /// Given the operands for an FMul, see if we can fold the result
    4295       15500 : static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
    4296             :                                const SimplifyQuery &Q, unsigned MaxRecurse) {
    4297       15500 :   if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
    4298             :     return C;
    4299             : 
    4300       15271 :   if (Constant *C = simplifyFPBinop(Op0, Op1))
    4301             :     return C;
    4302             : 
    4303             :   // fmul X, 1.0 ==> X
    4304       30278 :   if (match(Op1, m_FPOne()))
    4305          23 :     return Op0;
    4306             : 
    4307             :   // fmul nnan nsz X, 0 ==> 0
    4308       36017 :   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
    4309          15 :     return ConstantFP::getNullValue(Op0->getType());
    4310             : 
    4311             :   // sqrt(X) * sqrt(X) --> X, if we can:
    4312             :   // 1. Remove the intermediate rounding (reassociate).
    4313             :   // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
    4314             :   // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
    4315             :   Value *X;
    4316       31701 :   if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
    4317       15108 :       FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
    4318           2 :     return X;
    4319             : 
    4320             :   return nullptr;
    4321             : }
    4322             : 
    4323       14190 : Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
    4324             :                               const SimplifyQuery &Q) {
    4325       14190 :   return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
    4326             : }
    4327             : 
    4328             : 
    4329        8576 : Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
    4330             :                               const SimplifyQuery &Q) {
    4331        8576 :   return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
    4332             : }
    4333             : 
    4334       13841 : Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
    4335             :                               const SimplifyQuery &Q) {
    4336       13841 :   return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
    4337             : }
    4338             : 
    4339        3700 : static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
    4340             :                                const SimplifyQuery &Q, unsigned) {
    4341        3700 :   if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
    4342             :     return C;
    4343             : 
    4344        3688 :   if (Constant *C = simplifyFPBinop(Op0, Op1))
    4345             :     return C;
    4346             : 
    4347             :   // X / 1.0 -> X
    4348        7360 :   if (match(Op1, m_FPOne()))
    4349           2 :     return Op0;
    4350             : 
    4351             :   // 0 / X -> 0
    4352             :   // Requires that NaNs are off (X could be zero) and signed zeroes are
    4353             :   // ignored (X could be positive or negative, so the output sign is unknown).
    4354        9628 :   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
    4355           2 :     return ConstantFP::getNullValue(Op0->getType());
    4356             : 
    4357        3676 :   if (FMF.noNaNs()) {
    4358             :     // X / X -> 1.0 is legal when NaNs are ignored.
    4359             :     // We can ignore infinities because INF/INF is NaN.
    4360        1151 :     if (Op0 == Op1)
    4361           8 :       return ConstantFP::get(Op0->getType(), 1.0);
    4362             : 
    4363             :     // (X * Y) / Y --> X if we can reassociate to the above form.
    4364             :     Value *X;
    4365        2263 :     if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
    4366           2 :       return X;
    4367             : 
    4368             :     // -X /  X -> -1.0 and
    4369             :     //  X / -X -> -1.0 are legal when NaNs are ignored.
    4370             :     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
    4371        1187 :     if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
    4372        2333 :          BinaryOperator::getFNegArgument(Op0) == Op1) ||
    4373        1162 :         (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
    4374          16 :          BinaryOperator::getFNegArgument(Op1) == Op0))
    4375           4 :       return ConstantFP::get(Op0->getType(), -1.0);
    4376             :   }
    4377             : 
    4378             :   return nullptr;
    4379             : }
    4380             : 
    4381        3595 : Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
    4382             :                               const SimplifyQuery &Q) {
    4383        3595 :   return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
    4384             : }
    4385             : 
    4386         127 : static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
    4387             :                                const SimplifyQuery &Q, unsigned) {
    4388         127 :   if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
    4389             :     return C;
    4390             : 
    4391         119 :   if (Constant *C = simplifyFPBinop(Op0, Op1))
    4392             :     return C;
    4393             : 
    4394             :   // Unlike fdiv, the result of frem always matches the sign of the dividend.
    4395             :   // The constant match may include undef elements in a vector, so return a full
    4396             :   // zero constant as the result.
    4397         111 :   if (FMF.noNaNs()) {
    4398             :     // +0 % X -> 0
    4399          16 :     if (match(Op0, m_PosZeroFP()))
    4400           2 :       return ConstantFP::getNullValue(Op0->getType());
    4401             :     // -0 % X -> -0
    4402          12 :     if (match(Op0, m_NegZeroFP()))
    4403           2 :       return ConstantFP::getNegativeZero(Op0->getType());
    4404             :   }
    4405             : 
    4406             :   return nullptr;
    4407             : }
    4408             : 
    4409         127 : Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
    4410             :                               const SimplifyQuery &Q) {
    4411         127 :   return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
    4412             : }
    4413             : 
    4414             : //=== Helper functions for higher up the class hierarchy.
    4415             : 
    4416             : /// Given operands for a BinaryOperator, see if we can fold the result.
    4417             : /// If not, this returns null.
    4418     2824367 : static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
    4419             :                             const SimplifyQuery &Q, unsigned MaxRecurse) {
    4420     2824367 :   switch (Opcode) {
    4421     2504361 :   case Instruction::Add:
    4422     2504361 :     return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
    4423       35299 :   case Instruction::Sub:
    4424       35299 :     return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
    4425       58858 :   case Instruction::Mul:
    4426       58858 :     return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
    4427        3421 :   case Instruction::SDiv:
    4428        3421 :     return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
    4429        4066 :   case Instruction::UDiv:
    4430        4066 :     return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
    4431         284 :   case Instruction::SRem:
    4432         284 :     return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
    4433        2910 :   case Instruction::URem:
    4434        2910 :     return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
    4435       27637 :   case Instruction::Shl:
    4436       27637 :     return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
    4437       11399 :   case Instruction::LShr:
    4438       11399 :     return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
    4439        8865 :   case Instruction::AShr:
    4440        8865 :     return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
    4441       61466 :   case Instruction::And:
    4442       61466 :     return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
    4443       74966 :   case Instruction::Or:
    4444       74966 :     return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
    4445       28780 :   case Instruction::Xor:
    4446       28780 :     return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
    4447         519 :   case Instruction::FAdd:
    4448         519 :     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
    4449          14 :   case Instruction::FSub:
    4450          14 :     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
    4451        1513 :   case Instruction::FMul:
    4452        1513 :     return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
    4453           9 :   case Instruction::FDiv:
    4454           9 :     return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
    4455           0 :   case Instruction::FRem:
    4456           0 :     return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
    4457           0 :   default:
    4458           0 :     llvm_unreachable("Unexpected opcode");
    4459             :   }
    4460             : }
    4461             : 
    4462             : /// Given operands for a BinaryOperator, see if we can fold the result.
    4463             : /// If not, this returns null.
    4464             : /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
    4465             : /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
    4466         395 : static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
    4467             :                               const FastMathFlags &FMF, const SimplifyQuery &Q,
    4468             :                               unsigned MaxRecurse) {
    4469         395 :   switch (Opcode) {
    4470          86 :   case Instruction::FAdd:
    4471          86 :     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
    4472          67 :   case Instruction::FSub:
    4473          67 :     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
    4474         146 :   case Instruction::FMul:
    4475         146 :     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
    4476          96 :   case Instruction::FDiv:
    4477          96 :     return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
    4478           0 :   default:
    4479           0 :     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
    4480             :   }
    4481             : }
    4482             : 
    4483     2379947 : Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
    4484             :                            const SimplifyQuery &Q) {
    4485     2379947 :   return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
    4486             : }
    4487             : 
    4488         395 : Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
    4489             :                              FastMathFlags FMF, const SimplifyQuery &Q) {
    4490         395 :   return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
    4491             : }
    4492             : 
    4493             : /// Given operands for a CmpInst, see if we can fold the result.
    4494       94784 : static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
    4495             :                               const SimplifyQuery &Q, unsigned MaxRecurse) {
    4496       94784 :   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
    4497       94379 :     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
    4498         405 :   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
    4499             : }
    4500             : 
    4501        8469 : Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
    4502             :                              const SimplifyQuery &Q) {
    4503        8469 :   return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
    4504             : }
    4505             : 
    4506             : static bool IsIdempotent(Intrinsic::ID ID) {
    4507       26020 :   switch (ID) {
    4508             :   default: return false;
    4509             : 
    4510             :   // Unary idempotent: f(f(x)) = f(x)
    4511             :   case Intrinsic::fabs:
    4512             :   case Intrinsic::floor:
    4513             :   case Intrinsic::ceil:
    4514             :   case Intrinsic::trunc:
    4515             :   case Intrinsic::rint:
    4516             :   case Intrinsic::nearbyint:
    4517             :   case Intrinsic::round:
    4518             :   case Intrinsic::canonicalize:
    4519             :     return true;
    4520             :   }
    4521             : }
    4522             : 
    4523           9 : static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
    4524             :                                    const DataLayout &DL) {
    4525             :   GlobalValue *PtrSym;
    4526             :   APInt PtrOffset;
    4527           9 :   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
    4528             :     return nullptr;
    4529             : 
    4530           8 :   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
    4531           8 :   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
    4532           8 :   Type *Int32PtrTy = Int32Ty->getPointerTo();
    4533           8 :   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
    4534             : 
    4535             :   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
    4536           8 :   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
    4537             :     return nullptr;
    4538             : 
    4539           8 :   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
    4540           8 :   if (OffsetInt % 4 != 0)
    4541             :     return nullptr;
    4542             : 
    4543          14 :   Constant *C = ConstantExpr::getGetElementPtr(
    4544             :       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
    4545           7 :       ConstantInt::get(Int64Ty, OffsetInt / 4));
    4546           7 :   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
    4547           7 :   if (!Loaded)
    4548             :     return nullptr;
    4549             : 
    4550             :   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
    4551             :   if (!LoadedCE)
    4552             :     return nullptr;
    4553             : 
    4554           7 :   if (LoadedCE->getOpcode() == Instruction::Trunc) {
    4555             :     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
    4556             :     if (!LoadedCE)
    4557             :       return nullptr;
    4558             :   }
    4559             : 
    4560           7 :   if (LoadedCE->getOpcode() != Instruction::Sub)
    4561             :     return nullptr;
    4562             : 
    4563             :   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
    4564           5 :   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
    4565             :     return nullptr;
    4566             :   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
    4567             : 
    4568             :   Constant *LoadedRHS = LoadedCE->getOperand(1);
    4569             :   GlobalValue *LoadedRHSSym;
    4570             :   APInt LoadedRHSOffset;
    4571           5 :   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
    4572           4 :                                   DL) ||
    4573           9 :       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
    4574             :     return nullptr;
    4575             : 
    4576           4 :   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
    4577             : }
    4578             : 
    4579         724 : static bool maskIsAllZeroOrUndef(Value *Mask) {
    4580             :   auto *ConstMask = dyn_cast<Constant>(Mask);
    4581             :   if (!ConstMask)
    4582             :     return false;
    4583          32 :   if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
    4584             :     return true;
    4585          58 :   for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
    4586             :        ++I) {
    4587          29 :     if (auto *MaskElt = ConstMask->getAggregateElement(I))
    4588          42 :       if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
    4589             :         continue;
    4590             :     return false;
    4591             :   }
    4592             :   return true;
    4593             : }
    4594             : 
    4595             : template <typename IterTy>
    4596     1358433 : static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
    4597             :                                 const SimplifyQuery &Q, unsigned MaxRecurse) {
    4598     1358433 :   Intrinsic::ID IID = F->getIntrinsicID();
    4599     1358433 :   unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
    4600             : 
    4601             :   // Unary Ops
    4602     1358433 :   if (NumOperands == 1) {
    4603             :     // Perform idempotent optimizations
    4604             :     if (IsIdempotent(IID)) {
    4605           0 :       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) {
    4606         505 :         if (II->getIntrinsicID() == IID)
    4607             :           return II;
    4608             :       }
    4609             :     }
    4610             : 
    4611       26001 :     Value *IIOperand = *ArgBegin;
    4612             :     Value *X;
    4613       26001 :     switch (IID) {
    4614        2690 :     case Intrinsic::fabs: {
    4615        2690 :       if (SignBitMustBeZero(IIOperand, Q.TLI))
    4616             :         return IIOperand;
    4617             :       return nullptr;
    4618             :     }
    4619             :     case Intrinsic::bswap: {
    4620             :       // bswap(bswap(x)) -> x
    4621         848 :       if (match(IIOperand, m_BSwap(m_Value(X))))
    4622           1 :         return X;
    4623             :       return nullptr;
    4624             :     }
    4625             :     case Intrinsic::bitreverse: {
    4626             :       // bitreverse(bitreverse(x)) -> x
    4627         284 :       if (match(IIOperand, m_BitReverse(m_Value(X))))
    4628           2 :         return X;
    4629             :       return nullptr;
    4630             :     }
    4631          25 :     case Intrinsic::exp: {
    4632             :       // exp(log(x)) -> x
    4633          29 :       if (Q.CxtI->hasAllowReassoc() &&
    4634          22 :           match(IIOperand, m_Intrinsic<Intrinsic::log>(m_Value(X))))
    4635           3 :         return X;
    4636             :       return nullptr;
    4637             :     }
    4638         122 :     case Intrinsic::exp2: {
    4639             :       // exp2(log2(x)) -> x
    4640         126 :       if (Q.CxtI->hasAllowReassoc() &&
    4641         119 :           match(IIOperand, m_Intrinsic<Intrinsic::log2>(m_Value(X))))
    4642           3 :         return X;
    4643             :       return nullptr;
    4644             :     }
    4645          75 :     case Intrinsic::log: {
    4646             :       // log(exp(x)) -> x
    4647          79 :       if (Q.CxtI->hasAllowReassoc() &&
    4648          72 :           match(IIOperand, m_Intrinsic<Intrinsic::exp>(m_Value(X))))
    4649           3 :         return X;
    4650             :       return nullptr;
    4651             :     }
    4652          75 :     case Intrinsic::log2: {
    4653             :       // log2(exp2(x)) -> x
    4654          83 :       if (Q.CxtI->hasAllowReassoc() &&
    4655          72 :           match(IIOperand, m_Intrinsic<Intrinsic::exp2>(m_Value(X)))) {
    4656           3 :         return X;
    4657             :       }
    4658             :       return nullptr;
    4659             :     }
    4660             :     default:
    4661             :       return nullptr;
    4662             :     }
    4663             :   }
    4664             : 
    4665             :   // Binary Ops
    4666     1332413 :   if (NumOperands == 2) {
    4667      809362 :     Value *LHS = *ArgBegin;
    4668      809362 :     Value *RHS = *(ArgBegin + 1);
    4669             :     Type *ReturnType = F->getReturnType();
    4670             : 
    4671      809362 :     switch (IID) {
    4672         525 :     case Intrinsic::usub_with_overflow:
    4673             :     case Intrinsic::ssub_with_overflow: {
    4674             :       // X - X -> { 0, false }
    4675         525 :       if (LHS == RHS)
    4676           4 :         return Constant::getNullValue(ReturnType);
    4677             : 
    4678             :       // X - undef -> undef
    4679             :       // undef - X -> undef
    4680        1038 :       if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
    4681           8 :         return UndefValue::get(ReturnType);
    4682             : 
    4683             :       return nullptr;
    4684             :     }
    4685         547 :     case Intrinsic::uadd_with_overflow:
    4686             :     case Intrinsic::sadd_with_overflow: {
    4687             :       // X + undef -> undef
    4688        1089 :       if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
    4689           9 :         return UndefValue::get(ReturnType);
    4690             : 
    4691             :       return nullptr;
    4692             :     }
    4693             :     case Intrinsic::umul_with_overflow:
    4694             :     case Intrinsic::smul_with_overflow: {
    4695             :       // 0 * X -> { 0, false }
    4696             :       // X * 0 -> { 0, false }
    4697         181 :       if (match(LHS, m_Zero()) || match(RHS, m_Zero()))
    4698           9 :         return Constant::getNullValue(ReturnType);
    4699             : 
    4700             :       // undef * X -> { 0, false }
    4701             :       // X * undef -> { 0, false }
    4702         164 :       if (match(LHS, m_Undef()) || match(RHS, m_Undef()))
    4703           8 :         return Constant::getNullValue(ReturnType);
    4704             : 
    4705             :       return nullptr;
    4706             :     }
    4707           9 :     case Intrinsic::load_relative: {
    4708             :       Constant *C0 = dyn_cast<Constant>(LHS);
    4709             :       Constant *C1 = dyn_cast<Constant>(RHS);
    4710           9 :       if (C0 && C1)
    4711           9 :         return SimplifyRelativeLoad(C0, C1, Q.DL);
    4712             :       return nullptr;
    4713             :     }
    4714          20 :     case Intrinsic::powi:
    4715             :       if (ConstantInt *Power = dyn_cast<ConstantInt>(RHS)) {
    4716             :         // powi(x, 0) -> 1.0
    4717          11 :         if (Power->isZero())
    4718           1 :           return ConstantFP::get(LHS->getType(), 1.0);
    4719             :         // powi(x, 1) -> x
    4720          10 :         if (Power->isOne())
    4721             :           return LHS;
    4722             :       }
    4723             :       return nullptr;
    4724             :     default:
    4725             :       return nullptr;
    4726             :     }
    4727             :   }
    4728             : 
    4729             :   // Simplify calls to llvm.masked.load.*
    4730      523051 :   switch (IID) {
    4731         724 :   case Intrinsic::masked_load: {
    4732         724 :     Value *MaskArg = ArgBegin[2];
    4733         724 :     Value *PassthruArg = ArgBegin[3];
    4734             :     // If the mask is all zeros or undef, the "passthru" argument is the result.
    4735         724 :     if (maskIsAllZeroOrUndef(MaskArg))
    4736             :       return PassthruArg;
    4737             :     return nullptr;
    4738             :   }
    4739             :   default:
    4740             :     return nullptr;
    4741             :   }
    4742             : }
    4743             : 
    4744             : template <typename IterTy>
    4745     3525238 : static Value *SimplifyCall(ImmutableCallSite CS, Value *V, IterTy ArgBegin,
    4746             :                            IterTy ArgEnd, const SimplifyQuery &Q,
    4747             :                            unsigned MaxRecurse) {
    4748     3525238 :   Type *Ty = V->getType();
    4749             :   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
    4750     3525238 :     Ty = PTy->getElementType();
    4751             :   FunctionType *FTy = cast<FunctionType>(Ty);
    4752             : 
    4753             :   // call undef -> undef
    4754             :   // call null -> undef
    4755     3525238 :   if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
    4756          36 :     return UndefValue::get(FTy->getReturnType());
    4757             : 
    4758             :   Function *F = dyn_cast<Function>(V);
    4759             :   if (!F)
    4760             :     return nullptr;
    4761             : 
    4762     3498387 :   if (F->isIntrinsic())
    4763     1358433 :     if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
    4764             :       return Ret;
    4765             : 
    4766     3498267 :   if (!canConstantFoldCallTo(CS, F))
    4767             :     return nullptr;
    4768             : 
    4769             :   SmallVector<Constant *, 4> ConstantArgs;
    4770       25882 :   ConstantArgs.reserve(ArgEnd - ArgBegin);
    4771       28164 :   for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
    4772       26759 :     Constant *C = dyn_cast<Constant>(*I);
    4773       26759 :     if (!C)
    4774       25618 :       return nullptr;
    4775        1141 :     ConstantArgs.push_back(C);
    4776             :   }
    4777             : 
    4778         528 :   return ConstantFoldCall(CS, F, ConstantArgs, Q.TLI);
    4779             : }
    4780             : 
    4781           0 : Value *llvm::SimplifyCall(ImmutableCallSite CS, Value *V,
    4782             :                           User::op_iterator ArgBegin, User::op_iterator ArgEnd,
    4783             :                           const SimplifyQuery &Q) {
    4784           0 :   return ::SimplifyCall(CS, V, ArgBegin, ArgEnd, Q, RecursionLimit);
    4785             : }
    4786             : 
    4787           0 : Value *llvm::SimplifyCall(ImmutableCallSite CS, Value *V,
    4788             :                           ArrayRef<Value *> Args, const SimplifyQuery &Q) {
    4789           0 :   return ::SimplifyCall(CS, V, Args.begin(), Args.end(), Q, RecursionLimit);
    4790             : }
    4791             : 
    4792     3525238 : Value *llvm::SimplifyCall(ImmutableCallSite ICS, const SimplifyQuery &Q) {
    4793             :   CallSite CS(const_cast<Instruction*>(ICS.getInstruction()));
    4794     7050476 :   return ::SimplifyCall(CS, CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
    4795     7050476 :                         Q, RecursionLimit);
    4796             : }
    4797             : 
    4798             : /// See if we can compute a simplified version of this instruction.
    4799             : /// If not, this returns null.
    4800             : 
    4801    13836735 : Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
    4802             :                                  OptimizationRemarkEmitter *ORE) {
    4803    13836735 :   const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
    4804             :   Value *Result;
    4805             : 
    4806    13836735 :   switch (I->getOpcode()) {
    4807     6475062 :   default:
    4808     6475062 :     Result = ConstantFoldInstruction(I, Q.DL, Q.TLI);
    4809     6475062 :     break;
    4810       10116 :   case Instruction::FAdd:
    4811       20232 :     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
    4812             :                               I->getFastMathFlags(), Q);
    4813       10116 :     break;
    4814             :   case Instruction::Add:
    4815     4715451 :     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
    4816     1571817 :                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
    4817     1571817 :                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q);
    4818     1571817 :     break;
    4819        6265 :   case Instruction::FSub:
    4820       12530 :     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
    4821             :                               I->getFastMathFlags(), Q);
    4822        6265 :     break;
    4823             :   case Instruction::Sub:
    4824       66882 :     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
    4825       22294 :                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
    4826       22294 :                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q);
    4827       22294 :     break;
    4828        9118 :   case Instruction::FMul:
    4829       18236 :     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
    4830             :                               I->getFastMathFlags(), Q);
    4831        9118 :     break;
    4832        9416 :   case Instruction::Mul:
    4833       18832 :     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q);
    4834        9416 :     break;
    4835        2719 :   case Instruction::SDiv:
    4836        5438 :     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q);
    4837        2719 :     break;
    4838        1695 :   case Instruction::UDiv:
    4839        3390 :     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q);
    4840        1695 :     break;
    4841        2211 :   case Instruction::FDiv:
    4842        4422 :     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
    4843             :                               I->getFastMathFlags(), Q);
    4844        2211 :     break;
    4845         641 :   case Instruction::SRem:
    4846        1282 :     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q);
    4847         641 :     break;
    4848        1890 :   case Instruction::URem:
    4849        3780 :     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q);
    4850        1890 :     break;
    4851          95 :   case Instruction::FRem:
    4852         190 :     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
    4853             :                               I->getFastMathFlags(), Q);
    4854          95 :     break;
    4855             :   case Instruction::Shl:
    4856       42321 :     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
    4857       14107 :                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
    4858       14107 :                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q);
    4859       14107 :     break;
    4860             :   case Instruction::LShr:
    4861       21416 :     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
    4862       10708 :                               cast<BinaryOperator>(I)->isExact(), Q);
    4863       10708 :     break;
    4864             :   case Instruction::AShr:
    4865       15348 :     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
    4866        7674 :                               cast<BinaryOperator>(I)->isExact(), Q);
    4867        7674 :     break;
    4868       22493 :   case Instruction::And:
    4869       44986 :     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q);
    4870       22493 :     break;
    4871       12643 :   case Instruction::Or:
    4872       25286 :     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q);
    4873       12643 :     break;
    4874       17222 :   case Instruction::Xor:
    4875       34444 :     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q);
    4876       17222 :     break;
    4877      212555 :   case Instruction::ICmp:
    4878      425110 :     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
    4879             :                               I->getOperand(0), I->getOperand(1), Q);
    4880      212555 :     break;
    4881        4138 :   case Instruction::FCmp:
    4882        4138 :     Result =
    4883        4138 :         SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
    4884             :                          I->getOperand(1), I->getFastMathFlags(), Q);
    4885        4138 :     break;
    4886      154819 :   case Instruction::Select:
    4887      309638 :     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
    4888             :                                 I->getOperand(2), Q);
    4889      154819 :     break;
    4890      573460 :   case Instruction::GetElementPtr: {
    4891      573460 :     SmallVector<Value *, 8> Ops(I->op_begin(), I->op_end());
    4892      573460 :     Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
    4893             :                              Ops, Q);
    4894             :     break;
    4895             :   }
    4896             :   case Instruction::InsertValue: {
    4897             :     InsertValueInst *IV = cast<InsertValueInst>(I);
    4898       21815 :     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
    4899             :                                      IV->getInsertedValueOperand(),
    4900             :                                      IV->getIndices(), Q);
    4901       21815 :     break;
    4902             :   }
    4903             :   case Instruction::InsertElement: {
    4904             :     auto *IE = cast<InsertElementInst>(I);
    4905       19687 :     Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1),
    4906             :                                        IE->getOperand(2), Q);
    4907       19687 :     break;
    4908             :   }
    4909             :   case Instruction::ExtractValue: {
    4910             :     auto *EVI = cast<ExtractValueInst>(I);
    4911      208800 :     Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
    4912             :                                       EVI->getIndices(), Q);
    4913      208800 :     break;
    4914             :   }
    4915             :   case Instruction::ExtractElement: {
    4916             :     auto *EEI = cast<ExtractElementInst>(I);
    4917       12963 :     Result = SimplifyExtractElementInst(EEI->getVectorOperand(),
    4918             :                                         EEI->getIndexOperand(), Q);
    4919       12963 :     break;
    4920             :   }
    4921             :   case Instruction::ShuffleVector: {
    4922             :     auto *SVI = cast<ShuffleVectorInst>(I);
    4923        5892 :     Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
    4924             :                                        SVI->getMask(), SVI->getType(), Q);
    4925        5892 :     break;
    4926             :   }
    4927             :   case Instruction::PHI:
    4928     2124319 :     Result = SimplifyPHINode(cast<PHINode>(I), Q);
    4929     2124319 :     break;
    4930             :   case Instruction::Call: {
    4931             :     CallSite CS(cast<CallInst>(I));
    4932     1231830 :     Result = SimplifyCall(CS, Q);
    4933             :     break;
    4934             :   }
    4935             : #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
    4936             : #include "llvm/IR/Instruction.def"
    4937             : #undef HANDLE_CAST_INST
    4938      779303 :     Result =
    4939      779303 :         SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q);
    4940      779303 :     break;
    4941             :   case Instruction::Alloca:
    4942             :     // No simplifications for Alloca and it can't be constant folded.
    4943             :     Result = nullptr;
    4944             :     break;
    4945             :   }
    4946             : 
    4947             :   // In general, it is possible for computeKnownBits to determine all bits in a
    4948             :   // value even when the operands are not all constants.
    4949    27283635 :   if (!Result && I->getType()->isIntOrIntVectorTy()) {
    4950     9267832 :     KnownBits Known = computeKnownBits(I, Q.DL, /*Depth*/ 0, Q.AC, I, Q.DT, ORE);
    4951     4633916 :     if (Known.isConstant())
    4952         107 :       Result = ConstantInt::get(I->getType(), Known.getConstant());
    4953             :   }
    4954             : 
    4955             :   /// If called on unreachable code, the above logic may report that the
    4956             :   /// instruction simplified to itself.  Make life easier for users by
    4957             :   /// detecting that case here, returning a safe value instead.
    4958    13836735 :   return Result == I ? UndefValue::get(I->getType()) : Result;
    4959             : }
    4960             : 
    4961             : /// Implementation of recursive simplification through an instruction's
    4962             : /// uses.
    4963             : ///
    4964             : /// This is the common implementation of the recursive simplification routines.
    4965             : /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
    4966             : /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
    4967             : /// instructions to process and attempt to simplify it using
    4968             : /// InstructionSimplify.
    4969             : ///
    4970             : /// This routine returns 'true' only when *it* simplifies something. The passed
    4971             : /// in simplified value does not count toward this.
    4972          76 : static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
    4973             :                                               const TargetLibraryInfo *TLI,
    4974             :                                               const DominatorTree *DT,
    4975             :                                               AssumptionCache *AC) {
    4976             :   bool Simplified = false;
    4977             :   SmallSetVector<Instruction *, 8> Worklist;
    4978         152 :   const DataLayout &DL = I->getModule()->getDataLayout();
    4979             : 
    4980             :   // If we have an explicit value to collapse to, do that round of the
    4981             :   // simplification loop by hand initially.
    4982          76 :   if (SimpleV) {
    4983         227 :     for (User *U : I->users())
    4984          75 :       if (U != I)
    4985          75 :         Worklist.insert(cast<Instruction>(U));
    4986             : 
    4987             :     // Replace the instruction with its simplified value.
    4988          76 :     I->replaceAllUsesWith(SimpleV);
    4989             : 
    4990             :     // Gracefully handle edge cases where the instruction is not wired into any
    4991             :     // parent block.
    4992         228 :     if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
    4993          76 :         !I->mayHaveSideEffects())
    4994          76 :       I->eraseFromParent();
    4995             :   } else {
    4996           0 :     Worklist.insert(I);
    4997             :   }
    4998             : 
    4999             :   // Note that we must test the size on each iteration, the worklist can grow.
    5000         524 :   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
    5001         124 :     I = Worklist[Idx];
    5002             : 
    5003             :     // See if this instruction simplifies.
    5004         124 :     SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
    5005         124 :     if (!SimpleV)
    5006          75 :       continue;
    5007             : 
    5008             :     Simplified = true;
    5009             : 
    5010             :     // Stash away all the uses of the old instruction so we can check them for
    5011             :     // recursive simplifications after a RAUW. This is cheaper than checking all
    5012             :     // uses of To on the recursive step in most cases.
    5013         147 :     for (User *U : I->users())
    5014          49 :       Worklist.insert(cast<Instruction>(U));
    5015             : 
    5016             :     // Replace the instruction with its simplified value.
    5017          49 :     I->replaceAllUsesWith(SimpleV);
    5018             : 
    5019             :     // Gracefully handle edge cases where the instruction is not wired into any
    5020             :     // parent block.
    5021         147 :     if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
    5022          49 :         !I->mayHaveSideEffects())
    5023          49 :       I->eraseFromParent();
    5024             :   }
    5025          76 :   return Simplified;
    5026             : }
    5027             : 
    5028           0 : bool llvm::recursivelySimplifyInstruction(Instruction *I,
    5029             :                                           const TargetLibraryInfo *TLI,
    5030             :                                           const DominatorTree *DT,
    5031             :                                           AssumptionCache *AC) {
    5032           0 :   return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
    5033             : }
    5034             : 
    5035          76 : bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
    5036             :                                          const TargetLibraryInfo *TLI,
    5037             :                                          const DominatorTree *DT,
    5038             :                                          AssumptionCache *AC) {
    5039             :   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
    5040             :   assert(SimpleV && "Must provide a simplified value.");
    5041          76 :   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
    5042             : }
    5043             : 
    5044             : namespace llvm {
    5045       77511 : const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
    5046       77511 :   auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
    5047       77511 :   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
    5048       77511 :   auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
    5049       77511 :   auto *TLI = TLIWP ? &TLIWP->getTLI() : nullptr;
    5050       77511 :   auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
    5051       77511 :   auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
    5052      155022 :   return {F.getParent()->getDataLayout(), TLI, DT, AC};
    5053             : }
    5054             : 
    5055          65 : const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
    5056             :                                          const DataLayout &DL) {
    5057         130 :   return {DL, &AR.TLI, &AR.DT, &AR.AC};
    5058             : }
    5059             : 
    5060             : template <class T, class... TArgs>
    5061         266 : const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
    5062             :                                          Function &F) {
    5063             :   auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
    5064             :   auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
    5065             :   auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
    5066         532 :   return {F.getParent()->getDataLayout(), TLI, DT, AC};
    5067             : }
    5068             : template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
    5069             :                                                   Function &);
    5070             : }

Generated by: LCOV version 1.13