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