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