LLVM API Documentation

InstCombineSimplifyDemanded.cpp
Go to the documentation of this file.
00001 //===- InstCombineSimplifyDemanded.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 contains logic for simplifying instructions based on information
00011 // about how they are used.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "InstCombine.h"
00016 #include "llvm/IR/DataLayout.h"
00017 #include "llvm/IR/IntrinsicInst.h"
00018 #include "llvm/IR/PatternMatch.h"
00019 
00020 using namespace llvm;
00021 using namespace llvm::PatternMatch;
00022 
00023 #define DEBUG_TYPE "instcombine"
00024 
00025 /// ShrinkDemandedConstant - Check to see if the specified operand of the
00026 /// specified instruction is a constant integer.  If so, check to see if there
00027 /// are any bits set in the constant that are not demanded.  If so, shrink the
00028 /// constant and return true.
00029 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
00030                                    APInt Demanded) {
00031   assert(I && "No instruction?");
00032   assert(OpNo < I->getNumOperands() && "Operand index too large");
00033 
00034   // If the operand is not a constant integer, nothing to do.
00035   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
00036   if (!OpC) return false;
00037 
00038   // If there are no bits set that aren't demanded, nothing to do.
00039   Demanded = Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
00040   if ((~Demanded & OpC->getValue()) == 0)
00041     return false;
00042 
00043   // This instruction is producing bits that are not demanded. Shrink the RHS.
00044   Demanded &= OpC->getValue();
00045   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
00046 
00047   // If either 'nsw' or 'nuw' is set and the constant is negative,
00048   // removing *any* bits from the constant could make overflow occur.
00049   // Remove 'nsw' and 'nuw' from the instruction in this case.
00050   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I)) {
00051     assert(OBO->getOpcode() == Instruction::Add);
00052     if (OBO->hasNoSignedWrap() || OBO->hasNoUnsignedWrap()) {
00053       if (OpC->getValue().isNegative()) {
00054         cast<BinaryOperator>(OBO)->setHasNoSignedWrap(false);
00055         cast<BinaryOperator>(OBO)->setHasNoUnsignedWrap(false);
00056       }
00057     }
00058   }
00059 
00060   return true;
00061 }
00062 
00063 
00064 
00065 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
00066 /// SimplifyDemandedBits knows about.  See if the instruction has any
00067 /// properties that allow us to simplify its operands.
00068 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
00069   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
00070   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00071   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
00072 
00073   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
00074                                      KnownZero, KnownOne, 0, &Inst);
00075   if (!V) return false;
00076   if (V == &Inst) return true;
00077   ReplaceInstUsesWith(Inst, V);
00078   return true;
00079 }
00080 
00081 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
00082 /// specified instruction operand if possible, updating it in place.  It returns
00083 /// true if it made any change and false otherwise.
00084 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
00085                                         APInt &KnownZero, APInt &KnownOne,
00086                                         unsigned Depth) {
00087   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
00088                                           KnownZero, KnownOne, Depth,
00089                                           dyn_cast<Instruction>(U.getUser()));
00090   if (!NewVal) return false;
00091   U = NewVal;
00092   return true;
00093 }
00094 
00095 
00096 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
00097 /// value based on the demanded bits.  When this function is called, it is known
00098 /// that only the bits set in DemandedMask of the result of V are ever used
00099 /// downstream. Consequently, depending on the mask and V, it may be possible
00100 /// to replace V with a constant or one of its operands. In such cases, this
00101 /// function does the replacement and returns true. In all other cases, it
00102 /// returns false after analyzing the expression and setting KnownOne and known
00103 /// to be one in the expression.  KnownZero contains all the bits that are known
00104 /// to be zero in the expression. These are provided to potentially allow the
00105 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
00106 /// the expression. KnownOne and KnownZero always follow the invariant that
00107 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
00108 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
00109 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
00110 /// and KnownOne must all be the same.
00111 ///
00112 /// This returns null if it did not change anything and it permits no
00113 /// simplification.  This returns V itself if it did some simplification of V's
00114 /// operands based on the information about what bits are demanded. This returns
00115 /// some other non-null value if it found out that V is equal to another value
00116 /// in the context where the specified bits are demanded, but not for all users.
00117 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
00118                                              APInt &KnownZero, APInt &KnownOne,
00119                                              unsigned Depth,
00120                                              Instruction *CxtI) {
00121   assert(V != nullptr && "Null pointer of Value???");
00122   assert(Depth <= 6 && "Limit Search Depth");
00123   uint32_t BitWidth = DemandedMask.getBitWidth();
00124   Type *VTy = V->getType();
00125   assert((DL || !VTy->isPointerTy()) &&
00126          "SimplifyDemandedBits needs to know bit widths!");
00127   assert((!DL || DL->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
00128          (!VTy->isIntOrIntVectorTy() ||
00129           VTy->getScalarSizeInBits() == BitWidth) &&
00130          KnownZero.getBitWidth() == BitWidth &&
00131          KnownOne.getBitWidth() == BitWidth &&
00132          "Value *V, DemandedMask, KnownZero and KnownOne "
00133          "must have same BitWidth");
00134   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00135     // We know all of the bits for a constant!
00136     KnownOne = CI->getValue() & DemandedMask;
00137     KnownZero = ~KnownOne & DemandedMask;
00138     return nullptr;
00139   }
00140   if (isa<ConstantPointerNull>(V)) {
00141     // We know all of the bits for a constant!
00142     KnownOne.clearAllBits();
00143     KnownZero = DemandedMask;
00144     return nullptr;
00145   }
00146 
00147   KnownZero.clearAllBits();
00148   KnownOne.clearAllBits();
00149   if (DemandedMask == 0) {   // Not demanding any bits from V.
00150     if (isa<UndefValue>(V))
00151       return nullptr;
00152     return UndefValue::get(VTy);
00153   }
00154 
00155   if (Depth == 6)        // Limit search depth.
00156     return nullptr;
00157 
00158   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
00159   APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00160 
00161   Instruction *I = dyn_cast<Instruction>(V);
00162   if (!I) {
00163     computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
00164     return nullptr;        // Only analyze instructions.
00165   }
00166 
00167   // If there are multiple uses of this value and we aren't at the root, then
00168   // we can't do any simplifications of the operands, because DemandedMask
00169   // only reflects the bits demanded by *one* of the users.
00170   if (Depth != 0 && !I->hasOneUse()) {
00171     // Despite the fact that we can't simplify this instruction in all User's
00172     // context, we can at least compute the knownzero/knownone bits, and we can
00173     // do simplifications that apply to *just* the one user if we know that
00174     // this instruction has a simpler value in that context.
00175     if (I->getOpcode() == Instruction::And) {
00176       // If either the LHS or the RHS are Zero, the result is zero.
00177       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1,
00178                        CxtI);
00179       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1,
00180                        CxtI);
00181 
00182       // If all of the demanded bits are known 1 on one side, return the other.
00183       // These bits cannot contribute to the result of the 'and' in this
00184       // context.
00185       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
00186           (DemandedMask & ~LHSKnownZero))
00187         return I->getOperand(0);
00188       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
00189           (DemandedMask & ~RHSKnownZero))
00190         return I->getOperand(1);
00191 
00192       // If all of the demanded bits in the inputs are known zeros, return zero.
00193       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
00194         return Constant::getNullValue(VTy);
00195 
00196     } else if (I->getOpcode() == Instruction::Or) {
00197       // We can simplify (X|Y) -> X or Y in the user's context if we know that
00198       // only bits from X or Y are demanded.
00199 
00200       // If either the LHS or the RHS are One, the result is One.
00201       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1,
00202                        CxtI);
00203       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1,
00204                        CxtI);
00205 
00206       // If all of the demanded bits are known zero on one side, return the
00207       // other.  These bits cannot contribute to the result of the 'or' in this
00208       // context.
00209       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
00210           (DemandedMask & ~LHSKnownOne))
00211         return I->getOperand(0);
00212       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
00213           (DemandedMask & ~RHSKnownOne))
00214         return I->getOperand(1);
00215 
00216       // If all of the potentially set bits on one side are known to be set on
00217       // the other side, just use the 'other' side.
00218       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
00219           (DemandedMask & (~RHSKnownZero)))
00220         return I->getOperand(0);
00221       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
00222           (DemandedMask & (~LHSKnownZero)))
00223         return I->getOperand(1);
00224     } else if (I->getOpcode() == Instruction::Xor) {
00225       // We can simplify (X^Y) -> X or Y in the user's context if we know that
00226       // only bits from X or Y are demanded.
00227 
00228       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1,
00229                        CxtI);
00230       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1,
00231                        CxtI);
00232 
00233       // If all of the demanded bits are known zero on one side, return the
00234       // other.
00235       if ((DemandedMask & RHSKnownZero) == DemandedMask)
00236         return I->getOperand(0);
00237       if ((DemandedMask & LHSKnownZero) == DemandedMask)
00238         return I->getOperand(1);
00239     }
00240 
00241     // Compute the KnownZero/KnownOne bits to simplify things downstream.
00242     computeKnownBits(I, KnownZero, KnownOne, Depth, CxtI);
00243     return nullptr;
00244   }
00245 
00246   // If this is the root being simplified, allow it to have multiple uses,
00247   // just set the DemandedMask to all bits so that we can try to simplify the
00248   // operands.  This allows visitTruncInst (for example) to simplify the
00249   // operand of a trunc without duplicating all the logic below.
00250   if (Depth == 0 && !V->hasOneUse())
00251     DemandedMask = APInt::getAllOnesValue(BitWidth);
00252 
00253   switch (I->getOpcode()) {
00254   default:
00255     computeKnownBits(I, KnownZero, KnownOne, Depth, CxtI);
00256     break;
00257   case Instruction::And:
00258     // If either the LHS or the RHS are Zero, the result is zero.
00259     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
00260                              RHSKnownZero, RHSKnownOne, Depth+1) ||
00261         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
00262                              LHSKnownZero, LHSKnownOne, Depth+1))
00263       return I;
00264     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
00265     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
00266 
00267     // If the client is only demanding bits that we know, return the known
00268     // constant.
00269     if ((DemandedMask & ((RHSKnownZero | LHSKnownZero)|
00270                          (RHSKnownOne & LHSKnownOne))) == DemandedMask)
00271       return Constant::getIntegerValue(VTy, RHSKnownOne & LHSKnownOne);
00272 
00273     // If all of the demanded bits are known 1 on one side, return the other.
00274     // These bits cannot contribute to the result of the 'and'.
00275     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
00276         (DemandedMask & ~LHSKnownZero))
00277       return I->getOperand(0);
00278     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
00279         (DemandedMask & ~RHSKnownZero))
00280       return I->getOperand(1);
00281 
00282     // If all of the demanded bits in the inputs are known zeros, return zero.
00283     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
00284       return Constant::getNullValue(VTy);
00285 
00286     // If the RHS is a constant, see if we can simplify it.
00287     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
00288       return I;
00289 
00290     // Output known-1 bits are only known if set in both the LHS & RHS.
00291     KnownOne = RHSKnownOne & LHSKnownOne;
00292     // Output known-0 are known to be clear if zero in either the LHS | RHS.
00293     KnownZero = RHSKnownZero | LHSKnownZero;
00294     break;
00295   case Instruction::Or:
00296     // If either the LHS or the RHS are One, the result is One.
00297     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
00298                              RHSKnownZero, RHSKnownOne, Depth+1) ||
00299         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
00300                              LHSKnownZero, LHSKnownOne, Depth+1))
00301       return I;
00302     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
00303     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
00304 
00305     // If the client is only demanding bits that we know, return the known
00306     // constant.
00307     if ((DemandedMask & ((RHSKnownZero & LHSKnownZero)|
00308                          (RHSKnownOne | LHSKnownOne))) == DemandedMask)
00309       return Constant::getIntegerValue(VTy, RHSKnownOne | LHSKnownOne);
00310 
00311     // If all of the demanded bits are known zero on one side, return the other.
00312     // These bits cannot contribute to the result of the 'or'.
00313     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
00314         (DemandedMask & ~LHSKnownOne))
00315       return I->getOperand(0);
00316     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
00317         (DemandedMask & ~RHSKnownOne))
00318       return I->getOperand(1);
00319 
00320     // If all of the potentially set bits on one side are known to be set on
00321     // the other side, just use the 'other' side.
00322     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
00323         (DemandedMask & (~RHSKnownZero)))
00324       return I->getOperand(0);
00325     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
00326         (DemandedMask & (~LHSKnownZero)))
00327       return I->getOperand(1);
00328 
00329     // If the RHS is a constant, see if we can simplify it.
00330     if (ShrinkDemandedConstant(I, 1, DemandedMask))
00331       return I;
00332 
00333     // Output known-0 bits are only known if clear in both the LHS & RHS.
00334     KnownZero = RHSKnownZero & LHSKnownZero;
00335     // Output known-1 are known to be set if set in either the LHS | RHS.
00336     KnownOne = RHSKnownOne | LHSKnownOne;
00337     break;
00338   case Instruction::Xor: {
00339     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
00340                              RHSKnownZero, RHSKnownOne, Depth+1) ||
00341         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
00342                              LHSKnownZero, LHSKnownOne, Depth+1))
00343       return I;
00344     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
00345     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
00346 
00347     // Output known-0 bits are known if clear or set in both the LHS & RHS.
00348     APInt IKnownZero = (RHSKnownZero & LHSKnownZero) |
00349                        (RHSKnownOne & LHSKnownOne);
00350     // Output known-1 are known to be set if set in only one of the LHS, RHS.
00351     APInt IKnownOne =  (RHSKnownZero & LHSKnownOne) |
00352                        (RHSKnownOne & LHSKnownZero);
00353 
00354     // If the client is only demanding bits that we know, return the known
00355     // constant.
00356     if ((DemandedMask & (IKnownZero|IKnownOne)) == DemandedMask)
00357       return Constant::getIntegerValue(VTy, IKnownOne);
00358 
00359     // If all of the demanded bits are known zero on one side, return the other.
00360     // These bits cannot contribute to the result of the 'xor'.
00361     if ((DemandedMask & RHSKnownZero) == DemandedMask)
00362       return I->getOperand(0);
00363     if ((DemandedMask & LHSKnownZero) == DemandedMask)
00364       return I->getOperand(1);
00365 
00366     // If all of the demanded bits are known to be zero on one side or the
00367     // other, turn this into an *inclusive* or.
00368     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
00369     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
00370       Instruction *Or =
00371         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
00372                                  I->getName());
00373       return InsertNewInstWith(Or, *I);
00374     }
00375 
00376     // If all of the demanded bits on one side are known, and all of the set
00377     // bits on that side are also known to be set on the other side, turn this
00378     // into an AND, as we know the bits will be cleared.
00379     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
00380     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
00381       // all known
00382       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
00383         Constant *AndC = Constant::getIntegerValue(VTy,
00384                                                    ~RHSKnownOne & DemandedMask);
00385         Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
00386         return InsertNewInstWith(And, *I);
00387       }
00388     }
00389 
00390     // If the RHS is a constant, see if we can simplify it.
00391     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
00392     if (ShrinkDemandedConstant(I, 1, DemandedMask))
00393       return I;
00394 
00395     // If our LHS is an 'and' and if it has one use, and if any of the bits we
00396     // are flipping are known to be set, then the xor is just resetting those
00397     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
00398     // simplifying both of them.
00399     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
00400       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
00401           isa<ConstantInt>(I->getOperand(1)) &&
00402           isa<ConstantInt>(LHSInst->getOperand(1)) &&
00403           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
00404         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
00405         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
00406         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
00407 
00408         Constant *AndC =
00409           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
00410         Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
00411         InsertNewInstWith(NewAnd, *I);
00412 
00413         Constant *XorC =
00414           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
00415         Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
00416         return InsertNewInstWith(NewXor, *I);
00417       }
00418 
00419     // Output known-0 bits are known if clear or set in both the LHS & RHS.
00420     KnownZero= (RHSKnownZero & LHSKnownZero) | (RHSKnownOne & LHSKnownOne);
00421     // Output known-1 are known to be set if set in only one of the LHS, RHS.
00422     KnownOne = (RHSKnownZero & LHSKnownOne) | (RHSKnownOne & LHSKnownZero);
00423     break;
00424   }
00425   case Instruction::Select:
00426     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
00427                              RHSKnownZero, RHSKnownOne, Depth+1) ||
00428         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
00429                              LHSKnownZero, LHSKnownOne, Depth+1))
00430       return I;
00431     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
00432     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
00433 
00434     // If the operands are constants, see if we can simplify them.
00435     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
00436         ShrinkDemandedConstant(I, 2, DemandedMask))
00437       return I;
00438 
00439     // Only known if known in both the LHS and RHS.
00440     KnownOne = RHSKnownOne & LHSKnownOne;
00441     KnownZero = RHSKnownZero & LHSKnownZero;
00442     break;
00443   case Instruction::Trunc: {
00444     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
00445     DemandedMask = DemandedMask.zext(truncBf);
00446     KnownZero = KnownZero.zext(truncBf);
00447     KnownOne = KnownOne.zext(truncBf);
00448     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
00449                              KnownZero, KnownOne, Depth+1))
00450       return I;
00451     DemandedMask = DemandedMask.trunc(BitWidth);
00452     KnownZero = KnownZero.trunc(BitWidth);
00453     KnownOne = KnownOne.trunc(BitWidth);
00454     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00455     break;
00456   }
00457   case Instruction::BitCast:
00458     if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
00459       return nullptr;  // vector->int or fp->int?
00460 
00461     if (VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
00462       if (VectorType *SrcVTy =
00463             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
00464         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
00465           // Don't touch a bitcast between vectors of different element counts.
00466           return nullptr;
00467       } else
00468         // Don't touch a scalar-to-vector bitcast.
00469         return nullptr;
00470     } else if (I->getOperand(0)->getType()->isVectorTy())
00471       // Don't touch a vector-to-scalar bitcast.
00472       return nullptr;
00473 
00474     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
00475                              KnownZero, KnownOne, Depth+1))
00476       return I;
00477     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00478     break;
00479   case Instruction::ZExt: {
00480     // Compute the bits in the result that are not present in the input.
00481     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
00482 
00483     DemandedMask = DemandedMask.trunc(SrcBitWidth);
00484     KnownZero = KnownZero.trunc(SrcBitWidth);
00485     KnownOne = KnownOne.trunc(SrcBitWidth);
00486     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
00487                              KnownZero, KnownOne, Depth+1))
00488       return I;
00489     DemandedMask = DemandedMask.zext(BitWidth);
00490     KnownZero = KnownZero.zext(BitWidth);
00491     KnownOne = KnownOne.zext(BitWidth);
00492     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00493     // The top bits are known to be zero.
00494     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
00495     break;
00496   }
00497   case Instruction::SExt: {
00498     // Compute the bits in the result that are not present in the input.
00499     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
00500 
00501     APInt InputDemandedBits = DemandedMask &
00502                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
00503 
00504     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
00505     // If any of the sign extended bits are demanded, we know that the sign
00506     // bit is demanded.
00507     if ((NewBits & DemandedMask) != 0)
00508       InputDemandedBits.setBit(SrcBitWidth-1);
00509 
00510     InputDemandedBits = InputDemandedBits.trunc(SrcBitWidth);
00511     KnownZero = KnownZero.trunc(SrcBitWidth);
00512     KnownOne = KnownOne.trunc(SrcBitWidth);
00513     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
00514                              KnownZero, KnownOne, Depth+1))
00515       return I;
00516     InputDemandedBits = InputDemandedBits.zext(BitWidth);
00517     KnownZero = KnownZero.zext(BitWidth);
00518     KnownOne = KnownOne.zext(BitWidth);
00519     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00520 
00521     // If the sign bit of the input is known set or clear, then we know the
00522     // top bits of the result.
00523 
00524     // If the input sign bit is known zero, or if the NewBits are not demanded
00525     // convert this into a zero extension.
00526     if (KnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
00527       // Convert to ZExt cast
00528       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
00529       return InsertNewInstWith(NewCast, *I);
00530     } else if (KnownOne[SrcBitWidth-1]) {    // Input sign bit known set
00531       KnownOne |= NewBits;
00532     }
00533     break;
00534   }
00535   case Instruction::Add: {
00536     // Figure out what the input bits are.  If the top bits of the and result
00537     // are not demanded, then the add doesn't demand them from its input
00538     // either.
00539     unsigned NLZ = DemandedMask.countLeadingZeros();
00540 
00541     // If there is a constant on the RHS, there are a variety of xformations
00542     // we can do.
00543     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
00544       // If null, this should be simplified elsewhere.  Some of the xforms here
00545       // won't work if the RHS is zero.
00546       if (RHS->isZero())
00547         break;
00548 
00549       // If the top bit of the output is demanded, demand everything from the
00550       // input.  Otherwise, we demand all the input bits except NLZ top bits.
00551       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
00552 
00553       // Find information about known zero/one bits in the input.
00554       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
00555                                LHSKnownZero, LHSKnownOne, Depth+1))
00556         return I;
00557 
00558       // If the RHS of the add has bits set that can't affect the input, reduce
00559       // the constant.
00560       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
00561         return I;
00562 
00563       // Avoid excess work.
00564       if (LHSKnownZero == 0 && LHSKnownOne == 0)
00565         break;
00566 
00567       // Turn it into OR if input bits are zero.
00568       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
00569         Instruction *Or =
00570           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
00571                                    I->getName());
00572         return InsertNewInstWith(Or, *I);
00573       }
00574 
00575       // We can say something about the output known-zero and known-one bits,
00576       // depending on potential carries from the input constant and the
00577       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
00578       // bits set and the RHS constant is 0x01001, then we know we have a known
00579       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
00580 
00581       // To compute this, we first compute the potential carry bits.  These are
00582       // the bits which may be modified.  I'm not aware of a better way to do
00583       // this scan.
00584       const APInt &RHSVal = RHS->getValue();
00585       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
00586 
00587       // Now that we know which bits have carries, compute the known-1/0 sets.
00588 
00589       // Bits are known one if they are known zero in one operand and one in the
00590       // other, and there is no input carry.
00591       KnownOne = ((LHSKnownZero & RHSVal) |
00592                   (LHSKnownOne & ~RHSVal)) & ~CarryBits;
00593 
00594       // Bits are known zero if they are known zero in both operands and there
00595       // is no input carry.
00596       KnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
00597     } else {
00598       // If the high-bits of this ADD are not demanded, then it does not demand
00599       // the high bits of its LHS or RHS.
00600       if (DemandedMask[BitWidth-1] == 0) {
00601         // Right fill the mask of bits for this ADD to demand the most
00602         // significant bit and all those below it.
00603         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
00604         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
00605                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
00606             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
00607                                  LHSKnownZero, LHSKnownOne, Depth+1))
00608           return I;
00609       }
00610     }
00611     break;
00612   }
00613   case Instruction::Sub:
00614     // If the high-bits of this SUB are not demanded, then it does not demand
00615     // the high bits of its LHS or RHS.
00616     if (DemandedMask[BitWidth-1] == 0) {
00617       // Right fill the mask of bits for this SUB to demand the most
00618       // significant bit and all those below it.
00619       uint32_t NLZ = DemandedMask.countLeadingZeros();
00620       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
00621       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
00622                                LHSKnownZero, LHSKnownOne, Depth+1) ||
00623           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
00624                                LHSKnownZero, LHSKnownOne, Depth+1))
00625         return I;
00626     }
00627 
00628     // Otherwise just hand the sub off to computeKnownBits to fill in
00629     // the known zeros and ones.
00630     computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
00631 
00632     // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
00633     // zero.
00634     if (ConstantInt *C0 = dyn_cast<ConstantInt>(I->getOperand(0))) {
00635       APInt I0 = C0->getValue();
00636       if ((I0 + 1).isPowerOf2() && (I0 | KnownZero).isAllOnesValue()) {
00637         Instruction *Xor = BinaryOperator::CreateXor(I->getOperand(1), C0);
00638         return InsertNewInstWith(Xor, *I);
00639       }
00640     }
00641     break;
00642   case Instruction::Shl:
00643     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
00644       {
00645         Value *VarX; ConstantInt *C1;
00646         if (match(I->getOperand(0), m_Shr(m_Value(VarX), m_ConstantInt(C1)))) {
00647           Instruction *Shr = cast<Instruction>(I->getOperand(0));
00648           Value *R = SimplifyShrShlDemandedBits(Shr, I, DemandedMask,
00649                                                 KnownZero, KnownOne);
00650           if (R)
00651             return R;
00652         }
00653       }
00654 
00655       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
00656       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
00657 
00658       // If the shift is NUW/NSW, then it does demand the high bits.
00659       ShlOperator *IOp = cast<ShlOperator>(I);
00660       if (IOp->hasNoSignedWrap())
00661         DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
00662       else if (IOp->hasNoUnsignedWrap())
00663         DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
00664 
00665       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
00666                                KnownZero, KnownOne, Depth+1))
00667         return I;
00668       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00669       KnownZero <<= ShiftAmt;
00670       KnownOne  <<= ShiftAmt;
00671       // low bits known zero.
00672       if (ShiftAmt)
00673         KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
00674     }
00675     break;
00676   case Instruction::LShr:
00677     // For a logical shift right
00678     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
00679       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
00680 
00681       // Unsigned shift right.
00682       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
00683 
00684       // If the shift is exact, then it does demand the low bits (and knows that
00685       // they are zero).
00686       if (cast<LShrOperator>(I)->isExact())
00687         DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
00688 
00689       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
00690                                KnownZero, KnownOne, Depth+1))
00691         return I;
00692       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00693       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
00694       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
00695       if (ShiftAmt) {
00696         // Compute the new bits that are at the top now.
00697         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
00698         KnownZero |= HighBits;  // high bits known zero.
00699       }
00700     }
00701     break;
00702   case Instruction::AShr:
00703     // If this is an arithmetic shift right and only the low-bit is set, we can
00704     // always convert this into a logical shr, even if the shift amount is
00705     // variable.  The low bit of the shift cannot be an input sign bit unless
00706     // the shift amount is >= the size of the datatype, which is undefined.
00707     if (DemandedMask == 1) {
00708       // Perform the logical shift right.
00709       Instruction *NewVal = BinaryOperator::CreateLShr(
00710                         I->getOperand(0), I->getOperand(1), I->getName());
00711       return InsertNewInstWith(NewVal, *I);
00712     }
00713 
00714     // If the sign bit is the only bit demanded by this ashr, then there is no
00715     // need to do it, the shift doesn't change the high bit.
00716     if (DemandedMask.isSignBit())
00717       return I->getOperand(0);
00718 
00719     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
00720       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
00721 
00722       // Signed shift right.
00723       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
00724       // If any of the "high bits" are demanded, we should set the sign bit as
00725       // demanded.
00726       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
00727         DemandedMaskIn.setBit(BitWidth-1);
00728 
00729       // If the shift is exact, then it does demand the low bits (and knows that
00730       // they are zero).
00731       if (cast<AShrOperator>(I)->isExact())
00732         DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
00733 
00734       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
00735                                KnownZero, KnownOne, Depth+1))
00736         return I;
00737       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00738       // Compute the new bits that are at the top now.
00739       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
00740       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
00741       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
00742 
00743       // Handle the sign bits.
00744       APInt SignBit(APInt::getSignBit(BitWidth));
00745       // Adjust to where it is now in the mask.
00746       SignBit = APIntOps::lshr(SignBit, ShiftAmt);
00747 
00748       // If the input sign bit is known to be zero, or if none of the top bits
00749       // are demanded, turn this into an unsigned shift right.
00750       if (BitWidth <= ShiftAmt || KnownZero[BitWidth-ShiftAmt-1] ||
00751           (HighBits & ~DemandedMask) == HighBits) {
00752         // Perform the logical shift right.
00753         BinaryOperator *NewVal = BinaryOperator::CreateLShr(I->getOperand(0),
00754                                                             SA, I->getName());
00755         NewVal->setIsExact(cast<BinaryOperator>(I)->isExact());
00756         return InsertNewInstWith(NewVal, *I);
00757       } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
00758         KnownOne |= HighBits;
00759       }
00760     }
00761     break;
00762   case Instruction::SRem:
00763     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
00764       // X % -1 demands all the bits because we don't want to introduce
00765       // INT_MIN % -1 (== undef) by accident.
00766       if (Rem->isAllOnesValue())
00767         break;
00768       APInt RA = Rem->getValue().abs();
00769       if (RA.isPowerOf2()) {
00770         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
00771           return I->getOperand(0);
00772 
00773         APInt LowBits = RA - 1;
00774         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
00775         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
00776                                  LHSKnownZero, LHSKnownOne, Depth+1))
00777           return I;
00778 
00779         // The low bits of LHS are unchanged by the srem.
00780         KnownZero = LHSKnownZero & LowBits;
00781         KnownOne = LHSKnownOne & LowBits;
00782 
00783         // If LHS is non-negative or has all low bits zero, then the upper bits
00784         // are all zero.
00785         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
00786           KnownZero |= ~LowBits;
00787 
00788         // If LHS is negative and not all low bits are zero, then the upper bits
00789         // are all one.
00790         if (LHSKnownOne[BitWidth-1] && ((LHSKnownOne & LowBits) != 0))
00791           KnownOne |= ~LowBits;
00792 
00793         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00794       }
00795     }
00796 
00797     // The sign bit is the LHS's sign bit, except when the result of the
00798     // remainder is zero.
00799     if (DemandedMask.isNegative() && KnownZero.isNonNegative()) {
00800       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
00801       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1,
00802                        CxtI);
00803       // If it's known zero, our sign bit is also zero.
00804       if (LHSKnownZero.isNegative())
00805         KnownZero.setBit(KnownZero.getBitWidth() - 1);
00806     }
00807     break;
00808   case Instruction::URem: {
00809     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
00810     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
00811     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
00812                              KnownZero2, KnownOne2, Depth+1) ||
00813         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
00814                              KnownZero2, KnownOne2, Depth+1))
00815       return I;
00816 
00817     unsigned Leaders = KnownZero2.countLeadingOnes();
00818     Leaders = std::max(Leaders,
00819                        KnownZero2.countLeadingOnes());
00820     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
00821     break;
00822   }
00823   case Instruction::Call:
00824     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00825       switch (II->getIntrinsicID()) {
00826       default: break;
00827       case Intrinsic::bswap: {
00828         // If the only bits demanded come from one byte of the bswap result,
00829         // just shift the input byte into position to eliminate the bswap.
00830         unsigned NLZ = DemandedMask.countLeadingZeros();
00831         unsigned NTZ = DemandedMask.countTrailingZeros();
00832 
00833         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
00834         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
00835         // have 14 leading zeros, round to 8.
00836         NLZ &= ~7;
00837         NTZ &= ~7;
00838         // If we need exactly one byte, we can do this transformation.
00839         if (BitWidth-NLZ-NTZ == 8) {
00840           unsigned ResultBit = NTZ;
00841           unsigned InputBit = BitWidth-NTZ-8;
00842 
00843           // Replace this with either a left or right shift to get the byte into
00844           // the right place.
00845           Instruction *NewVal;
00846           if (InputBit > ResultBit)
00847             NewVal = BinaryOperator::CreateLShr(II->getArgOperand(0),
00848                     ConstantInt::get(I->getType(), InputBit-ResultBit));
00849           else
00850             NewVal = BinaryOperator::CreateShl(II->getArgOperand(0),
00851                     ConstantInt::get(I->getType(), ResultBit-InputBit));
00852           NewVal->takeName(I);
00853           return InsertNewInstWith(NewVal, *I);
00854         }
00855 
00856         // TODO: Could compute known zero/one bits based on the input.
00857         break;
00858       }
00859       case Intrinsic::x86_sse42_crc32_64_64:
00860         KnownZero = APInt::getHighBitsSet(64, 32);
00861         return nullptr;
00862       }
00863     }
00864     computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
00865     break;
00866   }
00867 
00868   // If the client is only demanding bits that we know, return the known
00869   // constant.
00870   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
00871     return Constant::getIntegerValue(VTy, KnownOne);
00872   return nullptr;
00873 }
00874 
00875 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
00876 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
00877 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
00878 /// of "C2-C1".
00879 ///
00880 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
00881 /// ..., bn}, without considering the specific value X is holding.
00882 /// This transformation is legal iff one of following conditions is hold:
00883 ///  1) All the bit in S are 0, in this case E1 == E2.
00884 ///  2) We don't care those bits in S, per the input DemandedMask.
00885 ///  3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
00886 ///     rest bits.
00887 ///
00888 /// Currently we only test condition 2).
00889 ///
00890 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
00891 /// not successful.
00892 Value *InstCombiner::SimplifyShrShlDemandedBits(Instruction *Shr,
00893   Instruction *Shl, APInt DemandedMask, APInt &KnownZero, APInt &KnownOne) {
00894 
00895   const APInt &ShlOp1 = cast<ConstantInt>(Shl->getOperand(1))->getValue();
00896   const APInt &ShrOp1 = cast<ConstantInt>(Shr->getOperand(1))->getValue();
00897   if (!ShlOp1 || !ShrOp1)
00898       return nullptr; // Noop.
00899 
00900   Value *VarX = Shr->getOperand(0);
00901   Type *Ty = VarX->getType();
00902   unsigned BitWidth = Ty->getIntegerBitWidth();
00903   if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
00904     return nullptr; // Undef.
00905 
00906   unsigned ShlAmt = ShlOp1.getZExtValue();
00907   unsigned ShrAmt = ShrOp1.getZExtValue();
00908 
00909   KnownOne.clearAllBits();
00910   KnownZero = APInt::getBitsSet(KnownZero.getBitWidth(), 0, ShlAmt-1);
00911   KnownZero &= DemandedMask;
00912 
00913   APInt BitMask1(APInt::getAllOnesValue(BitWidth));
00914   APInt BitMask2(APInt::getAllOnesValue(BitWidth));
00915 
00916   bool isLshr = (Shr->getOpcode() == Instruction::LShr);
00917   BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
00918                       (BitMask1.ashr(ShrAmt) << ShlAmt);
00919 
00920   if (ShrAmt <= ShlAmt) {
00921     BitMask2 <<= (ShlAmt - ShrAmt);
00922   } else {
00923     BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
00924                         BitMask2.ashr(ShrAmt - ShlAmt);
00925   }
00926 
00927   // Check if condition-2 (see the comment to this function) is satified.
00928   if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
00929     if (ShrAmt == ShlAmt)
00930       return VarX;
00931 
00932     if (!Shr->hasOneUse())
00933       return nullptr;
00934 
00935     BinaryOperator *New;
00936     if (ShrAmt < ShlAmt) {
00937       Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
00938       New = BinaryOperator::CreateShl(VarX, Amt);
00939       BinaryOperator *Orig = cast<BinaryOperator>(Shl);
00940       New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
00941       New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
00942     } else {
00943       Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
00944       New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
00945                      BinaryOperator::CreateAShr(VarX, Amt);
00946       if (cast<BinaryOperator>(Shr)->isExact())
00947         New->setIsExact(true);
00948     }
00949 
00950     return InsertNewInstWith(New, *Shl);
00951   }
00952 
00953   return nullptr;
00954 }
00955 
00956 /// SimplifyDemandedVectorElts - The specified value produces a vector with
00957 /// any number of elements. DemandedElts contains the set of elements that are
00958 /// actually used by the caller.  This method analyzes which elements of the
00959 /// operand are undef and returns that information in UndefElts.
00960 ///
00961 /// If the information about demanded elements can be used to simplify the
00962 /// operation, the operation is simplified, then the resultant value is
00963 /// returned.  This returns null if no change was made.
00964 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
00965                                                 APInt &UndefElts,
00966                                                 unsigned Depth) {
00967   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
00968   APInt EltMask(APInt::getAllOnesValue(VWidth));
00969   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
00970 
00971   if (isa<UndefValue>(V)) {
00972     // If the entire vector is undefined, just return this info.
00973     UndefElts = EltMask;
00974     return nullptr;
00975   }
00976 
00977   if (DemandedElts == 0) { // If nothing is demanded, provide undef.
00978     UndefElts = EltMask;
00979     return UndefValue::get(V->getType());
00980   }
00981 
00982   UndefElts = 0;
00983 
00984   // Handle ConstantAggregateZero, ConstantVector, ConstantDataSequential.
00985   if (Constant *C = dyn_cast<Constant>(V)) {
00986     // Check if this is identity. If so, return 0 since we are not simplifying
00987     // anything.
00988     if (DemandedElts.isAllOnesValue())
00989       return nullptr;
00990 
00991     Type *EltTy = cast<VectorType>(V->getType())->getElementType();
00992     Constant *Undef = UndefValue::get(EltTy);
00993 
00994     SmallVector<Constant*, 16> Elts;
00995     for (unsigned i = 0; i != VWidth; ++i) {
00996       if (!DemandedElts[i]) {   // If not demanded, set to undef.
00997         Elts.push_back(Undef);
00998         UndefElts.setBit(i);
00999         continue;
01000       }
01001 
01002       Constant *Elt = C->getAggregateElement(i);
01003       if (!Elt) return nullptr;
01004 
01005       if (isa<UndefValue>(Elt)) {   // Already undef.
01006         Elts.push_back(Undef);
01007         UndefElts.setBit(i);
01008       } else {                               // Otherwise, defined.
01009         Elts.push_back(Elt);
01010       }
01011     }
01012 
01013     // If we changed the constant, return it.
01014     Constant *NewCV = ConstantVector::get(Elts);
01015     return NewCV != C ? NewCV : nullptr;
01016   }
01017 
01018   // Limit search depth.
01019   if (Depth == 10)
01020     return nullptr;
01021 
01022   // If multiple users are using the root value, proceed with
01023   // simplification conservatively assuming that all elements
01024   // are needed.
01025   if (!V->hasOneUse()) {
01026     // Quit if we find multiple users of a non-root value though.
01027     // They'll be handled when it's their turn to be visited by
01028     // the main instcombine process.
01029     if (Depth != 0)
01030       // TODO: Just compute the UndefElts information recursively.
01031       return nullptr;
01032 
01033     // Conservatively assume that all elements are needed.
01034     DemandedElts = EltMask;
01035   }
01036 
01037   Instruction *I = dyn_cast<Instruction>(V);
01038   if (!I) return nullptr;        // Only analyze instructions.
01039 
01040   bool MadeChange = false;
01041   APInt UndefElts2(VWidth, 0);
01042   Value *TmpV;
01043   switch (I->getOpcode()) {
01044   default: break;
01045 
01046   case Instruction::InsertElement: {
01047     // If this is a variable index, we don't know which element it overwrites.
01048     // demand exactly the same input as we produce.
01049     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
01050     if (!Idx) {
01051       // Note that we can't propagate undef elt info, because we don't know
01052       // which elt is getting updated.
01053       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
01054                                         UndefElts2, Depth+1);
01055       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01056       break;
01057     }
01058 
01059     // If this is inserting an element that isn't demanded, remove this
01060     // insertelement.
01061     unsigned IdxNo = Idx->getZExtValue();
01062     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
01063       Worklist.Add(I);
01064       return I->getOperand(0);
01065     }
01066 
01067     // Otherwise, the element inserted overwrites whatever was there, so the
01068     // input demanded set is simpler than the output set.
01069     APInt DemandedElts2 = DemandedElts;
01070     DemandedElts2.clearBit(IdxNo);
01071     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
01072                                       UndefElts, Depth+1);
01073     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01074 
01075     // The inserted element is defined.
01076     UndefElts.clearBit(IdxNo);
01077     break;
01078   }
01079   case Instruction::ShuffleVector: {
01080     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
01081     uint64_t LHSVWidth =
01082       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
01083     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
01084     for (unsigned i = 0; i < VWidth; i++) {
01085       if (DemandedElts[i]) {
01086         unsigned MaskVal = Shuffle->getMaskValue(i);
01087         if (MaskVal != -1u) {
01088           assert(MaskVal < LHSVWidth * 2 &&
01089                  "shufflevector mask index out of range!");
01090           if (MaskVal < LHSVWidth)
01091             LeftDemanded.setBit(MaskVal);
01092           else
01093             RightDemanded.setBit(MaskVal - LHSVWidth);
01094         }
01095       }
01096     }
01097 
01098     APInt UndefElts4(LHSVWidth, 0);
01099     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
01100                                       UndefElts4, Depth+1);
01101     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01102 
01103     APInt UndefElts3(LHSVWidth, 0);
01104     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
01105                                       UndefElts3, Depth+1);
01106     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
01107 
01108     bool NewUndefElts = false;
01109     for (unsigned i = 0; i < VWidth; i++) {
01110       unsigned MaskVal = Shuffle->getMaskValue(i);
01111       if (MaskVal == -1u) {
01112         UndefElts.setBit(i);
01113       } else if (!DemandedElts[i]) {
01114         NewUndefElts = true;
01115         UndefElts.setBit(i);
01116       } else if (MaskVal < LHSVWidth) {
01117         if (UndefElts4[MaskVal]) {
01118           NewUndefElts = true;
01119           UndefElts.setBit(i);
01120         }
01121       } else {
01122         if (UndefElts3[MaskVal - LHSVWidth]) {
01123           NewUndefElts = true;
01124           UndefElts.setBit(i);
01125         }
01126       }
01127     }
01128 
01129     if (NewUndefElts) {
01130       // Add additional discovered undefs.
01131       SmallVector<Constant*, 16> Elts;
01132       for (unsigned i = 0; i < VWidth; ++i) {
01133         if (UndefElts[i])
01134           Elts.push_back(UndefValue::get(Type::getInt32Ty(I->getContext())));
01135         else
01136           Elts.push_back(ConstantInt::get(Type::getInt32Ty(I->getContext()),
01137                                           Shuffle->getMaskValue(i)));
01138       }
01139       I->setOperand(2, ConstantVector::get(Elts));
01140       MadeChange = true;
01141     }
01142     break;
01143   }
01144   case Instruction::Select: {
01145     APInt LeftDemanded(DemandedElts), RightDemanded(DemandedElts);
01146     if (ConstantVector* CV = dyn_cast<ConstantVector>(I->getOperand(0))) {
01147       for (unsigned i = 0; i < VWidth; i++) {
01148         if (CV->getAggregateElement(i)->isNullValue())
01149           LeftDemanded.clearBit(i);
01150         else
01151           RightDemanded.clearBit(i);
01152       }
01153     }
01154 
01155     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), LeftDemanded,
01156                                       UndefElts, Depth+1);
01157     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
01158 
01159     TmpV = SimplifyDemandedVectorElts(I->getOperand(2), RightDemanded,
01160                                       UndefElts2, Depth+1);
01161     if (TmpV) { I->setOperand(2, TmpV); MadeChange = true; }
01162 
01163     // Output elements are undefined if both are undefined.
01164     UndefElts &= UndefElts2;
01165     break;
01166   }
01167   case Instruction::BitCast: {
01168     // Vector->vector casts only.
01169     VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
01170     if (!VTy) break;
01171     unsigned InVWidth = VTy->getNumElements();
01172     APInt InputDemandedElts(InVWidth, 0);
01173     unsigned Ratio;
01174 
01175     if (VWidth == InVWidth) {
01176       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
01177       // elements as are demanded of us.
01178       Ratio = 1;
01179       InputDemandedElts = DemandedElts;
01180     } else if (VWidth > InVWidth) {
01181       // Untested so far.
01182       break;
01183 
01184       // If there are more elements in the result than there are in the source,
01185       // then an input element is live if any of the corresponding output
01186       // elements are live.
01187       Ratio = VWidth/InVWidth;
01188       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
01189         if (DemandedElts[OutIdx])
01190           InputDemandedElts.setBit(OutIdx/Ratio);
01191       }
01192     } else {
01193       // Untested so far.
01194       break;
01195 
01196       // If there are more elements in the source than there are in the result,
01197       // then an input element is live if the corresponding output element is
01198       // live.
01199       Ratio = InVWidth/VWidth;
01200       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
01201         if (DemandedElts[InIdx/Ratio])
01202           InputDemandedElts.setBit(InIdx);
01203     }
01204 
01205     // div/rem demand all inputs, because they don't want divide by zero.
01206     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
01207                                       UndefElts2, Depth+1);
01208     if (TmpV) {
01209       I->setOperand(0, TmpV);
01210       MadeChange = true;
01211     }
01212 
01213     UndefElts = UndefElts2;
01214     if (VWidth > InVWidth) {
01215       llvm_unreachable("Unimp");
01216       // If there are more elements in the result than there are in the source,
01217       // then an output element is undef if the corresponding input element is
01218       // undef.
01219       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
01220         if (UndefElts2[OutIdx/Ratio])
01221           UndefElts.setBit(OutIdx);
01222     } else if (VWidth < InVWidth) {
01223       llvm_unreachable("Unimp");
01224       // If there are more elements in the source than there are in the result,
01225       // then a result element is undef if all of the corresponding input
01226       // elements are undef.
01227       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
01228       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
01229         if (!UndefElts2[InIdx])            // Not undef?
01230           UndefElts.clearBit(InIdx/Ratio);    // Clear undef bit.
01231     }
01232     break;
01233   }
01234   case Instruction::And:
01235   case Instruction::Or:
01236   case Instruction::Xor:
01237   case Instruction::Add:
01238   case Instruction::Sub:
01239   case Instruction::Mul:
01240     // div/rem demand all inputs, because they don't want divide by zero.
01241     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
01242                                       UndefElts, Depth+1);
01243     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01244     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
01245                                       UndefElts2, Depth+1);
01246     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
01247 
01248     // Output elements are undefined if both are undefined.  Consider things
01249     // like undef&0.  The result is known zero, not undef.
01250     UndefElts &= UndefElts2;
01251     break;
01252   case Instruction::FPTrunc:
01253   case Instruction::FPExt:
01254     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
01255                                       UndefElts, Depth+1);
01256     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01257     break;
01258 
01259   case Instruction::Call: {
01260     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
01261     if (!II) break;
01262     switch (II->getIntrinsicID()) {
01263     default: break;
01264 
01265     // Binary vector operations that work column-wise.  A dest element is a
01266     // function of the corresponding input elements from the two inputs.
01267     case Intrinsic::x86_sse_sub_ss:
01268     case Intrinsic::x86_sse_mul_ss:
01269     case Intrinsic::x86_sse_min_ss:
01270     case Intrinsic::x86_sse_max_ss:
01271     case Intrinsic::x86_sse2_sub_sd:
01272     case Intrinsic::x86_sse2_mul_sd:
01273     case Intrinsic::x86_sse2_min_sd:
01274     case Intrinsic::x86_sse2_max_sd:
01275       TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0), DemandedElts,
01276                                         UndefElts, Depth+1);
01277       if (TmpV) { II->setArgOperand(0, TmpV); MadeChange = true; }
01278       TmpV = SimplifyDemandedVectorElts(II->getArgOperand(1), DemandedElts,
01279                                         UndefElts2, Depth+1);
01280       if (TmpV) { II->setArgOperand(1, TmpV); MadeChange = true; }
01281 
01282       // If only the low elt is demanded and this is a scalarizable intrinsic,
01283       // scalarize it now.
01284       if (DemandedElts == 1) {
01285         switch (II->getIntrinsicID()) {
01286         default: break;
01287         case Intrinsic::x86_sse_sub_ss:
01288         case Intrinsic::x86_sse_mul_ss:
01289         case Intrinsic::x86_sse2_sub_sd:
01290         case Intrinsic::x86_sse2_mul_sd:
01291           // TODO: Lower MIN/MAX/ABS/etc
01292           Value *LHS = II->getArgOperand(0);
01293           Value *RHS = II->getArgOperand(1);
01294           // Extract the element as scalars.
01295           LHS = InsertNewInstWith(ExtractElementInst::Create(LHS,
01296             ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
01297           RHS = InsertNewInstWith(ExtractElementInst::Create(RHS,
01298             ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
01299 
01300           switch (II->getIntrinsicID()) {
01301           default: llvm_unreachable("Case stmts out of sync!");
01302           case Intrinsic::x86_sse_sub_ss:
01303           case Intrinsic::x86_sse2_sub_sd:
01304             TmpV = InsertNewInstWith(BinaryOperator::CreateFSub(LHS, RHS,
01305                                                         II->getName()), *II);
01306             break;
01307           case Intrinsic::x86_sse_mul_ss:
01308           case Intrinsic::x86_sse2_mul_sd:
01309             TmpV = InsertNewInstWith(BinaryOperator::CreateFMul(LHS, RHS,
01310                                                          II->getName()), *II);
01311             break;
01312           }
01313 
01314           Instruction *New =
01315             InsertElementInst::Create(
01316               UndefValue::get(II->getType()), TmpV,
01317               ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U, false),
01318                                       II->getName());
01319           InsertNewInstWith(New, *II);
01320           return New;
01321         }
01322       }
01323 
01324       // Output elements are undefined if both are undefined.  Consider things
01325       // like undef&0.  The result is known zero, not undef.
01326       UndefElts &= UndefElts2;
01327       break;
01328     }
01329     break;
01330   }
01331   }
01332   return MadeChange ? I : nullptr;
01333 }