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