LLVM  mainline
InstCombineAndOrXor.cpp
Go to the documentation of this file.
00001 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
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 the visitAnd, visitOr, and visitXor functions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombineInternal.h"
00015 #include "llvm/Analysis/InstructionSimplify.h"
00016 #include "llvm/IR/ConstantRange.h"
00017 #include "llvm/IR/Intrinsics.h"
00018 #include "llvm/IR/PatternMatch.h"
00019 #include "llvm/Transforms/Utils/CmpInstAnalysis.h"
00020 using namespace llvm;
00021 using namespace PatternMatch;
00022 
00023 #define DEBUG_TYPE "instcombine"
00024 
00025 static inline Value *dyn_castNotVal(Value *V) {
00026   // If this is not(not(x)) don't return that this is a not: we want the two
00027   // not's to be folded first.
00028   if (BinaryOperator::isNot(V)) {
00029     Value *Operand = BinaryOperator::getNotArgument(V);
00030     if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
00031       return Operand;
00032   }
00033 
00034   // Constants can be considered to be not'ed values...
00035   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
00036     return ConstantInt::get(C->getType(), ~C->getValue());
00037   return nullptr;
00038 }
00039 
00040 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
00041 /// predicate into a three bit mask. It also returns whether it is an ordered
00042 /// predicate by reference.
00043 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
00044   isOrdered = false;
00045   switch (CC) {
00046   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
00047   case FCmpInst::FCMP_UNO:                   return 0;  // 000
00048   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
00049   case FCmpInst::FCMP_UGT:                   return 1;  // 001
00050   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
00051   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
00052   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
00053   case FCmpInst::FCMP_UGE:                   return 3;  // 011
00054   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
00055   case FCmpInst::FCMP_ULT:                   return 4;  // 100
00056   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
00057   case FCmpInst::FCMP_UNE:                   return 5;  // 101
00058   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
00059   case FCmpInst::FCMP_ULE:                   return 6;  // 110
00060     // True -> 7
00061   default:
00062     // Not expecting FCMP_FALSE and FCMP_TRUE;
00063     llvm_unreachable("Unexpected FCmp predicate!");
00064   }
00065 }
00066 
00067 /// getNewICmpValue - This is the complement of getICmpCode, which turns an
00068 /// opcode and two operands into either a constant true or false, or a brand
00069 /// new ICmp instruction. The sign is passed in to determine which kind
00070 /// of predicate to use in the new icmp instruction.
00071 static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
00072                               InstCombiner::BuilderTy *Builder) {
00073   ICmpInst::Predicate NewPred;
00074   if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
00075     return NewConstant;
00076   return Builder->CreateICmp(NewPred, LHS, RHS);
00077 }
00078 
00079 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
00080 /// opcode and two operands into either a FCmp instruction. isordered is passed
00081 /// in to determine which kind of predicate to use in the new fcmp instruction.
00082 static Value *getFCmpValue(bool isordered, unsigned code,
00083                            Value *LHS, Value *RHS,
00084                            InstCombiner::BuilderTy *Builder) {
00085   CmpInst::Predicate Pred;
00086   switch (code) {
00087   default: llvm_unreachable("Illegal FCmp code!");
00088   case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
00089   case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
00090   case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
00091   case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
00092   case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
00093   case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
00094   case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
00095   case 7:
00096     if (!isordered) return ConstantInt::getTrue(LHS->getContext());
00097     Pred = FCmpInst::FCMP_ORD; break;
00098   }
00099   return Builder->CreateFCmp(Pred, LHS, RHS);
00100 }
00101 
00102 /// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
00103 /// \param I Binary operator to transform.
00104 /// \return Pointer to node that must replace the original binary operator, or
00105 ///         null pointer if no transformation was made.
00106 Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
00107   IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
00108 
00109   // Can't do vectors.
00110   if (I.getType()->isVectorTy()) return nullptr;
00111 
00112   // Can only do bitwise ops.
00113   unsigned Op = I.getOpcode();
00114   if (Op != Instruction::And && Op != Instruction::Or &&
00115       Op != Instruction::Xor)
00116     return nullptr;
00117 
00118   Value *OldLHS = I.getOperand(0);
00119   Value *OldRHS = I.getOperand(1);
00120   ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
00121   ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
00122   IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
00123   IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
00124   bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
00125   bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
00126 
00127   if (!IsBswapLHS && !IsBswapRHS)
00128     return nullptr;
00129 
00130   if (!IsBswapLHS && !ConstLHS)
00131     return nullptr;
00132 
00133   if (!IsBswapRHS && !ConstRHS)
00134     return nullptr;
00135 
00136   /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
00137   /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
00138   Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
00139                   Builder->getInt(ConstLHS->getValue().byteSwap());
00140 
00141   Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
00142                   Builder->getInt(ConstRHS->getValue().byteSwap());
00143 
00144   Value *BinOp = nullptr;
00145   if (Op == Instruction::And)
00146     BinOp = Builder->CreateAnd(NewLHS, NewRHS);
00147   else if (Op == Instruction::Or)
00148     BinOp = Builder->CreateOr(NewLHS, NewRHS);
00149   else //if (Op == Instruction::Xor)
00150     BinOp = Builder->CreateXor(NewLHS, NewRHS);
00151 
00152   Module *M = I.getParent()->getParent()->getParent();
00153   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
00154   return Builder->CreateCall(F, BinOp);
00155 }
00156 
00157 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
00158 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
00159 // guaranteed to be a binary operator.
00160 Instruction *InstCombiner::OptAndOp(Instruction *Op,
00161                                     ConstantInt *OpRHS,
00162                                     ConstantInt *AndRHS,
00163                                     BinaryOperator &TheAnd) {
00164   Value *X = Op->getOperand(0);
00165   Constant *Together = nullptr;
00166   if (!Op->isShift())
00167     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
00168 
00169   switch (Op->getOpcode()) {
00170   case Instruction::Xor:
00171     if (Op->hasOneUse()) {
00172       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
00173       Value *And = Builder->CreateAnd(X, AndRHS);
00174       And->takeName(Op);
00175       return BinaryOperator::CreateXor(And, Together);
00176     }
00177     break;
00178   case Instruction::Or:
00179     if (Op->hasOneUse()){
00180       if (Together != OpRHS) {
00181         // (X | C1) & C2 --> (X | (C1&C2)) & C2
00182         Value *Or = Builder->CreateOr(X, Together);
00183         Or->takeName(Op);
00184         return BinaryOperator::CreateAnd(Or, AndRHS);
00185       }
00186 
00187       ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
00188       if (TogetherCI && !TogetherCI->isZero()){
00189         // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
00190         // NOTE: This reduces the number of bits set in the & mask, which
00191         // can expose opportunities for store narrowing.
00192         Together = ConstantExpr::getXor(AndRHS, Together);
00193         Value *And = Builder->CreateAnd(X, Together);
00194         And->takeName(Op);
00195         return BinaryOperator::CreateOr(And, OpRHS);
00196       }
00197     }
00198 
00199     break;
00200   case Instruction::Add:
00201     if (Op->hasOneUse()) {
00202       // Adding a one to a single bit bit-field should be turned into an XOR
00203       // of the bit.  First thing to check is to see if this AND is with a
00204       // single bit constant.
00205       const APInt &AndRHSV = AndRHS->getValue();
00206 
00207       // If there is only one bit set.
00208       if (AndRHSV.isPowerOf2()) {
00209         // Ok, at this point, we know that we are masking the result of the
00210         // ADD down to exactly one bit.  If the constant we are adding has
00211         // no bits set below this bit, then we can eliminate the ADD.
00212         const APInt& AddRHS = OpRHS->getValue();
00213 
00214         // Check to see if any bits below the one bit set in AndRHSV are set.
00215         if ((AddRHS & (AndRHSV-1)) == 0) {
00216           // If not, the only thing that can effect the output of the AND is
00217           // the bit specified by AndRHSV.  If that bit is set, the effect of
00218           // the XOR is to toggle the bit.  If it is clear, then the ADD has
00219           // no effect.
00220           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
00221             TheAnd.setOperand(0, X);
00222             return &TheAnd;
00223           } else {
00224             // Pull the XOR out of the AND.
00225             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
00226             NewAnd->takeName(Op);
00227             return BinaryOperator::CreateXor(NewAnd, AndRHS);
00228           }
00229         }
00230       }
00231     }
00232     break;
00233 
00234   case Instruction::Shl: {
00235     // We know that the AND will not produce any of the bits shifted in, so if
00236     // the anded constant includes them, clear them now!
00237     //
00238     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
00239     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
00240     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
00241     ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
00242 
00243     if (CI->getValue() == ShlMask)
00244       // Masking out bits that the shift already masks.
00245       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
00246 
00247     if (CI != AndRHS) {                  // Reducing bits set in and.
00248       TheAnd.setOperand(1, CI);
00249       return &TheAnd;
00250     }
00251     break;
00252   }
00253   case Instruction::LShr: {
00254     // We know that the AND will not produce any of the bits shifted in, so if
00255     // the anded constant includes them, clear them now!  This only applies to
00256     // unsigned shifts, because a signed shr may bring in set bits!
00257     //
00258     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
00259     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
00260     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
00261     ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
00262 
00263     if (CI->getValue() == ShrMask)
00264       // Masking out bits that the shift already masks.
00265       return ReplaceInstUsesWith(TheAnd, Op);
00266 
00267     if (CI != AndRHS) {
00268       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
00269       return &TheAnd;
00270     }
00271     break;
00272   }
00273   case Instruction::AShr:
00274     // Signed shr.
00275     // See if this is shifting in some sign extension, then masking it out
00276     // with an and.
00277     if (Op->hasOneUse()) {
00278       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
00279       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
00280       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
00281       Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
00282       if (C == AndRHS) {          // Masking out bits shifted in.
00283         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
00284         // Make the argument unsigned.
00285         Value *ShVal = Op->getOperand(0);
00286         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
00287         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
00288       }
00289     }
00290     break;
00291   }
00292   return nullptr;
00293 }
00294 
00295 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
00296 /// (V < Lo || V >= Hi).  In practice, we emit the more efficient
00297 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
00298 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
00299 /// insert new instructions.
00300 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
00301                                      bool isSigned, bool Inside) {
00302   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
00303             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
00304          "Lo is not <= Hi in range emission code!");
00305 
00306   if (Inside) {
00307     if (Lo == Hi)  // Trivially false.
00308       return Builder->getFalse();
00309 
00310     // V >= Min && V < Hi --> V < Hi
00311     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
00312       ICmpInst::Predicate pred = (isSigned ?
00313         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
00314       return Builder->CreateICmp(pred, V, Hi);
00315     }
00316 
00317     // Emit V-Lo <u Hi-Lo
00318     Constant *NegLo = ConstantExpr::getNeg(Lo);
00319     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
00320     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
00321     return Builder->CreateICmpULT(Add, UpperBound);
00322   }
00323 
00324   if (Lo == Hi)  // Trivially true.
00325     return Builder->getTrue();
00326 
00327   // V < Min || V >= Hi -> V > Hi-1
00328   Hi = SubOne(cast<ConstantInt>(Hi));
00329   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
00330     ICmpInst::Predicate pred = (isSigned ?
00331         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
00332     return Builder->CreateICmp(pred, V, Hi);
00333   }
00334 
00335   // Emit V-Lo >u Hi-1-Lo
00336   // Note that Hi has already had one subtracted from it, above.
00337   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
00338   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
00339   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
00340   return Builder->CreateICmpUGT(Add, LowerBound);
00341 }
00342 
00343 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
00344 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
00345 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
00346 // not, since all 1s are not contiguous.
00347 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
00348   const APInt& V = Val->getValue();
00349   uint32_t BitWidth = Val->getType()->getBitWidth();
00350   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
00351 
00352   // look for the first zero bit after the run of ones
00353   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
00354   // look for the first non-zero bit
00355   ME = V.getActiveBits();
00356   return true;
00357 }
00358 
00359 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
00360 /// where isSub determines whether the operator is a sub.  If we can fold one of
00361 /// the following xforms:
00362 ///
00363 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
00364 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
00365 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
00366 ///
00367 /// return (A +/- B).
00368 ///
00369 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
00370                                         ConstantInt *Mask, bool isSub,
00371                                         Instruction &I) {
00372   Instruction *LHSI = dyn_cast<Instruction>(LHS);
00373   if (!LHSI || LHSI->getNumOperands() != 2 ||
00374       !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
00375 
00376   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
00377 
00378   switch (LHSI->getOpcode()) {
00379   default: return nullptr;
00380   case Instruction::And:
00381     if (ConstantExpr::getAnd(N, Mask) == Mask) {
00382       // If the AndRHS is a power of two minus one (0+1+), this is simple.
00383       if ((Mask->getValue().countLeadingZeros() +
00384            Mask->getValue().countPopulation()) ==
00385           Mask->getValue().getBitWidth())
00386         break;
00387 
00388       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
00389       // part, we don't need any explicit masks to take them out of A.  If that
00390       // is all N is, ignore it.
00391       uint32_t MB = 0, ME = 0;
00392       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
00393         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
00394         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
00395         if (MaskedValueIsZero(RHS, Mask, 0, &I))
00396           break;
00397       }
00398     }
00399     return nullptr;
00400   case Instruction::Or:
00401   case Instruction::Xor:
00402     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
00403     if ((Mask->getValue().countLeadingZeros() +
00404          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
00405         && ConstantExpr::getAnd(N, Mask)->isNullValue())
00406       break;
00407     return nullptr;
00408   }
00409 
00410   if (isSub)
00411     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
00412   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
00413 }
00414 
00415 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
00416 /// One of A and B is considered the mask, the other the value. This is
00417 /// described as the "AMask" or "BMask" part of the enum. If the enum
00418 /// contains only "Mask", then both A and B can be considered masks.
00419 /// If A is the mask, then it was proven, that (A & C) == C. This
00420 /// is trivial if C == A, or C == 0. If both A and C are constants, this
00421 /// proof is also easy.
00422 /// For the following explanations we assume that A is the mask.
00423 /// The part "AllOnes" declares, that the comparison is true only
00424 /// if (A & B) == A, or all bits of A are set in B.
00425 ///   Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
00426 /// The part "AllZeroes" declares, that the comparison is true only
00427 /// if (A & B) == 0, or all bits of A are cleared in B.
00428 ///   Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
00429 /// The part "Mixed" declares, that (A & B) == C and C might or might not
00430 /// contain any number of one bits and zero bits.
00431 ///   Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
00432 /// The Part "Not" means, that in above descriptions "==" should be replaced
00433 /// by "!=".
00434 ///   Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
00435 /// If the mask A contains a single bit, then the following is equivalent:
00436 ///    (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
00437 ///    (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
00438 enum MaskedICmpType {
00439   FoldMskICmp_AMask_AllOnes           =     1,
00440   FoldMskICmp_AMask_NotAllOnes        =     2,
00441   FoldMskICmp_BMask_AllOnes           =     4,
00442   FoldMskICmp_BMask_NotAllOnes        =     8,
00443   FoldMskICmp_Mask_AllZeroes          =    16,
00444   FoldMskICmp_Mask_NotAllZeroes       =    32,
00445   FoldMskICmp_AMask_Mixed             =    64,
00446   FoldMskICmp_AMask_NotMixed          =   128,
00447   FoldMskICmp_BMask_Mixed             =   256,
00448   FoldMskICmp_BMask_NotMixed          =   512
00449 };
00450 
00451 /// return the set of pattern classes (from MaskedICmpType)
00452 /// that (icmp SCC (A & B), C) satisfies
00453 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
00454                                     ICmpInst::Predicate SCC)
00455 {
00456   ConstantInt *ACst = dyn_cast<ConstantInt>(A);
00457   ConstantInt *BCst = dyn_cast<ConstantInt>(B);
00458   ConstantInt *CCst = dyn_cast<ConstantInt>(C);
00459   bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
00460   bool icmp_abit = (ACst && !ACst->isZero() &&
00461                     ACst->getValue().isPowerOf2());
00462   bool icmp_bbit = (BCst && !BCst->isZero() &&
00463                     BCst->getValue().isPowerOf2());
00464   unsigned result = 0;
00465   if (CCst && CCst->isZero()) {
00466     // if C is zero, then both A and B qualify as mask
00467     result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
00468                           FoldMskICmp_Mask_AllZeroes |
00469                           FoldMskICmp_AMask_Mixed |
00470                           FoldMskICmp_BMask_Mixed)
00471                        : (FoldMskICmp_Mask_NotAllZeroes |
00472                           FoldMskICmp_Mask_NotAllZeroes |
00473                           FoldMskICmp_AMask_NotMixed |
00474                           FoldMskICmp_BMask_NotMixed));
00475     if (icmp_abit)
00476       result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
00477                             FoldMskICmp_AMask_NotMixed)
00478                          : (FoldMskICmp_AMask_AllOnes |
00479                             FoldMskICmp_AMask_Mixed));
00480     if (icmp_bbit)
00481       result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
00482                             FoldMskICmp_BMask_NotMixed)
00483                          : (FoldMskICmp_BMask_AllOnes |
00484                             FoldMskICmp_BMask_Mixed));
00485     return result;
00486   }
00487   if (A == C) {
00488     result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
00489                           FoldMskICmp_AMask_Mixed)
00490                        : (FoldMskICmp_AMask_NotAllOnes |
00491                           FoldMskICmp_AMask_NotMixed));
00492     if (icmp_abit)
00493       result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
00494                             FoldMskICmp_AMask_NotMixed)
00495                          : (FoldMskICmp_Mask_AllZeroes |
00496                             FoldMskICmp_AMask_Mixed));
00497   } else if (ACst && CCst &&
00498              ConstantExpr::getAnd(ACst, CCst) == CCst) {
00499     result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
00500                        : FoldMskICmp_AMask_NotMixed);
00501   }
00502   if (B == C) {
00503     result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
00504                           FoldMskICmp_BMask_Mixed)
00505                        : (FoldMskICmp_BMask_NotAllOnes |
00506                           FoldMskICmp_BMask_NotMixed));
00507     if (icmp_bbit)
00508       result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
00509                             FoldMskICmp_BMask_NotMixed)
00510                          : (FoldMskICmp_Mask_AllZeroes |
00511                             FoldMskICmp_BMask_Mixed));
00512   } else if (BCst && CCst &&
00513              ConstantExpr::getAnd(BCst, CCst) == CCst) {
00514     result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
00515                        : FoldMskICmp_BMask_NotMixed);
00516   }
00517   return result;
00518 }
00519 
00520 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
00521 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
00522 /// is adjacent to the corresponding normal flag (recording ==), this just
00523 /// involves swapping those bits over.
00524 static unsigned conjugateICmpMask(unsigned Mask) {
00525   unsigned NewMask;
00526   NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
00527                      FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
00528                      FoldMskICmp_BMask_Mixed))
00529             << 1;
00530 
00531   NewMask |=
00532       (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
00533                FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
00534                FoldMskICmp_BMask_NotMixed))
00535       >> 1;
00536 
00537   return NewMask;
00538 }
00539 
00540 /// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
00541 /// if possible. The returned predicate is either == or !=. Returns false if
00542 /// decomposition fails.
00543 static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
00544                                  Value *&X, Value *&Y, Value *&Z) {
00545   ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
00546   if (!C)
00547     return false;
00548 
00549   switch (I->getPredicate()) {
00550   default:
00551     return false;
00552   case ICmpInst::ICMP_SLT:
00553     // X < 0 is equivalent to (X & SignBit) != 0.
00554     if (!C->isZero())
00555       return false;
00556     Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
00557     Pred = ICmpInst::ICMP_NE;
00558     break;
00559   case ICmpInst::ICMP_SGT:
00560     // X > -1 is equivalent to (X & SignBit) == 0.
00561     if (!C->isAllOnesValue())
00562       return false;
00563     Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
00564     Pred = ICmpInst::ICMP_EQ;
00565     break;
00566   case ICmpInst::ICMP_ULT:
00567     // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
00568     if (!C->getValue().isPowerOf2())
00569       return false;
00570     Y = ConstantInt::get(I->getContext(), -C->getValue());
00571     Pred = ICmpInst::ICMP_EQ;
00572     break;
00573   case ICmpInst::ICMP_UGT:
00574     // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
00575     if (!(C->getValue() + 1).isPowerOf2())
00576       return false;
00577     Y = ConstantInt::get(I->getContext(), ~C->getValue());
00578     Pred = ICmpInst::ICMP_NE;
00579     break;
00580   }
00581 
00582   X = I->getOperand(0);
00583   Z = ConstantInt::getNullValue(C->getType());
00584   return true;
00585 }
00586 
00587 /// foldLogOpOfMaskedICmpsHelper:
00588 /// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
00589 /// return the set of pattern classes (from MaskedICmpType)
00590 /// that both LHS and RHS satisfy
00591 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
00592                                              Value*& B, Value*& C,
00593                                              Value*& D, Value*& E,
00594                                              ICmpInst *LHS, ICmpInst *RHS,
00595                                              ICmpInst::Predicate &LHSCC,
00596                                              ICmpInst::Predicate &RHSCC) {
00597   if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
00598   // vectors are not (yet?) supported
00599   if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
00600 
00601   // Here comes the tricky part:
00602   // LHS might be of the form L11 & L12 == X, X == L21 & L22,
00603   // and L11 & L12 == L21 & L22. The same goes for RHS.
00604   // Now we must find those components L** and R**, that are equal, so
00605   // that we can extract the parameters A, B, C, D, and E for the canonical
00606   // above.
00607   Value *L1 = LHS->getOperand(0);
00608   Value *L2 = LHS->getOperand(1);
00609   Value *L11,*L12,*L21,*L22;
00610   // Check whether the icmp can be decomposed into a bit test.
00611   if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
00612     L21 = L22 = L1 = nullptr;
00613   } else {
00614     // Look for ANDs in the LHS icmp.
00615     if (!L1->getType()->isIntegerTy()) {
00616       // You can icmp pointers, for example. They really aren't masks.
00617       L11 = L12 = nullptr;
00618     } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
00619       // Any icmp can be viewed as being trivially masked; if it allows us to
00620       // remove one, it's worth it.
00621       L11 = L1;
00622       L12 = Constant::getAllOnesValue(L1->getType());
00623     }
00624 
00625     if (!L2->getType()->isIntegerTy()) {
00626       // You can icmp pointers, for example. They really aren't masks.
00627       L21 = L22 = nullptr;
00628     } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
00629       L21 = L2;
00630       L22 = Constant::getAllOnesValue(L2->getType());
00631     }
00632   }
00633 
00634   // Bail if LHS was a icmp that can't be decomposed into an equality.
00635   if (!ICmpInst::isEquality(LHSCC))
00636     return 0;
00637 
00638   Value *R1 = RHS->getOperand(0);
00639   Value *R2 = RHS->getOperand(1);
00640   Value *R11,*R12;
00641   bool ok = false;
00642   if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
00643     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
00644       A = R11; D = R12;
00645     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
00646       A = R12; D = R11;
00647     } else {
00648       return 0;
00649     }
00650     E = R2; R1 = nullptr; ok = true;
00651   } else if (R1->getType()->isIntegerTy()) {
00652     if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
00653       // As before, model no mask as a trivial mask if it'll let us do an
00654       // optimization.
00655       R11 = R1;
00656       R12 = Constant::getAllOnesValue(R1->getType());
00657     }
00658 
00659     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
00660       A = R11; D = R12; E = R2; ok = true;
00661     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
00662       A = R12; D = R11; E = R2; ok = true;
00663     }
00664   }
00665 
00666   // Bail if RHS was a icmp that can't be decomposed into an equality.
00667   if (!ICmpInst::isEquality(RHSCC))
00668     return 0;
00669 
00670   // Look for ANDs in on the right side of the RHS icmp.
00671   if (!ok && R2->getType()->isIntegerTy()) {
00672     if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
00673       R11 = R2;
00674       R12 = Constant::getAllOnesValue(R2->getType());
00675     }
00676 
00677     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
00678       A = R11; D = R12; E = R1; ok = true;
00679     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
00680       A = R12; D = R11; E = R1; ok = true;
00681     } else {
00682       return 0;
00683     }
00684   }
00685   if (!ok)
00686     return 0;
00687 
00688   if (L11 == A) {
00689     B = L12; C = L2;
00690   } else if (L12 == A) {
00691     B = L11; C = L2;
00692   } else if (L21 == A) {
00693     B = L22; C = L1;
00694   } else if (L22 == A) {
00695     B = L21; C = L1;
00696   }
00697 
00698   unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
00699   unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
00700   return left_type & right_type;
00701 }
00702 /// foldLogOpOfMaskedICmps:
00703 /// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
00704 /// into a single (icmp(A & X) ==/!= Y)
00705 static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
00706                                      llvm::InstCombiner::BuilderTy *Builder) {
00707   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
00708   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
00709   unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
00710                                                LHSCC, RHSCC);
00711   if (mask == 0) return nullptr;
00712   assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
00713          "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
00714 
00715   // In full generality:
00716   //     (icmp (A & B) Op C) | (icmp (A & D) Op E)
00717   // ==  ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
00718   //
00719   // If the latter can be converted into (icmp (A & X) Op Y) then the former is
00720   // equivalent to (icmp (A & X) !Op Y).
00721   //
00722   // Therefore, we can pretend for the rest of this function that we're dealing
00723   // with the conjunction, provided we flip the sense of any comparisons (both
00724   // input and output).
00725 
00726   // In most cases we're going to produce an EQ for the "&&" case.
00727   ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
00728   if (!IsAnd) {
00729     // Convert the masking analysis into its equivalent with negated
00730     // comparisons.
00731     mask = conjugateICmpMask(mask);
00732   }
00733 
00734   if (mask & FoldMskICmp_Mask_AllZeroes) {
00735     // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
00736     // -> (icmp eq (A & (B|D)), 0)
00737     Value *newOr = Builder->CreateOr(B, D);
00738     Value *newAnd = Builder->CreateAnd(A, newOr);
00739     // we can't use C as zero, because we might actually handle
00740     //   (icmp ne (A & B), B) & (icmp ne (A & D), D)
00741     // with B and D, having a single bit set
00742     Value *zero = Constant::getNullValue(A->getType());
00743     return Builder->CreateICmp(NEWCC, newAnd, zero);
00744   }
00745   if (mask & FoldMskICmp_BMask_AllOnes) {
00746     // (icmp eq (A & B), B) & (icmp eq (A & D), D)
00747     // -> (icmp eq (A & (B|D)), (B|D))
00748     Value *newOr = Builder->CreateOr(B, D);
00749     Value *newAnd = Builder->CreateAnd(A, newOr);
00750     return Builder->CreateICmp(NEWCC, newAnd, newOr);
00751   }
00752   if (mask & FoldMskICmp_AMask_AllOnes) {
00753     // (icmp eq (A & B), A) & (icmp eq (A & D), A)
00754     // -> (icmp eq (A & (B&D)), A)
00755     Value *newAnd1 = Builder->CreateAnd(B, D);
00756     Value *newAnd = Builder->CreateAnd(A, newAnd1);
00757     return Builder->CreateICmp(NEWCC, newAnd, A);
00758   }
00759 
00760   // Remaining cases assume at least that B and D are constant, and depend on
00761   // their actual values. This isn't strictly, necessary, just a "handle the
00762   // easy cases for now" decision.
00763   ConstantInt *BCst = dyn_cast<ConstantInt>(B);
00764   if (!BCst) return nullptr;
00765   ConstantInt *DCst = dyn_cast<ConstantInt>(D);
00766   if (!DCst) return nullptr;
00767 
00768   if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
00769     // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
00770     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
00771     //     -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
00772     // Only valid if one of the masks is a superset of the other (check "B&D" is
00773     // the same as either B or D).
00774     APInt NewMask = BCst->getValue() & DCst->getValue();
00775 
00776     if (NewMask == BCst->getValue())
00777       return LHS;
00778     else if (NewMask == DCst->getValue())
00779       return RHS;
00780   }
00781   if (mask & FoldMskICmp_AMask_NotAllOnes) {
00782     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
00783     //     -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
00784     // Only valid if one of the masks is a superset of the other (check "B|D" is
00785     // the same as either B or D).
00786     APInt NewMask = BCst->getValue() | DCst->getValue();
00787 
00788     if (NewMask == BCst->getValue())
00789       return LHS;
00790     else if (NewMask == DCst->getValue())
00791       return RHS;
00792   }
00793   if (mask & FoldMskICmp_BMask_Mixed) {
00794     // (icmp eq (A & B), C) & (icmp eq (A & D), E)
00795     // We already know that B & C == C && D & E == E.
00796     // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
00797     // C and E, which are shared by both the mask B and the mask D, don't
00798     // contradict, then we can transform to
00799     // -> (icmp eq (A & (B|D)), (C|E))
00800     // Currently, we only handle the case of B, C, D, and E being constant.
00801     // we can't simply use C and E, because we might actually handle
00802     //   (icmp ne (A & B), B) & (icmp eq (A & D), D)
00803     // with B and D, having a single bit set
00804     ConstantInt *CCst = dyn_cast<ConstantInt>(C);
00805     if (!CCst) return nullptr;
00806     ConstantInt *ECst = dyn_cast<ConstantInt>(E);
00807     if (!ECst) return nullptr;
00808     if (LHSCC != NEWCC)
00809       CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
00810     if (RHSCC != NEWCC)
00811       ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
00812     // if there is a conflict we should actually return a false for the
00813     // whole construct
00814     if (((BCst->getValue() & DCst->getValue()) &
00815          (CCst->getValue() ^ ECst->getValue())) != 0)
00816       return ConstantInt::get(LHS->getType(), !IsAnd);
00817     Value *newOr1 = Builder->CreateOr(B, D);
00818     Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
00819     Value *newAnd = Builder->CreateAnd(A, newOr1);
00820     return Builder->CreateICmp(NEWCC, newAnd, newOr2);
00821   }
00822   return nullptr;
00823 }
00824 
00825 /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
00826 /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
00827 /// If \p Inverted is true then the check is for the inverted range, e.g.
00828 /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
00829 Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
00830                                         bool Inverted) {
00831   // Check the lower range comparison, e.g. x >= 0
00832   // InstCombine already ensured that if there is a constant it's on the RHS.
00833   ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
00834   if (!RangeStart)
00835     return nullptr;
00836 
00837   ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
00838                                Cmp0->getPredicate());
00839 
00840   // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
00841   if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
00842         (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
00843     return nullptr;
00844 
00845   ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
00846                                Cmp1->getPredicate());
00847 
00848   Value *Input = Cmp0->getOperand(0);
00849   Value *RangeEnd;
00850   if (Cmp1->getOperand(0) == Input) {
00851     // For the upper range compare we have: icmp x, n
00852     RangeEnd = Cmp1->getOperand(1);
00853   } else if (Cmp1->getOperand(1) == Input) {
00854     // For the upper range compare we have: icmp n, x
00855     RangeEnd = Cmp1->getOperand(0);
00856     Pred1 = ICmpInst::getSwappedPredicate(Pred1);
00857   } else {
00858     return nullptr;
00859   }
00860 
00861   // Check the upper range comparison, e.g. x < n
00862   ICmpInst::Predicate NewPred;
00863   switch (Pred1) {
00864     case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
00865     case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
00866     default: return nullptr;
00867   }
00868 
00869   // This simplification is only valid if the upper range is not negative.
00870   bool IsNegative, IsNotNegative;
00871   ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
00872   if (!IsNotNegative)
00873     return nullptr;
00874 
00875   if (Inverted)
00876     NewPred = ICmpInst::getInversePredicate(NewPred);
00877 
00878   return Builder->CreateICmp(NewPred, Input, RangeEnd);
00879 }
00880 
00881 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
00882 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
00883   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
00884 
00885   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
00886   if (PredicatesFoldable(LHSCC, RHSCC)) {
00887     if (LHS->getOperand(0) == RHS->getOperand(1) &&
00888         LHS->getOperand(1) == RHS->getOperand(0))
00889       LHS->swapOperands();
00890     if (LHS->getOperand(0) == RHS->getOperand(0) &&
00891         LHS->getOperand(1) == RHS->getOperand(1)) {
00892       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
00893       unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
00894       bool isSigned = LHS->isSigned() || RHS->isSigned();
00895       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
00896     }
00897   }
00898 
00899   // handle (roughly):  (icmp eq (A & B), C) & (icmp eq (A & D), E)
00900   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
00901     return V;
00902 
00903   // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
00904   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
00905     return V;
00906 
00907   // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
00908   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
00909     return V;
00910 
00911   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
00912   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
00913   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
00914   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
00915   if (!LHSCst || !RHSCst) return nullptr;
00916 
00917   if (LHSCst == RHSCst && LHSCC == RHSCC) {
00918     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
00919     // where C is a power of 2
00920     if (LHSCC == ICmpInst::ICMP_ULT &&
00921         LHSCst->getValue().isPowerOf2()) {
00922       Value *NewOr = Builder->CreateOr(Val, Val2);
00923       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
00924     }
00925 
00926     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
00927     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
00928       Value *NewOr = Builder->CreateOr(Val, Val2);
00929       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
00930     }
00931   }
00932 
00933   // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
00934   // where CMAX is the all ones value for the truncated type,
00935   // iff the lower bits of C2 and CA are zero.
00936   if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
00937       LHS->hasOneUse() && RHS->hasOneUse()) {
00938     Value *V;
00939     ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
00940 
00941     // (trunc x) == C1 & (and x, CA) == C2
00942     // (and x, CA) == C2 & (trunc x) == C1
00943     if (match(Val2, m_Trunc(m_Value(V))) &&
00944         match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
00945       SmallCst = RHSCst;
00946       BigCst = LHSCst;
00947     } else if (match(Val, m_Trunc(m_Value(V))) &&
00948                match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
00949       SmallCst = LHSCst;
00950       BigCst = RHSCst;
00951     }
00952 
00953     if (SmallCst && BigCst) {
00954       unsigned BigBitSize = BigCst->getType()->getBitWidth();
00955       unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
00956 
00957       // Check that the low bits are zero.
00958       APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
00959       if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
00960         Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
00961         APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
00962         Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
00963         return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
00964       }
00965     }
00966   }
00967 
00968   // From here on, we only handle:
00969   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
00970   if (Val != Val2) return nullptr;
00971 
00972   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
00973   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
00974       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
00975       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
00976       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
00977     return nullptr;
00978 
00979   // Make a constant range that's the intersection of the two icmp ranges.
00980   // If the intersection is empty, we know that the result is false.
00981   ConstantRange LHSRange =
00982       ConstantRange::makeAllowedICmpRegion(LHSCC, LHSCst->getValue());
00983   ConstantRange RHSRange =
00984       ConstantRange::makeAllowedICmpRegion(RHSCC, RHSCst->getValue());
00985 
00986   if (LHSRange.intersectWith(RHSRange).isEmptySet())
00987     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
00988 
00989   // We can't fold (ugt x, C) & (sgt x, C2).
00990   if (!PredicatesFoldable(LHSCC, RHSCC))
00991     return nullptr;
00992 
00993   // Ensure that the larger constant is on the RHS.
00994   bool ShouldSwap;
00995   if (CmpInst::isSigned(LHSCC) ||
00996       (ICmpInst::isEquality(LHSCC) &&
00997        CmpInst::isSigned(RHSCC)))
00998     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
00999   else
01000     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
01001 
01002   if (ShouldSwap) {
01003     std::swap(LHS, RHS);
01004     std::swap(LHSCst, RHSCst);
01005     std::swap(LHSCC, RHSCC);
01006   }
01007 
01008   // At this point, we know we have two icmp instructions
01009   // comparing a value against two constants and and'ing the result
01010   // together.  Because of the above check, we know that we only have
01011   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
01012   // (from the icmp folding check above), that the two constants
01013   // are not equal and that the larger constant is on the RHS
01014   assert(LHSCst != RHSCst && "Compares not folded above?");
01015 
01016   switch (LHSCC) {
01017   default: llvm_unreachable("Unknown integer condition code!");
01018   case ICmpInst::ICMP_EQ:
01019     switch (RHSCC) {
01020     default: llvm_unreachable("Unknown integer condition code!");
01021     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
01022     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
01023     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
01024       return LHS;
01025     }
01026   case ICmpInst::ICMP_NE:
01027     switch (RHSCC) {
01028     default: llvm_unreachable("Unknown integer condition code!");
01029     case ICmpInst::ICMP_ULT:
01030       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
01031         return Builder->CreateICmpULT(Val, LHSCst);
01032       if (LHSCst->isNullValue())    // (X !=  0 & X u< 14) -> X-1 u< 13
01033         return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
01034       break;                        // (X != 13 & X u< 15) -> no change
01035     case ICmpInst::ICMP_SLT:
01036       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
01037         return Builder->CreateICmpSLT(Val, LHSCst);
01038       break;                        // (X != 13 & X s< 15) -> no change
01039     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
01040     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
01041     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
01042       return RHS;
01043     case ICmpInst::ICMP_NE:
01044       // Special case to get the ordering right when the values wrap around
01045       // zero.
01046       if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
01047         std::swap(LHSCst, RHSCst);
01048       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
01049         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
01050         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
01051         return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
01052                                       Val->getName()+".cmp");
01053       }
01054       break;                        // (X != 13 & X != 15) -> no change
01055     }
01056     break;
01057   case ICmpInst::ICMP_ULT:
01058     switch (RHSCC) {
01059     default: llvm_unreachable("Unknown integer condition code!");
01060     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
01061     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
01062       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
01063     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
01064       break;
01065     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
01066     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
01067       return LHS;
01068     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
01069       break;
01070     }
01071     break;
01072   case ICmpInst::ICMP_SLT:
01073     switch (RHSCC) {
01074     default: llvm_unreachable("Unknown integer condition code!");
01075     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
01076       break;
01077     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
01078     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
01079       return LHS;
01080     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
01081       break;
01082     }
01083     break;
01084   case ICmpInst::ICMP_UGT:
01085     switch (RHSCC) {
01086     default: llvm_unreachable("Unknown integer condition code!");
01087     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
01088     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
01089       return RHS;
01090     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
01091       break;
01092     case ICmpInst::ICMP_NE:
01093       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
01094         return Builder->CreateICmp(LHSCC, Val, RHSCst);
01095       break;                        // (X u> 13 & X != 15) -> no change
01096     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
01097       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
01098     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
01099       break;
01100     }
01101     break;
01102   case ICmpInst::ICMP_SGT:
01103     switch (RHSCC) {
01104     default: llvm_unreachable("Unknown integer condition code!");
01105     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
01106     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
01107       return RHS;
01108     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
01109       break;
01110     case ICmpInst::ICMP_NE:
01111       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
01112         return Builder->CreateICmp(LHSCC, Val, RHSCst);
01113       break;                        // (X s> 13 & X != 15) -> no change
01114     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
01115       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
01116     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
01117       break;
01118     }
01119     break;
01120   }
01121 
01122   return nullptr;
01123 }
01124 
01125 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp).  NOTE: Unlike the rest of
01126 /// instcombine, this returns a Value which should already be inserted into the
01127 /// function.
01128 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
01129   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
01130       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
01131     if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
01132       return nullptr;
01133 
01134     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
01135     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
01136       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
01137         // If either of the constants are nans, then the whole thing returns
01138         // false.
01139         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
01140           return Builder->getFalse();
01141         return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
01142       }
01143 
01144     // Handle vector zeros.  This occurs because the canonical form of
01145     // "fcmp ord x,x" is "fcmp ord x, 0".
01146     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
01147         isa<ConstantAggregateZero>(RHS->getOperand(1)))
01148       return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
01149     return nullptr;
01150   }
01151 
01152   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
01153   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
01154   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
01155 
01156 
01157   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
01158     // Swap RHS operands to match LHS.
01159     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
01160     std::swap(Op1LHS, Op1RHS);
01161   }
01162 
01163   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
01164     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
01165     if (Op0CC == Op1CC)
01166       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
01167     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
01168       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
01169     if (Op0CC == FCmpInst::FCMP_TRUE)
01170       return RHS;
01171     if (Op1CC == FCmpInst::FCMP_TRUE)
01172       return LHS;
01173 
01174     bool Op0Ordered;
01175     bool Op1Ordered;
01176     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
01177     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
01178     // uno && ord -> false
01179     if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
01180         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
01181     if (Op1Pred == 0) {
01182       std::swap(LHS, RHS);
01183       std::swap(Op0Pred, Op1Pred);
01184       std::swap(Op0Ordered, Op1Ordered);
01185     }
01186     if (Op0Pred == 0) {
01187       // uno && ueq -> uno && (uno || eq) -> uno
01188       // ord && olt -> ord && (ord && lt) -> olt
01189       if (!Op0Ordered && (Op0Ordered == Op1Ordered))
01190         return LHS;
01191       if (Op0Ordered && (Op0Ordered == Op1Ordered))
01192         return RHS;
01193 
01194       // uno && oeq -> uno && (ord && eq) -> false
01195       if (!Op0Ordered)
01196         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
01197       // ord && ueq -> ord && (uno || eq) -> oeq
01198       return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
01199     }
01200   }
01201 
01202   return nullptr;
01203 }
01204 
01205 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
01206   bool Changed = SimplifyAssociativeOrCommutative(I);
01207   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01208 
01209   if (Value *V = SimplifyVectorOp(I))
01210     return ReplaceInstUsesWith(I, V);
01211 
01212   if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AC))
01213     return ReplaceInstUsesWith(I, V);
01214 
01215   // (A|B)&(A|C) -> A|(B&C) etc
01216   if (Value *V = SimplifyUsingDistributiveLaws(I))
01217     return ReplaceInstUsesWith(I, V);
01218 
01219   // See if we can simplify any instructions used by the instruction whose sole
01220   // purpose is to compute bits we don't care about.
01221   if (SimplifyDemandedInstructionBits(I))
01222     return &I;
01223 
01224   if (Value *V = SimplifyBSwap(I))
01225     return ReplaceInstUsesWith(I, V);
01226 
01227   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
01228     const APInt &AndRHSMask = AndRHS->getValue();
01229 
01230     // Optimize a variety of ((val OP C1) & C2) combinations...
01231     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
01232       Value *Op0LHS = Op0I->getOperand(0);
01233       Value *Op0RHS = Op0I->getOperand(1);
01234       switch (Op0I->getOpcode()) {
01235       default: break;
01236       case Instruction::Xor:
01237       case Instruction::Or: {
01238         // If the mask is only needed on one incoming arm, push it up.
01239         if (!Op0I->hasOneUse()) break;
01240 
01241         APInt NotAndRHS(~AndRHSMask);
01242         if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
01243           // Not masking anything out for the LHS, move to RHS.
01244           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
01245                                              Op0RHS->getName()+".masked");
01246           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
01247         }
01248         if (!isa<Constant>(Op0RHS) &&
01249             MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
01250           // Not masking anything out for the RHS, move to LHS.
01251           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
01252                                              Op0LHS->getName()+".masked");
01253           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
01254         }
01255 
01256         break;
01257       }
01258       case Instruction::Add:
01259         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
01260         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
01261         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
01262         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
01263           return BinaryOperator::CreateAnd(V, AndRHS);
01264         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
01265           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
01266         break;
01267 
01268       case Instruction::Sub:
01269         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
01270         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
01271         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
01272         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
01273           return BinaryOperator::CreateAnd(V, AndRHS);
01274 
01275         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
01276         // has 1's for all bits that the subtraction with A might affect.
01277         if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
01278           uint32_t BitWidth = AndRHSMask.getBitWidth();
01279           uint32_t Zeros = AndRHSMask.countLeadingZeros();
01280           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
01281 
01282           if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
01283             Value *NewNeg = Builder->CreateNeg(Op0RHS);
01284             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
01285           }
01286         }
01287         break;
01288 
01289       case Instruction::Shl:
01290       case Instruction::LShr:
01291         // (1 << x) & 1 --> zext(x == 0)
01292         // (1 >> x) & 1 --> zext(x == 0)
01293         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
01294           Value *NewICmp =
01295             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
01296           return new ZExtInst(NewICmp, I.getType());
01297         }
01298         break;
01299       }
01300 
01301       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
01302         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
01303           return Res;
01304     }
01305 
01306     // If this is an integer truncation, and if the source is an 'and' with
01307     // immediate, transform it.  This frequently occurs for bitfield accesses.
01308     {
01309       Value *X = nullptr; ConstantInt *YC = nullptr;
01310       if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
01311         // Change: and (trunc (and X, YC) to T), C2
01312         // into  : and (trunc X to T), trunc(YC) & C2
01313         // This will fold the two constants together, which may allow
01314         // other simplifications.
01315         Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
01316         Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
01317         C3 = ConstantExpr::getAnd(C3, AndRHS);
01318         return BinaryOperator::CreateAnd(NewCast, C3);
01319       }
01320     }
01321 
01322     // Try to fold constant and into select arguments.
01323     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
01324       if (Instruction *R = FoldOpIntoSelect(I, SI))
01325         return R;
01326     if (isa<PHINode>(Op0))
01327       if (Instruction *NV = FoldOpIntoPhi(I))
01328         return NV;
01329   }
01330 
01331 
01332   // (~A & ~B) == (~(A | B)) - De Morgan's Law
01333   if (Value *Op0NotVal = dyn_castNotVal(Op0))
01334     if (Value *Op1NotVal = dyn_castNotVal(Op1))
01335       if (Op0->hasOneUse() && Op1->hasOneUse()) {
01336         Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
01337                                       I.getName()+".demorgan");
01338         return BinaryOperator::CreateNot(Or);
01339       }
01340 
01341   {
01342     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
01343     // (A|B) & ~(A&B) -> A^B
01344     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
01345         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
01346         ((A == C && B == D) || (A == D && B == C)))
01347       return BinaryOperator::CreateXor(A, B);
01348 
01349     // ~(A&B) & (A|B) -> A^B
01350     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
01351         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
01352         ((A == C && B == D) || (A == D && B == C)))
01353       return BinaryOperator::CreateXor(A, B);
01354 
01355     // A&(A^B) => A & ~B
01356     {
01357       Value *tmpOp0 = Op0;
01358       Value *tmpOp1 = Op1;
01359       if (Op0->hasOneUse() &&
01360           match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
01361         if (A == Op1 || B == Op1 ) {
01362           tmpOp1 = Op0;
01363           tmpOp0 = Op1;
01364           // Simplify below
01365         }
01366       }
01367 
01368       if (tmpOp1->hasOneUse() &&
01369           match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
01370         if (B == tmpOp0) {
01371           std::swap(A, B);
01372         }
01373         // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
01374         // A is originally -1 (or a vector of -1 and undefs), then we enter
01375         // an endless loop. By checking that A is non-constant we ensure that
01376         // we will never get to the loop.
01377         if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
01378           return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
01379       }
01380     }
01381 
01382     // (A&((~A)|B)) -> A&B
01383     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
01384         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
01385       return BinaryOperator::CreateAnd(A, Op1);
01386     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
01387         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
01388       return BinaryOperator::CreateAnd(A, Op0);
01389 
01390     // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
01391     if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
01392       if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
01393         if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
01394           return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
01395 
01396     // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
01397     if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
01398       if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
01399         if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
01400           return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
01401 
01402     // (A | B) & ((~A) ^ B) -> (A & B)
01403     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
01404         match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
01405       return BinaryOperator::CreateAnd(A, B);
01406 
01407     // ((~A) ^ B) & (A | B) -> (A & B)
01408     if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
01409         match(Op1, m_Or(m_Specific(A), m_Specific(B))))
01410       return BinaryOperator::CreateAnd(A, B);
01411   }
01412 
01413   {
01414     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
01415     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
01416     if (LHS && RHS)
01417       if (Value *Res = FoldAndOfICmps(LHS, RHS))
01418         return ReplaceInstUsesWith(I, Res);
01419 
01420     // TODO: Make this recursive; it's a little tricky because an arbitrary
01421     // number of 'and' instructions might have to be created.
01422     Value *X, *Y;
01423     if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
01424       if (auto *Cmp = dyn_cast<ICmpInst>(X))
01425         if (Value *Res = FoldAndOfICmps(LHS, Cmp))
01426           return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
01427       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
01428         if (Value *Res = FoldAndOfICmps(LHS, Cmp))
01429           return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
01430     }
01431     if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
01432       if (auto *Cmp = dyn_cast<ICmpInst>(X))
01433         if (Value *Res = FoldAndOfICmps(Cmp, RHS))
01434           return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
01435       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
01436         if (Value *Res = FoldAndOfICmps(Cmp, RHS))
01437           return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
01438     }
01439   }
01440 
01441   // If and'ing two fcmp, try combine them into one.
01442   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
01443     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
01444       if (Value *Res = FoldAndOfFCmps(LHS, RHS))
01445         return ReplaceInstUsesWith(I, Res);
01446 
01447 
01448   // fold (and (cast A), (cast B)) -> (cast (and A, B))
01449   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
01450     if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
01451       Type *SrcTy = Op0C->getOperand(0)->getType();
01452       if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
01453           SrcTy == Op1C->getOperand(0)->getType() &&
01454           SrcTy->isIntOrIntVectorTy()) {
01455         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
01456 
01457         // Only do this if the casts both really cause code to be generated.
01458         if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
01459             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
01460           Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
01461           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
01462         }
01463 
01464         // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
01465         // cast is otherwise not optimizable.  This happens for vector sexts.
01466         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
01467           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
01468             if (Value *Res = FoldAndOfICmps(LHS, RHS))
01469               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
01470 
01471         // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
01472         // cast is otherwise not optimizable.  This happens for vector sexts.
01473         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
01474           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
01475             if (Value *Res = FoldAndOfFCmps(LHS, RHS))
01476               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
01477       }
01478     }
01479 
01480   {
01481     Value *X = nullptr;
01482     bool OpsSwapped = false;
01483     // Canonicalize SExt or Not to the LHS
01484     if (match(Op1, m_SExt(m_Value())) ||
01485         match(Op1, m_Not(m_Value()))) {
01486       std::swap(Op0, Op1);
01487       OpsSwapped = true;
01488     }
01489 
01490     // Fold (and (sext bool to A), B) --> (select bool, B, 0)
01491     if (match(Op0, m_SExt(m_Value(X))) &&
01492         X->getType()->getScalarType()->isIntegerTy(1)) {
01493       Value *Zero = Constant::getNullValue(Op1->getType());
01494       return SelectInst::Create(X, Op1, Zero);
01495     }
01496 
01497     // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
01498     if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
01499         X->getType()->getScalarType()->isIntegerTy(1)) {
01500       Value *Zero = Constant::getNullValue(Op0->getType());
01501       return SelectInst::Create(X, Zero, Op1);
01502     }
01503 
01504     if (OpsSwapped)
01505       std::swap(Op0, Op1);
01506   }
01507 
01508   return Changed ? &I : nullptr;
01509 }
01510 
01511 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
01512 /// capable of providing pieces of a bswap.  The subexpression provides pieces
01513 /// of a bswap if it is proven that each of the non-zero bytes in the output of
01514 /// the expression came from the corresponding "byte swapped" byte in some other
01515 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
01516 /// we know that the expression deposits the low byte of %X into the high byte
01517 /// of the bswap result and that all other bytes are zero.  This expression is
01518 /// accepted, the high byte of ByteValues is set to X to indicate a correct
01519 /// match.
01520 ///
01521 /// This function returns true if the match was unsuccessful and false if so.
01522 /// On entry to the function the "OverallLeftShift" is a signed integer value
01523 /// indicating the number of bytes that the subexpression is later shifted.  For
01524 /// example, if the expression is later right shifted by 16 bits, the
01525 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
01526 /// byte of ByteValues is actually being set.
01527 ///
01528 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
01529 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
01530 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
01531 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
01532 /// always in the local (OverallLeftShift) coordinate space.
01533 ///
01534 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
01535                               SmallVectorImpl<Value *> &ByteValues) {
01536   if (Instruction *I = dyn_cast<Instruction>(V)) {
01537     // If this is an or instruction, it may be an inner node of the bswap.
01538     if (I->getOpcode() == Instruction::Or) {
01539       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
01540                                ByteValues) ||
01541              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
01542                                ByteValues);
01543     }
01544 
01545     // If this is a logical shift by a constant multiple of 8, recurse with
01546     // OverallLeftShift and ByteMask adjusted.
01547     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
01548       unsigned ShAmt =
01549         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
01550       // Ensure the shift amount is defined and of a byte value.
01551       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
01552         return true;
01553 
01554       unsigned ByteShift = ShAmt >> 3;
01555       if (I->getOpcode() == Instruction::Shl) {
01556         // X << 2 -> collect(X, +2)
01557         OverallLeftShift += ByteShift;
01558         ByteMask >>= ByteShift;
01559       } else {
01560         // X >>u 2 -> collect(X, -2)
01561         OverallLeftShift -= ByteShift;
01562         ByteMask <<= ByteShift;
01563         ByteMask &= (~0U >> (32-ByteValues.size()));
01564       }
01565 
01566       if (OverallLeftShift >= (int)ByteValues.size()) return true;
01567       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
01568 
01569       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
01570                                ByteValues);
01571     }
01572 
01573     // If this is a logical 'and' with a mask that clears bytes, clear the
01574     // corresponding bytes in ByteMask.
01575     if (I->getOpcode() == Instruction::And &&
01576         isa<ConstantInt>(I->getOperand(1))) {
01577       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
01578       unsigned NumBytes = ByteValues.size();
01579       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
01580       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
01581 
01582       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
01583         // If this byte is masked out by a later operation, we don't care what
01584         // the and mask is.
01585         if ((ByteMask & (1 << i)) == 0)
01586           continue;
01587 
01588         // If the AndMask is all zeros for this byte, clear the bit.
01589         APInt MaskB = AndMask & Byte;
01590         if (MaskB == 0) {
01591           ByteMask &= ~(1U << i);
01592           continue;
01593         }
01594 
01595         // If the AndMask is not all ones for this byte, it's not a bytezap.
01596         if (MaskB != Byte)
01597           return true;
01598 
01599         // Otherwise, this byte is kept.
01600       }
01601 
01602       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
01603                                ByteValues);
01604     }
01605   }
01606 
01607   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
01608   // the input value to the bswap.  Some observations: 1) if more than one byte
01609   // is demanded from this input, then it could not be successfully assembled
01610   // into a byteswap.  At least one of the two bytes would not be aligned with
01611   // their ultimate destination.
01612   if (!isPowerOf2_32(ByteMask)) return true;
01613   unsigned InputByteNo = countTrailingZeros(ByteMask);
01614 
01615   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
01616   // is demanded, it needs to go into byte 0 of the result.  This means that the
01617   // byte needs to be shifted until it lands in the right byte bucket.  The
01618   // shift amount depends on the position: if the byte is coming from the high
01619   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
01620   // low part, it must be shifted left.
01621   unsigned DestByteNo = InputByteNo + OverallLeftShift;
01622   if (ByteValues.size()-1-DestByteNo != InputByteNo)
01623     return true;
01624 
01625   // If the destination byte value is already defined, the values are or'd
01626   // together, which isn't a bswap (unless it's an or of the same bits).
01627   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
01628     return true;
01629   ByteValues[DestByteNo] = V;
01630   return false;
01631 }
01632 
01633 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
01634 /// If so, insert the new bswap intrinsic and return it.
01635 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
01636   IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
01637   if (!ITy || ITy->getBitWidth() % 16 ||
01638       // ByteMask only allows up to 32-byte values.
01639       ITy->getBitWidth() > 32*8)
01640     return nullptr;   // Can only bswap pairs of bytes.  Can't do vectors.
01641 
01642   /// ByteValues - For each byte of the result, we keep track of which value
01643   /// defines each byte.
01644   SmallVector<Value*, 8> ByteValues;
01645   ByteValues.resize(ITy->getBitWidth()/8);
01646 
01647   // Try to find all the pieces corresponding to the bswap.
01648   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
01649   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
01650     return nullptr;
01651 
01652   // Check to see if all of the bytes come from the same value.
01653   Value *V = ByteValues[0];
01654   if (!V) return nullptr;  // Didn't find a byte?  Must be zero.
01655 
01656   // Check to make sure that all of the bytes come from the same value.
01657   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
01658     if (ByteValues[i] != V)
01659       return nullptr;
01660   Module *M = I.getParent()->getParent()->getParent();
01661   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
01662   return CallInst::Create(F, V);
01663 }
01664 
01665 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
01666 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
01667 /// we can simplify this expression to "cond ? C : D or B".
01668 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
01669                                          Value *C, Value *D) {
01670   // If A is not a select of -1/0, this cannot match.
01671   Value *Cond = nullptr;
01672   if (!match(A, m_SExt(m_Value(Cond))) ||
01673       !Cond->getType()->isIntegerTy(1))
01674     return nullptr;
01675 
01676   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
01677   if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
01678     return SelectInst::Create(Cond, C, B);
01679   if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
01680     return SelectInst::Create(Cond, C, B);
01681 
01682   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
01683   if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
01684     return SelectInst::Create(Cond, C, D);
01685   if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
01686     return SelectInst::Create(Cond, C, D);
01687   return nullptr;
01688 }
01689 
01690 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
01691 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
01692                                    Instruction *CxtI) {
01693   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
01694 
01695   // Fold (iszero(A & K1) | iszero(A & K2)) ->  (A & (K1 | K2)) != (K1 | K2)
01696   // if K1 and K2 are a one-bit mask.
01697   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
01698   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
01699 
01700   if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
01701       RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
01702 
01703     BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
01704     BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
01705     if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
01706         LAnd->getOpcode() == Instruction::And &&
01707         RAnd->getOpcode() == Instruction::And) {
01708 
01709       Value *Mask = nullptr;
01710       Value *Masked = nullptr;
01711       if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
01712           isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, AC, CxtI,
01713                                  DT) &&
01714           isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, AC, CxtI,
01715                                  DT)) {
01716         Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
01717         Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
01718       } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
01719                  isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, AC,
01720                                         CxtI, DT) &&
01721                  isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, AC,
01722                                         CxtI, DT)) {
01723         Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
01724         Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
01725       }
01726 
01727       if (Masked)
01728         return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
01729     }
01730   }
01731 
01732   // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
01733   //                   -->  (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
01734   // The original condition actually refers to the following two ranges:
01735   // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
01736   // We can fold these two ranges if:
01737   // 1) C1 and C2 is unsigned greater than C3.
01738   // 2) The two ranges are separated.
01739   // 3) C1 ^ C2 is one-bit mask.
01740   // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
01741   // This implies all values in the two ranges differ by exactly one bit.
01742 
01743   if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
01744       LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
01745       RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
01746       LHSCst->getValue() == (RHSCst->getValue())) {
01747 
01748     Value *LAdd = LHS->getOperand(0);
01749     Value *RAdd = RHS->getOperand(0);
01750 
01751     Value *LAddOpnd, *RAddOpnd;
01752     ConstantInt *LAddCst, *RAddCst;
01753     if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
01754         match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
01755         LAddCst->getValue().ugt(LHSCst->getValue()) &&
01756         RAddCst->getValue().ugt(LHSCst->getValue())) {
01757 
01758       APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
01759       if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
01760         ConstantInt *MaxAddCst = nullptr;
01761         if (LAddCst->getValue().ult(RAddCst->getValue()))
01762           MaxAddCst = RAddCst;
01763         else
01764           MaxAddCst = LAddCst;
01765 
01766         APInt RRangeLow = -RAddCst->getValue();
01767         APInt RRangeHigh = RRangeLow + LHSCst->getValue();
01768         APInt LRangeLow = -LAddCst->getValue();
01769         APInt LRangeHigh = LRangeLow + LHSCst->getValue();
01770         APInt LowRangeDiff = RRangeLow ^ LRangeLow;
01771         APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
01772         APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
01773                                                    : RRangeLow - LRangeLow;
01774 
01775         if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
01776             RangeDiff.ugt(LHSCst->getValue())) {
01777           Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
01778 
01779           Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
01780           Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
01781           return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
01782         }
01783       }
01784     }
01785   }
01786 
01787   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
01788   if (PredicatesFoldable(LHSCC, RHSCC)) {
01789     if (LHS->getOperand(0) == RHS->getOperand(1) &&
01790         LHS->getOperand(1) == RHS->getOperand(0))
01791       LHS->swapOperands();
01792     if (LHS->getOperand(0) == RHS->getOperand(0) &&
01793         LHS->getOperand(1) == RHS->getOperand(1)) {
01794       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
01795       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
01796       bool isSigned = LHS->isSigned() || RHS->isSigned();
01797       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
01798     }
01799   }
01800 
01801   // handle (roughly):
01802   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
01803   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
01804     return V;
01805 
01806   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
01807   if (LHS->hasOneUse() || RHS->hasOneUse()) {
01808     // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
01809     // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
01810     Value *A = nullptr, *B = nullptr;
01811     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
01812       B = Val;
01813       if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
01814         A = Val2;
01815       else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
01816         A = RHS->getOperand(1);
01817     }
01818     // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
01819     // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
01820     else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
01821       B = Val2;
01822       if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
01823         A = Val;
01824       else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
01825         A = LHS->getOperand(1);
01826     }
01827     if (A && B)
01828       return Builder->CreateICmp(
01829           ICmpInst::ICMP_UGE,
01830           Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
01831   }
01832 
01833   // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
01834   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
01835     return V;
01836 
01837   // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
01838   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
01839     return V;
01840  
01841   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
01842   if (!LHSCst || !RHSCst) return nullptr;
01843 
01844   if (LHSCst == RHSCst && LHSCC == RHSCC) {
01845     // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
01846     if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
01847       Value *NewOr = Builder->CreateOr(Val, Val2);
01848       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
01849     }
01850   }
01851 
01852   // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
01853   //   iff C2 + CA == C1.
01854   if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
01855     ConstantInt *AddCst;
01856     if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
01857       if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
01858         return Builder->CreateICmpULE(Val, LHSCst);
01859   }
01860 
01861   // From here on, we only handle:
01862   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
01863   if (Val != Val2) return nullptr;
01864 
01865   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
01866   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
01867       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
01868       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
01869       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
01870     return nullptr;
01871 
01872   // We can't fold (ugt x, C) | (sgt x, C2).
01873   if (!PredicatesFoldable(LHSCC, RHSCC))
01874     return nullptr;
01875 
01876   // Ensure that the larger constant is on the RHS.
01877   bool ShouldSwap;
01878   if (CmpInst::isSigned(LHSCC) ||
01879       (ICmpInst::isEquality(LHSCC) &&
01880        CmpInst::isSigned(RHSCC)))
01881     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
01882   else
01883     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
01884 
01885   if (ShouldSwap) {
01886     std::swap(LHS, RHS);
01887     std::swap(LHSCst, RHSCst);
01888     std::swap(LHSCC, RHSCC);
01889   }
01890 
01891   // At this point, we know we have two icmp instructions
01892   // comparing a value against two constants and or'ing the result
01893   // together.  Because of the above check, we know that we only have
01894   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
01895   // icmp folding check above), that the two constants are not
01896   // equal.
01897   assert(LHSCst != RHSCst && "Compares not folded above?");
01898 
01899   switch (LHSCC) {
01900   default: llvm_unreachable("Unknown integer condition code!");
01901   case ICmpInst::ICMP_EQ:
01902     switch (RHSCC) {
01903     default: llvm_unreachable("Unknown integer condition code!");
01904     case ICmpInst::ICMP_EQ:
01905       if (LHS->getOperand(0) == RHS->getOperand(0)) {
01906         // if LHSCst and RHSCst differ only by one bit:
01907         // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
01908         assert(LHSCst->getValue().ule(LHSCst->getValue()));
01909 
01910         APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
01911         if (Xor.isPowerOf2()) {
01912           Value *NegCst = Builder->getInt(~Xor);
01913           Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
01914           return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
01915         }
01916       }
01917 
01918       if (LHSCst == SubOne(RHSCst)) {
01919         // (X == 13 | X == 14) -> X-13 <u 2
01920         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
01921         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
01922         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
01923         return Builder->CreateICmpULT(Add, AddCST);
01924       }
01925 
01926       break;                         // (X == 13 | X == 15) -> no change
01927     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
01928     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
01929       break;
01930     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
01931     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
01932     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
01933       return RHS;
01934     }
01935     break;
01936   case ICmpInst::ICMP_NE:
01937     switch (RHSCC) {
01938     default: llvm_unreachable("Unknown integer condition code!");
01939     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
01940     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
01941     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
01942       return LHS;
01943     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
01944     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
01945     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
01946       return Builder->getTrue();
01947     }
01948   case ICmpInst::ICMP_ULT:
01949     switch (RHSCC) {
01950     default: llvm_unreachable("Unknown integer condition code!");
01951     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
01952       break;
01953     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
01954       // If RHSCst is [us]MAXINT, it is always false.  Not handling
01955       // this can cause overflow.
01956       if (RHSCst->isMaxValue(false))
01957         return LHS;
01958       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
01959     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
01960       break;
01961     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
01962     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
01963       return RHS;
01964     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
01965       break;
01966     }
01967     break;
01968   case ICmpInst::ICMP_SLT:
01969     switch (RHSCC) {
01970     default: llvm_unreachable("Unknown integer condition code!");
01971     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
01972       break;
01973     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
01974       // If RHSCst is [us]MAXINT, it is always false.  Not handling
01975       // this can cause overflow.
01976       if (RHSCst->isMaxValue(true))
01977         return LHS;
01978       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
01979     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
01980       break;
01981     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
01982     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
01983       return RHS;
01984     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
01985       break;
01986     }
01987     break;
01988   case ICmpInst::ICMP_UGT:
01989     switch (RHSCC) {
01990     default: llvm_unreachable("Unknown integer condition code!");
01991     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
01992     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
01993       return LHS;
01994     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
01995       break;
01996     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
01997     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
01998       return Builder->getTrue();
01999     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
02000       break;
02001     }
02002     break;
02003   case ICmpInst::ICMP_SGT:
02004     switch (RHSCC) {
02005     default: llvm_unreachable("Unknown integer condition code!");
02006     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
02007     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
02008       return LHS;
02009     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
02010       break;
02011     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
02012     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
02013       return Builder->getTrue();
02014     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
02015       break;
02016     }
02017     break;
02018   }
02019   return nullptr;
02020 }
02021 
02022 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp).  NOTE: Unlike the rest of
02023 /// instcombine, this returns a Value which should already be inserted into the
02024 /// function.
02025 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
02026   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
02027       RHS->getPredicate() == FCmpInst::FCMP_UNO &&
02028       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
02029     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
02030       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
02031         // If either of the constants are nans, then the whole thing returns
02032         // true.
02033         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
02034           return Builder->getTrue();
02035 
02036         // Otherwise, no need to compare the two constants, compare the
02037         // rest.
02038         return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
02039       }
02040 
02041     // Handle vector zeros.  This occurs because the canonical form of
02042     // "fcmp uno x,x" is "fcmp uno x, 0".
02043     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
02044         isa<ConstantAggregateZero>(RHS->getOperand(1)))
02045       return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
02046 
02047     return nullptr;
02048   }
02049 
02050   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
02051   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
02052   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
02053 
02054   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
02055     // Swap RHS operands to match LHS.
02056     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
02057     std::swap(Op1LHS, Op1RHS);
02058   }
02059   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
02060     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
02061     if (Op0CC == Op1CC)
02062       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
02063     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
02064       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
02065     if (Op0CC == FCmpInst::FCMP_FALSE)
02066       return RHS;
02067     if (Op1CC == FCmpInst::FCMP_FALSE)
02068       return LHS;
02069     bool Op0Ordered;
02070     bool Op1Ordered;
02071     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
02072     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
02073     if (Op0Ordered == Op1Ordered) {
02074       // If both are ordered or unordered, return a new fcmp with
02075       // or'ed predicates.
02076       return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
02077     }
02078   }
02079   return nullptr;
02080 }
02081 
02082 /// FoldOrWithConstants - This helper function folds:
02083 ///
02084 ///     ((A | B) & C1) | (B & C2)
02085 ///
02086 /// into:
02087 ///
02088 ///     (A & C1) | B
02089 ///
02090 /// when the XOR of the two constants is "all ones" (-1).
02091 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
02092                                                Value *A, Value *B, Value *C) {
02093   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
02094   if (!CI1) return nullptr;
02095 
02096   Value *V1 = nullptr;
02097   ConstantInt *CI2 = nullptr;
02098   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
02099 
02100   APInt Xor = CI1->getValue() ^ CI2->getValue();
02101   if (!Xor.isAllOnesValue()) return nullptr;
02102 
02103   if (V1 == A || V1 == B) {
02104     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
02105     return BinaryOperator::CreateOr(NewOp, V1);
02106   }
02107 
02108   return nullptr;
02109 }
02110 
02111 /// \brief This helper function folds:
02112 ///
02113 ///     ((A | B) & C1) ^ (B & C2)
02114 ///
02115 /// into:
02116 ///
02117 ///     (A & C1) ^ B
02118 ///
02119 /// when the XOR of the two constants is "all ones" (-1).
02120 Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
02121                                                 Value *A, Value *B, Value *C) {
02122   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
02123   if (!CI1)
02124     return nullptr;
02125 
02126   Value *V1 = nullptr;
02127   ConstantInt *CI2 = nullptr;
02128   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
02129     return nullptr;
02130 
02131   APInt Xor = CI1->getValue() ^ CI2->getValue();
02132   if (!Xor.isAllOnesValue())
02133     return nullptr;
02134 
02135   if (V1 == A || V1 == B) {
02136     Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
02137     return BinaryOperator::CreateXor(NewOp, V1);
02138   }
02139 
02140   return nullptr;
02141 }
02142 
02143 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
02144   bool Changed = SimplifyAssociativeOrCommutative(I);
02145   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02146 
02147   if (Value *V = SimplifyVectorOp(I))
02148     return ReplaceInstUsesWith(I, V);
02149 
02150   if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
02151     return ReplaceInstUsesWith(I, V);
02152 
02153   // (A&B)|(A&C) -> A&(B|C) etc
02154   if (Value *V = SimplifyUsingDistributiveLaws(I))
02155     return ReplaceInstUsesWith(I, V);
02156 
02157   // See if we can simplify any instructions used by the instruction whose sole
02158   // purpose is to compute bits we don't care about.
02159   if (SimplifyDemandedInstructionBits(I))
02160     return &I;
02161 
02162   if (Value *V = SimplifyBSwap(I))
02163     return ReplaceInstUsesWith(I, V);
02164 
02165   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
02166     ConstantInt *C1 = nullptr; Value *X = nullptr;
02167     // (X & C1) | C2 --> (X | C2) & (C1|C2)
02168     // iff (C1 & C2) == 0.
02169     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
02170         (RHS->getValue() & C1->getValue()) != 0 &&
02171         Op0->hasOneUse()) {
02172       Value *Or = Builder->CreateOr(X, RHS);
02173       Or->takeName(Op0);
02174       return BinaryOperator::CreateAnd(Or,
02175                              Builder->getInt(RHS->getValue() | C1->getValue()));
02176     }
02177 
02178     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
02179     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
02180         Op0->hasOneUse()) {
02181       Value *Or = Builder->CreateOr(X, RHS);
02182       Or->takeName(Op0);
02183       return BinaryOperator::CreateXor(Or,
02184                             Builder->getInt(C1->getValue() & ~RHS->getValue()));
02185     }
02186 
02187     // Try to fold constant and into select arguments.
02188     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
02189       if (Instruction *R = FoldOpIntoSelect(I, SI))
02190         return R;
02191 
02192     if (isa<PHINode>(Op0))
02193       if (Instruction *NV = FoldOpIntoPhi(I))
02194         return NV;
02195   }
02196 
02197   Value *A = nullptr, *B = nullptr;
02198   ConstantInt *C1 = nullptr, *C2 = nullptr;
02199 
02200   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
02201   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
02202   if (match(Op0, m_Or(m_Value(), m_Value())) ||
02203       match(Op1, m_Or(m_Value(), m_Value())) ||
02204       (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
02205        match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
02206     if (Instruction *BSwap = MatchBSwap(I))
02207       return BSwap;
02208   }
02209 
02210   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
02211   if (Op0->hasOneUse() &&
02212       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
02213       MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
02214     Value *NOr = Builder->CreateOr(A, Op1);
02215     NOr->takeName(Op0);
02216     return BinaryOperator::CreateXor(NOr, C1);
02217   }
02218 
02219   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
02220   if (Op1->hasOneUse() &&
02221       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
02222       MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
02223     Value *NOr = Builder->CreateOr(A, Op0);
02224     NOr->takeName(Op0);
02225     return BinaryOperator::CreateXor(NOr, C1);
02226   }
02227 
02228   // ((~A & B) | A) -> (A | B)
02229   if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
02230       match(Op1, m_Specific(A)))
02231     return BinaryOperator::CreateOr(A, B);
02232 
02233   // ((A & B) | ~A) -> (~A | B)
02234   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
02235       match(Op1, m_Not(m_Specific(A))))
02236     return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
02237 
02238   // (A & (~B)) | (A ^ B) -> (A ^ B)
02239   if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
02240       match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
02241     return BinaryOperator::CreateXor(A, B);
02242 
02243   // (A ^ B) | ( A & (~B)) -> (A ^ B)
02244   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
02245       match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
02246     return BinaryOperator::CreateXor(A, B);
02247 
02248   // (A & C)|(B & D)
02249   Value *C = nullptr, *D = nullptr;
02250   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
02251       match(Op1, m_And(m_Value(B), m_Value(D)))) {
02252     Value *V1 = nullptr, *V2 = nullptr;
02253     C1 = dyn_cast<ConstantInt>(C);
02254     C2 = dyn_cast<ConstantInt>(D);
02255     if (C1 && C2) {  // (A & C1)|(B & C2)
02256       if ((C1->getValue() & C2->getValue()) == 0) {
02257         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
02258         // iff (C1&C2) == 0 and (N&~C1) == 0
02259         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
02260             ((V1 == B &&
02261               MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
02262              (V2 == B &&
02263               MaskedValueIsZero(V1, ~C1->getValue(), 0, &I))))  // (N|V)
02264           return BinaryOperator::CreateAnd(A,
02265                                 Builder->getInt(C1->getValue()|C2->getValue()));
02266         // Or commutes, try both ways.
02267         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
02268             ((V1 == A &&
02269               MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
02270              (V2 == A &&
02271               MaskedValueIsZero(V1, ~C2->getValue(), 0, &I))))  // (N|V)
02272           return BinaryOperator::CreateAnd(B,
02273                                 Builder->getInt(C1->getValue()|C2->getValue()));
02274 
02275         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
02276         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
02277         ConstantInt *C3 = nullptr, *C4 = nullptr;
02278         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
02279             (C3->getValue() & ~C1->getValue()) == 0 &&
02280             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
02281             (C4->getValue() & ~C2->getValue()) == 0) {
02282           V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
02283           return BinaryOperator::CreateAnd(V2,
02284                                 Builder->getInt(C1->getValue()|C2->getValue()));
02285         }
02286       }
02287     }
02288 
02289     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants.
02290     // Don't do this for vector select idioms, the code generator doesn't handle
02291     // them well yet.
02292     if (!I.getType()->isVectorTy()) {
02293       if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
02294         return Match;
02295       if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
02296         return Match;
02297       if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
02298         return Match;
02299       if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
02300         return Match;
02301     }
02302 
02303     // ((A&~B)|(~A&B)) -> A^B
02304     if ((match(C, m_Not(m_Specific(D))) &&
02305          match(B, m_Not(m_Specific(A)))))
02306       return BinaryOperator::CreateXor(A, D);
02307     // ((~B&A)|(~A&B)) -> A^B
02308     if ((match(A, m_Not(m_Specific(D))) &&
02309          match(B, m_Not(m_Specific(C)))))
02310       return BinaryOperator::CreateXor(C, D);
02311     // ((A&~B)|(B&~A)) -> A^B
02312     if ((match(C, m_Not(m_Specific(B))) &&
02313          match(D, m_Not(m_Specific(A)))))
02314       return BinaryOperator::CreateXor(A, B);
02315     // ((~B&A)|(B&~A)) -> A^B
02316     if ((match(A, m_Not(m_Specific(B))) &&
02317          match(D, m_Not(m_Specific(C)))))
02318       return BinaryOperator::CreateXor(C, B);
02319 
02320     // ((A|B)&1)|(B&-2) -> (A&1) | B
02321     if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
02322         match(A, m_Or(m_Specific(B), m_Value(V1)))) {
02323       Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
02324       if (Ret) return Ret;
02325     }
02326     // (B&-2)|((A|B)&1) -> (A&1) | B
02327     if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
02328         match(B, m_Or(m_Value(V1), m_Specific(A)))) {
02329       Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
02330       if (Ret) return Ret;
02331     }
02332     // ((A^B)&1)|(B&-2) -> (A&1) ^ B
02333     if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
02334         match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
02335       Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
02336       if (Ret) return Ret;
02337     }
02338     // (B&-2)|((A^B)&1) -> (A&1) ^ B
02339     if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
02340         match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
02341       Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
02342       if (Ret) return Ret;
02343     }
02344   }
02345 
02346   // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
02347   if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
02348     if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
02349       if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
02350         return BinaryOperator::CreateOr(Op0, C);
02351 
02352   // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
02353   if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
02354     if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
02355       if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
02356         return BinaryOperator::CreateOr(Op1, C);
02357 
02358   // ((B | C) & A) | B -> B | (A & C)
02359   if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
02360     return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
02361 
02362   // (~A | ~B) == (~(A & B)) - De Morgan's Law
02363   if (Value *Op0NotVal = dyn_castNotVal(Op0))
02364     if (Value *Op1NotVal = dyn_castNotVal(Op1))
02365       if (Op0->hasOneUse() && Op1->hasOneUse()) {
02366         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
02367                                         I.getName()+".demorgan");
02368         return BinaryOperator::CreateNot(And);
02369       }
02370 
02371   // Canonicalize xor to the RHS.
02372   bool SwappedForXor = false;
02373   if (match(Op0, m_Xor(m_Value(), m_Value()))) {
02374     std::swap(Op0, Op1);
02375     SwappedForXor = true;
02376   }
02377 
02378   // A | ( A ^ B) -> A |  B
02379   // A | (~A ^ B) -> A | ~B
02380   // (A & B) | (A ^ B)
02381   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
02382     if (Op0 == A || Op0 == B)
02383       return BinaryOperator::CreateOr(A, B);
02384 
02385     if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
02386         match(Op0, m_And(m_Specific(B), m_Specific(A))))
02387       return BinaryOperator::CreateOr(A, B);
02388 
02389     if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
02390       Value *Not = Builder->CreateNot(B, B->getName()+".not");
02391       return BinaryOperator::CreateOr(Not, Op0);
02392     }
02393     if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
02394       Value *Not = Builder->CreateNot(A, A->getName()+".not");
02395       return BinaryOperator::CreateOr(Not, Op0);
02396     }
02397   }
02398 
02399   // A | ~(A | B) -> A | ~B
02400   // A | ~(A ^ B) -> A | ~B
02401   if (match(Op1, m_Not(m_Value(A))))
02402     if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
02403       if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
02404           Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
02405                                B->getOpcode() == Instruction::Xor)) {
02406         Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
02407                                                  B->getOperand(0);
02408         Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
02409         return BinaryOperator::CreateOr(Not, Op0);
02410       }
02411 
02412   // (A & B) | ((~A) ^ B) -> (~A ^ B)
02413   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
02414       match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
02415     return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
02416 
02417   // ((~A) ^ B) | (A & B) -> (~A ^ B)
02418   if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
02419       match(Op1, m_And(m_Specific(A), m_Specific(B))))
02420     return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
02421 
02422   if (SwappedForXor)
02423     std::swap(Op0, Op1);
02424 
02425   {
02426     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
02427     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
02428     if (LHS && RHS)
02429       if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
02430         return ReplaceInstUsesWith(I, Res);
02431 
02432     // TODO: Make this recursive; it's a little tricky because an arbitrary
02433     // number of 'or' instructions might have to be created.
02434     Value *X, *Y;
02435     if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
02436       if (auto *Cmp = dyn_cast<ICmpInst>(X))
02437         if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
02438           return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
02439       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
02440         if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
02441           return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
02442     }
02443     if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
02444       if (auto *Cmp = dyn_cast<ICmpInst>(X))
02445         if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
02446           return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
02447       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
02448         if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
02449           return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
02450     }
02451   }
02452 
02453   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
02454   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
02455     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
02456       if (Value *Res = FoldOrOfFCmps(LHS, RHS))
02457         return ReplaceInstUsesWith(I, Res);
02458 
02459   // fold (or (cast A), (cast B)) -> (cast (or A, B))
02460   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
02461     CastInst *Op1C = dyn_cast<CastInst>(Op1);
02462     if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
02463       Type *SrcTy = Op0C->getOperand(0)->getType();
02464       if (SrcTy == Op1C->getOperand(0)->getType() &&
02465           SrcTy->isIntOrIntVectorTy()) {
02466         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
02467 
02468         if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
02469             // Only do this if the casts both really cause code to be
02470             // generated.
02471             ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
02472             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
02473           Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
02474           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
02475         }
02476 
02477         // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
02478         // cast is otherwise not optimizable.  This happens for vector sexts.
02479         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
02480           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
02481             if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
02482               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
02483 
02484         // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
02485         // cast is otherwise not optimizable.  This happens for vector sexts.
02486         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
02487           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
02488             if (Value *Res = FoldOrOfFCmps(LHS, RHS))
02489               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
02490       }
02491     }
02492   }
02493 
02494   // or(sext(A), B) -> A ? -1 : B where A is an i1
02495   // or(A, sext(B)) -> B ? -1 : A where B is an i1
02496   if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
02497     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
02498   if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
02499     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
02500 
02501   // Note: If we've gotten to the point of visiting the outer OR, then the
02502   // inner one couldn't be simplified.  If it was a constant, then it won't
02503   // be simplified by a later pass either, so we try swapping the inner/outer
02504   // ORs in the hopes that we'll be able to simplify it this way.
02505   // (X|C) | V --> (X|V) | C
02506   if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
02507       match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
02508     Value *Inner = Builder->CreateOr(A, Op1);
02509     Inner->takeName(Op0);
02510     return BinaryOperator::CreateOr(Inner, C1);
02511   }
02512 
02513   // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
02514   // Since this OR statement hasn't been optimized further yet, we hope
02515   // that this transformation will allow the new ORs to be optimized.
02516   {
02517     Value *X = nullptr, *Y = nullptr;
02518     if (Op0->hasOneUse() && Op1->hasOneUse() &&
02519         match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
02520         match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
02521       Value *orTrue = Builder->CreateOr(A, C);
02522       Value *orFalse = Builder->CreateOr(B, D);
02523       return SelectInst::Create(X, orTrue, orFalse);
02524     }
02525   }
02526 
02527   return Changed ? &I : nullptr;
02528 }
02529 
02530 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
02531   bool Changed = SimplifyAssociativeOrCommutative(I);
02532   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02533 
02534   if (Value *V = SimplifyVectorOp(I))
02535     return ReplaceInstUsesWith(I, V);
02536 
02537   if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
02538     return ReplaceInstUsesWith(I, V);
02539 
02540   // (A&B)^(A&C) -> A&(B^C) etc
02541   if (Value *V = SimplifyUsingDistributiveLaws(I))
02542     return ReplaceInstUsesWith(I, V);
02543 
02544   // See if we can simplify any instructions used by the instruction whose sole
02545   // purpose is to compute bits we don't care about.
02546   if (SimplifyDemandedInstructionBits(I))
02547     return &I;
02548 
02549   if (Value *V = SimplifyBSwap(I))
02550     return ReplaceInstUsesWith(I, V);
02551 
02552   // Is this a ~ operation?
02553   if (Value *NotOp = dyn_castNotVal(&I)) {
02554     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
02555       if (Op0I->getOpcode() == Instruction::And ||
02556           Op0I->getOpcode() == Instruction::Or) {
02557         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
02558         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
02559         if (dyn_castNotVal(Op0I->getOperand(1)))
02560           Op0I->swapOperands();
02561         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
02562           Value *NotY =
02563             Builder->CreateNot(Op0I->getOperand(1),
02564                                Op0I->getOperand(1)->getName()+".not");
02565           if (Op0I->getOpcode() == Instruction::And)
02566             return BinaryOperator::CreateOr(Op0NotVal, NotY);
02567           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
02568         }
02569 
02570         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
02571         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
02572         if (IsFreeToInvert(Op0I->getOperand(0),
02573                            Op0I->getOperand(0)->hasOneUse()) &&
02574             IsFreeToInvert(Op0I->getOperand(1),
02575                            Op0I->getOperand(1)->hasOneUse())) {
02576           Value *NotX =
02577             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
02578           Value *NotY =
02579             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
02580           if (Op0I->getOpcode() == Instruction::And)
02581             return BinaryOperator::CreateOr(NotX, NotY);
02582           return BinaryOperator::CreateAnd(NotX, NotY);
02583         }
02584 
02585       } else if (Op0I->getOpcode() == Instruction::AShr) {
02586         // ~(~X >>s Y) --> (X >>s Y)
02587         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
02588           return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
02589       }
02590     }
02591   }
02592 
02593   if (Constant *RHS = dyn_cast<Constant>(Op1)) {
02594     if (RHS->isAllOnesValue() && Op0->hasOneUse())
02595       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
02596       if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
02597         return CmpInst::Create(CI->getOpcode(),
02598                                CI->getInversePredicate(),
02599                                CI->getOperand(0), CI->getOperand(1));
02600   }
02601 
02602   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
02603     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
02604     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
02605       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
02606         if (CI->hasOneUse() && Op0C->hasOneUse()) {
02607           Instruction::CastOps Opcode = Op0C->getOpcode();
02608           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
02609               (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
02610                                             Op0C->getDestTy()))) {
02611             CI->setPredicate(CI->getInversePredicate());
02612             return CastInst::Create(Opcode, CI, Op0C->getType());
02613           }
02614         }
02615       }
02616     }
02617 
02618     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
02619       // ~(c-X) == X-c-1 == X+(-c-1)
02620       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
02621         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
02622           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
02623           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
02624                                       ConstantInt::get(I.getType(), 1));
02625           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
02626         }
02627 
02628       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
02629         if (Op0I->getOpcode() == Instruction::Add) {
02630           // ~(X-c) --> (-c-1)-X
02631           if (RHS->isAllOnesValue()) {
02632             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
02633             return BinaryOperator::CreateSub(
02634                            ConstantExpr::getSub(NegOp0CI,
02635                                       ConstantInt::get(I.getType(), 1)),
02636                                       Op0I->getOperand(0));
02637           } else if (RHS->getValue().isSignBit()) {
02638             // (X + C) ^ signbit -> (X + C + signbit)
02639             Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
02640             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
02641 
02642           }
02643         } else if (Op0I->getOpcode() == Instruction::Or) {
02644           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
02645           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
02646                                 0, &I)) {
02647             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
02648             // Anything in both C1 and C2 is known to be zero, remove it from
02649             // NewRHS.
02650             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
02651             NewRHS = ConstantExpr::getAnd(NewRHS,
02652                                        ConstantExpr::getNot(CommonBits));
02653             Worklist.Add(Op0I);
02654             I.setOperand(0, Op0I->getOperand(0));
02655             I.setOperand(1, NewRHS);
02656             return &I;
02657           }
02658         } else if (Op0I->getOpcode() == Instruction::LShr) {
02659           // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
02660           // E1 = "X ^ C1"
02661           BinaryOperator *E1;
02662           ConstantInt *C1;
02663           if (Op0I->hasOneUse() &&
02664               (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
02665               E1->getOpcode() == Instruction::Xor &&
02666               (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
02667             // fold (C1 >> C2) ^ C3
02668             ConstantInt *C2 = Op0CI, *C3 = RHS;
02669             APInt FoldConst = C1->getValue().lshr(C2->getValue());
02670             FoldConst ^= C3->getValue();
02671             // Prepare the two operands.
02672             Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
02673             Opnd0->takeName(Op0I);
02674             cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
02675             Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
02676 
02677             return BinaryOperator::CreateXor(Opnd0, FoldVal);
02678           }
02679         }
02680       }
02681     }
02682 
02683     // Try to fold constant and into select arguments.
02684     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
02685       if (Instruction *R = FoldOpIntoSelect(I, SI))
02686         return R;
02687     if (isa<PHINode>(Op0))
02688       if (Instruction *NV = FoldOpIntoPhi(I))
02689         return NV;
02690   }
02691 
02692   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
02693   if (Op1I) {
02694     Value *A, *B;
02695     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
02696       if (A == Op0) {              // B^(B|A) == (A|B)^B
02697         Op1I->swapOperands();
02698         I.swapOperands();
02699         std::swap(Op0, Op1);
02700       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
02701         I.swapOperands();     // Simplified below.
02702         std::swap(Op0, Op1);
02703       }
02704     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
02705                Op1I->hasOneUse()){
02706       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
02707         Op1I->swapOperands();
02708         std::swap(A, B);
02709       }
02710       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
02711         I.swapOperands();     // Simplified below.
02712         std::swap(Op0, Op1);
02713       }
02714     }
02715   }
02716 
02717   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
02718   if (Op0I) {
02719     Value *A, *B;
02720     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
02721         Op0I->hasOneUse()) {
02722       if (A == Op1)                                  // (B|A)^B == (A|B)^B
02723         std::swap(A, B);
02724       if (B == Op1)                                  // (A|B)^B == A & ~B
02725         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
02726     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
02727                Op0I->hasOneUse()){
02728       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
02729         std::swap(A, B);
02730       if (B == Op1 &&                                      // (B&A)^A == ~B & A
02731           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
02732         return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
02733       }
02734     }
02735   }
02736 
02737   if (Op0I && Op1I) {
02738     Value *A, *B, *C, *D;
02739     // (A & B)^(A | B) -> A ^ B
02740     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
02741         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
02742       if ((A == C && B == D) || (A == D && B == C))
02743         return BinaryOperator::CreateXor(A, B);
02744     }
02745     // (A | B)^(A & B) -> A ^ B
02746     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
02747         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
02748       if ((A == C && B == D) || (A == D && B == C))
02749         return BinaryOperator::CreateXor(A, B);
02750     }
02751     // (A | ~B) ^ (~A | B) -> A ^ B
02752     if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
02753         match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
02754       return BinaryOperator::CreateXor(A, B);
02755     }
02756     // (~A | B) ^ (A | ~B) -> A ^ B
02757     if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
02758         match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
02759       return BinaryOperator::CreateXor(A, B);
02760     }
02761     // (A & ~B) ^ (~A & B) -> A ^ B
02762     if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
02763         match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
02764       return BinaryOperator::CreateXor(A, B);
02765     }
02766     // (~A & B) ^ (A & ~B) -> A ^ B
02767     if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
02768         match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
02769       return BinaryOperator::CreateXor(A, B);
02770     }
02771     // (A ^ C)^(A | B) -> ((~A) & B) ^ C
02772     if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
02773         match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
02774       if (D == A)
02775         return BinaryOperator::CreateXor(
02776             Builder->CreateAnd(Builder->CreateNot(A), B), C);
02777       if (D == B)
02778         return BinaryOperator::CreateXor(
02779             Builder->CreateAnd(Builder->CreateNot(B), A), C);
02780     }
02781     // (A | B)^(A ^ C) -> ((~A) & B) ^ C
02782     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
02783         match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
02784       if (D == A)
02785         return BinaryOperator::CreateXor(
02786             Builder->CreateAnd(Builder->CreateNot(A), B), C);
02787       if (D == B)
02788         return BinaryOperator::CreateXor(
02789             Builder->CreateAnd(Builder->CreateNot(B), A), C);
02790     }
02791     // (A & B) ^ (A ^ B) -> (A | B)
02792     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
02793         match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
02794       return BinaryOperator::CreateOr(A, B);
02795     // (A ^ B) ^ (A & B) -> (A | B)
02796     if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
02797         match(Op1I, m_And(m_Specific(A), m_Specific(B))))
02798       return BinaryOperator::CreateOr(A, B);
02799   }
02800 
02801   Value *A = nullptr, *B = nullptr;
02802   // (A & ~B) ^ (~A) -> ~(A & B)
02803   if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
02804       match(Op1, m_Not(m_Specific(A))))
02805     return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
02806 
02807   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
02808   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
02809     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
02810       if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
02811         if (LHS->getOperand(0) == RHS->getOperand(1) &&
02812             LHS->getOperand(1) == RHS->getOperand(0))
02813           LHS->swapOperands();
02814         if (LHS->getOperand(0) == RHS->getOperand(0) &&
02815             LHS->getOperand(1) == RHS->getOperand(1)) {
02816           Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
02817           unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
02818           bool isSigned = LHS->isSigned() || RHS->isSigned();
02819           return ReplaceInstUsesWith(I,
02820                                getNewICmpValue(isSigned, Code, Op0, Op1,
02821                                                Builder));
02822         }
02823       }
02824 
02825   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
02826   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
02827     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
02828       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
02829         Type *SrcTy = Op0C->getOperand(0)->getType();
02830         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
02831             // Only do this if the casts both really cause code to be generated.
02832             ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
02833                                I.getType()) &&
02834             ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
02835                                I.getType())) {
02836           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
02837                                             Op1C->getOperand(0), I.getName());
02838           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
02839         }
02840       }
02841   }
02842 
02843   return Changed ? &I : nullptr;
02844 }