LLVM API Documentation

InstructionSimplify.cpp
Go to the documentation of this file.
00001 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements routines for folding instructions into simpler forms
00011 // that do not require creating new instructions.  This does constant folding
00012 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
00013 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
00014 // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
00015 // simplified: This is usually true and assuming it simplifies the logic (if
00016 // they have not been simplified then results are correct but maybe suboptimal).
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #include "llvm/Analysis/InstructionSimplify.h"
00021 #include "llvm/ADT/SetVector.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/Analysis/ConstantFolding.h"
00024 #include "llvm/Analysis/MemoryBuiltins.h"
00025 #include "llvm/Analysis/ValueTracking.h"
00026 #include "llvm/IR/ConstantRange.h"
00027 #include "llvm/IR/DataLayout.h"
00028 #include "llvm/IR/Dominators.h"
00029 #include "llvm/IR/GetElementPtrTypeIterator.h"
00030 #include "llvm/IR/GlobalAlias.h"
00031 #include "llvm/IR/Operator.h"
00032 #include "llvm/IR/PatternMatch.h"
00033 #include "llvm/IR/ValueHandle.h"
00034 using namespace llvm;
00035 using namespace llvm::PatternMatch;
00036 
00037 #define DEBUG_TYPE "instsimplify"
00038 
00039 enum { RecursionLimit = 3 };
00040 
00041 STATISTIC(NumExpand,  "Number of expansions");
00042 STATISTIC(NumReassoc, "Number of reassociations");
00043 
00044 namespace {
00045 struct Query {
00046   const DataLayout *DL;
00047   const TargetLibraryInfo *TLI;
00048   const DominatorTree *DT;
00049   AssumptionTracker *AT;
00050   const Instruction *CxtI;
00051 
00052   Query(const DataLayout *DL, const TargetLibraryInfo *tli,
00053         const DominatorTree *dt, AssumptionTracker *at = nullptr,
00054         const Instruction *cxti = nullptr)
00055     : DL(DL), TLI(tli), DT(dt), AT(at), CxtI(cxti) {}
00056 };
00057 } // end anonymous namespace
00058 
00059 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
00060 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
00061                             unsigned);
00062 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
00063                               unsigned);
00064 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
00065 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
00066 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
00067 
00068 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
00069 /// a vector with every element false, as appropriate for the type.
00070 static Constant *getFalse(Type *Ty) {
00071   assert(Ty->getScalarType()->isIntegerTy(1) &&
00072          "Expected i1 type or a vector of i1!");
00073   return Constant::getNullValue(Ty);
00074 }
00075 
00076 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
00077 /// a vector with every element true, as appropriate for the type.
00078 static Constant *getTrue(Type *Ty) {
00079   assert(Ty->getScalarType()->isIntegerTy(1) &&
00080          "Expected i1 type or a vector of i1!");
00081   return Constant::getAllOnesValue(Ty);
00082 }
00083 
00084 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
00085 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
00086                           Value *RHS) {
00087   CmpInst *Cmp = dyn_cast<CmpInst>(V);
00088   if (!Cmp)
00089     return false;
00090   CmpInst::Predicate CPred = Cmp->getPredicate();
00091   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
00092   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
00093     return true;
00094   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
00095     CRHS == LHS;
00096 }
00097 
00098 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
00099 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
00100   Instruction *I = dyn_cast<Instruction>(V);
00101   if (!I)
00102     // Arguments and constants dominate all instructions.
00103     return true;
00104 
00105   // If we are processing instructions (and/or basic blocks) that have not been
00106   // fully added to a function, the parent nodes may still be null. Simply
00107   // return the conservative answer in these cases.
00108   if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
00109     return false;
00110 
00111   // If we have a DominatorTree then do a precise test.
00112   if (DT) {
00113     if (!DT->isReachableFromEntry(P->getParent()))
00114       return true;
00115     if (!DT->isReachableFromEntry(I->getParent()))
00116       return false;
00117     return DT->dominates(I, P);
00118   }
00119 
00120   // Otherwise, if the instruction is in the entry block, and is not an invoke,
00121   // then it obviously dominates all phi nodes.
00122   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
00123       !isa<InvokeInst>(I))
00124     return true;
00125 
00126   return false;
00127 }
00128 
00129 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
00130 /// it into "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
00131 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
00132 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
00133 /// Returns the simplified value, or null if no simplification was performed.
00134 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
00135                           unsigned OpcToExpand, const Query &Q,
00136                           unsigned MaxRecurse) {
00137   Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
00138   // Recursion is always used, so bail out at once if we already hit the limit.
00139   if (!MaxRecurse--)
00140     return nullptr;
00141 
00142   // Check whether the expression has the form "(A op' B) op C".
00143   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
00144     if (Op0->getOpcode() == OpcodeToExpand) {
00145       // It does!  Try turning it into "(A op C) op' (B op C)".
00146       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
00147       // Do "A op C" and "B op C" both simplify?
00148       if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
00149         if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
00150           // They do! Return "L op' R" if it simplifies or is already available.
00151           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
00152           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
00153                                      && L == B && R == A)) {
00154             ++NumExpand;
00155             return LHS;
00156           }
00157           // Otherwise return "L op' R" if it simplifies.
00158           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
00159             ++NumExpand;
00160             return V;
00161           }
00162         }
00163     }
00164 
00165   // Check whether the expression has the form "A op (B op' C)".
00166   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
00167     if (Op1->getOpcode() == OpcodeToExpand) {
00168       // It does!  Try turning it into "(A op B) op' (A op C)".
00169       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
00170       // Do "A op B" and "A op C" both simplify?
00171       if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
00172         if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
00173           // They do! Return "L op' R" if it simplifies or is already available.
00174           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
00175           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
00176                                      && L == C && R == B)) {
00177             ++NumExpand;
00178             return RHS;
00179           }
00180           // Otherwise return "L op' R" if it simplifies.
00181           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
00182             ++NumExpand;
00183             return V;
00184           }
00185         }
00186     }
00187 
00188   return nullptr;
00189 }
00190 
00191 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
00192 /// operations.  Returns the simpler value, or null if none was found.
00193 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
00194                                        const Query &Q, unsigned MaxRecurse) {
00195   Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
00196   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
00197 
00198   // Recursion is always used, so bail out at once if we already hit the limit.
00199   if (!MaxRecurse--)
00200     return nullptr;
00201 
00202   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
00203   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
00204 
00205   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
00206   if (Op0 && Op0->getOpcode() == Opcode) {
00207     Value *A = Op0->getOperand(0);
00208     Value *B = Op0->getOperand(1);
00209     Value *C = RHS;
00210 
00211     // Does "B op C" simplify?
00212     if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
00213       // It does!  Return "A op V" if it simplifies or is already available.
00214       // If V equals B then "A op V" is just the LHS.
00215       if (V == B) return LHS;
00216       // Otherwise return "A op V" if it simplifies.
00217       if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
00218         ++NumReassoc;
00219         return W;
00220       }
00221     }
00222   }
00223 
00224   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
00225   if (Op1 && Op1->getOpcode() == Opcode) {
00226     Value *A = LHS;
00227     Value *B = Op1->getOperand(0);
00228     Value *C = Op1->getOperand(1);
00229 
00230     // Does "A op B" simplify?
00231     if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
00232       // It does!  Return "V op C" if it simplifies or is already available.
00233       // If V equals B then "V op C" is just the RHS.
00234       if (V == B) return RHS;
00235       // Otherwise return "V op C" if it simplifies.
00236       if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
00237         ++NumReassoc;
00238         return W;
00239       }
00240     }
00241   }
00242 
00243   // The remaining transforms require commutativity as well as associativity.
00244   if (!Instruction::isCommutative(Opcode))
00245     return nullptr;
00246 
00247   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
00248   if (Op0 && Op0->getOpcode() == Opcode) {
00249     Value *A = Op0->getOperand(0);
00250     Value *B = Op0->getOperand(1);
00251     Value *C = RHS;
00252 
00253     // Does "C op A" simplify?
00254     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
00255       // It does!  Return "V op B" if it simplifies or is already available.
00256       // If V equals A then "V op B" is just the LHS.
00257       if (V == A) return LHS;
00258       // Otherwise return "V op B" if it simplifies.
00259       if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
00260         ++NumReassoc;
00261         return W;
00262       }
00263     }
00264   }
00265 
00266   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
00267   if (Op1 && Op1->getOpcode() == Opcode) {
00268     Value *A = LHS;
00269     Value *B = Op1->getOperand(0);
00270     Value *C = Op1->getOperand(1);
00271 
00272     // Does "C op A" simplify?
00273     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
00274       // It does!  Return "B op V" if it simplifies or is already available.
00275       // If V equals C then "B op V" is just the RHS.
00276       if (V == C) return RHS;
00277       // Otherwise return "B op V" if it simplifies.
00278       if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
00279         ++NumReassoc;
00280         return W;
00281       }
00282     }
00283   }
00284 
00285   return nullptr;
00286 }
00287 
00288 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
00289 /// instruction as an operand, try to simplify the binop by seeing whether
00290 /// evaluating it on both branches of the select results in the same value.
00291 /// Returns the common value if so, otherwise returns null.
00292 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
00293                                     const Query &Q, unsigned MaxRecurse) {
00294   // Recursion is always used, so bail out at once if we already hit the limit.
00295   if (!MaxRecurse--)
00296     return nullptr;
00297 
00298   SelectInst *SI;
00299   if (isa<SelectInst>(LHS)) {
00300     SI = cast<SelectInst>(LHS);
00301   } else {
00302     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
00303     SI = cast<SelectInst>(RHS);
00304   }
00305 
00306   // Evaluate the BinOp on the true and false branches of the select.
00307   Value *TV;
00308   Value *FV;
00309   if (SI == LHS) {
00310     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
00311     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
00312   } else {
00313     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
00314     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
00315   }
00316 
00317   // If they simplified to the same value, then return the common value.
00318   // If they both failed to simplify then return null.
00319   if (TV == FV)
00320     return TV;
00321 
00322   // If one branch simplified to undef, return the other one.
00323   if (TV && isa<UndefValue>(TV))
00324     return FV;
00325   if (FV && isa<UndefValue>(FV))
00326     return TV;
00327 
00328   // If applying the operation did not change the true and false select values,
00329   // then the result of the binop is the select itself.
00330   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
00331     return SI;
00332 
00333   // If one branch simplified and the other did not, and the simplified
00334   // value is equal to the unsimplified one, return the simplified value.
00335   // For example, select (cond, X, X & Z) & Z -> X & Z.
00336   if ((FV && !TV) || (TV && !FV)) {
00337     // Check that the simplified value has the form "X op Y" where "op" is the
00338     // same as the original operation.
00339     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
00340     if (Simplified && Simplified->getOpcode() == Opcode) {
00341       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
00342       // We already know that "op" is the same as for the simplified value.  See
00343       // if the operands match too.  If so, return the simplified value.
00344       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
00345       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
00346       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
00347       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
00348           Simplified->getOperand(1) == UnsimplifiedRHS)
00349         return Simplified;
00350       if (Simplified->isCommutative() &&
00351           Simplified->getOperand(1) == UnsimplifiedLHS &&
00352           Simplified->getOperand(0) == UnsimplifiedRHS)
00353         return Simplified;
00354     }
00355   }
00356 
00357   return nullptr;
00358 }
00359 
00360 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
00361 /// try to simplify the comparison by seeing whether both branches of the select
00362 /// result in the same value.  Returns the common value if so, otherwise returns
00363 /// null.
00364 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
00365                                   Value *RHS, const Query &Q,
00366                                   unsigned MaxRecurse) {
00367   // Recursion is always used, so bail out at once if we already hit the limit.
00368   if (!MaxRecurse--)
00369     return nullptr;
00370 
00371   // Make sure the select is on the LHS.
00372   if (!isa<SelectInst>(LHS)) {
00373     std::swap(LHS, RHS);
00374     Pred = CmpInst::getSwappedPredicate(Pred);
00375   }
00376   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
00377   SelectInst *SI = cast<SelectInst>(LHS);
00378   Value *Cond = SI->getCondition();
00379   Value *TV = SI->getTrueValue();
00380   Value *FV = SI->getFalseValue();
00381 
00382   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
00383   // Does "cmp TV, RHS" simplify?
00384   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
00385   if (TCmp == Cond) {
00386     // It not only simplified, it simplified to the select condition.  Replace
00387     // it with 'true'.
00388     TCmp = getTrue(Cond->getType());
00389   } else if (!TCmp) {
00390     // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
00391     // condition then we can replace it with 'true'.  Otherwise give up.
00392     if (!isSameCompare(Cond, Pred, TV, RHS))
00393       return nullptr;
00394     TCmp = getTrue(Cond->getType());
00395   }
00396 
00397   // Does "cmp FV, RHS" simplify?
00398   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
00399   if (FCmp == Cond) {
00400     // It not only simplified, it simplified to the select condition.  Replace
00401     // it with 'false'.
00402     FCmp = getFalse(Cond->getType());
00403   } else if (!FCmp) {
00404     // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
00405     // condition then we can replace it with 'false'.  Otherwise give up.
00406     if (!isSameCompare(Cond, Pred, FV, RHS))
00407       return nullptr;
00408     FCmp = getFalse(Cond->getType());
00409   }
00410 
00411   // If both sides simplified to the same value, then use it as the result of
00412   // the original comparison.
00413   if (TCmp == FCmp)
00414     return TCmp;
00415 
00416   // The remaining cases only make sense if the select condition has the same
00417   // type as the result of the comparison, so bail out if this is not so.
00418   if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
00419     return nullptr;
00420   // If the false value simplified to false, then the result of the compare
00421   // is equal to "Cond && TCmp".  This also catches the case when the false
00422   // value simplified to false and the true value to true, returning "Cond".
00423   if (match(FCmp, m_Zero()))
00424     if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
00425       return V;
00426   // If the true value simplified to true, then the result of the compare
00427   // is equal to "Cond || FCmp".
00428   if (match(TCmp, m_One()))
00429     if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
00430       return V;
00431   // Finally, if the false value simplified to true and the true value to
00432   // false, then the result of the compare is equal to "!Cond".
00433   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
00434     if (Value *V =
00435         SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
00436                         Q, MaxRecurse))
00437       return V;
00438 
00439   return nullptr;
00440 }
00441 
00442 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
00443 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
00444 /// it on the incoming phi values yields the same result for every value.  If so
00445 /// returns the common value, otherwise returns null.
00446 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
00447                                  const Query &Q, unsigned MaxRecurse) {
00448   // Recursion is always used, so bail out at once if we already hit the limit.
00449   if (!MaxRecurse--)
00450     return nullptr;
00451 
00452   PHINode *PI;
00453   if (isa<PHINode>(LHS)) {
00454     PI = cast<PHINode>(LHS);
00455     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
00456     if (!ValueDominatesPHI(RHS, PI, Q.DT))
00457       return nullptr;
00458   } else {
00459     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
00460     PI = cast<PHINode>(RHS);
00461     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
00462     if (!ValueDominatesPHI(LHS, PI, Q.DT))
00463       return nullptr;
00464   }
00465 
00466   // Evaluate the BinOp on the incoming phi values.
00467   Value *CommonValue = nullptr;
00468   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
00469     Value *Incoming = PI->getIncomingValue(i);
00470     // If the incoming value is the phi node itself, it can safely be skipped.
00471     if (Incoming == PI) continue;
00472     Value *V = PI == LHS ?
00473       SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
00474       SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
00475     // If the operation failed to simplify, or simplified to a different value
00476     // to previously, then give up.
00477     if (!V || (CommonValue && V != CommonValue))
00478       return nullptr;
00479     CommonValue = V;
00480   }
00481 
00482   return CommonValue;
00483 }
00484 
00485 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
00486 /// try to simplify the comparison by seeing whether comparing with all of the
00487 /// incoming phi values yields the same result every time.  If so returns the
00488 /// common result, otherwise returns null.
00489 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
00490                                const Query &Q, unsigned MaxRecurse) {
00491   // Recursion is always used, so bail out at once if we already hit the limit.
00492   if (!MaxRecurse--)
00493     return nullptr;
00494 
00495   // Make sure the phi is on the LHS.
00496   if (!isa<PHINode>(LHS)) {
00497     std::swap(LHS, RHS);
00498     Pred = CmpInst::getSwappedPredicate(Pred);
00499   }
00500   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
00501   PHINode *PI = cast<PHINode>(LHS);
00502 
00503   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
00504   if (!ValueDominatesPHI(RHS, PI, Q.DT))
00505     return nullptr;
00506 
00507   // Evaluate the BinOp on the incoming phi values.
00508   Value *CommonValue = nullptr;
00509   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
00510     Value *Incoming = PI->getIncomingValue(i);
00511     // If the incoming value is the phi node itself, it can safely be skipped.
00512     if (Incoming == PI) continue;
00513     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
00514     // If the operation failed to simplify, or simplified to a different value
00515     // to previously, then give up.
00516     if (!V || (CommonValue && V != CommonValue))
00517       return nullptr;
00518     CommonValue = V;
00519   }
00520 
00521   return CommonValue;
00522 }
00523 
00524 /// SimplifyAddInst - Given operands for an Add, see if we can
00525 /// fold the result.  If not, this returns null.
00526 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
00527                               const Query &Q, unsigned MaxRecurse) {
00528   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
00529     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
00530       Constant *Ops[] = { CLHS, CRHS };
00531       return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
00532                                       Q.DL, Q.TLI);
00533     }
00534 
00535     // Canonicalize the constant to the RHS.
00536     std::swap(Op0, Op1);
00537   }
00538 
00539   // X + undef -> undef
00540   if (match(Op1, m_Undef()))
00541     return Op1;
00542 
00543   // X + 0 -> X
00544   if (match(Op1, m_Zero()))
00545     return Op0;
00546 
00547   // X + (Y - X) -> Y
00548   // (Y - X) + X -> Y
00549   // Eg: X + -X -> 0
00550   Value *Y = nullptr;
00551   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
00552       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
00553     return Y;
00554 
00555   // X + ~X -> -1   since   ~X = -X-1
00556   if (match(Op0, m_Not(m_Specific(Op1))) ||
00557       match(Op1, m_Not(m_Specific(Op0))))
00558     return Constant::getAllOnesValue(Op0->getType());
00559 
00560   /// i1 add -> xor.
00561   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
00562     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
00563       return V;
00564 
00565   // Try some generic simplifications for associative operations.
00566   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
00567                                           MaxRecurse))
00568     return V;
00569 
00570   // Threading Add over selects and phi nodes is pointless, so don't bother.
00571   // Threading over the select in "A + select(cond, B, C)" means evaluating
00572   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
00573   // only if B and C are equal.  If B and C are equal then (since we assume
00574   // that operands have already been simplified) "select(cond, B, C)" should
00575   // have been simplified to the common value of B and C already.  Analysing
00576   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
00577   // for threading over phi nodes.
00578 
00579   return nullptr;
00580 }
00581 
00582 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
00583                              const DataLayout *DL, const TargetLibraryInfo *TLI,
00584                              const DominatorTree *DT, AssumptionTracker *AT,
00585                              const Instruction *CxtI) {
00586   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW,
00587                            Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
00588 }
00589 
00590 /// \brief Compute the base pointer and cumulative constant offsets for V.
00591 ///
00592 /// This strips all constant offsets off of V, leaving it the base pointer, and
00593 /// accumulates the total constant offset applied in the returned constant. It
00594 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
00595 /// no constant offsets applied.
00596 ///
00597 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
00598 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
00599 /// folding.
00600 static Constant *stripAndComputeConstantOffsets(const DataLayout *DL,
00601                                                 Value *&V,
00602                                                 bool AllowNonInbounds = false) {
00603   assert(V->getType()->getScalarType()->isPointerTy());
00604 
00605   // Without DataLayout, just be conservative for now. Theoretically, more could
00606   // be done in this case.
00607   if (!DL)
00608     return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
00609 
00610   Type *IntPtrTy = DL->getIntPtrType(V->getType())->getScalarType();
00611   APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
00612 
00613   // Even though we don't look through PHI nodes, we could be called on an
00614   // instruction in an unreachable block, which may be on a cycle.
00615   SmallPtrSet<Value *, 4> Visited;
00616   Visited.insert(V);
00617   do {
00618     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00619       if ((!AllowNonInbounds && !GEP->isInBounds()) ||
00620           !GEP->accumulateConstantOffset(*DL, Offset))
00621         break;
00622       V = GEP->getPointerOperand();
00623     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
00624       V = cast<Operator>(V)->getOperand(0);
00625     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00626       if (GA->mayBeOverridden())
00627         break;
00628       V = GA->getAliasee();
00629     } else {
00630       break;
00631     }
00632     assert(V->getType()->getScalarType()->isPointerTy() &&
00633            "Unexpected operand type!");
00634   } while (Visited.insert(V));
00635 
00636   Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
00637   if (V->getType()->isVectorTy())
00638     return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
00639                                     OffsetIntPtr);
00640   return OffsetIntPtr;
00641 }
00642 
00643 /// \brief Compute the constant difference between two pointer values.
00644 /// If the difference is not a constant, returns zero.
00645 static Constant *computePointerDifference(const DataLayout *DL,
00646                                           Value *LHS, Value *RHS) {
00647   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
00648   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
00649 
00650   // If LHS and RHS are not related via constant offsets to the same base
00651   // value, there is nothing we can do here.
00652   if (LHS != RHS)
00653     return nullptr;
00654 
00655   // Otherwise, the difference of LHS - RHS can be computed as:
00656   //    LHS - RHS
00657   //  = (LHSOffset + Base) - (RHSOffset + Base)
00658   //  = LHSOffset - RHSOffset
00659   return ConstantExpr::getSub(LHSOffset, RHSOffset);
00660 }
00661 
00662 /// SimplifySubInst - Given operands for a Sub, see if we can
00663 /// fold the result.  If not, this returns null.
00664 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
00665                               const Query &Q, unsigned MaxRecurse) {
00666   if (Constant *CLHS = dyn_cast<Constant>(Op0))
00667     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
00668       Constant *Ops[] = { CLHS, CRHS };
00669       return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
00670                                       Ops, Q.DL, Q.TLI);
00671     }
00672 
00673   // X - undef -> undef
00674   // undef - X -> undef
00675   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
00676     return UndefValue::get(Op0->getType());
00677 
00678   // X - 0 -> X
00679   if (match(Op1, m_Zero()))
00680     return Op0;
00681 
00682   // X - X -> 0
00683   if (Op0 == Op1)
00684     return Constant::getNullValue(Op0->getType());
00685 
00686   // X - (0 - Y) -> X if the second sub is NUW.
00687   // If Y != 0, 0 - Y is a poison value.
00688   // If Y == 0, 0 - Y simplifies to 0.
00689   if (BinaryOperator::isNeg(Op1)) {
00690     if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
00691       assert(BO->getOpcode() == Instruction::Sub &&
00692              "Expected a subtraction operator!");
00693       if (BO->hasNoUnsignedWrap())
00694         return Op0;
00695     }
00696   }
00697 
00698   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
00699   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
00700   Value *X = nullptr, *Y = nullptr, *Z = Op1;
00701   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
00702     // See if "V === Y - Z" simplifies.
00703     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
00704       // It does!  Now see if "X + V" simplifies.
00705       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
00706         // It does, we successfully reassociated!
00707         ++NumReassoc;
00708         return W;
00709       }
00710     // See if "V === X - Z" simplifies.
00711     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
00712       // It does!  Now see if "Y + V" simplifies.
00713       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
00714         // It does, we successfully reassociated!
00715         ++NumReassoc;
00716         return W;
00717       }
00718   }
00719 
00720   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
00721   // For example, X - (X + 1) -> -1
00722   X = Op0;
00723   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
00724     // See if "V === X - Y" simplifies.
00725     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
00726       // It does!  Now see if "V - Z" simplifies.
00727       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
00728         // It does, we successfully reassociated!
00729         ++NumReassoc;
00730         return W;
00731       }
00732     // See if "V === X - Z" simplifies.
00733     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
00734       // It does!  Now see if "V - Y" simplifies.
00735       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
00736         // It does, we successfully reassociated!
00737         ++NumReassoc;
00738         return W;
00739       }
00740   }
00741 
00742   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
00743   // For example, X - (X - Y) -> Y.
00744   Z = Op0;
00745   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
00746     // See if "V === Z - X" simplifies.
00747     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
00748       // It does!  Now see if "V + Y" simplifies.
00749       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
00750         // It does, we successfully reassociated!
00751         ++NumReassoc;
00752         return W;
00753       }
00754 
00755   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
00756   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
00757       match(Op1, m_Trunc(m_Value(Y))))
00758     if (X->getType() == Y->getType())
00759       // See if "V === X - Y" simplifies.
00760       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
00761         // It does!  Now see if "trunc V" simplifies.
00762         if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
00763           // It does, return the simplified "trunc V".
00764           return W;
00765 
00766   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
00767   if (match(Op0, m_PtrToInt(m_Value(X))) &&
00768       match(Op1, m_PtrToInt(m_Value(Y))))
00769     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
00770       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
00771 
00772   // i1 sub -> xor.
00773   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
00774     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
00775       return V;
00776 
00777   // Threading Sub over selects and phi nodes is pointless, so don't bother.
00778   // Threading over the select in "A - select(cond, B, C)" means evaluating
00779   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
00780   // only if B and C are equal.  If B and C are equal then (since we assume
00781   // that operands have already been simplified) "select(cond, B, C)" should
00782   // have been simplified to the common value of B and C already.  Analysing
00783   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
00784   // for threading over phi nodes.
00785 
00786   return nullptr;
00787 }
00788 
00789 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
00790                              const DataLayout *DL, const TargetLibraryInfo *TLI,
00791                              const DominatorTree *DT, AssumptionTracker *AT,
00792                              const Instruction *CxtI) {
00793   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW,
00794                            Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
00795 }
00796 
00797 /// Given operands for an FAdd, see if we can fold the result.  If not, this
00798 /// returns null.
00799 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
00800                               const Query &Q, unsigned MaxRecurse) {
00801   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
00802     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
00803       Constant *Ops[] = { CLHS, CRHS };
00804       return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
00805                                       Ops, Q.DL, Q.TLI);
00806     }
00807 
00808     // Canonicalize the constant to the RHS.
00809     std::swap(Op0, Op1);
00810   }
00811 
00812   // fadd X, -0 ==> X
00813   if (match(Op1, m_NegZero()))
00814     return Op0;
00815 
00816   // fadd X, 0 ==> X, when we know X is not -0
00817   if (match(Op1, m_Zero()) &&
00818       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
00819     return Op0;
00820 
00821   // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
00822   //   where nnan and ninf have to occur at least once somewhere in this
00823   //   expression
00824   Value *SubOp = nullptr;
00825   if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
00826     SubOp = Op1;
00827   else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
00828     SubOp = Op0;
00829   if (SubOp) {
00830     Instruction *FSub = cast<Instruction>(SubOp);
00831     if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
00832         (FMF.noInfs() || FSub->hasNoInfs()))
00833       return Constant::getNullValue(Op0->getType());
00834   }
00835 
00836   return nullptr;
00837 }
00838 
00839 /// Given operands for an FSub, see if we can fold the result.  If not, this
00840 /// returns null.
00841 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
00842                               const Query &Q, unsigned MaxRecurse) {
00843   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
00844     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
00845       Constant *Ops[] = { CLHS, CRHS };
00846       return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
00847                                       Ops, Q.DL, Q.TLI);
00848     }
00849   }
00850 
00851   // fsub X, 0 ==> X
00852   if (match(Op1, m_Zero()))
00853     return Op0;
00854 
00855   // fsub X, -0 ==> X, when we know X is not -0
00856   if (match(Op1, m_NegZero()) &&
00857       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
00858     return Op0;
00859 
00860   // fsub 0, (fsub -0.0, X) ==> X
00861   Value *X;
00862   if (match(Op0, m_AnyZero())) {
00863     if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
00864       return X;
00865     if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
00866       return X;
00867   }
00868 
00869   // fsub nnan ninf x, x ==> 0.0
00870   if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
00871     return Constant::getNullValue(Op0->getType());
00872 
00873   return nullptr;
00874 }
00875 
00876 /// Given the operands for an FMul, see if we can fold the result
00877 static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
00878                                FastMathFlags FMF,
00879                                const Query &Q,
00880                                unsigned MaxRecurse) {
00881  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
00882     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
00883       Constant *Ops[] = { CLHS, CRHS };
00884       return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
00885                                       Ops, Q.DL, Q.TLI);
00886     }
00887 
00888     // Canonicalize the constant to the RHS.
00889     std::swap(Op0, Op1);
00890  }
00891 
00892  // fmul X, 1.0 ==> X
00893  if (match(Op1, m_FPOne()))
00894    return Op0;
00895 
00896  // fmul nnan nsz X, 0 ==> 0
00897  if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
00898    return Op1;
00899 
00900  return nullptr;
00901 }
00902 
00903 /// SimplifyMulInst - Given operands for a Mul, see if we can
00904 /// fold the result.  If not, this returns null.
00905 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
00906                               unsigned MaxRecurse) {
00907   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
00908     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
00909       Constant *Ops[] = { CLHS, CRHS };
00910       return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
00911                                       Ops, Q.DL, Q.TLI);
00912     }
00913 
00914     // Canonicalize the constant to the RHS.
00915     std::swap(Op0, Op1);
00916   }
00917 
00918   // X * undef -> 0
00919   if (match(Op1, m_Undef()))
00920     return Constant::getNullValue(Op0->getType());
00921 
00922   // X * 0 -> 0
00923   if (match(Op1, m_Zero()))
00924     return Op1;
00925 
00926   // X * 1 -> X
00927   if (match(Op1, m_One()))
00928     return Op0;
00929 
00930   // (X / Y) * Y -> X if the division is exact.
00931   Value *X = nullptr;
00932   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
00933       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
00934     return X;
00935 
00936   // i1 mul -> and.
00937   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
00938     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
00939       return V;
00940 
00941   // Try some generic simplifications for associative operations.
00942   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
00943                                           MaxRecurse))
00944     return V;
00945 
00946   // Mul distributes over Add.  Try some generic simplifications based on this.
00947   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
00948                              Q, MaxRecurse))
00949     return V;
00950 
00951   // If the operation is with the result of a select instruction, check whether
00952   // operating on either branch of the select always yields the same value.
00953   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
00954     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
00955                                          MaxRecurse))
00956       return V;
00957 
00958   // If the operation is with the result of a phi instruction, check whether
00959   // operating on all incoming values of the phi always yields the same value.
00960   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
00961     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
00962                                       MaxRecurse))
00963       return V;
00964 
00965   return nullptr;
00966 }
00967 
00968 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
00969                              const DataLayout *DL, const TargetLibraryInfo *TLI,
00970                              const DominatorTree *DT, AssumptionTracker *AT,
00971                              const Instruction *CxtI) {
00972   return ::SimplifyFAddInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
00973                             RecursionLimit);
00974 }
00975 
00976 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
00977                              const DataLayout *DL, const TargetLibraryInfo *TLI,
00978                              const DominatorTree *DT, AssumptionTracker *AT,
00979                              const Instruction *CxtI) {
00980   return ::SimplifyFSubInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
00981                             RecursionLimit);
00982 }
00983 
00984 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
00985                               FastMathFlags FMF,
00986                               const DataLayout *DL,
00987                               const TargetLibraryInfo *TLI,
00988                               const DominatorTree *DT,
00989                               AssumptionTracker *AT,
00990                               const Instruction *CxtI) {
00991   return ::SimplifyFMulInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
00992                             RecursionLimit);
00993 }
00994 
00995 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *DL,
00996                              const TargetLibraryInfo *TLI,
00997                              const DominatorTree *DT, AssumptionTracker *AT,
00998                              const Instruction *CxtI) {
00999   return ::SimplifyMulInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
01000                            RecursionLimit);
01001 }
01002 
01003 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
01004 /// fold the result.  If not, this returns null.
01005 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
01006                           const Query &Q, unsigned MaxRecurse) {
01007   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
01008     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
01009       Constant *Ops[] = { C0, C1 };
01010       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
01011     }
01012   }
01013 
01014   bool isSigned = Opcode == Instruction::SDiv;
01015 
01016   // X / undef -> undef
01017   if (match(Op1, m_Undef()))
01018     return Op1;
01019 
01020   // undef / X -> 0
01021   if (match(Op0, m_Undef()))
01022     return Constant::getNullValue(Op0->getType());
01023 
01024   // 0 / X -> 0, we don't need to preserve faults!
01025   if (match(Op0, m_Zero()))
01026     return Op0;
01027 
01028   // X / 1 -> X
01029   if (match(Op1, m_One()))
01030     return Op0;
01031 
01032   if (Op0->getType()->isIntegerTy(1))
01033     // It can't be division by zero, hence it must be division by one.
01034     return Op0;
01035 
01036   // X / X -> 1
01037   if (Op0 == Op1)
01038     return ConstantInt::get(Op0->getType(), 1);
01039 
01040   // (X * Y) / Y -> X if the multiplication does not overflow.
01041   Value *X = nullptr, *Y = nullptr;
01042   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
01043     if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
01044     OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
01045     // If the Mul knows it does not overflow, then we are good to go.
01046     if ((isSigned && Mul->hasNoSignedWrap()) ||
01047         (!isSigned && Mul->hasNoUnsignedWrap()))
01048       return X;
01049     // If X has the form X = A / Y then X * Y cannot overflow.
01050     if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
01051       if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
01052         return X;
01053   }
01054 
01055   // (X rem Y) / Y -> 0
01056   if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
01057       (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
01058     return Constant::getNullValue(Op0->getType());
01059 
01060   // If the operation is with the result of a select instruction, check whether
01061   // operating on either branch of the select always yields the same value.
01062   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
01063     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
01064       return V;
01065 
01066   // If the operation is with the result of a phi instruction, check whether
01067   // operating on all incoming values of the phi always yields the same value.
01068   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
01069     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
01070       return V;
01071 
01072   return nullptr;
01073 }
01074 
01075 /// SimplifySDivInst - Given operands for an SDiv, see if we can
01076 /// fold the result.  If not, this returns null.
01077 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
01078                                unsigned MaxRecurse) {
01079   if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
01080     return V;
01081 
01082   return nullptr;
01083 }
01084 
01085 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
01086                               const TargetLibraryInfo *TLI,
01087                               const DominatorTree *DT,
01088                               AssumptionTracker *AT,
01089                               const Instruction *CxtI) {
01090   return ::SimplifySDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
01091                             RecursionLimit);
01092 }
01093 
01094 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
01095 /// fold the result.  If not, this returns null.
01096 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
01097                                unsigned MaxRecurse) {
01098   if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
01099     return V;
01100 
01101   return nullptr;
01102 }
01103 
01104 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
01105                               const TargetLibraryInfo *TLI,
01106                               const DominatorTree *DT,
01107                               AssumptionTracker *AT,
01108                               const Instruction *CxtI) {
01109   return ::SimplifyUDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
01110                             RecursionLimit);
01111 }
01112 
01113 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
01114                                unsigned) {
01115   // undef / X -> undef    (the undef could be a snan).
01116   if (match(Op0, m_Undef()))
01117     return Op0;
01118 
01119   // X / undef -> undef
01120   if (match(Op1, m_Undef()))
01121     return Op1;
01122 
01123   return nullptr;
01124 }
01125 
01126 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
01127                               const TargetLibraryInfo *TLI,
01128                               const DominatorTree *DT,
01129                               AssumptionTracker *AT,
01130                               const Instruction *CxtI) {
01131   return ::SimplifyFDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
01132                             RecursionLimit);
01133 }
01134 
01135 /// SimplifyRem - Given operands for an SRem or URem, see if we can
01136 /// fold the result.  If not, this returns null.
01137 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
01138                           const Query &Q, unsigned MaxRecurse) {
01139   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
01140     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
01141       Constant *Ops[] = { C0, C1 };
01142       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
01143     }
01144   }
01145 
01146   // X % undef -> undef
01147   if (match(Op1, m_Undef()))
01148     return Op1;
01149 
01150   // undef % X -> 0
01151   if (match(Op0, m_Undef()))
01152     return Constant::getNullValue(Op0->getType());
01153 
01154   // 0 % X -> 0, we don't need to preserve faults!
01155   if (match(Op0, m_Zero()))
01156     return Op0;
01157 
01158   // X % 0 -> undef, we don't need to preserve faults!
01159   if (match(Op1, m_Zero()))
01160     return UndefValue::get(Op0->getType());
01161 
01162   // X % 1 -> 0
01163   if (match(Op1, m_One()))
01164     return Constant::getNullValue(Op0->getType());
01165 
01166   if (Op0->getType()->isIntegerTy(1))
01167     // It can't be remainder by zero, hence it must be remainder by one.
01168     return Constant::getNullValue(Op0->getType());
01169 
01170   // X % X -> 0
01171   if (Op0 == Op1)
01172     return Constant::getNullValue(Op0->getType());
01173 
01174   // If the operation is with the result of a select instruction, check whether
01175   // operating on either branch of the select always yields the same value.
01176   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
01177     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
01178       return V;
01179 
01180   // If the operation is with the result of a phi instruction, check whether
01181   // operating on all incoming values of the phi always yields the same value.
01182   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
01183     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
01184       return V;
01185 
01186   return nullptr;
01187 }
01188 
01189 /// SimplifySRemInst - Given operands for an SRem, see if we can
01190 /// fold the result.  If not, this returns null.
01191 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
01192                                unsigned MaxRecurse) {
01193   if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
01194     return V;
01195 
01196   return nullptr;
01197 }
01198 
01199 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
01200                               const TargetLibraryInfo *TLI,
01201                               const DominatorTree *DT,
01202                               AssumptionTracker *AT,
01203                               const Instruction *CxtI) {
01204   return ::SimplifySRemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
01205                             RecursionLimit);
01206 }
01207 
01208 /// SimplifyURemInst - Given operands for a URem, see if we can
01209 /// fold the result.  If not, this returns null.
01210 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
01211                                unsigned MaxRecurse) {
01212   if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
01213     return V;
01214 
01215   return nullptr;
01216 }
01217 
01218 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL,
01219                               const TargetLibraryInfo *TLI,
01220                               const DominatorTree *DT,
01221                               AssumptionTracker *AT,
01222                               const Instruction *CxtI) {
01223   return ::SimplifyURemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
01224                             RecursionLimit);
01225 }
01226 
01227 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
01228                                unsigned) {
01229   // undef % X -> undef    (the undef could be a snan).
01230   if (match(Op0, m_Undef()))
01231     return Op0;
01232 
01233   // X % undef -> undef
01234   if (match(Op1, m_Undef()))
01235     return Op1;
01236 
01237   return nullptr;
01238 }
01239 
01240 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
01241                               const TargetLibraryInfo *TLI,
01242                               const DominatorTree *DT,
01243                               AssumptionTracker *AT,
01244                               const Instruction *CxtI) {
01245   return ::SimplifyFRemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
01246                             RecursionLimit);
01247 }
01248 
01249 /// isUndefShift - Returns true if a shift by \c Amount always yields undef.
01250 static bool isUndefShift(Value *Amount) {
01251   Constant *C = dyn_cast<Constant>(Amount);
01252   if (!C)
01253     return false;
01254 
01255   // X shift by undef -> undef because it may shift by the bitwidth.
01256   if (isa<UndefValue>(C))
01257     return true;
01258 
01259   // Shifting by the bitwidth or more is undefined.
01260   if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
01261     if (CI->getValue().getLimitedValue() >=
01262         CI->getType()->getScalarSizeInBits())
01263       return true;
01264 
01265   // If all lanes of a vector shift are undefined the whole shift is.
01266   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
01267     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
01268       if (!isUndefShift(C->getAggregateElement(I)))
01269         return false;
01270     return true;
01271   }
01272 
01273   return false;
01274 }
01275 
01276 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
01277 /// fold the result.  If not, this returns null.
01278 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
01279                             const Query &Q, unsigned MaxRecurse) {
01280   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
01281     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
01282       Constant *Ops[] = { C0, C1 };
01283       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
01284     }
01285   }
01286 
01287   // 0 shift by X -> 0
01288   if (match(Op0, m_Zero()))
01289     return Op0;
01290 
01291   // X shift by 0 -> X
01292   if (match(Op1, m_Zero()))
01293     return Op0;
01294 
01295   // Fold undefined shifts.
01296   if (isUndefShift(Op1))
01297     return UndefValue::get(Op0->getType());
01298 
01299   // If the operation is with the result of a select instruction, check whether
01300   // operating on either branch of the select always yields the same value.
01301   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
01302     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
01303       return V;
01304 
01305   // If the operation is with the result of a phi instruction, check whether
01306   // operating on all incoming values of the phi always yields the same value.
01307   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
01308     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
01309       return V;
01310 
01311   return nullptr;
01312 }
01313 
01314 /// SimplifyShlInst - Given operands for an Shl, see if we can
01315 /// fold the result.  If not, this returns null.
01316 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
01317                               const Query &Q, unsigned MaxRecurse) {
01318   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
01319     return V;
01320 
01321   // undef << X -> 0
01322   if (match(Op0, m_Undef()))
01323     return Constant::getNullValue(Op0->getType());
01324 
01325   // (X >> A) << A -> X
01326   Value *X;
01327   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
01328     return X;
01329   return nullptr;
01330 }
01331 
01332 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
01333                              const DataLayout *DL, const TargetLibraryInfo *TLI,
01334                              const DominatorTree *DT, AssumptionTracker *AT,
01335                              const Instruction *CxtI) {
01336   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT, AT, CxtI),
01337                            RecursionLimit);
01338 }
01339 
01340 /// SimplifyLShrInst - Given operands for an LShr, see if we can
01341 /// fold the result.  If not, this returns null.
01342 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
01343                                const Query &Q, unsigned MaxRecurse) {
01344   if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
01345     return V;
01346 
01347   // X >> X -> 0
01348   if (Op0 == Op1)
01349     return Constant::getNullValue(Op0->getType());
01350 
01351   // undef >>l X -> 0
01352   if (match(Op0, m_Undef()))
01353     return Constant::getNullValue(Op0->getType());
01354 
01355   // (X << A) >> A -> X
01356   Value *X;
01357   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
01358       cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
01359     return X;
01360 
01361   return nullptr;
01362 }
01363 
01364 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
01365                               const DataLayout *DL,
01366                               const TargetLibraryInfo *TLI,
01367                               const DominatorTree *DT,
01368                               AssumptionTracker *AT,
01369                               const Instruction *CxtI) {
01370   return ::SimplifyLShrInst(Op0, Op1, isExact, Query (DL, TLI, DT, AT, CxtI),
01371                             RecursionLimit);
01372 }
01373 
01374 /// SimplifyAShrInst - Given operands for an AShr, see if we can
01375 /// fold the result.  If not, this returns null.
01376 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
01377                                const Query &Q, unsigned MaxRecurse) {
01378   if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
01379     return V;
01380 
01381   // X >> X -> 0
01382   if (Op0 == Op1)
01383     return Constant::getNullValue(Op0->getType());
01384 
01385   // all ones >>a X -> all ones
01386   if (match(Op0, m_AllOnes()))
01387     return Op0;
01388 
01389   // undef >>a X -> all ones
01390   if (match(Op0, m_Undef()))
01391     return Constant::getAllOnesValue(Op0->getType());
01392 
01393   // (X << A) >> A -> X
01394   Value *X;
01395   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
01396       cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
01397     return X;
01398 
01399   // Arithmetic shifting an all-sign-bit value is a no-op.
01400   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AT, Q.CxtI, Q.DT);
01401   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
01402     return Op0;
01403 
01404   return nullptr;
01405 }
01406 
01407 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
01408                               const DataLayout *DL,
01409                               const TargetLibraryInfo *TLI,
01410                               const DominatorTree *DT,
01411                               AssumptionTracker *AT,
01412                               const Instruction *CxtI) {
01413   return ::SimplifyAShrInst(Op0, Op1, isExact, Query (DL, TLI, DT, AT, CxtI),
01414                             RecursionLimit);
01415 }
01416 
01417 // Simplify (and (icmp ...) (icmp ...)) to true when we can tell that the range
01418 // of possible values cannot be satisfied.
01419 static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
01420   ICmpInst::Predicate Pred0, Pred1;
01421   ConstantInt *CI1, *CI2;
01422   Value *V;
01423   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
01424                          m_ConstantInt(CI2))))
01425    return nullptr;
01426 
01427   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
01428     return nullptr;
01429 
01430   Type *ITy = Op0->getType();
01431 
01432   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
01433   bool isNSW = AddInst->hasNoSignedWrap();
01434   bool isNUW = AddInst->hasNoUnsignedWrap();
01435 
01436   const APInt &CI1V = CI1->getValue();
01437   const APInt &CI2V = CI2->getValue();
01438   const APInt Delta = CI2V - CI1V;
01439   if (CI1V.isStrictlyPositive()) {
01440     if (Delta == 2) {
01441       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
01442         return getFalse(ITy);
01443       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
01444         return getFalse(ITy);
01445     }
01446     if (Delta == 1) {
01447       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
01448         return getFalse(ITy);
01449       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
01450         return getFalse(ITy);
01451     }
01452   }
01453   if (CI1V.getBoolValue() && isNUW) {
01454     if (Delta == 2)
01455       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
01456         return getFalse(ITy);
01457     if (Delta == 1)
01458       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
01459         return getFalse(ITy);
01460   }
01461 
01462   return nullptr;
01463 }
01464 
01465 /// SimplifyAndInst - Given operands for an And, see if we can
01466 /// fold the result.  If not, this returns null.
01467 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
01468                               unsigned MaxRecurse) {
01469   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
01470     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
01471       Constant *Ops[] = { CLHS, CRHS };
01472       return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
01473                                       Ops, Q.DL, Q.TLI);
01474     }
01475 
01476     // Canonicalize the constant to the RHS.
01477     std::swap(Op0, Op1);
01478   }
01479 
01480   // X & undef -> 0
01481   if (match(Op1, m_Undef()))
01482     return Constant::getNullValue(Op0->getType());
01483 
01484   // X & X = X
01485   if (Op0 == Op1)
01486     return Op0;
01487 
01488   // X & 0 = 0
01489   if (match(Op1, m_Zero()))
01490     return Op1;
01491 
01492   // X & -1 = X
01493   if (match(Op1, m_AllOnes()))
01494     return Op0;
01495 
01496   // A & ~A  =  ~A & A  =  0
01497   if (match(Op0, m_Not(m_Specific(Op1))) ||
01498       match(Op1, m_Not(m_Specific(Op0))))
01499     return Constant::getNullValue(Op0->getType());
01500 
01501   // (A | ?) & A = A
01502   Value *A = nullptr, *B = nullptr;
01503   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
01504       (A == Op1 || B == Op1))
01505     return Op1;
01506 
01507   // A & (A | ?) = A
01508   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
01509       (A == Op0 || B == Op0))
01510     return Op0;
01511 
01512   // A & (-A) = A if A is a power of two or zero.
01513   if (match(Op0, m_Neg(m_Specific(Op1))) ||
01514       match(Op1, m_Neg(m_Specific(Op0)))) {
01515     if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true, 0, Q.AT, Q.CxtI, Q.DT))
01516       return Op0;
01517     if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, Q.AT, Q.CxtI, Q.DT))
01518       return Op1;
01519   }
01520 
01521   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
01522     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
01523       if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
01524         return V;
01525       if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
01526         return V;
01527     }
01528   }
01529 
01530   // Try some generic simplifications for associative operations.
01531   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
01532                                           MaxRecurse))
01533     return V;
01534 
01535   // And distributes over Or.  Try some generic simplifications based on this.
01536   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
01537                              Q, MaxRecurse))
01538     return V;
01539 
01540   // And distributes over Xor.  Try some generic simplifications based on this.
01541   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
01542                              Q, MaxRecurse))
01543     return V;
01544 
01545   // If the operation is with the result of a select instruction, check whether
01546   // operating on either branch of the select always yields the same value.
01547   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
01548     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
01549                                          MaxRecurse))
01550       return V;
01551 
01552   // If the operation is with the result of a phi instruction, check whether
01553   // operating on all incoming values of the phi always yields the same value.
01554   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
01555     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
01556                                       MaxRecurse))
01557       return V;
01558 
01559   return nullptr;
01560 }
01561 
01562 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL,
01563                              const TargetLibraryInfo *TLI,
01564                              const DominatorTree *DT, AssumptionTracker *AT,
01565                              const Instruction *CxtI) {
01566   return ::SimplifyAndInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
01567                            RecursionLimit);
01568 }
01569 
01570 // Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
01571 // contains all possible values.
01572 static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
01573   ICmpInst::Predicate Pred0, Pred1;
01574   ConstantInt *CI1, *CI2;
01575   Value *V;
01576   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
01577                          m_ConstantInt(CI2))))
01578    return nullptr;
01579 
01580   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
01581     return nullptr;
01582 
01583   Type *ITy = Op0->getType();
01584 
01585   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
01586   bool isNSW = AddInst->hasNoSignedWrap();
01587   bool isNUW = AddInst->hasNoUnsignedWrap();
01588 
01589   const APInt &CI1V = CI1->getValue();
01590   const APInt &CI2V = CI2->getValue();
01591   const APInt Delta = CI2V - CI1V;
01592   if (CI1V.isStrictlyPositive()) {
01593     if (Delta == 2) {
01594       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
01595         return getTrue(ITy);
01596       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
01597         return getTrue(ITy);
01598     }
01599     if (Delta == 1) {
01600       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
01601         return getTrue(ITy);
01602       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
01603         return getTrue(ITy);
01604     }
01605   }
01606   if (CI1V.getBoolValue() && isNUW) {
01607     if (Delta == 2)
01608       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
01609         return getTrue(ITy);
01610     if (Delta == 1)
01611       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
01612         return getTrue(ITy);
01613   }
01614 
01615   return nullptr;
01616 }
01617 
01618 /// SimplifyOrInst - Given operands for an Or, see if we can
01619 /// fold the result.  If not, this returns null.
01620 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
01621                              unsigned MaxRecurse) {
01622   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
01623     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
01624       Constant *Ops[] = { CLHS, CRHS };
01625       return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
01626                                       Ops, Q.DL, Q.TLI);
01627     }
01628 
01629     // Canonicalize the constant to the RHS.
01630     std::swap(Op0, Op1);
01631   }
01632 
01633   // X | undef -> -1
01634   if (match(Op1, m_Undef()))
01635     return Constant::getAllOnesValue(Op0->getType());
01636 
01637   // X | X = X
01638   if (Op0 == Op1)
01639     return Op0;
01640 
01641   // X | 0 = X
01642   if (match(Op1, m_Zero()))
01643     return Op0;
01644 
01645   // X | -1 = -1
01646   if (match(Op1, m_AllOnes()))
01647     return Op1;
01648 
01649   // A | ~A  =  ~A | A  =  -1
01650   if (match(Op0, m_Not(m_Specific(Op1))) ||
01651       match(Op1, m_Not(m_Specific(Op0))))
01652     return Constant::getAllOnesValue(Op0->getType());
01653 
01654   // (A & ?) | A = A
01655   Value *A = nullptr, *B = nullptr;
01656   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
01657       (A == Op1 || B == Op1))
01658     return Op1;
01659 
01660   // A | (A & ?) = A
01661   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
01662       (A == Op0 || B == Op0))
01663     return Op0;
01664 
01665   // ~(A & ?) | A = -1
01666   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
01667       (A == Op1 || B == Op1))
01668     return Constant::getAllOnesValue(Op1->getType());
01669 
01670   // A | ~(A & ?) = -1
01671   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
01672       (A == Op0 || B == Op0))
01673     return Constant::getAllOnesValue(Op0->getType());
01674 
01675   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
01676     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
01677       if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
01678         return V;
01679       if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
01680         return V;
01681     }
01682   }
01683 
01684   // Try some generic simplifications for associative operations.
01685   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
01686                                           MaxRecurse))
01687     return V;
01688 
01689   // Or distributes over And.  Try some generic simplifications based on this.
01690   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
01691                              MaxRecurse))
01692     return V;
01693 
01694   // If the operation is with the result of a select instruction, check whether
01695   // operating on either branch of the select always yields the same value.
01696   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
01697     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
01698                                          MaxRecurse))
01699       return V;
01700 
01701   // (A & C)|(B & D)
01702   Value *C = nullptr, *D = nullptr;
01703   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
01704       match(Op1, m_And(m_Value(B), m_Value(D)))) {
01705     ConstantInt *C1 = dyn_cast<ConstantInt>(C);
01706     ConstantInt *C2 = dyn_cast<ConstantInt>(D);
01707     if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
01708       // (A & C1)|(B & C2)
01709       // If we have: ((V + N) & C1) | (V & C2)
01710       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
01711       // replace with V+N.
01712       Value *V1, *V2;
01713       if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
01714           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
01715         // Add commutes, try both ways.
01716         if (V1 == B && MaskedValueIsZero(V2, C2->getValue(), Q.DL,
01717                                          0, Q.AT, Q.CxtI, Q.DT))
01718           return A;
01719         if (V2 == B && MaskedValueIsZero(V1, C2->getValue(), Q.DL,
01720                                          0, Q.AT, Q.CxtI, Q.DT))
01721           return A;
01722       }
01723       // Or commutes, try both ways.
01724       if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
01725           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
01726         // Add commutes, try both ways.
01727         if (V1 == A && MaskedValueIsZero(V2, C1->getValue(), Q.DL,
01728                                          0, Q.AT, Q.CxtI, Q.DT))
01729           return B;
01730         if (V2 == A && MaskedValueIsZero(V1, C1->getValue(), Q.DL,
01731                                          0, Q.AT, Q.CxtI, Q.DT))
01732           return B;
01733       }
01734     }
01735   }
01736 
01737   // If the operation is with the result of a phi instruction, check whether
01738   // operating on all incoming values of the phi always yields the same value.
01739   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
01740     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
01741       return V;
01742 
01743   return nullptr;
01744 }
01745 
01746 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL,
01747                             const TargetLibraryInfo *TLI,
01748                             const DominatorTree *DT, AssumptionTracker *AT,
01749                             const Instruction *CxtI) {
01750   return ::SimplifyOrInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
01751                           RecursionLimit);
01752 }
01753 
01754 /// SimplifyXorInst - Given operands for a Xor, see if we can
01755 /// fold the result.  If not, this returns null.
01756 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
01757                               unsigned MaxRecurse) {
01758   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
01759     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
01760       Constant *Ops[] = { CLHS, CRHS };
01761       return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
01762                                       Ops, Q.DL, Q.TLI);
01763     }
01764 
01765     // Canonicalize the constant to the RHS.
01766     std::swap(Op0, Op1);
01767   }
01768 
01769   // A ^ undef -> undef
01770   if (match(Op1, m_Undef()))
01771     return Op1;
01772 
01773   // A ^ 0 = A
01774   if (match(Op1, m_Zero()))
01775     return Op0;
01776 
01777   // A ^ A = 0
01778   if (Op0 == Op1)
01779     return Constant::getNullValue(Op0->getType());
01780 
01781   // A ^ ~A  =  ~A ^ A  =  -1
01782   if (match(Op0, m_Not(m_Specific(Op1))) ||
01783       match(Op1, m_Not(m_Specific(Op0))))
01784     return Constant::getAllOnesValue(Op0->getType());
01785 
01786   // Try some generic simplifications for associative operations.
01787   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
01788                                           MaxRecurse))
01789     return V;
01790 
01791   // Threading Xor over selects and phi nodes is pointless, so don't bother.
01792   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
01793   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
01794   // only if B and C are equal.  If B and C are equal then (since we assume
01795   // that operands have already been simplified) "select(cond, B, C)" should
01796   // have been simplified to the common value of B and C already.  Analysing
01797   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
01798   // for threading over phi nodes.
01799 
01800   return nullptr;
01801 }
01802 
01803 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL,
01804                              const TargetLibraryInfo *TLI,
01805                              const DominatorTree *DT, AssumptionTracker *AT,
01806                              const Instruction *CxtI) {
01807   return ::SimplifyXorInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
01808                            RecursionLimit);
01809 }
01810 
01811 static Type *GetCompareTy(Value *Op) {
01812   return CmpInst::makeCmpResultType(Op->getType());
01813 }
01814 
01815 /// ExtractEquivalentCondition - Rummage around inside V looking for something
01816 /// equivalent to the comparison "LHS Pred RHS".  Return such a value if found,
01817 /// otherwise return null.  Helper function for analyzing max/min idioms.
01818 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
01819                                          Value *LHS, Value *RHS) {
01820   SelectInst *SI = dyn_cast<SelectInst>(V);
01821   if (!SI)
01822     return nullptr;
01823   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
01824   if (!Cmp)
01825     return nullptr;
01826   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
01827   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
01828     return Cmp;
01829   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
01830       LHS == CmpRHS && RHS == CmpLHS)
01831     return Cmp;
01832   return nullptr;
01833 }
01834 
01835 // A significant optimization not implemented here is assuming that alloca
01836 // addresses are not equal to incoming argument values. They don't *alias*,
01837 // as we say, but that doesn't mean they aren't equal, so we take a
01838 // conservative approach.
01839 //
01840 // This is inspired in part by C++11 5.10p1:
01841 //   "Two pointers of the same type compare equal if and only if they are both
01842 //    null, both point to the same function, or both represent the same
01843 //    address."
01844 //
01845 // This is pretty permissive.
01846 //
01847 // It's also partly due to C11 6.5.9p6:
01848 //   "Two pointers compare equal if and only if both are null pointers, both are
01849 //    pointers to the same object (including a pointer to an object and a
01850 //    subobject at its beginning) or function, both are pointers to one past the
01851 //    last element of the same array object, or one is a pointer to one past the
01852 //    end of one array object and the other is a pointer to the start of a
01853 //    different array object that happens to immediately follow the first array
01854 //    object in the address space.)
01855 //
01856 // C11's version is more restrictive, however there's no reason why an argument
01857 // couldn't be a one-past-the-end value for a stack object in the caller and be
01858 // equal to the beginning of a stack object in the callee.
01859 //
01860 // If the C and C++ standards are ever made sufficiently restrictive in this
01861 // area, it may be possible to update LLVM's semantics accordingly and reinstate
01862 // this optimization.
01863 static Constant *computePointerICmp(const DataLayout *DL,
01864                                     const TargetLibraryInfo *TLI,
01865                                     CmpInst::Predicate Pred,
01866                                     Value *LHS, Value *RHS) {
01867   // First, skip past any trivial no-ops.
01868   LHS = LHS->stripPointerCasts();
01869   RHS = RHS->stripPointerCasts();
01870 
01871   // A non-null pointer is not equal to a null pointer.
01872   if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
01873       (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
01874     return ConstantInt::get(GetCompareTy(LHS),
01875                             !CmpInst::isTrueWhenEqual(Pred));
01876 
01877   // We can only fold certain predicates on pointer comparisons.
01878   switch (Pred) {
01879   default:
01880     return nullptr;
01881 
01882     // Equality comaprisons are easy to fold.
01883   case CmpInst::ICMP_EQ:
01884   case CmpInst::ICMP_NE:
01885     break;
01886 
01887     // We can only handle unsigned relational comparisons because 'inbounds' on
01888     // a GEP only protects against unsigned wrapping.
01889   case CmpInst::ICMP_UGT:
01890   case CmpInst::ICMP_UGE:
01891   case CmpInst::ICMP_ULT:
01892   case CmpInst::ICMP_ULE:
01893     // However, we have to switch them to their signed variants to handle
01894     // negative indices from the base pointer.
01895     Pred = ICmpInst::getSignedPredicate(Pred);
01896     break;
01897   }
01898 
01899   // Strip off any constant offsets so that we can reason about them.
01900   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
01901   // here and compare base addresses like AliasAnalysis does, however there are
01902   // numerous hazards. AliasAnalysis and its utilities rely on special rules
01903   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
01904   // doesn't need to guarantee pointer inequality when it says NoAlias.
01905   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
01906   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
01907 
01908   // If LHS and RHS are related via constant offsets to the same base
01909   // value, we can replace it with an icmp which just compares the offsets.
01910   if (LHS == RHS)
01911     return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
01912 
01913   // Various optimizations for (in)equality comparisons.
01914   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
01915     // Different non-empty allocations that exist at the same time have
01916     // different addresses (if the program can tell). Global variables always
01917     // exist, so they always exist during the lifetime of each other and all
01918     // allocas. Two different allocas usually have different addresses...
01919     //
01920     // However, if there's an @llvm.stackrestore dynamically in between two
01921     // allocas, they may have the same address. It's tempting to reduce the
01922     // scope of the problem by only looking at *static* allocas here. That would
01923     // cover the majority of allocas while significantly reducing the likelihood
01924     // of having an @llvm.stackrestore pop up in the middle. However, it's not
01925     // actually impossible for an @llvm.stackrestore to pop up in the middle of
01926     // an entry block. Also, if we have a block that's not attached to a
01927     // function, we can't tell if it's "static" under the current definition.
01928     // Theoretically, this problem could be fixed by creating a new kind of
01929     // instruction kind specifically for static allocas. Such a new instruction
01930     // could be required to be at the top of the entry block, thus preventing it
01931     // from being subject to a @llvm.stackrestore. Instcombine could even
01932     // convert regular allocas into these special allocas. It'd be nifty.
01933     // However, until then, this problem remains open.
01934     //
01935     // So, we'll assume that two non-empty allocas have different addresses
01936     // for now.
01937     //
01938     // With all that, if the offsets are within the bounds of their allocations
01939     // (and not one-past-the-end! so we can't use inbounds!), and their
01940     // allocations aren't the same, the pointers are not equal.
01941     //
01942     // Note that it's not necessary to check for LHS being a global variable
01943     // address, due to canonicalization and constant folding.
01944     if (isa<AllocaInst>(LHS) &&
01945         (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
01946       ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
01947       ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
01948       uint64_t LHSSize, RHSSize;
01949       if (LHSOffsetCI && RHSOffsetCI &&
01950           getObjectSize(LHS, LHSSize, DL, TLI) &&
01951           getObjectSize(RHS, RHSSize, DL, TLI)) {
01952         const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
01953         const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
01954         if (!LHSOffsetValue.isNegative() &&
01955             !RHSOffsetValue.isNegative() &&
01956             LHSOffsetValue.ult(LHSSize) &&
01957             RHSOffsetValue.ult(RHSSize)) {
01958           return ConstantInt::get(GetCompareTy(LHS),
01959                                   !CmpInst::isTrueWhenEqual(Pred));
01960         }
01961       }
01962 
01963       // Repeat the above check but this time without depending on DataLayout
01964       // or being able to compute a precise size.
01965       if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
01966           !cast<PointerType>(RHS->getType())->isEmptyTy() &&
01967           LHSOffset->isNullValue() &&
01968           RHSOffset->isNullValue())
01969         return ConstantInt::get(GetCompareTy(LHS),
01970                                 !CmpInst::isTrueWhenEqual(Pred));
01971     }
01972 
01973     // Even if an non-inbounds GEP occurs along the path we can still optimize
01974     // equality comparisons concerning the result. We avoid walking the whole
01975     // chain again by starting where the last calls to
01976     // stripAndComputeConstantOffsets left off and accumulate the offsets.
01977     Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
01978     Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
01979     if (LHS == RHS)
01980       return ConstantExpr::getICmp(Pred,
01981                                    ConstantExpr::getAdd(LHSOffset, LHSNoBound),
01982                                    ConstantExpr::getAdd(RHSOffset, RHSNoBound));
01983   }
01984 
01985   // Otherwise, fail.
01986   return nullptr;
01987 }
01988 
01989 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
01990 /// fold the result.  If not, this returns null.
01991 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
01992                                const Query &Q, unsigned MaxRecurse) {
01993   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
01994   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
01995 
01996   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
01997     if (Constant *CRHS = dyn_cast<Constant>(RHS))
01998       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
01999 
02000     // If we have a constant, make sure it is on the RHS.
02001     std::swap(LHS, RHS);
02002     Pred = CmpInst::getSwappedPredicate(Pred);
02003   }
02004 
02005   Type *ITy = GetCompareTy(LHS); // The return type.
02006   Type *OpTy = LHS->getType();   // The operand type.
02007 
02008   // icmp X, X -> true/false
02009   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
02010   // because X could be 0.
02011   if (LHS == RHS || isa<UndefValue>(RHS))
02012     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
02013 
02014   // Special case logic when the operands have i1 type.
02015   if (OpTy->getScalarType()->isIntegerTy(1)) {
02016     switch (Pred) {
02017     default: break;
02018     case ICmpInst::ICMP_EQ:
02019       // X == 1 -> X
02020       if (match(RHS, m_One()))
02021         return LHS;
02022       break;
02023     case ICmpInst::ICMP_NE:
02024       // X != 0 -> X
02025       if (match(RHS, m_Zero()))
02026         return LHS;
02027       break;
02028     case ICmpInst::ICMP_UGT:
02029       // X >u 0 -> X
02030       if (match(RHS, m_Zero()))
02031         return LHS;
02032       break;
02033     case ICmpInst::ICMP_UGE:
02034       // X >=u 1 -> X
02035       if (match(RHS, m_One()))
02036         return LHS;
02037       break;
02038     case ICmpInst::ICMP_SLT:
02039       // X <s 0 -> X
02040       if (match(RHS, m_Zero()))
02041         return LHS;
02042       break;
02043     case ICmpInst::ICMP_SLE:
02044       // X <=s -1 -> X
02045       if (match(RHS, m_One()))
02046         return LHS;
02047       break;
02048     }
02049   }
02050 
02051   // If we are comparing with zero then try hard since this is a common case.
02052   if (match(RHS, m_Zero())) {
02053     bool LHSKnownNonNegative, LHSKnownNegative;
02054     switch (Pred) {
02055     default: llvm_unreachable("Unknown ICmp predicate!");
02056     case ICmpInst::ICMP_ULT:
02057       return getFalse(ITy);
02058     case ICmpInst::ICMP_UGE:
02059       return getTrue(ITy);
02060     case ICmpInst::ICMP_EQ:
02061     case ICmpInst::ICMP_ULE:
02062       if (isKnownNonZero(LHS, Q.DL, 0, Q.AT, Q.CxtI, Q.DT))
02063         return getFalse(ITy);
02064       break;
02065     case ICmpInst::ICMP_NE:
02066     case ICmpInst::ICMP_UGT:
02067       if (isKnownNonZero(LHS, Q.DL, 0, Q.AT, Q.CxtI, Q.DT))
02068         return getTrue(ITy);
02069       break;
02070     case ICmpInst::ICMP_SLT:
02071       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
02072                      0, Q.AT, Q.CxtI, Q.DT);
02073       if (LHSKnownNegative)
02074         return getTrue(ITy);
02075       if (LHSKnownNonNegative)
02076         return getFalse(ITy);
02077       break;
02078     case ICmpInst::ICMP_SLE:
02079       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
02080                      0, Q.AT, Q.CxtI, Q.DT);
02081       if (LHSKnownNegative)
02082         return getTrue(ITy);
02083       if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL,
02084                                                 0, Q.AT, Q.CxtI, Q.DT))
02085         return getFalse(ITy);
02086       break;
02087     case ICmpInst::ICMP_SGE:
02088       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
02089                      0, Q.AT, Q.CxtI, Q.DT);
02090       if (LHSKnownNegative)
02091         return getFalse(ITy);
02092       if (LHSKnownNonNegative)
02093         return getTrue(ITy);
02094       break;
02095     case ICmpInst::ICMP_SGT:
02096       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
02097                      0, Q.AT, Q.CxtI, Q.DT);
02098       if (LHSKnownNegative)
02099         return getFalse(ITy);
02100       if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 
02101                                                 0, Q.AT, Q.CxtI, Q.DT))
02102         return getTrue(ITy);
02103       break;
02104     }
02105   }
02106 
02107   // See if we are doing a comparison with a constant integer.
02108   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
02109     // Rule out tautological comparisons (eg., ult 0 or uge 0).
02110     ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
02111     if (RHS_CR.isEmptySet())
02112       return ConstantInt::getFalse(CI->getContext());
02113     if (RHS_CR.isFullSet())
02114       return ConstantInt::getTrue(CI->getContext());
02115 
02116     // Many binary operators with constant RHS have easy to compute constant
02117     // range.  Use them to check whether the comparison is a tautology.
02118     unsigned Width = CI->getBitWidth();
02119     APInt Lower = APInt(Width, 0);
02120     APInt Upper = APInt(Width, 0);
02121     ConstantInt *CI2;
02122     if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
02123       // 'urem x, CI2' produces [0, CI2).
02124       Upper = CI2->getValue();
02125     } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
02126       // 'srem x, CI2' produces (-|CI2|, |CI2|).
02127       Upper = CI2->getValue().abs();
02128       Lower = (-Upper) + 1;
02129     } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
02130       // 'udiv CI2, x' produces [0, CI2].
02131       Upper = CI2->getValue() + 1;
02132     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
02133       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
02134       APInt NegOne = APInt::getAllOnesValue(Width);
02135       if (!CI2->isZero())
02136         Upper = NegOne.udiv(CI2->getValue()) + 1;
02137     } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
02138       if (CI2->isMinSignedValue()) {
02139         // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
02140         Lower = CI2->getValue();
02141         Upper = Lower.lshr(1) + 1;
02142       } else {
02143         // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
02144         Upper = CI2->getValue().abs() + 1;
02145         Lower = (-Upper) + 1;
02146       }
02147     } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
02148       APInt IntMin = APInt::getSignedMinValue(Width);
02149       APInt IntMax = APInt::getSignedMaxValue(Width);
02150       APInt Val = CI2->getValue();
02151       if (Val.isAllOnesValue()) {
02152         // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
02153         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
02154         Lower = IntMin + 1;
02155         Upper = IntMax + 1;
02156       } else if (Val.countLeadingZeros() < Width - 1) {
02157         // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
02158         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
02159         Lower = IntMin.sdiv(Val);
02160         Upper = IntMax.sdiv(Val);
02161         if (Lower.sgt(Upper))
02162           std::swap(Lower, Upper);
02163         Upper = Upper + 1;
02164         assert(Upper != Lower && "Upper part of range has wrapped!");
02165       }
02166     } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
02167       // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
02168       Lower = CI2->getValue();
02169       Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
02170     } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
02171       if (CI2->isNegative()) {
02172         // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
02173         unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
02174         Lower = CI2->getValue().shl(ShiftAmount);
02175         Upper = CI2->getValue() + 1;
02176       } else {
02177         // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
02178         unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
02179         Lower = CI2->getValue();
02180         Upper = CI2->getValue().shl(ShiftAmount) + 1;
02181       }
02182     } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
02183       // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
02184       APInt NegOne = APInt::getAllOnesValue(Width);
02185       if (CI2->getValue().ult(Width))
02186         Upper = NegOne.lshr(CI2->getValue()) + 1;
02187     } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
02188       // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
02189       unsigned ShiftAmount = Width - 1;
02190       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
02191         ShiftAmount = CI2->getValue().countTrailingZeros();
02192       Lower = CI2->getValue().lshr(ShiftAmount);
02193       Upper = CI2->getValue() + 1;
02194     } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
02195       // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
02196       APInt IntMin = APInt::getSignedMinValue(Width);
02197       APInt IntMax = APInt::getSignedMaxValue(Width);
02198       if (CI2->getValue().ult(Width)) {
02199         Lower = IntMin.ashr(CI2->getValue());
02200         Upper = IntMax.ashr(CI2->getValue()) + 1;
02201       }
02202     } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
02203       unsigned ShiftAmount = Width - 1;
02204       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
02205         ShiftAmount = CI2->getValue().countTrailingZeros();
02206       if (CI2->isNegative()) {
02207         // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
02208         Lower = CI2->getValue();
02209         Upper = CI2->getValue().ashr(ShiftAmount) + 1;
02210       } else {
02211         // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
02212         Lower = CI2->getValue().ashr(ShiftAmount);
02213         Upper = CI2->getValue() + 1;
02214       }
02215     } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
02216       // 'or x, CI2' produces [CI2, UINT_MAX].
02217       Lower = CI2->getValue();
02218     } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
02219       // 'and x, CI2' produces [0, CI2].
02220       Upper = CI2->getValue() + 1;
02221     }
02222     if (Lower != Upper) {
02223       ConstantRange LHS_CR = ConstantRange(Lower, Upper);
02224       if (RHS_CR.contains(LHS_CR))
02225         return ConstantInt::getTrue(RHS->getContext());
02226       if (RHS_CR.inverse().contains(LHS_CR))
02227         return ConstantInt::getFalse(RHS->getContext());
02228     }
02229   }
02230 
02231   // Compare of cast, for example (zext X) != 0 -> X != 0
02232   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
02233     Instruction *LI = cast<CastInst>(LHS);
02234     Value *SrcOp = LI->getOperand(0);
02235     Type *SrcTy = SrcOp->getType();
02236     Type *DstTy = LI->getType();
02237 
02238     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
02239     // if the integer type is the same size as the pointer type.
02240     if (MaxRecurse && Q.DL && isa<PtrToIntInst>(LI) &&
02241         Q.DL->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
02242       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
02243         // Transfer the cast to the constant.
02244         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
02245                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
02246                                         Q, MaxRecurse-1))
02247           return V;
02248       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
02249         if (RI->getOperand(0)->getType() == SrcTy)
02250           // Compare without the cast.
02251           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
02252                                           Q, MaxRecurse-1))
02253             return V;
02254       }
02255     }
02256 
02257     if (isa<ZExtInst>(LHS)) {
02258       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
02259       // same type.
02260       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
02261         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
02262           // Compare X and Y.  Note that signed predicates become unsigned.
02263           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
02264                                           SrcOp, RI->getOperand(0), Q,
02265                                           MaxRecurse-1))
02266             return V;
02267       }
02268       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
02269       // too.  If not, then try to deduce the result of the comparison.
02270       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
02271         // Compute the constant that would happen if we truncated to SrcTy then
02272         // reextended to DstTy.
02273         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
02274         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
02275 
02276         // If the re-extended constant didn't change then this is effectively
02277         // also a case of comparing two zero-extended values.
02278         if (RExt == CI && MaxRecurse)
02279           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
02280                                         SrcOp, Trunc, Q, MaxRecurse-1))
02281             return V;
02282 
02283         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
02284         // there.  Use this to work out the result of the comparison.
02285         if (RExt != CI) {
02286           switch (Pred) {
02287           default: llvm_unreachable("Unknown ICmp predicate!");
02288           // LHS <u RHS.
02289           case ICmpInst::ICMP_EQ:
02290           case ICmpInst::ICMP_UGT:
02291           case ICmpInst::ICMP_UGE:
02292             return ConstantInt::getFalse(CI->getContext());
02293 
02294           case ICmpInst::ICMP_NE:
02295           case ICmpInst::ICMP_ULT:
02296           case ICmpInst::ICMP_ULE:
02297             return ConstantInt::getTrue(CI->getContext());
02298 
02299           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
02300           // is non-negative then LHS <s RHS.
02301           case ICmpInst::ICMP_SGT:
02302           case ICmpInst::ICMP_SGE:
02303             return CI->getValue().isNegative() ?
02304               ConstantInt::getTrue(CI->getContext()) :
02305               ConstantInt::getFalse(CI->getContext());
02306 
02307           case ICmpInst::ICMP_SLT:
02308           case ICmpInst::ICMP_SLE:
02309             return CI->getValue().isNegative() ?
02310               ConstantInt::getFalse(CI->getContext()) :
02311               ConstantInt::getTrue(CI->getContext());
02312           }
02313         }
02314       }
02315     }
02316 
02317     if (isa<SExtInst>(LHS)) {
02318       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
02319       // same type.
02320       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
02321         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
02322           // Compare X and Y.  Note that the predicate does not change.
02323           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
02324                                           Q, MaxRecurse-1))
02325             return V;
02326       }
02327       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
02328       // too.  If not, then try to deduce the result of the comparison.
02329       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
02330         // Compute the constant that would happen if we truncated to SrcTy then
02331         // reextended to DstTy.
02332         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
02333         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
02334 
02335         // If the re-extended constant didn't change then this is effectively
02336         // also a case of comparing two sign-extended values.
02337         if (RExt == CI && MaxRecurse)
02338           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
02339             return V;
02340 
02341         // Otherwise the upper bits of LHS are all equal, while RHS has varying
02342         // bits there.  Use this to work out the result of the comparison.
02343         if (RExt != CI) {
02344           switch (Pred) {
02345           default: llvm_unreachable("Unknown ICmp predicate!");
02346           case ICmpInst::ICMP_EQ:
02347             return ConstantInt::getFalse(CI->getContext());
02348           case ICmpInst::ICMP_NE:
02349             return ConstantInt::getTrue(CI->getContext());
02350 
02351           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
02352           // LHS >s RHS.
02353           case ICmpInst::ICMP_SGT:
02354           case ICmpInst::ICMP_SGE:
02355             return CI->getValue().isNegative() ?
02356               ConstantInt::getTrue(CI->getContext()) :
02357               ConstantInt::getFalse(CI->getContext());
02358           case ICmpInst::ICMP_SLT:
02359           case ICmpInst::ICMP_SLE:
02360             return CI->getValue().isNegative() ?
02361               ConstantInt::getFalse(CI->getContext()) :
02362               ConstantInt::getTrue(CI->getContext());
02363 
02364           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
02365           // LHS >u RHS.
02366           case ICmpInst::ICMP_UGT:
02367           case ICmpInst::ICMP_UGE:
02368             // Comparison is true iff the LHS <s 0.
02369             if (MaxRecurse)
02370               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
02371                                               Constant::getNullValue(SrcTy),
02372                                               Q, MaxRecurse-1))
02373                 return V;
02374             break;
02375           case ICmpInst::ICMP_ULT:
02376           case ICmpInst::ICMP_ULE:
02377             // Comparison is true iff the LHS >=s 0.
02378             if (MaxRecurse)
02379               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
02380                                               Constant::getNullValue(SrcTy),
02381                                               Q, MaxRecurse-1))
02382                 return V;
02383             break;
02384           }
02385         }
02386       }
02387     }
02388   }
02389 
02390   // If a bit is known to be zero for A and known to be one for B,
02391   // then A and B cannot be equal.
02392   if (ICmpInst::isEquality(Pred)) {
02393     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
02394       uint32_t BitWidth = CI->getBitWidth();
02395       APInt LHSKnownZero(BitWidth, 0);
02396       APInt LHSKnownOne(BitWidth, 0);
02397       computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL,
02398                        0, Q.AT, Q.CxtI, Q.DT);
02399       APInt RHSKnownZero(BitWidth, 0);
02400       APInt RHSKnownOne(BitWidth, 0);
02401       computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, Q.DL,
02402                        0, Q.AT, Q.CxtI, Q.DT);
02403       if (((LHSKnownOne & RHSKnownZero) != 0) ||
02404           ((LHSKnownZero & RHSKnownOne) != 0))
02405         return (Pred == ICmpInst::ICMP_EQ)
02406                    ? ConstantInt::getFalse(CI->getContext())
02407                    : ConstantInt::getTrue(CI->getContext());
02408     }
02409   }
02410 
02411   // Special logic for binary operators.
02412   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
02413   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
02414   if (MaxRecurse && (LBO || RBO)) {
02415     // Analyze the case when either LHS or RHS is an add instruction.
02416     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
02417     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
02418     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
02419     if (LBO && LBO->getOpcode() == Instruction::Add) {
02420       A = LBO->getOperand(0); B = LBO->getOperand(1);
02421       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
02422         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
02423         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
02424     }
02425     if (RBO && RBO->getOpcode() == Instruction::Add) {
02426       C = RBO->getOperand(0); D = RBO->getOperand(1);
02427       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
02428         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
02429         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
02430     }
02431 
02432     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
02433     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
02434       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
02435                                       Constant::getNullValue(RHS->getType()),
02436                                       Q, MaxRecurse-1))
02437         return V;
02438 
02439     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
02440     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
02441       if (Value *V = SimplifyICmpInst(Pred,
02442                                       Constant::getNullValue(LHS->getType()),
02443                                       C == LHS ? D : C, Q, MaxRecurse-1))
02444         return V;
02445 
02446     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
02447     if (A && C && (A == C || A == D || B == C || B == D) &&
02448         NoLHSWrapProblem && NoRHSWrapProblem) {
02449       // Determine Y and Z in the form icmp (X+Y), (X+Z).
02450       Value *Y, *Z;
02451       if (A == C) {
02452         // C + B == C + D  ->  B == D
02453         Y = B;
02454         Z = D;
02455       } else if (A == D) {
02456         // D + B == C + D  ->  B == C
02457         Y = B;
02458         Z = C;
02459       } else if (B == C) {
02460         // A + C == C + D  ->  A == D
02461         Y = A;
02462         Z = D;
02463       } else {
02464         assert(B == D);
02465         // A + D == C + D  ->  A == C
02466         Y = A;
02467         Z = C;
02468       }
02469       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
02470         return V;
02471     }
02472   }
02473 
02474   // 0 - (zext X) pred C
02475   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
02476     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
02477       if (RHSC->getValue().isStrictlyPositive()) {
02478         if (Pred == ICmpInst::ICMP_SLT)
02479           return ConstantInt::getTrue(RHSC->getContext());
02480         if (Pred == ICmpInst::ICMP_SGE)
02481           return ConstantInt::getFalse(RHSC->getContext());
02482         if (Pred == ICmpInst::ICMP_EQ)
02483           return ConstantInt::getFalse(RHSC->getContext());
02484         if (Pred == ICmpInst::ICMP_NE)
02485           return ConstantInt::getTrue(RHSC->getContext());
02486       }
02487       if (RHSC->getValue().isNonNegative()) {
02488         if (Pred == ICmpInst::ICMP_SLE)
02489           return ConstantInt::getTrue(RHSC->getContext());
02490         if (Pred == ICmpInst::ICMP_SGT)
02491           return ConstantInt::getFalse(RHSC->getContext());
02492       }
02493     }
02494   }
02495 
02496   // icmp pred (urem X, Y), Y
02497   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
02498     bool KnownNonNegative, KnownNegative;
02499     switch (Pred) {
02500     default:
02501       break;
02502     case ICmpInst::ICMP_SGT:
02503     case ICmpInst::ICMP_SGE:
02504       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL,
02505                      0, Q.AT, Q.CxtI, Q.DT);
02506       if (!KnownNonNegative)
02507         break;
02508       // fall-through
02509     case ICmpInst::ICMP_EQ:
02510     case ICmpInst::ICMP_UGT:
02511     case ICmpInst::ICMP_UGE:
02512       return getFalse(ITy);
02513     case ICmpInst::ICMP_SLT:
02514     case ICmpInst::ICMP_SLE:
02515       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL,
02516                      0, Q.AT, Q.CxtI, Q.DT);
02517       if (!KnownNonNegative)
02518         break;
02519       // fall-through
02520     case ICmpInst::ICMP_NE:
02521     case ICmpInst::ICMP_ULT:
02522     case ICmpInst::ICMP_ULE:
02523       return getTrue(ITy);
02524     }
02525   }
02526 
02527   // icmp pred X, (urem Y, X)
02528   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
02529     bool KnownNonNegative, KnownNegative;
02530     switch (Pred) {
02531     default:
02532       break;
02533     case ICmpInst::ICMP_SGT:
02534     case ICmpInst::ICMP_SGE:
02535       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL,
02536                      0, Q.AT, Q.CxtI, Q.DT);
02537       if (!KnownNonNegative)
02538         break;
02539       // fall-through
02540     case ICmpInst::ICMP_NE:
02541     case ICmpInst::ICMP_UGT:
02542     case ICmpInst::ICMP_UGE:
02543       return getTrue(ITy);
02544     case ICmpInst::ICMP_SLT:
02545     case ICmpInst::ICMP_SLE:
02546       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL,
02547                      0, Q.AT, Q.CxtI, Q.DT);
02548       if (!KnownNonNegative)
02549         break;
02550       // fall-through
02551     case ICmpInst::ICMP_EQ:
02552     case ICmpInst::ICMP_ULT:
02553     case ICmpInst::ICMP_ULE:
02554       return getFalse(ITy);
02555     }
02556   }
02557 
02558   // x udiv y <=u x.
02559   if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
02560     // icmp pred (X /u Y), X
02561     if (Pred == ICmpInst::ICMP_UGT)
02562       return getFalse(ITy);
02563     if (Pred == ICmpInst::ICMP_ULE)
02564       return getTrue(ITy);
02565   }
02566 
02567   // handle:
02568   //   CI2 << X == CI
02569   //   CI2 << X != CI
02570   //
02571   //   where CI2 is a power of 2 and CI isn't
02572   if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
02573     const APInt *CI2Val, *CIVal = &CI->getValue();
02574     if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
02575         CI2Val->isPowerOf2()) {
02576       if (!CIVal->isPowerOf2()) {
02577         // CI2 << X can equal zero in some circumstances,
02578         // this simplification is unsafe if CI is zero.
02579         //
02580         // We know it is safe if:
02581         // - The shift is nsw, we can't shift out the one bit.
02582         // - The shift is nuw, we can't shift out the one bit.
02583         // - CI2 is one
02584         // - CI isn't zero
02585         if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
02586             *CI2Val == 1 || !CI->isZero()) {
02587           if (Pred == ICmpInst::ICMP_EQ)
02588             return ConstantInt::getFalse(RHS->getContext());
02589           if (Pred == ICmpInst::ICMP_NE)
02590             return ConstantInt::getTrue(RHS->getContext());
02591         }
02592       }
02593       if (CIVal->isSignBit() && *CI2Val == 1) {
02594         if (Pred == ICmpInst::ICMP_UGT)
02595           return ConstantInt::getFalse(RHS->getContext());
02596         if (Pred == ICmpInst::ICMP_ULE)
02597           return ConstantInt::getTrue(RHS->getContext());
02598       }
02599     }
02600   }
02601 
02602   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
02603       LBO->getOperand(1) == RBO->getOperand(1)) {
02604     switch (LBO->getOpcode()) {
02605     default: break;
02606     case Instruction::UDiv:
02607     case Instruction::LShr:
02608       if (ICmpInst::isSigned(Pred))
02609         break;
02610       // fall-through
02611     case Instruction::SDiv:
02612     case Instruction::AShr:
02613       if (!LBO->isExact() || !RBO->isExact())
02614         break;
02615       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
02616                                       RBO->getOperand(0), Q, MaxRecurse-1))
02617         return V;
02618       break;
02619     case Instruction::Shl: {
02620       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
02621       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
02622       if (!NUW && !NSW)
02623         break;
02624       if (!NSW && ICmpInst::isSigned(Pred))
02625         break;
02626       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
02627                                       RBO->getOperand(0), Q, MaxRecurse-1))
02628         return V;
02629       break;
02630     }
02631     }
02632   }
02633 
02634   // Simplify comparisons involving max/min.
02635   Value *A, *B;
02636   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
02637   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
02638 
02639   // Signed variants on "max(a,b)>=a -> true".
02640   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
02641     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
02642     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
02643     // We analyze this as smax(A, B) pred A.
02644     P = Pred;
02645   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
02646              (A == LHS || B == LHS)) {
02647     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
02648     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
02649     // We analyze this as smax(A, B) swapped-pred A.
02650     P = CmpInst::getSwappedPredicate(Pred);
02651   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
02652              (A == RHS || B == RHS)) {
02653     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
02654     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
02655     // We analyze this as smax(-A, -B) swapped-pred -A.
02656     // Note that we do not need to actually form -A or -B thanks to EqP.
02657     P = CmpInst::getSwappedPredicate(Pred);
02658   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
02659              (A == LHS || B == LHS)) {
02660     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
02661     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
02662     // We analyze this as smax(-A, -B) pred -A.
02663     // Note that we do not need to actually form -A or -B thanks to EqP.
02664     P = Pred;
02665   }
02666   if (P != CmpInst::BAD_ICMP_PREDICATE) {
02667     // Cases correspond to "max(A, B) p A".
02668     switch (P) {
02669     default:
02670       break;
02671     case CmpInst::ICMP_EQ:
02672     case CmpInst::ICMP_SLE:
02673       // Equivalent to "A EqP B".  This may be the same as the condition tested
02674       // in the max/min; if so, we can just return that.
02675       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
02676         return V;
02677       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
02678         return V;
02679       // Otherwise, see if "A EqP B" simplifies.
02680       if (MaxRecurse)
02681         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
02682           return V;
02683       break;
02684     case CmpInst::ICMP_NE:
02685     case CmpInst::ICMP_SGT: {
02686       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
02687       // Equivalent to "A InvEqP B".  This may be the same as the condition
02688       // tested in the max/min; if so, we can just return that.
02689       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
02690         return V;
02691       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
02692         return V;
02693       // Otherwise, see if "A InvEqP B" simplifies.
02694       if (MaxRecurse)
02695         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
02696           return V;
02697       break;
02698     }
02699     case CmpInst::ICMP_SGE:
02700       // Always true.
02701       return getTrue(ITy);
02702     case CmpInst::ICMP_SLT:
02703       // Always false.
02704       return getFalse(ITy);
02705     }
02706   }
02707 
02708   // Unsigned variants on "max(a,b)>=a -> true".
02709   P = CmpInst::BAD_ICMP_PREDICATE;
02710   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
02711     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
02712     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
02713     // We analyze this as umax(A, B) pred A.
02714     P = Pred;
02715   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
02716              (A == LHS || B == LHS)) {
02717     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
02718     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
02719     // We analyze this as umax(A, B) swapped-pred A.
02720     P = CmpInst::getSwappedPredicate(Pred);
02721   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
02722              (A == RHS || B == RHS)) {
02723     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
02724     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
02725     // We analyze this as umax(-A, -B) swapped-pred -A.
02726     // Note that we do not need to actually form -A or -B thanks to EqP.
02727     P = CmpInst::getSwappedPredicate(Pred);
02728   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
02729              (A == LHS || B == LHS)) {
02730     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
02731     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
02732     // We analyze this as umax(-A, -B) pred -A.
02733     // Note that we do not need to actually form -A or -B thanks to EqP.
02734     P = Pred;
02735   }
02736   if (P != CmpInst::BAD_ICMP_PREDICATE) {
02737     // Cases correspond to "max(A, B) p A".
02738     switch (P) {
02739     default:
02740       break;
02741     case CmpInst::ICMP_EQ:
02742     case CmpInst::ICMP_ULE:
02743       // Equivalent to "A EqP B".  This may be the same as the condition tested
02744       // in the max/min; if so, we can just return that.
02745       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
02746         return V;
02747       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
02748         return V;
02749       // Otherwise, see if "A EqP B" simplifies.
02750       if (MaxRecurse)
02751         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
02752           return V;
02753       break;
02754     case CmpInst::ICMP_NE:
02755     case CmpInst::ICMP_UGT: {
02756       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
02757       // Equivalent to "A InvEqP B".  This may be the same as the condition
02758       // tested in the max/min; if so, we can just return that.
02759       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
02760         return V;
02761       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
02762         return V;
02763       // Otherwise, see if "A InvEqP B" simplifies.
02764       if (MaxRecurse)
02765         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
02766           return V;
02767       break;
02768     }
02769     case CmpInst::ICMP_UGE:
02770       // Always true.
02771       return getTrue(ITy);
02772     case CmpInst::ICMP_ULT:
02773       // Always false.
02774       return getFalse(ITy);
02775     }
02776   }
02777 
02778   // Variants on "max(x,y) >= min(x,z)".
02779   Value *C, *D;
02780   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
02781       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
02782       (A == C || A == D || B == C || B == D)) {
02783     // max(x, ?) pred min(x, ?).
02784     if (Pred == CmpInst::ICMP_SGE)
02785       // Always true.
02786       return getTrue(ITy);
02787     if (Pred == CmpInst::ICMP_SLT)
02788       // Always false.
02789       return getFalse(ITy);
02790   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
02791              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
02792              (A == C || A == D || B == C || B == D)) {
02793     // min(x, ?) pred max(x, ?).
02794     if (Pred == CmpInst::ICMP_SLE)
02795       // Always true.
02796       return getTrue(ITy);
02797     if (Pred == CmpInst::ICMP_SGT)
02798       // Always false.
02799       return getFalse(ITy);
02800   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
02801              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
02802              (A == C || A == D || B == C || B == D)) {
02803     // max(x, ?) pred min(x, ?).
02804     if (Pred == CmpInst::ICMP_UGE)
02805       // Always true.
02806       return getTrue(ITy);
02807     if (Pred == CmpInst::ICMP_ULT)
02808       // Always false.
02809       return getFalse(ITy);
02810   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
02811              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
02812              (A == C || A == D || B == C || B == D)) {
02813     // min(x, ?) pred max(x, ?).
02814     if (Pred == CmpInst::ICMP_ULE)
02815       // Always true.
02816       return getTrue(ITy);
02817     if (Pred == CmpInst::ICMP_UGT)
02818       // Always false.
02819       return getFalse(ITy);
02820   }
02821 
02822   // Simplify comparisons of related pointers using a powerful, recursive
02823   // GEP-walk when we have target data available..
02824   if (LHS->getType()->isPointerTy())
02825     if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
02826       return C;
02827 
02828   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
02829     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
02830       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
02831           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
02832           (ICmpInst::isEquality(Pred) ||
02833            (GLHS->isInBounds() && GRHS->isInBounds() &&
02834             Pred == ICmpInst::getSignedPredicate(Pred)))) {
02835         // The bases are equal and the indices are constant.  Build a constant
02836         // expression GEP with the same indices and a null base pointer to see
02837         // what constant folding can make out of it.
02838         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
02839         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
02840         Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
02841 
02842         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
02843         Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
02844         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
02845       }
02846     }
02847   }
02848 
02849   // If the comparison is with the result of a select instruction, check whether
02850   // comparing with either branch of the select always yields the same value.
02851   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
02852     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
02853       return V;
02854 
02855   // If the comparison is with the result of a phi instruction, check whether
02856   // doing the compare with each incoming phi value yields a common result.
02857   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
02858     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
02859       return V;
02860 
02861   return nullptr;
02862 }
02863 
02864 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
02865                               const DataLayout *DL,
02866                               const TargetLibraryInfo *TLI,
02867                               const DominatorTree *DT,
02868                               AssumptionTracker *AT,
02869                               Instruction *CxtI) {
02870   return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
02871                             RecursionLimit);
02872 }
02873 
02874 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
02875 /// fold the result.  If not, this returns null.
02876 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
02877                                const Query &Q, unsigned MaxRecurse) {
02878   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
02879   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
02880 
02881   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
02882     if (Constant *CRHS = dyn_cast<Constant>(RHS))
02883       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
02884 
02885     // If we have a constant, make sure it is on the RHS.
02886     std::swap(LHS, RHS);
02887     Pred = CmpInst::getSwappedPredicate(Pred);
02888   }
02889 
02890   // Fold trivial predicates.
02891   if (Pred == FCmpInst::FCMP_FALSE)
02892     return ConstantInt::get(GetCompareTy(LHS), 0);
02893   if (Pred == FCmpInst::FCMP_TRUE)
02894     return ConstantInt::get(GetCompareTy(LHS), 1);
02895 
02896   if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
02897     return UndefValue::get(GetCompareTy(LHS));
02898 
02899   // fcmp x,x -> true/false.  Not all compares are foldable.
02900   if (LHS == RHS) {
02901     if (CmpInst::isTrueWhenEqual(Pred))
02902       return ConstantInt::get(GetCompareTy(LHS), 1);
02903     if (CmpInst::isFalseWhenEqual(Pred))
02904       return ConstantInt::get(GetCompareTy(LHS), 0);
02905   }
02906 
02907   // Handle fcmp with constant RHS
02908   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
02909     // If the constant is a nan, see if we can fold the comparison based on it.
02910     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
02911       if (CFP->getValueAPF().isNaN()) {
02912         if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
02913           return ConstantInt::getFalse(CFP->getContext());
02914         assert(FCmpInst::isUnordered(Pred) &&
02915                "Comparison must be either ordered or unordered!");
02916         // True if unordered.
02917         return ConstantInt::getTrue(CFP->getContext());
02918       }
02919       // Check whether the constant is an infinity.
02920       if (CFP->getValueAPF().isInfinity()) {
02921         if (CFP->getValueAPF().isNegative()) {
02922           switch (Pred) {
02923           case FCmpInst::FCMP_OLT:
02924             // No value is ordered and less than negative infinity.
02925             return ConstantInt::getFalse(CFP->getContext());
02926           case FCmpInst::FCMP_UGE:
02927             // All values are unordered with or at least negative infinity.
02928             return ConstantInt::getTrue(CFP->getContext());
02929           default:
02930             break;
02931           }
02932         } else {
02933           switch (Pred) {
02934           case FCmpInst::FCMP_OGT:
02935             // No value is ordered and greater than infinity.
02936             return ConstantInt::getFalse(CFP->getContext());
02937           case FCmpInst::FCMP_ULE:
02938             // All values are unordered with and at most infinity.
02939             return ConstantInt::getTrue(CFP->getContext());
02940           default:
02941             break;
02942           }
02943         }
02944       }
02945     }
02946   }
02947 
02948   // If the comparison is with the result of a select instruction, check whether
02949   // comparing with either branch of the select always yields the same value.
02950   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
02951     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
02952       return V;
02953 
02954   // If the comparison is with the result of a phi instruction, check whether
02955   // doing the compare with each incoming phi value yields a common result.
02956   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
02957     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
02958       return V;
02959 
02960   return nullptr;
02961 }
02962 
02963 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
02964                               const DataLayout *DL,
02965                               const TargetLibraryInfo *TLI,
02966                               const DominatorTree *DT,
02967                               AssumptionTracker *AT,
02968                               const Instruction *CxtI) {
02969   return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
02970                             RecursionLimit);
02971 }
02972 
02973 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
02974 /// the result.  If not, this returns null.
02975 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
02976                                  Value *FalseVal, const Query &Q,
02977                                  unsigned MaxRecurse) {
02978   // select true, X, Y  -> X
02979   // select false, X, Y -> Y
02980   if (Constant *CB = dyn_cast<Constant>(CondVal)) {
02981     if (CB->isAllOnesValue())
02982       return TrueVal;
02983     if (CB->isNullValue())
02984       return FalseVal;
02985   }
02986 
02987   // select C, X, X -> X
02988   if (TrueVal == FalseVal)
02989     return TrueVal;
02990 
02991   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
02992     if (isa<Constant>(TrueVal))
02993       return TrueVal;
02994     return FalseVal;
02995   }
02996   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
02997     return FalseVal;
02998   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
02999     return TrueVal;
03000 
03001   return nullptr;
03002 }
03003 
03004 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
03005                                 const DataLayout *DL,
03006                                 const TargetLibraryInfo *TLI,
03007                                 const DominatorTree *DT,
03008                                 AssumptionTracker *AT,
03009                                 const Instruction *CxtI) {
03010   return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
03011                               Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
03012 }
03013 
03014 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
03015 /// fold the result.  If not, this returns null.
03016 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
03017   // The type of the GEP pointer operand.
03018   PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType());
03019   unsigned AS = PtrTy->getAddressSpace();
03020 
03021   // getelementptr P -> P.
03022   if (Ops.size() == 1)
03023     return Ops[0];
03024 
03025   // Compute the (pointer) type returned by the GEP instruction.
03026   Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
03027   Type *GEPTy = PointerType::get(LastType, AS);
03028   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
03029     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
03030 
03031   if (isa<UndefValue>(Ops[0]))
03032     return UndefValue::get(GEPTy);
03033 
03034   if (Ops.size() == 2) {
03035     // getelementptr P, 0 -> P.
03036     if (match(Ops[1], m_Zero()))
03037       return Ops[0];
03038 
03039     Type *Ty = PtrTy->getElementType();
03040     if (Q.DL && Ty->isSized()) {
03041       Value *P;
03042       uint64_t C;
03043       uint64_t TyAllocSize = Q.DL->getTypeAllocSize(Ty);
03044       // getelementptr P, N -> P if P points to a type of zero size.
03045       if (TyAllocSize == 0)
03046         return Ops[0];
03047 
03048       // The following transforms are only safe if the ptrtoint cast
03049       // doesn't truncate the pointers.
03050       if (Ops[1]->getType()->getScalarSizeInBits() ==
03051           Q.DL->getPointerSizeInBits(AS)) {
03052         auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
03053           if (match(P, m_Zero()))
03054             return Constant::getNullValue(GEPTy);
03055           Value *Temp;
03056           if (match(P, m_PtrToInt(m_Value(Temp))))
03057             if (Temp->getType() == GEPTy)
03058               return Temp;
03059           return nullptr;
03060         };
03061 
03062         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
03063         if (TyAllocSize == 1 &&
03064             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
03065           if (Value *R = PtrToIntOrZero(P))
03066             return R;
03067 
03068         // getelementptr V, (ashr (sub P, V), C) -> Q
03069         // if P points to a type of size 1 << C.
03070         if (match(Ops[1],
03071                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
03072                          m_ConstantInt(C))) &&
03073             TyAllocSize == 1ULL << C)
03074           if (Value *R = PtrToIntOrZero(P))
03075             return R;
03076 
03077         // getelementptr V, (sdiv (sub P, V), C) -> Q
03078         // if P points to a type of size C.
03079         if (match(Ops[1],
03080                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
03081                          m_SpecificInt(TyAllocSize))))
03082           if (Value *R = PtrToIntOrZero(P))
03083             return R;
03084       }
03085     }
03086   }
03087 
03088   // Check to see if this is constant foldable.
03089   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
03090     if (!isa<Constant>(Ops[i]))
03091       return nullptr;
03092 
03093   return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
03094 }
03095 
03096 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *DL,
03097                              const TargetLibraryInfo *TLI,
03098                              const DominatorTree *DT, AssumptionTracker *AT,
03099                              const Instruction *CxtI) {
03100   return ::SimplifyGEPInst(Ops, Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
03101 }
03102 
03103 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
03104 /// can fold the result.  If not, this returns null.
03105 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
03106                                       ArrayRef<unsigned> Idxs, const Query &Q,
03107                                       unsigned) {
03108   if (Constant *CAgg = dyn_cast<Constant>(Agg))
03109     if (Constant *CVal = dyn_cast<Constant>(Val))
03110       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
03111 
03112   // insertvalue x, undef, n -> x
03113   if (match(Val, m_Undef()))
03114     return Agg;
03115 
03116   // insertvalue x, (extractvalue y, n), n
03117   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
03118     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
03119         EV->getIndices() == Idxs) {
03120       // insertvalue undef, (extractvalue y, n), n -> y
03121       if (match(Agg, m_Undef()))
03122         return EV->getAggregateOperand();
03123 
03124       // insertvalue y, (extractvalue y, n), n -> y
03125       if (Agg == EV->getAggregateOperand())
03126         return Agg;
03127     }
03128 
03129   return nullptr;
03130 }
03131 
03132 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
03133                                      ArrayRef<unsigned> Idxs,
03134                                      const DataLayout *DL,
03135                                      const TargetLibraryInfo *TLI,
03136                                      const DominatorTree *DT,
03137                                      AssumptionTracker *AT,
03138                                      const Instruction *CxtI) {
03139   return ::SimplifyInsertValueInst(Agg, Val, Idxs,
03140                                    Query (DL, TLI, DT, AT, CxtI),
03141                                    RecursionLimit);
03142 }
03143 
03144 /// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
03145 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
03146   // If all of the PHI's incoming values are the same then replace the PHI node
03147   // with the common value.
03148   Value *CommonValue = nullptr;
03149   bool HasUndefInput = false;
03150   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
03151     Value *Incoming = PN->getIncomingValue(i);
03152     // If the incoming value is the phi node itself, it can safely be skipped.
03153     if (Incoming == PN) continue;
03154     if (isa<UndefValue>(Incoming)) {
03155       // Remember that we saw an undef value, but otherwise ignore them.
03156       HasUndefInput = true;
03157       continue;
03158     }
03159     if (CommonValue && Incoming != CommonValue)
03160       return nullptr;  // Not the same, bail out.
03161     CommonValue = Incoming;
03162   }
03163 
03164   // If CommonValue is null then all of the incoming values were either undef or
03165   // equal to the phi node itself.
03166   if (!CommonValue)
03167     return UndefValue::get(PN->getType());
03168 
03169   // If we have a PHI node like phi(X, undef, X), where X is defined by some
03170   // instruction, we cannot return X as the result of the PHI node unless it
03171   // dominates the PHI block.
03172   if (HasUndefInput)
03173     return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
03174 
03175   return CommonValue;
03176 }
03177 
03178 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
03179   if (Constant *C = dyn_cast<Constant>(Op))
03180     return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
03181 
03182   return nullptr;
03183 }
03184 
03185 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL,
03186                                const TargetLibraryInfo *TLI,
03187                                const DominatorTree *DT,
03188                                AssumptionTracker *AT,
03189                                const Instruction *CxtI) {
03190   return ::SimplifyTruncInst(Op, Ty, Query (DL, TLI, DT, AT, CxtI),
03191                              RecursionLimit);
03192 }
03193 
03194 //=== Helper functions for higher up the class hierarchy.
03195 
03196 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
03197 /// fold the result.  If not, this returns null.
03198 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
03199                             const Query &Q, unsigned MaxRecurse) {
03200   switch (Opcode) {
03201   case Instruction::Add:
03202     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
03203                            Q, MaxRecurse);
03204   case Instruction::FAdd:
03205     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
03206 
03207   case Instruction::Sub:
03208     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
03209                            Q, MaxRecurse);
03210   case Instruction::FSub:
03211     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
03212 
03213   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
03214   case Instruction::FMul:
03215     return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
03216   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
03217   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
03218   case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
03219   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
03220   case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
03221   case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
03222   case Instruction::Shl:
03223     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
03224                            Q, MaxRecurse);
03225   case Instruction::LShr:
03226     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
03227   case Instruction::AShr:
03228     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
03229   case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
03230   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
03231   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
03232   default:
03233     if (Constant *CLHS = dyn_cast<Constant>(LHS))
03234       if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
03235         Constant *COps[] = {CLHS, CRHS};
03236         return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL,
03237                                         Q.TLI);
03238       }
03239 
03240     // If the operation is associative, try some generic simplifications.
03241     if (Instruction::isAssociative(Opcode))
03242       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
03243         return V;
03244 
03245     // If the operation is with the result of a select instruction check whether
03246     // operating on either branch of the select always yields the same value.
03247     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
03248       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
03249         return V;
03250 
03251     // If the operation is with the result of a phi instruction, check whether
03252     // operating on all incoming values of the phi always yields the same value.
03253     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
03254       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
03255         return V;
03256 
03257     return nullptr;
03258   }
03259 }
03260 
03261 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
03262                            const DataLayout *DL, const TargetLibraryInfo *TLI,
03263                            const DominatorTree *DT, AssumptionTracker *AT,
03264                            const Instruction *CxtI) {
03265   return ::SimplifyBinOp(Opcode, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
03266                          RecursionLimit);
03267 }
03268 
03269 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
03270 /// fold the result.
03271 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
03272                               const Query &Q, unsigned MaxRecurse) {
03273   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
03274     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
03275   return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
03276 }
03277 
03278 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
03279                              const DataLayout *DL, const TargetLibraryInfo *TLI,
03280                              const DominatorTree *DT, AssumptionTracker *AT,
03281                              const Instruction *CxtI) {
03282   return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
03283                            RecursionLimit);
03284 }
03285 
03286 static bool IsIdempotent(Intrinsic::ID ID) {
03287   switch (ID) {
03288   default: return false;
03289 
03290   // Unary idempotent: f(f(x)) = f(x)
03291   case Intrinsic::fabs:
03292   case Intrinsic::floor:
03293   case Intrinsic::ceil:
03294   case Intrinsic::trunc:
03295   case Intrinsic::rint:
03296   case Intrinsic::nearbyint:
03297   case Intrinsic::round:
03298     return true;
03299   }
03300 }
03301 
03302 template <typename IterTy>
03303 static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
03304                                 const Query &Q, unsigned MaxRecurse) {
03305   // Perform idempotent optimizations
03306   if (!IsIdempotent(IID))
03307     return nullptr;
03308 
03309   // Unary Ops
03310   if (std::distance(ArgBegin, ArgEnd) == 1)
03311     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
03312       if (II->getIntrinsicID() == IID)
03313         return II;
03314 
03315   return nullptr;
03316 }
03317 
03318 template <typename IterTy>
03319 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
03320                            const Query &Q, unsigned MaxRecurse) {
03321   Type *Ty = V->getType();
03322   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
03323     Ty = PTy->getElementType();
03324   FunctionType *FTy = cast<FunctionType>(Ty);
03325 
03326   // call undef -> undef
03327   if (isa<UndefValue>(V))
03328     return UndefValue::get(FTy->getReturnType());
03329 
03330   Function *F = dyn_cast<Function>(V);
03331   if (!F)
03332     return nullptr;
03333 
03334   if (unsigned IID = F->getIntrinsicID())
03335     if (Value *Ret =
03336         SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
03337       return Ret;
03338 
03339   if (!canConstantFoldCallTo(F))
03340     return nullptr;
03341 
03342   SmallVector<Constant *, 4> ConstantArgs;
03343   ConstantArgs.reserve(ArgEnd - ArgBegin);
03344   for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
03345     Constant *C = dyn_cast<Constant>(*I);
03346     if (!C)
03347       return nullptr;
03348     ConstantArgs.push_back(C);
03349   }
03350 
03351   return ConstantFoldCall(F, ConstantArgs, Q.TLI);
03352 }
03353 
03354 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
03355                           User::op_iterator ArgEnd, const DataLayout *DL,
03356                           const TargetLibraryInfo *TLI,
03357                           const DominatorTree *DT, AssumptionTracker *AT,
03358                           const Instruction *CxtI) {
03359   return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AT, CxtI),
03360                         RecursionLimit);
03361 }
03362 
03363 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
03364                           const DataLayout *DL, const TargetLibraryInfo *TLI,
03365                           const DominatorTree *DT, AssumptionTracker *AT,
03366                           const Instruction *CxtI) {
03367   return ::SimplifyCall(V, Args.begin(), Args.end(),
03368                         Query(DL, TLI, DT, AT, CxtI), RecursionLimit);
03369 }
03370 
03371 /// SimplifyInstruction - See if we can compute a simplified version of this
03372 /// instruction.  If not, this returns null.
03373 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *DL,
03374                                  const TargetLibraryInfo *TLI,
03375                                  const DominatorTree *DT,
03376                                  AssumptionTracker *AT) {
03377   Value *Result;
03378 
03379   switch (I->getOpcode()) {
03380   default:
03381     Result = ConstantFoldInstruction(I, DL, TLI);
03382     break;
03383   case Instruction::FAdd:
03384     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
03385                               I->getFastMathFlags(), DL, TLI, DT, AT, I);
03386     break;
03387   case Instruction::Add:
03388     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
03389                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
03390                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
03391                              DL, TLI, DT, AT, I);
03392     break;
03393   case Instruction::FSub:
03394     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
03395                               I->getFastMathFlags(), DL, TLI, DT, AT, I);
03396     break;
03397   case Instruction::Sub:
03398     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
03399                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
03400                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
03401                              DL, TLI, DT, AT, I);
03402     break;
03403   case Instruction::FMul:
03404     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
03405                               I->getFastMathFlags(), DL, TLI, DT, AT, I);
03406     break;
03407   case Instruction::Mul:
03408     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1),
03409                              DL, TLI, DT, AT, I);
03410     break;
03411   case Instruction::SDiv:
03412     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1),
03413                               DL, TLI, DT, AT, I);
03414     break;
03415   case Instruction::UDiv:
03416     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1),
03417                               DL, TLI, DT, AT, I);
03418     break;
03419   case Instruction::FDiv:
03420     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
03421                               DL, TLI, DT, AT, I);
03422     break;
03423   case Instruction::SRem:
03424     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1),
03425                               DL, TLI, DT, AT, I);
03426     break;
03427   case Instruction::URem:
03428     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1),
03429                               DL, TLI, DT, AT, I);
03430     break;
03431   case Instruction::FRem:
03432     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
03433                               DL, TLI, DT, AT, I);
03434     break;
03435   case Instruction::Shl:
03436     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
03437                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
03438                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
03439                              DL, TLI, DT, AT, I);
03440     break;
03441   case Instruction::LShr:
03442     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
03443                               cast<BinaryOperator>(I)->isExact(),
03444                               DL, TLI, DT, AT, I);
03445     break;
03446   case Instruction::AShr:
03447     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
03448                               cast<BinaryOperator>(I)->isExact(),
03449                               DL, TLI, DT, AT, I);
03450     break;
03451   case Instruction::And:
03452     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1),
03453                              DL, TLI, DT, AT, I);
03454     break;
03455   case Instruction::Or:
03456     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
03457                             AT, I);
03458     break;
03459   case Instruction::Xor:
03460     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1),
03461                              DL, TLI, DT, AT, I);
03462     break;
03463   case Instruction::ICmp:
03464     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
03465                               I->getOperand(0), I->getOperand(1),
03466                               DL, TLI, DT, AT, I);
03467     break;
03468   case Instruction::FCmp:
03469     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
03470                               I->getOperand(0), I->getOperand(1),
03471                               DL, TLI, DT, AT, I);
03472     break;
03473   case Instruction::Select:
03474     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
03475                                 I->getOperand(2), DL, TLI, DT, AT, I);
03476     break;
03477   case Instruction::GetElementPtr: {
03478     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
03479     Result = SimplifyGEPInst(Ops, DL, TLI, DT, AT, I);
03480     break;
03481   }
03482   case Instruction::InsertValue: {
03483     InsertValueInst *IV = cast<InsertValueInst>(I);
03484     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
03485                                      IV->getInsertedValueOperand(),
03486                                      IV->getIndices(), DL, TLI, DT, AT, I);
03487     break;
03488   }
03489   case Instruction::PHI:
03490     Result = SimplifyPHINode(cast<PHINode>(I), Query (DL, TLI, DT, AT, I));
03491     break;
03492   case Instruction::Call: {
03493     CallSite CS(cast<CallInst>(I));
03494     Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
03495                           DL, TLI, DT, AT, I);
03496     break;
03497   }
03498   case Instruction::Trunc:
03499     Result = SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT,
03500                                AT, I);
03501     break;
03502   }
03503 
03504   /// If called on unreachable code, the above logic may report that the
03505   /// instruction simplified to itself.  Make life easier for users by
03506   /// detecting that case here, returning a safe value instead.
03507   return Result == I ? UndefValue::get(I->getType()) : Result;
03508 }
03509 
03510 /// \brief Implementation of recursive simplification through an instructions
03511 /// uses.
03512 ///
03513 /// This is the common implementation of the recursive simplification routines.
03514 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
03515 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
03516 /// instructions to process and attempt to simplify it using
03517 /// InstructionSimplify.
03518 ///
03519 /// This routine returns 'true' only when *it* simplifies something. The passed
03520 /// in simplified value does not count toward this.
03521 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
03522                                               const DataLayout *DL,
03523                                               const TargetLibraryInfo *TLI,
03524                                               const DominatorTree *DT,
03525                                               AssumptionTracker *AT) {
03526   bool Simplified = false;
03527   SmallSetVector<Instruction *, 8> Worklist;
03528 
03529   // If we have an explicit value to collapse to, do that round of the
03530   // simplification loop by hand initially.
03531   if (SimpleV) {
03532     for (User *U : I->users())
03533       if (U != I)
03534         Worklist.insert(cast<Instruction>(U));
03535 
03536     // Replace the instruction with its simplified value.
03537     I->replaceAllUsesWith(SimpleV);
03538 
03539     // Gracefully handle edge cases where the instruction is not wired into any
03540     // parent block.
03541     if (I->getParent())
03542       I->eraseFromParent();
03543   } else {
03544     Worklist.insert(I);
03545   }
03546 
03547   // Note that we must test the size on each iteration, the worklist can grow.
03548   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
03549     I = Worklist[Idx];
03550 
03551     // See if this instruction simplifies.
03552     SimpleV = SimplifyInstruction(I, DL, TLI, DT, AT);
03553     if (!SimpleV)
03554       continue;
03555 
03556     Simplified = true;
03557 
03558     // Stash away all the uses of the old instruction so we can check them for
03559     // recursive simplifications after a RAUW. This is cheaper than checking all
03560     // uses of To on the recursive step in most cases.
03561     for (User *U : I->users())
03562       Worklist.insert(cast<Instruction>(U));
03563 
03564     // Replace the instruction with its simplified value.
03565     I->replaceAllUsesWith(SimpleV);
03566 
03567     // Gracefully handle edge cases where the instruction is not wired into any
03568     // parent block.
03569     if (I->getParent())
03570       I->eraseFromParent();
03571   }
03572   return Simplified;
03573 }
03574 
03575 bool llvm::recursivelySimplifyInstruction(Instruction *I,
03576                                           const DataLayout *DL,
03577                                           const TargetLibraryInfo *TLI,
03578                                           const DominatorTree *DT,
03579                                           AssumptionTracker *AT) {
03580   return replaceAndRecursivelySimplifyImpl(I, nullptr, DL, TLI, DT, AT);
03581 }
03582 
03583 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
03584                                          const DataLayout *DL,
03585                                          const TargetLibraryInfo *TLI,
03586                                          const DominatorTree *DT,
03587                                          AssumptionTracker *AT) {
03588   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
03589   assert(SimpleV && "Must provide a simplified value.");
03590   return replaceAndRecursivelySimplifyImpl(I, SimpleV, DL, TLI, DT, AT);
03591 }