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