LLVM API Documentation

InstCombineShifts.cpp
Go to the documentation of this file.
00001 //===- InstCombineShifts.cpp ----------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visitShl, visitLShr, and visitAShr functions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombine.h"
00015 #include "llvm/Analysis/ConstantFolding.h"
00016 #include "llvm/Analysis/InstructionSimplify.h"
00017 #include "llvm/IR/IntrinsicInst.h"
00018 #include "llvm/IR/PatternMatch.h"
00019 using namespace llvm;
00020 using namespace PatternMatch;
00021 
00022 #define DEBUG_TYPE "instcombine"
00023 
00024 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
00025   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
00026   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
00027 
00028   // See if we can fold away this shift.
00029   if (SimplifyDemandedInstructionBits(I))
00030     return &I;
00031 
00032   // Try to fold constant and into select arguments.
00033   if (isa<Constant>(Op0))
00034     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
00035       if (Instruction *R = FoldOpIntoSelect(I, SI))
00036         return R;
00037 
00038   if (Constant *CUI = dyn_cast<Constant>(Op1))
00039     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
00040       return Res;
00041 
00042   // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
00043   // Because shifts by negative values (which could occur if A were negative)
00044   // are undefined.
00045   Value *A; const APInt *B;
00046   if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
00047     // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
00048     // demand the sign bit (and many others) here??
00049     Value *Rem = Builder->CreateAnd(A, ConstantInt::get(I.getType(), *B-1),
00050                                     Op1->getName());
00051     I.setOperand(1, Rem);
00052     return &I;
00053   }
00054 
00055   return 0;
00056 }
00057 
00058 /// CanEvaluateShifted - See if we can compute the specified value, but shifted
00059 /// logically to the left or right by some number of bits.  This should return
00060 /// true if the expression can be computed for the same cost as the current
00061 /// expression tree.  This is used to eliminate extraneous shifting from things
00062 /// like:
00063 ///      %C = shl i128 %A, 64
00064 ///      %D = shl i128 %B, 96
00065 ///      %E = or i128 %C, %D
00066 ///      %F = lshr i128 %E, 64
00067 /// where the client will ask if E can be computed shifted right by 64-bits.  If
00068 /// this succeeds, the GetShiftedValue function will be called to produce the
00069 /// value.
00070 static bool CanEvaluateShifted(Value *V, unsigned NumBits, bool isLeftShift,
00071                                InstCombiner &IC) {
00072   // We can always evaluate constants shifted.
00073   if (isa<Constant>(V))
00074     return true;
00075 
00076   Instruction *I = dyn_cast<Instruction>(V);
00077   if (!I) return false;
00078 
00079   // If this is the opposite shift, we can directly reuse the input of the shift
00080   // if the needed bits are already zero in the input.  This allows us to reuse
00081   // the value which means that we don't care if the shift has multiple uses.
00082   //  TODO:  Handle opposite shift by exact value.
00083   ConstantInt *CI = 0;
00084   if ((isLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
00085       (!isLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
00086     if (CI->getZExtValue() == NumBits) {
00087       // TODO: Check that the input bits are already zero with MaskedValueIsZero
00088 #if 0
00089       // If this is a truncate of a logical shr, we can truncate it to a smaller
00090       // lshr iff we know that the bits we would otherwise be shifting in are
00091       // already zeros.
00092       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
00093       uint32_t BitWidth = Ty->getScalarSizeInBits();
00094       if (MaskedValueIsZero(I->getOperand(0),
00095             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
00096           CI->getLimitedValue(BitWidth) < BitWidth) {
00097         return CanEvaluateTruncated(I->getOperand(0), Ty);
00098       }
00099 #endif
00100 
00101     }
00102   }
00103 
00104   // We can't mutate something that has multiple uses: doing so would
00105   // require duplicating the instruction in general, which isn't profitable.
00106   if (!I->hasOneUse()) return false;
00107 
00108   switch (I->getOpcode()) {
00109   default: return false;
00110   case Instruction::And:
00111   case Instruction::Or:
00112   case Instruction::Xor:
00113     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
00114     return CanEvaluateShifted(I->getOperand(0), NumBits, isLeftShift, IC) &&
00115            CanEvaluateShifted(I->getOperand(1), NumBits, isLeftShift, IC);
00116 
00117   case Instruction::Shl: {
00118     // We can often fold the shift into shifts-by-a-constant.
00119     CI = dyn_cast<ConstantInt>(I->getOperand(1));
00120     if (CI == 0) return false;
00121 
00122     // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
00123     if (isLeftShift) return true;
00124 
00125     // We can always turn shl(c)+shr(c) -> and(c2).
00126     if (CI->getValue() == NumBits) return true;
00127 
00128     unsigned TypeWidth = I->getType()->getScalarSizeInBits();
00129 
00130     // We can turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but it isn't
00131     // profitable unless we know the and'd out bits are already zero.
00132     if (CI->getZExtValue() > NumBits) {
00133       unsigned LowBits = TypeWidth - CI->getZExtValue();
00134       if (MaskedValueIsZero(I->getOperand(0),
00135                        APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
00136         return true;
00137     }
00138 
00139     return false;
00140   }
00141   case Instruction::LShr: {
00142     // We can often fold the shift into shifts-by-a-constant.
00143     CI = dyn_cast<ConstantInt>(I->getOperand(1));
00144     if (CI == 0) return false;
00145 
00146     // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
00147     if (!isLeftShift) return true;
00148 
00149     // We can always turn lshr(c)+shl(c) -> and(c2).
00150     if (CI->getValue() == NumBits) return true;
00151 
00152     unsigned TypeWidth = I->getType()->getScalarSizeInBits();
00153 
00154     // We can always turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but it isn't
00155     // profitable unless we know the and'd out bits are already zero.
00156     if (CI->getValue().ult(TypeWidth) && CI->getZExtValue() > NumBits) {
00157       unsigned LowBits = CI->getZExtValue() - NumBits;
00158       if (MaskedValueIsZero(I->getOperand(0),
00159                           APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
00160         return true;
00161     }
00162 
00163     return false;
00164   }
00165   case Instruction::Select: {
00166     SelectInst *SI = cast<SelectInst>(I);
00167     return CanEvaluateShifted(SI->getTrueValue(), NumBits, isLeftShift, IC) &&
00168            CanEvaluateShifted(SI->getFalseValue(), NumBits, isLeftShift, IC);
00169   }
00170   case Instruction::PHI: {
00171     // We can change a phi if we can change all operands.  Note that we never
00172     // get into trouble with cyclic PHIs here because we only consider
00173     // instructions with a single use.
00174     PHINode *PN = cast<PHINode>(I);
00175     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00176       if (!CanEvaluateShifted(PN->getIncomingValue(i), NumBits, isLeftShift,IC))
00177         return false;
00178     return true;
00179   }
00180   }
00181 }
00182 
00183 /// GetShiftedValue - When CanEvaluateShifted returned true for an expression,
00184 /// this value inserts the new computation that produces the shifted value.
00185 static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
00186                               InstCombiner &IC) {
00187   // We can always evaluate constants shifted.
00188   if (Constant *C = dyn_cast<Constant>(V)) {
00189     if (isLeftShift)
00190       V = IC.Builder->CreateShl(C, NumBits);
00191     else
00192       V = IC.Builder->CreateLShr(C, NumBits);
00193     // If we got a constantexpr back, try to simplify it with TD info.
00194     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
00195       V = ConstantFoldConstantExpression(CE, IC.getDataLayout(),
00196                                          IC.getTargetLibraryInfo());
00197     return V;
00198   }
00199 
00200   Instruction *I = cast<Instruction>(V);
00201   IC.Worklist.Add(I);
00202 
00203   switch (I->getOpcode()) {
00204   default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
00205   case Instruction::And:
00206   case Instruction::Or:
00207   case Instruction::Xor:
00208     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
00209     I->setOperand(0, GetShiftedValue(I->getOperand(0), NumBits,isLeftShift,IC));
00210     I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
00211     return I;
00212 
00213   case Instruction::Shl: {
00214     BinaryOperator *BO = cast<BinaryOperator>(I);
00215     unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
00216 
00217     // We only accept shifts-by-a-constant in CanEvaluateShifted.
00218     ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
00219 
00220     // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
00221     if (isLeftShift) {
00222       // If this is oversized composite shift, then unsigned shifts get 0.
00223       unsigned NewShAmt = NumBits+CI->getZExtValue();
00224       if (NewShAmt >= TypeWidth)
00225         return Constant::getNullValue(I->getType());
00226 
00227       BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
00228       BO->setHasNoUnsignedWrap(false);
00229       BO->setHasNoSignedWrap(false);
00230       return I;
00231     }
00232 
00233     // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
00234     // zeros.
00235     if (CI->getValue() == NumBits) {
00236       APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
00237       V = IC.Builder->CreateAnd(BO->getOperand(0),
00238                                 ConstantInt::get(BO->getContext(), Mask));
00239       if (Instruction *VI = dyn_cast<Instruction>(V)) {
00240         VI->moveBefore(BO);
00241         VI->takeName(BO);
00242       }
00243       return V;
00244     }
00245 
00246     // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
00247     // the and won't be needed.
00248     assert(CI->getZExtValue() > NumBits);
00249     BO->setOperand(1, ConstantInt::get(BO->getType(),
00250                                        CI->getZExtValue() - NumBits));
00251     BO->setHasNoUnsignedWrap(false);
00252     BO->setHasNoSignedWrap(false);
00253     return BO;
00254   }
00255   case Instruction::LShr: {
00256     BinaryOperator *BO = cast<BinaryOperator>(I);
00257     unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
00258     // We only accept shifts-by-a-constant in CanEvaluateShifted.
00259     ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
00260 
00261     // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
00262     if (!isLeftShift) {
00263       // If this is oversized composite shift, then unsigned shifts get 0.
00264       unsigned NewShAmt = NumBits+CI->getZExtValue();
00265       if (NewShAmt >= TypeWidth)
00266         return Constant::getNullValue(BO->getType());
00267 
00268       BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
00269       BO->setIsExact(false);
00270       return I;
00271     }
00272 
00273     // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
00274     // zeros.
00275     if (CI->getValue() == NumBits) {
00276       APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
00277       V = IC.Builder->CreateAnd(I->getOperand(0),
00278                                 ConstantInt::get(BO->getContext(), Mask));
00279       if (Instruction *VI = dyn_cast<Instruction>(V)) {
00280         VI->moveBefore(I);
00281         VI->takeName(I);
00282       }
00283       return V;
00284     }
00285 
00286     // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
00287     // the and won't be needed.
00288     assert(CI->getZExtValue() > NumBits);
00289     BO->setOperand(1, ConstantInt::get(BO->getType(),
00290                                        CI->getZExtValue() - NumBits));
00291     BO->setIsExact(false);
00292     return BO;
00293   }
00294 
00295   case Instruction::Select:
00296     I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
00297     I->setOperand(2, GetShiftedValue(I->getOperand(2), NumBits,isLeftShift,IC));
00298     return I;
00299   case Instruction::PHI: {
00300     // We can change a phi if we can change all operands.  Note that we never
00301     // get into trouble with cyclic PHIs here because we only consider
00302     // instructions with a single use.
00303     PHINode *PN = cast<PHINode>(I);
00304     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00305       PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i),
00306                                               NumBits, isLeftShift, IC));
00307     return PN;
00308   }
00309   }
00310 }
00311 
00312 
00313 
00314 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
00315                                                BinaryOperator &I) {
00316   bool isLeftShift = I.getOpcode() == Instruction::Shl;
00317 
00318   ConstantInt *COp1 = nullptr;
00319   if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(Op1))
00320     COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
00321   else if (ConstantVector *CV = dyn_cast<ConstantVector>(Op1))
00322     COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
00323   else
00324     COp1 = dyn_cast<ConstantInt>(Op1);
00325 
00326   if (!COp1)
00327     return nullptr;
00328 
00329   // See if we can propagate this shift into the input, this covers the trivial
00330   // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
00331   if (I.getOpcode() != Instruction::AShr &&
00332       CanEvaluateShifted(Op0, COp1->getZExtValue(), isLeftShift, *this)) {
00333     DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
00334               " to eliminate shift:\n  IN: " << *Op0 << "\n  SH: " << I <<"\n");
00335 
00336     return ReplaceInstUsesWith(I,
00337                  GetShiftedValue(Op0, COp1->getZExtValue(), isLeftShift, *this));
00338   }
00339 
00340   // See if we can simplify any instructions used by the instruction whose sole
00341   // purpose is to compute bits we don't care about.
00342   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
00343 
00344   assert(!COp1->uge(TypeBits) &&
00345          "Shift over the type width should have been removed already");
00346 
00347   // ((X*C1) << C2) == (X * (C1 << C2))
00348   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
00349     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
00350       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
00351         return BinaryOperator::CreateMul(BO->getOperand(0),
00352                                         ConstantExpr::getShl(BOOp, Op1));
00353 
00354   // Try to fold constant and into select arguments.
00355   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
00356     if (Instruction *R = FoldOpIntoSelect(I, SI))
00357       return R;
00358   if (isa<PHINode>(Op0))
00359     if (Instruction *NV = FoldOpIntoPhi(I))
00360       return NV;
00361 
00362   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
00363   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
00364     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
00365     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
00366     // place.  Don't try to do this transformation in this case.  Also, we
00367     // require that the input operand is a shift-by-constant so that we have
00368     // confidence that the shifts will get folded together.  We could do this
00369     // xform in more cases, but it is unlikely to be profitable.
00370     if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
00371         isa<ConstantInt>(TrOp->getOperand(1))) {
00372       // Okay, we'll do this xform.  Make the shift of shift.
00373       Constant *ShAmt = ConstantExpr::getZExt(COp1, TrOp->getType());
00374       // (shift2 (shift1 & 0x00FF), c2)
00375       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
00376 
00377       // For logical shifts, the truncation has the effect of making the high
00378       // part of the register be zeros.  Emulate this by inserting an AND to
00379       // clear the top bits as needed.  This 'and' will usually be zapped by
00380       // other xforms later if dead.
00381       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
00382       unsigned DstSize = TI->getType()->getScalarSizeInBits();
00383       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
00384 
00385       // The mask we constructed says what the trunc would do if occurring
00386       // between the shifts.  We want to know the effect *after* the second
00387       // shift.  We know that it is a logical shift by a constant, so adjust the
00388       // mask as appropriate.
00389       if (I.getOpcode() == Instruction::Shl)
00390         MaskV <<= COp1->getZExtValue();
00391       else {
00392         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
00393         MaskV = MaskV.lshr(COp1->getZExtValue());
00394       }
00395 
00396       // shift1 & 0x00FF
00397       Value *And = Builder->CreateAnd(NSh,
00398                                       ConstantInt::get(I.getContext(), MaskV),
00399                                       TI->getName());
00400 
00401       // Return the value truncated to the interesting size.
00402       return new TruncInst(And, I.getType());
00403     }
00404   }
00405 
00406   if (Op0->hasOneUse()) {
00407     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
00408       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
00409       Value *V1, *V2;
00410       ConstantInt *CC;
00411       switch (Op0BO->getOpcode()) {
00412       default: break;
00413       case Instruction::Add:
00414       case Instruction::And:
00415       case Instruction::Or:
00416       case Instruction::Xor: {
00417         // These operators commute.
00418         // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
00419         if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
00420             match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
00421                   m_Specific(Op1)))) {
00422           Value *YS =         // (Y << C)
00423             Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
00424           // (X + (Y << C))
00425           Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
00426                                           Op0BO->getOperand(1)->getName());
00427           uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
00428 
00429           APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
00430           Constant *Mask = ConstantInt::get(I.getContext(), Bits);
00431           if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
00432             Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
00433           return BinaryOperator::CreateAnd(X, Mask);
00434         }
00435 
00436         // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
00437         Value *Op0BOOp1 = Op0BO->getOperand(1);
00438         if (isLeftShift && Op0BOOp1->hasOneUse() &&
00439             match(Op0BOOp1,
00440                   m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
00441                         m_ConstantInt(CC)))) {
00442           Value *YS =   // (Y << C)
00443             Builder->CreateShl(Op0BO->getOperand(0), Op1,
00444                                          Op0BO->getName());
00445           // X & (CC << C)
00446           Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
00447                                          V1->getName()+".mask");
00448           return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
00449         }
00450       }
00451 
00452       // FALL THROUGH.
00453       case Instruction::Sub: {
00454         // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
00455         if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
00456             match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
00457                   m_Specific(Op1)))) {
00458           Value *YS =  // (Y << C)
00459             Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
00460           // (X + (Y << C))
00461           Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
00462                                           Op0BO->getOperand(0)->getName());
00463           uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
00464 
00465           APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
00466           Constant *Mask = ConstantInt::get(I.getContext(), Bits);
00467           if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
00468             Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
00469           return BinaryOperator::CreateAnd(X, Mask);
00470         }
00471 
00472         // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
00473         if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
00474             match(Op0BO->getOperand(0),
00475                   m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
00476                         m_ConstantInt(CC))) && V2 == Op1) {
00477           Value *YS = // (Y << C)
00478             Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
00479           // X & (CC << C)
00480           Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
00481                                          V1->getName()+".mask");
00482 
00483           return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
00484         }
00485 
00486         break;
00487       }
00488       }
00489 
00490 
00491       // If the operand is an bitwise operator with a constant RHS, and the
00492       // shift is the only use, we can pull it out of the shift.
00493       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
00494         bool isValid = true;     // Valid only for And, Or, Xor
00495         bool highBitSet = false; // Transform if high bit of constant set?
00496 
00497         switch (Op0BO->getOpcode()) {
00498         default: isValid = false; break;   // Do not perform transform!
00499         case Instruction::Add:
00500           isValid = isLeftShift;
00501           break;
00502         case Instruction::Or:
00503         case Instruction::Xor:
00504           highBitSet = false;
00505           break;
00506         case Instruction::And:
00507           highBitSet = true;
00508           break;
00509         }
00510 
00511         // If this is a signed shift right, and the high bit is modified
00512         // by the logical operation, do not perform the transformation.
00513         // The highBitSet boolean indicates the value of the high bit of
00514         // the constant which would cause it to be modified for this
00515         // operation.
00516         //
00517         if (isValid && I.getOpcode() == Instruction::AShr)
00518           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
00519 
00520         if (isValid) {
00521           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
00522 
00523           Value *NewShift =
00524             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
00525           NewShift->takeName(Op0BO);
00526 
00527           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
00528                                         NewRHS);
00529         }
00530       }
00531     }
00532   }
00533 
00534   // Find out if this is a shift of a shift by a constant.
00535   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
00536   if (ShiftOp && !ShiftOp->isShift())
00537     ShiftOp = 0;
00538 
00539   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
00540 
00541     // This is a constant shift of a constant shift. Be careful about hiding
00542     // shl instructions behind bit masks. They are used to represent multiplies
00543     // by a constant, and it is important that simple arithmetic expressions
00544     // are still recognizable by scalar evolution.
00545     //
00546     // The transforms applied to shl are very similar to the transforms applied
00547     // to mul by constant. We can be more aggressive about optimizing right
00548     // shifts.
00549     //
00550     // Combinations of right and left shifts will still be optimized in
00551     // DAGCombine where scalar evolution no longer applies.
00552 
00553     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
00554     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
00555     uint32_t ShiftAmt2 = COp1->getLimitedValue(TypeBits);
00556     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
00557     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
00558     Value *X = ShiftOp->getOperand(0);
00559 
00560     IntegerType *Ty = cast<IntegerType>(I.getType());
00561 
00562     // Check for (X << c1) << c2  and  (X >> c1) >> c2
00563     if (I.getOpcode() == ShiftOp->getOpcode()) {
00564       uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
00565       // If this is oversized composite shift, then unsigned shifts get 0, ashr
00566       // saturates.
00567       if (AmtSum >= TypeBits) {
00568         if (I.getOpcode() != Instruction::AShr)
00569           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
00570         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
00571       }
00572 
00573       return BinaryOperator::Create(I.getOpcode(), X,
00574                                     ConstantInt::get(Ty, AmtSum));
00575     }
00576 
00577     if (ShiftAmt1 == ShiftAmt2) {
00578       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
00579       if (I.getOpcode() == Instruction::LShr &&
00580           ShiftOp->getOpcode() == Instruction::Shl) {
00581         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
00582         return BinaryOperator::CreateAnd(X,
00583                                         ConstantInt::get(I.getContext(), Mask));
00584       }
00585     } else if (ShiftAmt1 < ShiftAmt2) {
00586       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
00587 
00588       // (X >>?,exact C1) << C2 --> X << (C2-C1)
00589       // The inexact version is deferred to DAGCombine so we don't hide shl
00590       // behind a bit mask.
00591       if (I.getOpcode() == Instruction::Shl &&
00592           ShiftOp->getOpcode() != Instruction::Shl &&
00593           ShiftOp->isExact()) {
00594         assert(ShiftOp->getOpcode() == Instruction::LShr ||
00595                ShiftOp->getOpcode() == Instruction::AShr);
00596         ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
00597         BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
00598                                                         X, ShiftDiffCst);
00599         NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
00600         NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
00601         return NewShl;
00602       }
00603 
00604       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
00605       if (I.getOpcode() == Instruction::LShr &&
00606           ShiftOp->getOpcode() == Instruction::Shl) {
00607         ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
00608         // (X <<nuw C1) >>u C2 --> X >>u (C2-C1)
00609         if (ShiftOp->hasNoUnsignedWrap()) {
00610           BinaryOperator *NewLShr = BinaryOperator::Create(Instruction::LShr,
00611                                                            X, ShiftDiffCst);
00612           NewLShr->setIsExact(I.isExact());
00613           return NewLShr;
00614         }
00615         Value *Shift = Builder->CreateLShr(X, ShiftDiffCst);
00616 
00617         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
00618         return BinaryOperator::CreateAnd(Shift,
00619                                          ConstantInt::get(I.getContext(),Mask));
00620       }
00621 
00622       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
00623       // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
00624       if (I.getOpcode() == Instruction::AShr &&
00625           ShiftOp->getOpcode() == Instruction::Shl) {
00626         if (ShiftOp->hasNoSignedWrap()) {
00627           // (X <<nsw C1) >>s C2 --> X >>s (C2-C1)
00628           ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
00629           BinaryOperator *NewAShr = BinaryOperator::Create(Instruction::AShr,
00630                                                            X, ShiftDiffCst);
00631           NewAShr->setIsExact(I.isExact());
00632           return NewAShr;
00633         }
00634       }
00635     } else {
00636       assert(ShiftAmt2 < ShiftAmt1);
00637       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
00638 
00639       // (X >>?exact C1) << C2 --> X >>?exact (C1-C2)
00640       // The inexact version is deferred to DAGCombine so we don't hide shl
00641       // behind a bit mask.
00642       if (I.getOpcode() == Instruction::Shl &&
00643           ShiftOp->getOpcode() != Instruction::Shl &&
00644           ShiftOp->isExact()) {
00645         ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
00646         BinaryOperator *NewShr = BinaryOperator::Create(ShiftOp->getOpcode(),
00647                                                         X, ShiftDiffCst);
00648         NewShr->setIsExact(true);
00649         return NewShr;
00650       }
00651 
00652       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
00653       if (I.getOpcode() == Instruction::LShr &&
00654           ShiftOp->getOpcode() == Instruction::Shl) {
00655         ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
00656         if (ShiftOp->hasNoUnsignedWrap()) {
00657           // (X <<nuw C1) >>u C2 --> X <<nuw (C1-C2)
00658           BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
00659                                                           X, ShiftDiffCst);
00660           NewShl->setHasNoUnsignedWrap(true);
00661           return NewShl;
00662         }
00663         Value *Shift = Builder->CreateShl(X, ShiftDiffCst);
00664 
00665         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
00666         return BinaryOperator::CreateAnd(Shift,
00667                                          ConstantInt::get(I.getContext(),Mask));
00668       }
00669 
00670       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
00671       // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
00672       if (I.getOpcode() == Instruction::AShr &&
00673           ShiftOp->getOpcode() == Instruction::Shl) {
00674         if (ShiftOp->hasNoSignedWrap()) {
00675           // (X <<nsw C1) >>s C2 --> X <<nsw (C1-C2)
00676           ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
00677           BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
00678                                                           X, ShiftDiffCst);
00679           NewShl->setHasNoSignedWrap(true);
00680           return NewShl;
00681         }
00682       }
00683     }
00684   }
00685   return 0;
00686 }
00687 
00688 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
00689   if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
00690                                  I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
00691                                  DL))
00692     return ReplaceInstUsesWith(I, V);
00693 
00694   if (Instruction *V = commonShiftTransforms(I))
00695     return V;
00696 
00697   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(I.getOperand(1))) {
00698     unsigned ShAmt = Op1C->getZExtValue();
00699 
00700     // If the shifted-out value is known-zero, then this is a NUW shift.
00701     if (!I.hasNoUnsignedWrap() &&
00702         MaskedValueIsZero(I.getOperand(0),
00703                           APInt::getHighBitsSet(Op1C->getBitWidth(), ShAmt))) {
00704           I.setHasNoUnsignedWrap();
00705           return &I;
00706         }
00707 
00708     // If the shifted out value is all signbits, this is a NSW shift.
00709     if (!I.hasNoSignedWrap() &&
00710         ComputeNumSignBits(I.getOperand(0)) > ShAmt) {
00711       I.setHasNoSignedWrap();
00712       return &I;
00713     }
00714   }
00715 
00716   // (C1 << A) << C2 -> (C1 << C2) << A
00717   Constant *C1, *C2;
00718   Value *A;
00719   if (match(I.getOperand(0), m_OneUse(m_Shl(m_Constant(C1), m_Value(A)))) &&
00720       match(I.getOperand(1), m_Constant(C2)))
00721     return BinaryOperator::CreateShl(ConstantExpr::getShl(C1, C2), A);
00722 
00723   return 0;
00724 }
00725 
00726 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
00727   if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1),
00728                                   I.isExact(), DL))
00729     return ReplaceInstUsesWith(I, V);
00730 
00731   if (Instruction *R = commonShiftTransforms(I))
00732     return R;
00733 
00734   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
00735 
00736   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
00737     unsigned ShAmt = Op1C->getZExtValue();
00738 
00739     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
00740       unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
00741       // ctlz.i32(x)>>5  --> zext(x == 0)
00742       // cttz.i32(x)>>5  --> zext(x == 0)
00743       // ctpop.i32(x)>>5 --> zext(x == -1)
00744       if ((II->getIntrinsicID() == Intrinsic::ctlz ||
00745            II->getIntrinsicID() == Intrinsic::cttz ||
00746            II->getIntrinsicID() == Intrinsic::ctpop) &&
00747           isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt) {
00748         bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
00749         Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
00750         Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
00751         return new ZExtInst(Cmp, II->getType());
00752       }
00753     }
00754 
00755     // If the shifted-out value is known-zero, then this is an exact shift.
00756     if (!I.isExact() &&
00757         MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
00758       I.setIsExact();
00759       return &I;
00760     }
00761   }
00762 
00763   return 0;
00764 }
00765 
00766 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
00767   if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1),
00768                                   I.isExact(), DL))
00769     return ReplaceInstUsesWith(I, V);
00770 
00771   if (Instruction *R = commonShiftTransforms(I))
00772     return R;
00773 
00774   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
00775 
00776   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
00777     unsigned ShAmt = Op1C->getZExtValue();
00778 
00779     // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
00780     // have a sign-extend idiom.
00781     Value *X;
00782     if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
00783       // If the left shift is just shifting out partial signbits, delete the
00784       // extension.
00785       if (cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
00786         return ReplaceInstUsesWith(I, X);
00787 
00788       // If the input is an extension from the shifted amount value, e.g.
00789       //   %x = zext i8 %A to i32
00790       //   %y = shl i32 %x, 24
00791       //   %z = ashr %y, 24
00792       // then turn this into "z = sext i8 A to i32".
00793       if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
00794         uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
00795         uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
00796         if (Op1C->getZExtValue() == DestBits-SrcBits)
00797           return new SExtInst(ZI->getOperand(0), ZI->getType());
00798       }
00799     }
00800 
00801     // If the shifted-out value is known-zero, then this is an exact shift.
00802     if (!I.isExact() &&
00803         MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
00804       I.setIsExact();
00805       return &I;
00806     }
00807   }
00808 
00809   // See if we can turn a signed shr into an unsigned shr.
00810   if (MaskedValueIsZero(Op0,
00811                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
00812     return BinaryOperator::CreateLShr(Op0, Op1);
00813 
00814   // Arithmetic shifting an all-sign-bit value is a no-op.
00815   unsigned NumSignBits = ComputeNumSignBits(Op0);
00816   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
00817     return ReplaceInstUsesWith(I, Op0);
00818 
00819   return 0;
00820 }