LLVM API Documentation

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::makeICmpRegion(LHSCC, LHSCst->getValue());
00983   ConstantRange RHSRange =
00984     ConstantRange::makeICmpRegion(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), false, 0, AC, CxtI, DT) &&
01713           isKnownToBeAPowerOfTwo(RAnd->getOperand(1), false, 0, AC, CxtI, DT)) {
01714         Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
01715         Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
01716       } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
01717                  isKnownToBeAPowerOfTwo(LAnd->getOperand(0), false, 0, AC, CxtI,
01718                                         DT) &&
01719                  isKnownToBeAPowerOfTwo(RAnd->getOperand(0), false, 0, AC, CxtI,
01720                                         DT)) {
01721         Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
01722         Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
01723       }
01724 
01725       if (Masked)
01726         return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
01727     }
01728   }
01729 
01730   // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
01731   //                   -->  (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
01732   // The original condition actually refers to the following two ranges:
01733   // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
01734   // We can fold these two ranges if:
01735   // 1) C1 and C2 is unsigned greater than C3.
01736   // 2) The two ranges are separated.
01737   // 3) C1 ^ C2 is one-bit mask.
01738   // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
01739   // This implies all values in the two ranges differ by exactly one bit.
01740 
01741   if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
01742       LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
01743       RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
01744       LHSCst->getValue() == (RHSCst->getValue())) {
01745 
01746     Value *LAdd = LHS->getOperand(0);
01747     Value *RAdd = RHS->getOperand(0);
01748 
01749     Value *LAddOpnd, *RAddOpnd;
01750     ConstantInt *LAddCst, *RAddCst;
01751     if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
01752         match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
01753         LAddCst->getValue().ugt(LHSCst->getValue()) &&
01754         RAddCst->getValue().ugt(LHSCst->getValue())) {
01755 
01756       APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
01757       if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
01758         ConstantInt *MaxAddCst = nullptr;
01759         if (LAddCst->getValue().ult(RAddCst->getValue()))
01760           MaxAddCst = RAddCst;
01761         else
01762           MaxAddCst = LAddCst;
01763 
01764         APInt RRangeLow = -RAddCst->getValue();
01765         APInt RRangeHigh = RRangeLow + LHSCst->getValue();
01766         APInt LRangeLow = -LAddCst->getValue();
01767         APInt LRangeHigh = LRangeLow + LHSCst->getValue();
01768         APInt LowRangeDiff = RRangeLow ^ LRangeLow;
01769         APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
01770         APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
01771                                                    : RRangeLow - LRangeLow;
01772 
01773         if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
01774             RangeDiff.ugt(LHSCst->getValue())) {
01775           Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
01776 
01777           Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
01778           Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
01779           return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
01780         }
01781       }
01782     }
01783   }
01784 
01785   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
01786   if (PredicatesFoldable(LHSCC, RHSCC)) {
01787     if (LHS->getOperand(0) == RHS->getOperand(1) &&
01788         LHS->getOperand(1) == RHS->getOperand(0))
01789       LHS->swapOperands();
01790     if (LHS->getOperand(0) == RHS->getOperand(0) &&
01791         LHS->getOperand(1) == RHS->getOperand(1)) {
01792       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
01793       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
01794       bool isSigned = LHS->isSigned() || RHS->isSigned();
01795       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
01796     }
01797   }
01798 
01799   // handle (roughly):
01800   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
01801   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
01802     return V;
01803 
01804   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
01805   if (LHS->hasOneUse() || RHS->hasOneUse()) {
01806     // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
01807     // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
01808     Value *A = nullptr, *B = nullptr;
01809     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
01810       B = Val;
01811       if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
01812         A = Val2;
01813       else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
01814         A = RHS->getOperand(1);
01815     }
01816     // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
01817     // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
01818     else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
01819       B = Val2;
01820       if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
01821         A = Val;
01822       else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
01823         A = LHS->getOperand(1);
01824     }
01825     if (A && B)
01826       return Builder->CreateICmp(
01827           ICmpInst::ICMP_UGE,
01828           Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
01829   }
01830 
01831   // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
01832   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
01833     return V;
01834 
01835   // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
01836   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
01837     return V;
01838  
01839   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
01840   if (!LHSCst || !RHSCst) return nullptr;
01841 
01842   if (LHSCst == RHSCst && LHSCC == RHSCC) {
01843     // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
01844     if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
01845       Value *NewOr = Builder->CreateOr(Val, Val2);
01846       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
01847     }
01848   }
01849 
01850   // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
01851   //   iff C2 + CA == C1.
01852   if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
01853     ConstantInt *AddCst;
01854     if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
01855       if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
01856         return Builder->CreateICmpULE(Val, LHSCst);
01857   }
01858 
01859   // From here on, we only handle:
01860   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
01861   if (Val != Val2) return nullptr;
01862 
01863   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
01864   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
01865       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
01866       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
01867       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
01868     return nullptr;
01869 
01870   // We can't fold (ugt x, C) | (sgt x, C2).
01871   if (!PredicatesFoldable(LHSCC, RHSCC))
01872     return nullptr;
01873 
01874   // Ensure that the larger constant is on the RHS.
01875   bool ShouldSwap;
01876   if (CmpInst::isSigned(LHSCC) ||
01877       (ICmpInst::isEquality(LHSCC) &&
01878        CmpInst::isSigned(RHSCC)))
01879     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
01880   else
01881     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
01882 
01883   if (ShouldSwap) {
01884     std::swap(LHS, RHS);
01885     std::swap(LHSCst, RHSCst);
01886     std::swap(LHSCC, RHSCC);
01887   }
01888 
01889   // At this point, we know we have two icmp instructions
01890   // comparing a value against two constants and or'ing the result
01891   // together.  Because of the above check, we know that we only have
01892   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
01893   // icmp folding check above), that the two constants are not
01894   // equal.
01895   assert(LHSCst != RHSCst && "Compares not folded above?");
01896 
01897   switch (LHSCC) {
01898   default: llvm_unreachable("Unknown integer condition code!");
01899   case ICmpInst::ICMP_EQ:
01900     switch (RHSCC) {
01901     default: llvm_unreachable("Unknown integer condition code!");
01902     case ICmpInst::ICMP_EQ:
01903       if (LHS->getOperand(0) == RHS->getOperand(0)) {
01904         // if LHSCst and RHSCst differ only by one bit:
01905         // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
01906         assert(LHSCst->getValue().ule(LHSCst->getValue()));
01907 
01908         APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
01909         if (Xor.isPowerOf2()) {
01910           Value *NegCst = Builder->getInt(~Xor);
01911           Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
01912           return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
01913         }
01914       }
01915 
01916       if (LHSCst == SubOne(RHSCst)) {
01917         // (X == 13 | X == 14) -> X-13 <u 2
01918         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
01919         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
01920         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
01921         return Builder->CreateICmpULT(Add, AddCST);
01922       }
01923 
01924       break;                         // (X == 13 | X == 15) -> no change
01925     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
01926     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
01927       break;
01928     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
01929     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
01930     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
01931       return RHS;
01932     }
01933     break;
01934   case ICmpInst::ICMP_NE:
01935     switch (RHSCC) {
01936     default: llvm_unreachable("Unknown integer condition code!");
01937     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
01938     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
01939     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
01940       return LHS;
01941     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
01942     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
01943     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
01944       return Builder->getTrue();
01945     }
01946   case ICmpInst::ICMP_ULT:
01947     switch (RHSCC) {
01948     default: llvm_unreachable("Unknown integer condition code!");
01949     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
01950       break;
01951     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
01952       // If RHSCst is [us]MAXINT, it is always false.  Not handling
01953       // this can cause overflow.
01954       if (RHSCst->isMaxValue(false))
01955         return LHS;
01956       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
01957     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
01958       break;
01959     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
01960     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
01961       return RHS;
01962     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
01963       break;
01964     }
01965     break;
01966   case ICmpInst::ICMP_SLT:
01967     switch (RHSCC) {
01968     default: llvm_unreachable("Unknown integer condition code!");
01969     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
01970       break;
01971     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
01972       // If RHSCst is [us]MAXINT, it is always false.  Not handling
01973       // this can cause overflow.
01974       if (RHSCst->isMaxValue(true))
01975         return LHS;
01976       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
01977     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
01978       break;
01979     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
01980     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
01981       return RHS;
01982     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
01983       break;
01984     }
01985     break;
01986   case ICmpInst::ICMP_UGT:
01987     switch (RHSCC) {
01988     default: llvm_unreachable("Unknown integer condition code!");
01989     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
01990     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
01991       return LHS;
01992     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
01993       break;
01994     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
01995     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
01996       return Builder->getTrue();
01997     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
01998       break;
01999     }
02000     break;
02001   case ICmpInst::ICMP_SGT:
02002     switch (RHSCC) {
02003     default: llvm_unreachable("Unknown integer condition code!");
02004     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
02005     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
02006       return LHS;
02007     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
02008       break;
02009     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
02010     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
02011       return Builder->getTrue();
02012     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
02013       break;
02014     }
02015     break;
02016   }
02017   return nullptr;
02018 }
02019 
02020 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp).  NOTE: Unlike the rest of
02021 /// instcombine, this returns a Value which should already be inserted into the
02022 /// function.
02023 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
02024   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
02025       RHS->getPredicate() == FCmpInst::FCMP_UNO &&
02026       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
02027     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
02028       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
02029         // If either of the constants are nans, then the whole thing returns
02030         // true.
02031         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
02032           return Builder->getTrue();
02033 
02034         // Otherwise, no need to compare the two constants, compare the
02035         // rest.
02036         return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
02037       }
02038 
02039     // Handle vector zeros.  This occurs because the canonical form of
02040     // "fcmp uno x,x" is "fcmp uno x, 0".
02041     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
02042         isa<ConstantAggregateZero>(RHS->getOperand(1)))
02043       return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
02044 
02045     return nullptr;
02046   }
02047 
02048   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
02049   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
02050   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
02051 
02052   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
02053     // Swap RHS operands to match LHS.
02054     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
02055     std::swap(Op1LHS, Op1RHS);
02056   }
02057   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
02058     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
02059     if (Op0CC == Op1CC)
02060       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
02061     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
02062       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
02063     if (Op0CC == FCmpInst::FCMP_FALSE)
02064       return RHS;
02065     if (Op1CC == FCmpInst::FCMP_FALSE)
02066       return LHS;
02067     bool Op0Ordered;
02068     bool Op1Ordered;
02069     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
02070     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
02071     if (Op0Ordered == Op1Ordered) {
02072       // If both are ordered or unordered, return a new fcmp with
02073       // or'ed predicates.
02074       return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
02075     }
02076   }
02077   return nullptr;
02078 }
02079 
02080 /// FoldOrWithConstants - This helper function folds:
02081 ///
02082 ///     ((A | B) & C1) | (B & C2)
02083 ///
02084 /// into:
02085 ///
02086 ///     (A & C1) | B
02087 ///
02088 /// when the XOR of the two constants is "all ones" (-1).
02089 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
02090                                                Value *A, Value *B, Value *C) {
02091   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
02092   if (!CI1) return nullptr;
02093 
02094   Value *V1 = nullptr;
02095   ConstantInt *CI2 = nullptr;
02096   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
02097 
02098   APInt Xor = CI1->getValue() ^ CI2->getValue();
02099   if (!Xor.isAllOnesValue()) return nullptr;
02100 
02101   if (V1 == A || V1 == B) {
02102     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
02103     return BinaryOperator::CreateOr(NewOp, V1);
02104   }
02105 
02106   return nullptr;
02107 }
02108 
02109 /// \brief This helper function folds:
02110 ///
02111 ///     ((A | B) & C1) ^ (B & C2)
02112 ///
02113 /// into:
02114 ///
02115 ///     (A & C1) ^ B
02116 ///
02117 /// when the XOR of the two constants is "all ones" (-1).
02118 Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
02119                                                 Value *A, Value *B, Value *C) {
02120   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
02121   if (!CI1)
02122     return nullptr;
02123 
02124   Value *V1 = nullptr;
02125   ConstantInt *CI2 = nullptr;
02126   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
02127     return nullptr;
02128 
02129   APInt Xor = CI1->getValue() ^ CI2->getValue();
02130   if (!Xor.isAllOnesValue())
02131     return nullptr;
02132 
02133   if (V1 == A || V1 == B) {
02134     Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
02135     return BinaryOperator::CreateXor(NewOp, V1);
02136   }
02137 
02138   return nullptr;
02139 }
02140 
02141 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
02142   bool Changed = SimplifyAssociativeOrCommutative(I);
02143   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02144 
02145   if (Value *V = SimplifyVectorOp(I))
02146     return ReplaceInstUsesWith(I, V);
02147 
02148   if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
02149     return ReplaceInstUsesWith(I, V);
02150 
02151   // (A&B)|(A&C) -> A&(B|C) etc
02152   if (Value *V = SimplifyUsingDistributiveLaws(I))
02153     return ReplaceInstUsesWith(I, V);
02154 
02155   // See if we can simplify any instructions used by the instruction whose sole
02156   // purpose is to compute bits we don't care about.
02157   if (SimplifyDemandedInstructionBits(I))
02158     return &I;
02159 
02160   if (Value *V = SimplifyBSwap(I))
02161     return ReplaceInstUsesWith(I, V);
02162 
02163   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
02164     ConstantInt *C1 = nullptr; Value *X = nullptr;
02165     // (X & C1) | C2 --> (X | C2) & (C1|C2)
02166     // iff (C1 & C2) == 0.
02167     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
02168         (RHS->getValue() & C1->getValue()) != 0 &&
02169         Op0->hasOneUse()) {
02170       Value *Or = Builder->CreateOr(X, RHS);
02171       Or->takeName(Op0);
02172       return BinaryOperator::CreateAnd(Or,
02173                              Builder->getInt(RHS->getValue() | C1->getValue()));
02174     }
02175 
02176     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
02177     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
02178         Op0->hasOneUse()) {
02179       Value *Or = Builder->CreateOr(X, RHS);
02180       Or->takeName(Op0);
02181       return BinaryOperator::CreateXor(Or,
02182                             Builder->getInt(C1->getValue() & ~RHS->getValue()));
02183     }
02184 
02185     // Try to fold constant and into select arguments.
02186     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
02187       if (Instruction *R = FoldOpIntoSelect(I, SI))
02188         return R;
02189 
02190     if (isa<PHINode>(Op0))
02191       if (Instruction *NV = FoldOpIntoPhi(I))
02192         return NV;
02193   }
02194 
02195   Value *A = nullptr, *B = nullptr;
02196   ConstantInt *C1 = nullptr, *C2 = nullptr;
02197 
02198   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
02199   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
02200   if (match(Op0, m_Or(m_Value(), m_Value())) ||
02201       match(Op1, m_Or(m_Value(), m_Value())) ||
02202       (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
02203        match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
02204     if (Instruction *BSwap = MatchBSwap(I))
02205       return BSwap;
02206   }
02207 
02208   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
02209   if (Op0->hasOneUse() &&
02210       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
02211       MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
02212     Value *NOr = Builder->CreateOr(A, Op1);
02213     NOr->takeName(Op0);
02214     return BinaryOperator::CreateXor(NOr, C1);
02215   }
02216 
02217   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
02218   if (Op1->hasOneUse() &&
02219       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
02220       MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
02221     Value *NOr = Builder->CreateOr(A, Op0);
02222     NOr->takeName(Op0);
02223     return BinaryOperator::CreateXor(NOr, C1);
02224   }
02225 
02226   // ((~A & B) | A) -> (A | B)
02227   if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
02228       match(Op1, m_Specific(A)))
02229     return BinaryOperator::CreateOr(A, B);
02230 
02231   // ((A & B) | ~A) -> (~A | B)
02232   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
02233       match(Op1, m_Not(m_Specific(A))))
02234     return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
02235 
02236   // (A & (~B)) | (A ^ B) -> (A ^ B)
02237   if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
02238       match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
02239     return BinaryOperator::CreateXor(A, B);
02240 
02241   // (A ^ B) | ( A & (~B)) -> (A ^ B)
02242   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
02243       match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
02244     return BinaryOperator::CreateXor(A, B);
02245 
02246   // (A & C)|(B & D)
02247   Value *C = nullptr, *D = nullptr;
02248   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
02249       match(Op1, m_And(m_Value(B), m_Value(D)))) {
02250     Value *V1 = nullptr, *V2 = nullptr;
02251     C1 = dyn_cast<ConstantInt>(C);
02252     C2 = dyn_cast<ConstantInt>(D);
02253     if (C1 && C2) {  // (A & C1)|(B & C2)
02254       if ((C1->getValue() & C2->getValue()) == 0) {
02255         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
02256         // iff (C1&C2) == 0 and (N&~C1) == 0
02257         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
02258             ((V1 == B &&
02259               MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
02260              (V2 == B &&
02261               MaskedValueIsZero(V1, ~C1->getValue(), 0, &I))))  // (N|V)
02262           return BinaryOperator::CreateAnd(A,
02263                                 Builder->getInt(C1->getValue()|C2->getValue()));
02264         // Or commutes, try both ways.
02265         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
02266             ((V1 == A &&
02267               MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
02268              (V2 == A &&
02269               MaskedValueIsZero(V1, ~C2->getValue(), 0, &I))))  // (N|V)
02270           return BinaryOperator::CreateAnd(B,
02271                                 Builder->getInt(C1->getValue()|C2->getValue()));
02272 
02273         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
02274         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
02275         ConstantInt *C3 = nullptr, *C4 = nullptr;
02276         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
02277             (C3->getValue() & ~C1->getValue()) == 0 &&
02278             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
02279             (C4->getValue() & ~C2->getValue()) == 0) {
02280           V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
02281           return BinaryOperator::CreateAnd(V2,
02282                                 Builder->getInt(C1->getValue()|C2->getValue()));
02283         }
02284       }
02285     }
02286 
02287     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants.
02288     // Don't do this for vector select idioms, the code generator doesn't handle
02289     // them well yet.
02290     if (!I.getType()->isVectorTy()) {
02291       if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
02292         return Match;
02293       if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
02294         return Match;
02295       if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
02296         return Match;
02297       if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
02298         return Match;
02299     }
02300 
02301     // ((A&~B)|(~A&B)) -> A^B
02302     if ((match(C, m_Not(m_Specific(D))) &&
02303          match(B, m_Not(m_Specific(A)))))
02304       return BinaryOperator::CreateXor(A, D);
02305     // ((~B&A)|(~A&B)) -> A^B
02306     if ((match(A, m_Not(m_Specific(D))) &&
02307          match(B, m_Not(m_Specific(C)))))
02308       return BinaryOperator::CreateXor(C, D);
02309     // ((A&~B)|(B&~A)) -> A^B
02310     if ((match(C, m_Not(m_Specific(B))) &&
02311          match(D, m_Not(m_Specific(A)))))
02312       return BinaryOperator::CreateXor(A, B);
02313     // ((~B&A)|(B&~A)) -> A^B
02314     if ((match(A, m_Not(m_Specific(B))) &&
02315          match(D, m_Not(m_Specific(C)))))
02316       return BinaryOperator::CreateXor(C, B);
02317 
02318     // ((A|B)&1)|(B&-2) -> (A&1) | B
02319     if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
02320         match(A, m_Or(m_Specific(B), m_Value(V1)))) {
02321       Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
02322       if (Ret) return Ret;
02323     }
02324     // (B&-2)|((A|B)&1) -> (A&1) | B
02325     if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
02326         match(B, m_Or(m_Value(V1), m_Specific(A)))) {
02327       Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
02328       if (Ret) return Ret;
02329     }
02330     // ((A^B)&1)|(B&-2) -> (A&1) ^ B
02331     if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
02332         match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
02333       Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
02334       if (Ret) return Ret;
02335     }
02336     // (B&-2)|((A^B)&1) -> (A&1) ^ B
02337     if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
02338         match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
02339       Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
02340       if (Ret) return Ret;
02341     }
02342   }
02343 
02344   // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
02345   if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
02346     if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
02347       if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
02348         return BinaryOperator::CreateOr(Op0, C);
02349 
02350   // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
02351   if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
02352     if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
02353       if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
02354         return BinaryOperator::CreateOr(Op1, C);
02355 
02356   // ((B | C) & A) | B -> B | (A & C)
02357   if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
02358     return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
02359 
02360   // (~A | ~B) == (~(A & B)) - De Morgan's Law
02361   if (Value *Op0NotVal = dyn_castNotVal(Op0))
02362     if (Value *Op1NotVal = dyn_castNotVal(Op1))
02363       if (Op0->hasOneUse() && Op1->hasOneUse()) {
02364         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
02365                                         I.getName()+".demorgan");
02366         return BinaryOperator::CreateNot(And);
02367       }
02368 
02369   // Canonicalize xor to the RHS.
02370   bool SwappedForXor = false;
02371   if (match(Op0, m_Xor(m_Value(), m_Value()))) {
02372     std::swap(Op0, Op1);
02373     SwappedForXor = true;
02374   }
02375 
02376   // A | ( A ^ B) -> A |  B
02377   // A | (~A ^ B) -> A | ~B
02378   // (A & B) | (A ^ B)
02379   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
02380     if (Op0 == A || Op0 == B)
02381       return BinaryOperator::CreateOr(A, B);
02382 
02383     if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
02384         match(Op0, m_And(m_Specific(B), m_Specific(A))))
02385       return BinaryOperator::CreateOr(A, B);
02386 
02387     if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
02388       Value *Not = Builder->CreateNot(B, B->getName()+".not");
02389       return BinaryOperator::CreateOr(Not, Op0);
02390     }
02391     if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
02392       Value *Not = Builder->CreateNot(A, A->getName()+".not");
02393       return BinaryOperator::CreateOr(Not, Op0);
02394     }
02395   }
02396 
02397   // A | ~(A | B) -> A | ~B
02398   // A | ~(A ^ B) -> A | ~B
02399   if (match(Op1, m_Not(m_Value(A))))
02400     if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
02401       if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
02402           Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
02403                                B->getOpcode() == Instruction::Xor)) {
02404         Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
02405                                                  B->getOperand(0);
02406         Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
02407         return BinaryOperator::CreateOr(Not, Op0);
02408       }
02409 
02410   // (A & B) | ((~A) ^ B) -> (~A ^ B)
02411   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
02412       match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
02413     return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
02414 
02415   // ((~A) ^ B) | (A & B) -> (~A ^ B)
02416   if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
02417       match(Op1, m_And(m_Specific(A), m_Specific(B))))
02418     return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
02419 
02420   if (SwappedForXor)
02421     std::swap(Op0, Op1);
02422 
02423   {
02424     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
02425     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
02426     if (LHS && RHS)
02427       if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
02428         return ReplaceInstUsesWith(I, Res);
02429 
02430     // TODO: Make this recursive; it's a little tricky because an arbitrary
02431     // number of 'or' instructions might have to be created.
02432     Value *X, *Y;
02433     if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
02434       if (auto *Cmp = dyn_cast<ICmpInst>(X))
02435         if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
02436           return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
02437       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
02438         if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
02439           return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
02440     }
02441     if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
02442       if (auto *Cmp = dyn_cast<ICmpInst>(X))
02443         if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
02444           return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
02445       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
02446         if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
02447           return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
02448     }
02449   }
02450 
02451   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
02452   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
02453     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
02454       if (Value *Res = FoldOrOfFCmps(LHS, RHS))
02455         return ReplaceInstUsesWith(I, Res);
02456 
02457   // fold (or (cast A), (cast B)) -> (cast (or A, B))
02458   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
02459     CastInst *Op1C = dyn_cast<CastInst>(Op1);
02460     if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
02461       Type *SrcTy = Op0C->getOperand(0)->getType();
02462       if (SrcTy == Op1C->getOperand(0)->getType() &&
02463           SrcTy->isIntOrIntVectorTy()) {
02464         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
02465 
02466         if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
02467             // Only do this if the casts both really cause code to be
02468             // generated.
02469             ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
02470             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
02471           Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
02472           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
02473         }
02474 
02475         // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
02476         // cast is otherwise not optimizable.  This happens for vector sexts.
02477         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
02478           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
02479             if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
02480               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
02481 
02482         // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
02483         // cast is otherwise not optimizable.  This happens for vector sexts.
02484         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
02485           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
02486             if (Value *Res = FoldOrOfFCmps(LHS, RHS))
02487               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
02488       }
02489     }
02490   }
02491 
02492   // or(sext(A), B) -> A ? -1 : B where A is an i1
02493   // or(A, sext(B)) -> B ? -1 : A where B is an i1
02494   if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
02495     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
02496   if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
02497     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
02498 
02499   // Note: If we've gotten to the point of visiting the outer OR, then the
02500   // inner one couldn't be simplified.  If it was a constant, then it won't
02501   // be simplified by a later pass either, so we try swapping the inner/outer
02502   // ORs in the hopes that we'll be able to simplify it this way.
02503   // (X|C) | V --> (X|V) | C
02504   if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
02505       match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
02506     Value *Inner = Builder->CreateOr(A, Op1);
02507     Inner->takeName(Op0);
02508     return BinaryOperator::CreateOr(Inner, C1);
02509   }
02510 
02511   // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
02512   // Since this OR statement hasn't been optimized further yet, we hope
02513   // that this transformation will allow the new ORs to be optimized.
02514   {
02515     Value *X = nullptr, *Y = nullptr;
02516     if (Op0->hasOneUse() && Op1->hasOneUse() &&
02517         match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
02518         match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
02519       Value *orTrue = Builder->CreateOr(A, C);
02520       Value *orFalse = Builder->CreateOr(B, D);
02521       return SelectInst::Create(X, orTrue, orFalse);
02522     }
02523   }
02524 
02525   return Changed ? &I : nullptr;
02526 }
02527 
02528 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
02529   bool Changed = SimplifyAssociativeOrCommutative(I);
02530   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02531 
02532   if (Value *V = SimplifyVectorOp(I))
02533     return ReplaceInstUsesWith(I, V);
02534 
02535   if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
02536     return ReplaceInstUsesWith(I, V);
02537 
02538   // (A&B)^(A&C) -> A&(B^C) etc
02539   if (Value *V = SimplifyUsingDistributiveLaws(I))
02540     return ReplaceInstUsesWith(I, V);
02541 
02542   // See if we can simplify any instructions used by the instruction whose sole
02543   // purpose is to compute bits we don't care about.
02544   if (SimplifyDemandedInstructionBits(I))
02545     return &I;
02546 
02547   if (Value *V = SimplifyBSwap(I))
02548     return ReplaceInstUsesWith(I, V);
02549 
02550   // Is this a ~ operation?
02551   if (Value *NotOp = dyn_castNotVal(&I)) {
02552     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
02553       if (Op0I->getOpcode() == Instruction::And ||
02554           Op0I->getOpcode() == Instruction::Or) {
02555         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
02556         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
02557         if (dyn_castNotVal(Op0I->getOperand(1)))
02558           Op0I->swapOperands();
02559         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
02560           Value *NotY =
02561             Builder->CreateNot(Op0I->getOperand(1),
02562                                Op0I->getOperand(1)->getName()+".not");
02563           if (Op0I->getOpcode() == Instruction::And)
02564             return BinaryOperator::CreateOr(Op0NotVal, NotY);
02565           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
02566         }
02567 
02568         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
02569         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
02570         if (IsFreeToInvert(Op0I->getOperand(0),
02571                            Op0I->getOperand(0)->hasOneUse()) &&
02572             IsFreeToInvert(Op0I->getOperand(1),
02573                            Op0I->getOperand(1)->hasOneUse())) {
02574           Value *NotX =
02575             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
02576           Value *NotY =
02577             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
02578           if (Op0I->getOpcode() == Instruction::And)
02579             return BinaryOperator::CreateOr(NotX, NotY);
02580           return BinaryOperator::CreateAnd(NotX, NotY);
02581         }
02582 
02583       } else if (Op0I->getOpcode() == Instruction::AShr) {
02584         // ~(~X >>s Y) --> (X >>s Y)
02585         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
02586           return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
02587       }
02588     }
02589   }
02590 
02591   if (Constant *RHS = dyn_cast<Constant>(Op1)) {
02592     if (RHS->isAllOnesValue() && Op0->hasOneUse())
02593       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
02594       if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
02595         return CmpInst::Create(CI->getOpcode(),
02596                                CI->getInversePredicate(),
02597                                CI->getOperand(0), CI->getOperand(1));
02598   }
02599 
02600   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
02601     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
02602     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
02603       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
02604         if (CI->hasOneUse() && Op0C->hasOneUse()) {
02605           Instruction::CastOps Opcode = Op0C->getOpcode();
02606           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
02607               (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
02608                                             Op0C->getDestTy()))) {
02609             CI->setPredicate(CI->getInversePredicate());
02610             return CastInst::Create(Opcode, CI, Op0C->getType());
02611           }
02612         }
02613       }
02614     }
02615 
02616     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
02617       // ~(c-X) == X-c-1 == X+(-c-1)
02618       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
02619         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
02620           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
02621           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
02622                                       ConstantInt::get(I.getType(), 1));
02623           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
02624         }
02625 
02626       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
02627         if (Op0I->getOpcode() == Instruction::Add) {
02628           // ~(X-c) --> (-c-1)-X
02629           if (RHS->isAllOnesValue()) {
02630             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
02631             return BinaryOperator::CreateSub(
02632                            ConstantExpr::getSub(NegOp0CI,
02633                                       ConstantInt::get(I.getType(), 1)),
02634                                       Op0I->getOperand(0));
02635           } else if (RHS->getValue().isSignBit()) {
02636             // (X + C) ^ signbit -> (X + C + signbit)
02637             Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
02638             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
02639 
02640           }
02641         } else if (Op0I->getOpcode() == Instruction::Or) {
02642           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
02643           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
02644                                 0, &I)) {
02645             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
02646             // Anything in both C1 and C2 is known to be zero, remove it from
02647             // NewRHS.
02648             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
02649             NewRHS = ConstantExpr::getAnd(NewRHS,
02650                                        ConstantExpr::getNot(CommonBits));
02651             Worklist.Add(Op0I);
02652             I.setOperand(0, Op0I->getOperand(0));
02653             I.setOperand(1, NewRHS);
02654             return &I;
02655           }
02656         } else if (Op0I->getOpcode() == Instruction::LShr) {
02657           // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
02658           // E1 = "X ^ C1"
02659           BinaryOperator *E1;
02660           ConstantInt *C1;
02661           if (Op0I->hasOneUse() &&
02662               (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
02663               E1->getOpcode() == Instruction::Xor &&
02664               (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
02665             // fold (C1 >> C2) ^ C3
02666             ConstantInt *C2 = Op0CI, *C3 = RHS;
02667             APInt FoldConst = C1->getValue().lshr(C2->getValue());
02668             FoldConst ^= C3->getValue();
02669             // Prepare the two operands.
02670             Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
02671             Opnd0->takeName(Op0I);
02672             cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
02673             Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
02674 
02675             return BinaryOperator::CreateXor(Opnd0, FoldVal);
02676           }
02677         }
02678       }
02679     }
02680 
02681     // Try to fold constant and into select arguments.
02682     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
02683       if (Instruction *R = FoldOpIntoSelect(I, SI))
02684         return R;
02685     if (isa<PHINode>(Op0))
02686       if (Instruction *NV = FoldOpIntoPhi(I))
02687         return NV;
02688   }
02689 
02690   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
02691   if (Op1I) {
02692     Value *A, *B;
02693     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
02694       if (A == Op0) {              // B^(B|A) == (A|B)^B
02695         Op1I->swapOperands();
02696         I.swapOperands();
02697         std::swap(Op0, Op1);
02698       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
02699         I.swapOperands();     // Simplified below.
02700         std::swap(Op0, Op1);
02701       }
02702     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
02703                Op1I->hasOneUse()){
02704       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
02705         Op1I->swapOperands();
02706         std::swap(A, B);
02707       }
02708       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
02709         I.swapOperands();     // Simplified below.
02710         std::swap(Op0, Op1);
02711       }
02712     }
02713   }
02714 
02715   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
02716   if (Op0I) {
02717     Value *A, *B;
02718     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
02719         Op0I->hasOneUse()) {
02720       if (A == Op1)                                  // (B|A)^B == (A|B)^B
02721         std::swap(A, B);
02722       if (B == Op1)                                  // (A|B)^B == A & ~B
02723         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
02724     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
02725                Op0I->hasOneUse()){
02726       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
02727         std::swap(A, B);
02728       if (B == Op1 &&                                      // (B&A)^A == ~B & A
02729           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
02730         return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
02731       }
02732     }
02733   }
02734 
02735   if (Op0I && Op1I) {
02736     Value *A, *B, *C, *D;
02737     // (A & B)^(A | B) -> A ^ B
02738     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
02739         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
02740       if ((A == C && B == D) || (A == D && B == C))
02741         return BinaryOperator::CreateXor(A, B);
02742     }
02743     // (A | B)^(A & B) -> A ^ B
02744     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
02745         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
02746       if ((A == C && B == D) || (A == D && B == C))
02747         return BinaryOperator::CreateXor(A, B);
02748     }
02749     // (A | ~B) ^ (~A | B) -> A ^ B
02750     if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
02751         match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
02752       return BinaryOperator::CreateXor(A, B);
02753     }
02754     // (~A | B) ^ (A | ~B) -> A ^ B
02755     if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
02756         match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
02757       return BinaryOperator::CreateXor(A, B);
02758     }
02759     // (A & ~B) ^ (~A & B) -> A ^ B
02760     if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
02761         match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
02762       return BinaryOperator::CreateXor(A, B);
02763     }
02764     // (~A & B) ^ (A & ~B) -> A ^ B
02765     if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
02766         match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
02767       return BinaryOperator::CreateXor(A, B);
02768     }
02769     // (A ^ C)^(A | B) -> ((~A) & B) ^ C
02770     if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
02771         match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
02772       if (D == A)
02773         return BinaryOperator::CreateXor(
02774             Builder->CreateAnd(Builder->CreateNot(A), B), C);
02775       if (D == B)
02776         return BinaryOperator::CreateXor(
02777             Builder->CreateAnd(Builder->CreateNot(B), A), C);
02778     }
02779     // (A | B)^(A ^ C) -> ((~A) & B) ^ C
02780     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
02781         match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
02782       if (D == A)
02783         return BinaryOperator::CreateXor(
02784             Builder->CreateAnd(Builder->CreateNot(A), B), C);
02785       if (D == B)
02786         return BinaryOperator::CreateXor(
02787             Builder->CreateAnd(Builder->CreateNot(B), A), C);
02788     }
02789     // (A & B) ^ (A ^ B) -> (A | B)
02790     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
02791         match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
02792       return BinaryOperator::CreateOr(A, B);
02793     // (A ^ B) ^ (A & B) -> (A | B)
02794     if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
02795         match(Op1I, m_And(m_Specific(A), m_Specific(B))))
02796       return BinaryOperator::CreateOr(A, B);
02797   }
02798 
02799   Value *A = nullptr, *B = nullptr;
02800   // (A & ~B) ^ (~A) -> ~(A & B)
02801   if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
02802       match(Op1, m_Not(m_Specific(A))))
02803     return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
02804 
02805   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
02806   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
02807     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
02808       if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
02809         if (LHS->getOperand(0) == RHS->getOperand(1) &&
02810             LHS->getOperand(1) == RHS->getOperand(0))
02811           LHS->swapOperands();
02812         if (LHS->getOperand(0) == RHS->getOperand(0) &&
02813             LHS->getOperand(1) == RHS->getOperand(1)) {
02814           Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
02815           unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
02816           bool isSigned = LHS->isSigned() || RHS->isSigned();
02817           return ReplaceInstUsesWith(I,
02818                                getNewICmpValue(isSigned, Code, Op0, Op1,
02819                                                Builder));
02820         }
02821       }
02822 
02823   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
02824   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
02825     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
02826       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
02827         Type *SrcTy = Op0C->getOperand(0)->getType();
02828         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
02829             // Only do this if the casts both really cause code to be generated.
02830             ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
02831                                I.getType()) &&
02832             ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
02833                                I.getType())) {
02834           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
02835                                             Op1C->getOperand(0), I.getName());
02836           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
02837         }
02838       }
02839   }
02840 
02841   return Changed ? &I : nullptr;
02842 }