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