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