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