1 //===- InstCombineShifts.cpp ----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitShl, visitLShr, and visitAShr functions.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/PatternMatch.h"
20 using namespace PatternMatch;
22 #define DEBUG_TYPE "instcombine"
24 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
25 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
26 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
28 // See if we can fold away this shift.
29 if (SimplifyDemandedInstructionBits(I))
32 // Try to fold constant and into select arguments.
33 if (isa<Constant>(Op0))
34 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
35 if (Instruction *R = FoldOpIntoSelect(I, SI))
38 if (Constant *CUI = dyn_cast<Constant>(Op1))
39 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
42 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
43 // Because shifts by negative values (which could occur if A were negative)
45 Value *A; const APInt *B;
46 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
47 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
48 // demand the sign bit (and many others) here??
49 Value *Rem = Builder->CreateAnd(A, ConstantInt::get(I.getType(), *B-1),
58 /// CanEvaluateShifted - See if we can compute the specified value, but shifted
59 /// logically to the left or right by some number of bits. This should return
60 /// true if the expression can be computed for the same cost as the current
61 /// expression tree. This is used to eliminate extraneous shifting from things
63 /// %C = shl i128 %A, 64
64 /// %D = shl i128 %B, 96
65 /// %E = or i128 %C, %D
66 /// %F = lshr i128 %E, 64
67 /// where the client will ask if E can be computed shifted right by 64-bits. If
68 /// this succeeds, the GetShiftedValue function will be called to produce the
70 static bool CanEvaluateShifted(Value *V, unsigned NumBits, bool isLeftShift,
71 InstCombiner &IC, Instruction *CxtI) {
72 // We can always evaluate constants shifted.
76 Instruction *I = dyn_cast<Instruction>(V);
79 // If this is the opposite shift, we can directly reuse the input of the shift
80 // if the needed bits are already zero in the input. This allows us to reuse
81 // the value which means that we don't care if the shift has multiple uses.
82 // TODO: Handle opposite shift by exact value.
83 ConstantInt *CI = nullptr;
84 if ((isLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
85 (!isLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
86 if (CI->getZExtValue() == NumBits) {
87 // TODO: Check that the input bits are already zero with MaskedValueIsZero
89 // If this is a truncate of a logical shr, we can truncate it to a smaller
90 // lshr iff we know that the bits we would otherwise be shifting in are
92 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
93 uint32_t BitWidth = Ty->getScalarSizeInBits();
94 if (MaskedValueIsZero(I->getOperand(0),
95 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
96 CI->getLimitedValue(BitWidth) < BitWidth) {
97 return CanEvaluateTruncated(I->getOperand(0), Ty);
104 // We can't mutate something that has multiple uses: doing so would
105 // require duplicating the instruction in general, which isn't profitable.
106 if (!I->hasOneUse()) return false;
108 switch (I->getOpcode()) {
109 default: return false;
110 case Instruction::And:
111 case Instruction::Or:
112 case Instruction::Xor:
113 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
114 return CanEvaluateShifted(I->getOperand(0), NumBits, isLeftShift, IC, I) &&
115 CanEvaluateShifted(I->getOperand(1), NumBits, isLeftShift, IC, I);
117 case Instruction::Shl: {
118 // We can often fold the shift into shifts-by-a-constant.
119 CI = dyn_cast<ConstantInt>(I->getOperand(1));
120 if (!CI) return false;
122 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
123 if (isLeftShift) return true;
125 // We can always turn shl(c)+shr(c) -> and(c2).
126 if (CI->getValue() == NumBits) return true;
128 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
130 // We can turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but it isn't
131 // profitable unless we know the and'd out bits are already zero.
132 if (CI->getZExtValue() > NumBits) {
133 unsigned LowBits = TypeWidth - CI->getZExtValue();
134 if (IC.MaskedValueIsZero(I->getOperand(0),
135 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits,
142 case Instruction::LShr: {
143 // We can often fold the shift into shifts-by-a-constant.
144 CI = dyn_cast<ConstantInt>(I->getOperand(1));
145 if (!CI) return false;
147 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
148 if (!isLeftShift) return true;
150 // We can always turn lshr(c)+shl(c) -> and(c2).
151 if (CI->getValue() == NumBits) return true;
153 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
155 // We can always turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but it isn't
156 // profitable unless we know the and'd out bits are already zero.
157 if (CI->getValue().ult(TypeWidth) && CI->getZExtValue() > NumBits) {
158 unsigned LowBits = CI->getZExtValue() - NumBits;
159 if (IC.MaskedValueIsZero(I->getOperand(0),
160 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits,
167 case Instruction::Select: {
168 SelectInst *SI = cast<SelectInst>(I);
169 return CanEvaluateShifted(SI->getTrueValue(), NumBits, isLeftShift,
171 CanEvaluateShifted(SI->getFalseValue(), NumBits, isLeftShift, IC, SI);
173 case Instruction::PHI: {
174 // We can change a phi if we can change all operands. Note that we never
175 // get into trouble with cyclic PHIs here because we only consider
176 // instructions with a single use.
177 PHINode *PN = cast<PHINode>(I);
178 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
179 if (!CanEvaluateShifted(PN->getIncomingValue(i), NumBits, isLeftShift,
187 /// GetShiftedValue - When CanEvaluateShifted returned true for an expression,
188 /// this value inserts the new computation that produces the shifted value.
189 static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
191 // We can always evaluate constants shifted.
192 if (Constant *C = dyn_cast<Constant>(V)) {
194 V = IC.Builder->CreateShl(C, NumBits);
196 V = IC.Builder->CreateLShr(C, NumBits);
197 // If we got a constantexpr back, try to simplify it with TD info.
198 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
199 V = ConstantFoldConstantExpression(CE, IC.getDataLayout(),
200 IC.getTargetLibraryInfo());
204 Instruction *I = cast<Instruction>(V);
207 switch (I->getOpcode()) {
208 default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
209 case Instruction::And:
210 case Instruction::Or:
211 case Instruction::Xor:
212 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
213 I->setOperand(0, GetShiftedValue(I->getOperand(0), NumBits,isLeftShift,IC));
214 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
217 case Instruction::Shl: {
218 BinaryOperator *BO = cast<BinaryOperator>(I);
219 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
221 // We only accept shifts-by-a-constant in CanEvaluateShifted.
222 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
224 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
226 // If this is oversized composite shift, then unsigned shifts get 0.
227 unsigned NewShAmt = NumBits+CI->getZExtValue();
228 if (NewShAmt >= TypeWidth)
229 return Constant::getNullValue(I->getType());
231 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
232 BO->setHasNoUnsignedWrap(false);
233 BO->setHasNoSignedWrap(false);
237 // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
239 if (CI->getValue() == NumBits) {
240 APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
241 V = IC.Builder->CreateAnd(BO->getOperand(0),
242 ConstantInt::get(BO->getContext(), Mask));
243 if (Instruction *VI = dyn_cast<Instruction>(V)) {
250 // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
251 // the and won't be needed.
252 assert(CI->getZExtValue() > NumBits);
253 BO->setOperand(1, ConstantInt::get(BO->getType(),
254 CI->getZExtValue() - NumBits));
255 BO->setHasNoUnsignedWrap(false);
256 BO->setHasNoSignedWrap(false);
259 case Instruction::LShr: {
260 BinaryOperator *BO = cast<BinaryOperator>(I);
261 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
262 // We only accept shifts-by-a-constant in CanEvaluateShifted.
263 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
265 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
267 // If this is oversized composite shift, then unsigned shifts get 0.
268 unsigned NewShAmt = NumBits+CI->getZExtValue();
269 if (NewShAmt >= TypeWidth)
270 return Constant::getNullValue(BO->getType());
272 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
273 BO->setIsExact(false);
277 // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
279 if (CI->getValue() == NumBits) {
280 APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
281 V = IC.Builder->CreateAnd(I->getOperand(0),
282 ConstantInt::get(BO->getContext(), Mask));
283 if (Instruction *VI = dyn_cast<Instruction>(V)) {
290 // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
291 // the and won't be needed.
292 assert(CI->getZExtValue() > NumBits);
293 BO->setOperand(1, ConstantInt::get(BO->getType(),
294 CI->getZExtValue() - NumBits));
295 BO->setIsExact(false);
299 case Instruction::Select:
300 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
301 I->setOperand(2, GetShiftedValue(I->getOperand(2), NumBits,isLeftShift,IC));
303 case Instruction::PHI: {
304 // We can change a phi if we can change all operands. Note that we never
305 // get into trouble with cyclic PHIs here because we only consider
306 // instructions with a single use.
307 PHINode *PN = cast<PHINode>(I);
308 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
309 PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i),
310 NumBits, isLeftShift, IC));
318 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
320 bool isLeftShift = I.getOpcode() == Instruction::Shl;
322 ConstantInt *COp1 = nullptr;
323 if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(Op1))
324 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
325 else if (ConstantVector *CV = dyn_cast<ConstantVector>(Op1))
326 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
328 COp1 = dyn_cast<ConstantInt>(Op1);
333 // See if we can propagate this shift into the input, this covers the trivial
334 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
335 if (I.getOpcode() != Instruction::AShr &&
336 CanEvaluateShifted(Op0, COp1->getZExtValue(), isLeftShift, *this, &I)) {
337 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
338 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
340 return ReplaceInstUsesWith(I,
341 GetShiftedValue(Op0, COp1->getZExtValue(), isLeftShift, *this));
344 // See if we can simplify any instructions used by the instruction whose sole
345 // purpose is to compute bits we don't care about.
346 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
348 assert(!COp1->uge(TypeBits) &&
349 "Shift over the type width should have been removed already");
351 // ((X*C1) << C2) == (X * (C1 << C2))
352 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
353 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
354 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
355 return BinaryOperator::CreateMul(BO->getOperand(0),
356 ConstantExpr::getShl(BOOp, Op1));
358 // Try to fold constant and into select arguments.
359 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
360 if (Instruction *R = FoldOpIntoSelect(I, SI))
362 if (isa<PHINode>(Op0))
363 if (Instruction *NV = FoldOpIntoPhi(I))
366 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
367 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
368 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
369 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
370 // place. Don't try to do this transformation in this case. Also, we
371 // require that the input operand is a shift-by-constant so that we have
372 // confidence that the shifts will get folded together. We could do this
373 // xform in more cases, but it is unlikely to be profitable.
374 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
375 isa<ConstantInt>(TrOp->getOperand(1))) {
376 // Okay, we'll do this xform. Make the shift of shift.
377 Constant *ShAmt = ConstantExpr::getZExt(COp1, TrOp->getType());
378 // (shift2 (shift1 & 0x00FF), c2)
379 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
381 // For logical shifts, the truncation has the effect of making the high
382 // part of the register be zeros. Emulate this by inserting an AND to
383 // clear the top bits as needed. This 'and' will usually be zapped by
384 // other xforms later if dead.
385 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
386 unsigned DstSize = TI->getType()->getScalarSizeInBits();
387 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
389 // The mask we constructed says what the trunc would do if occurring
390 // between the shifts. We want to know the effect *after* the second
391 // shift. We know that it is a logical shift by a constant, so adjust the
392 // mask as appropriate.
393 if (I.getOpcode() == Instruction::Shl)
394 MaskV <<= COp1->getZExtValue();
396 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
397 MaskV = MaskV.lshr(COp1->getZExtValue());
401 Value *And = Builder->CreateAnd(NSh,
402 ConstantInt::get(I.getContext(), MaskV),
405 // Return the value truncated to the interesting size.
406 return new TruncInst(And, I.getType());
410 if (Op0->hasOneUse()) {
411 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
412 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
415 switch (Op0BO->getOpcode()) {
417 case Instruction::Add:
418 case Instruction::And:
419 case Instruction::Or:
420 case Instruction::Xor: {
421 // These operators commute.
422 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
423 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
424 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
426 Value *YS = // (Y << C)
427 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
429 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
430 Op0BO->getOperand(1)->getName());
431 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
433 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
434 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
435 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
436 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
437 return BinaryOperator::CreateAnd(X, Mask);
440 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
441 Value *Op0BOOp1 = Op0BO->getOperand(1);
442 if (isLeftShift && Op0BOOp1->hasOneUse() &&
444 m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
445 m_ConstantInt(CC)))) {
446 Value *YS = // (Y << C)
447 Builder->CreateShl(Op0BO->getOperand(0), Op1,
450 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
451 V1->getName()+".mask");
452 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
457 case Instruction::Sub: {
458 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
459 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
460 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
462 Value *YS = // (Y << C)
463 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
465 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
466 Op0BO->getOperand(0)->getName());
467 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
469 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
470 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
471 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
472 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
473 return BinaryOperator::CreateAnd(X, Mask);
476 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
477 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
478 match(Op0BO->getOperand(0),
479 m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
480 m_ConstantInt(CC))) && V2 == Op1) {
481 Value *YS = // (Y << C)
482 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
484 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
485 V1->getName()+".mask");
487 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
495 // If the operand is a bitwise operator with a constant RHS, and the
496 // shift is the only use, we can pull it out of the shift.
497 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
498 bool isValid = true; // Valid only for And, Or, Xor
499 bool highBitSet = false; // Transform if high bit of constant set?
501 switch (Op0BO->getOpcode()) {
502 default: isValid = false; break; // Do not perform transform!
503 case Instruction::Add:
504 isValid = isLeftShift;
506 case Instruction::Or:
507 case Instruction::Xor:
510 case Instruction::And:
515 // If this is a signed shift right, and the high bit is modified
516 // by the logical operation, do not perform the transformation.
517 // The highBitSet boolean indicates the value of the high bit of
518 // the constant which would cause it to be modified for this
521 if (isValid && I.getOpcode() == Instruction::AShr)
522 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
525 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
528 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
529 NewShift->takeName(Op0BO);
531 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
538 // Find out if this is a shift of a shift by a constant.
539 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
540 if (ShiftOp && !ShiftOp->isShift())
543 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
545 // This is a constant shift of a constant shift. Be careful about hiding
546 // shl instructions behind bit masks. They are used to represent multiplies
547 // by a constant, and it is important that simple arithmetic expressions
548 // are still recognizable by scalar evolution.
550 // The transforms applied to shl are very similar to the transforms applied
551 // to mul by constant. We can be more aggressive about optimizing right
554 // Combinations of right and left shifts will still be optimized in
555 // DAGCombine where scalar evolution no longer applies.
557 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
558 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
559 uint32_t ShiftAmt2 = COp1->getLimitedValue(TypeBits);
560 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
561 if (ShiftAmt1 == 0) return nullptr; // Will be simplified in the future.
562 Value *X = ShiftOp->getOperand(0);
564 IntegerType *Ty = cast<IntegerType>(I.getType());
566 // Check for (X << c1) << c2 and (X >> c1) >> c2
567 if (I.getOpcode() == ShiftOp->getOpcode()) {
568 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
569 // If this is oversized composite shift, then unsigned shifts get 0, ashr
571 if (AmtSum >= TypeBits) {
572 if (I.getOpcode() != Instruction::AShr)
573 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
574 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
577 return BinaryOperator::Create(I.getOpcode(), X,
578 ConstantInt::get(Ty, AmtSum));
581 if (ShiftAmt1 == ShiftAmt2) {
582 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
583 if (I.getOpcode() == Instruction::LShr &&
584 ShiftOp->getOpcode() == Instruction::Shl) {
585 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
586 return BinaryOperator::CreateAnd(X,
587 ConstantInt::get(I.getContext(), Mask));
589 } else if (ShiftAmt1 < ShiftAmt2) {
590 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
592 // (X >>?,exact C1) << C2 --> X << (C2-C1)
593 // The inexact version is deferred to DAGCombine so we don't hide shl
594 // behind a bit mask.
595 if (I.getOpcode() == Instruction::Shl &&
596 ShiftOp->getOpcode() != Instruction::Shl &&
597 ShiftOp->isExact()) {
598 assert(ShiftOp->getOpcode() == Instruction::LShr ||
599 ShiftOp->getOpcode() == Instruction::AShr);
600 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
601 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
603 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
604 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
608 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
609 if (I.getOpcode() == Instruction::LShr &&
610 ShiftOp->getOpcode() == Instruction::Shl) {
611 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
612 // (X <<nuw C1) >>u C2 --> X >>u (C2-C1)
613 if (ShiftOp->hasNoUnsignedWrap()) {
614 BinaryOperator *NewLShr = BinaryOperator::Create(Instruction::LShr,
616 NewLShr->setIsExact(I.isExact());
619 Value *Shift = Builder->CreateLShr(X, ShiftDiffCst);
621 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
622 return BinaryOperator::CreateAnd(Shift,
623 ConstantInt::get(I.getContext(),Mask));
626 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
627 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
628 if (I.getOpcode() == Instruction::AShr &&
629 ShiftOp->getOpcode() == Instruction::Shl) {
630 if (ShiftOp->hasNoSignedWrap()) {
631 // (X <<nsw C1) >>s C2 --> X >>s (C2-C1)
632 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
633 BinaryOperator *NewAShr = BinaryOperator::Create(Instruction::AShr,
635 NewAShr->setIsExact(I.isExact());
640 assert(ShiftAmt2 < ShiftAmt1);
641 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
643 // (X >>?exact C1) << C2 --> X >>?exact (C1-C2)
644 // The inexact version is deferred to DAGCombine so we don't hide shl
645 // behind a bit mask.
646 if (I.getOpcode() == Instruction::Shl &&
647 ShiftOp->getOpcode() != Instruction::Shl &&
648 ShiftOp->isExact()) {
649 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
650 BinaryOperator *NewShr = BinaryOperator::Create(ShiftOp->getOpcode(),
652 NewShr->setIsExact(true);
656 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
657 if (I.getOpcode() == Instruction::LShr &&
658 ShiftOp->getOpcode() == Instruction::Shl) {
659 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
660 if (ShiftOp->hasNoUnsignedWrap()) {
661 // (X <<nuw C1) >>u C2 --> X <<nuw (C1-C2)
662 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
664 NewShl->setHasNoUnsignedWrap(true);
667 Value *Shift = Builder->CreateShl(X, ShiftDiffCst);
669 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
670 return BinaryOperator::CreateAnd(Shift,
671 ConstantInt::get(I.getContext(),Mask));
674 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
675 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
676 if (I.getOpcode() == Instruction::AShr &&
677 ShiftOp->getOpcode() == Instruction::Shl) {
678 if (ShiftOp->hasNoSignedWrap()) {
679 // (X <<nsw C1) >>s C2 --> X <<nsw (C1-C2)
680 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
681 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
683 NewShl->setHasNoSignedWrap(true);
692 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
693 if (Value *V = SimplifyVectorOp(I))
694 return ReplaceInstUsesWith(I, V);
696 if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
697 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
699 return ReplaceInstUsesWith(I, V);
701 if (Instruction *V = commonShiftTransforms(I))
704 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(I.getOperand(1))) {
705 unsigned ShAmt = Op1C->getZExtValue();
707 // If the shifted-out value is known-zero, then this is a NUW shift.
708 if (!I.hasNoUnsignedWrap() &&
709 MaskedValueIsZero(I.getOperand(0),
710 APInt::getHighBitsSet(Op1C->getBitWidth(), ShAmt),
712 I.setHasNoUnsignedWrap();
716 // If the shifted out value is all signbits, this is a NSW shift.
717 if (!I.hasNoSignedWrap() &&
718 ComputeNumSignBits(I.getOperand(0), 0, &I) > ShAmt) {
719 I.setHasNoSignedWrap();
724 // (C1 << A) << C2 -> (C1 << C2) << A
727 if (match(I.getOperand(0), m_OneUse(m_Shl(m_Constant(C1), m_Value(A)))) &&
728 match(I.getOperand(1), m_Constant(C2)))
729 return BinaryOperator::CreateShl(ConstantExpr::getShl(C1, C2), A);
734 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
735 if (Value *V = SimplifyVectorOp(I))
736 return ReplaceInstUsesWith(I, V);
738 if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1),
739 I.isExact(), DL, TLI, DT, AT))
740 return ReplaceInstUsesWith(I, V);
742 if (Instruction *R = commonShiftTransforms(I))
745 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
747 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
748 unsigned ShAmt = Op1C->getZExtValue();
750 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
751 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
752 // ctlz.i32(x)>>5 --> zext(x == 0)
753 // cttz.i32(x)>>5 --> zext(x == 0)
754 // ctpop.i32(x)>>5 --> zext(x == -1)
755 if ((II->getIntrinsicID() == Intrinsic::ctlz ||
756 II->getIntrinsicID() == Intrinsic::cttz ||
757 II->getIntrinsicID() == Intrinsic::ctpop) &&
758 isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt) {
759 bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
760 Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
761 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
762 return new ZExtInst(Cmp, II->getType());
766 // If the shifted-out value is known-zero, then this is an exact shift.
768 MaskedValueIsZero(Op0, APInt::getLowBitsSet(Op1C->getBitWidth(), ShAmt),
778 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
779 if (Value *V = SimplifyVectorOp(I))
780 return ReplaceInstUsesWith(I, V);
782 if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1),
783 I.isExact(), DL, TLI, DT, AT))
784 return ReplaceInstUsesWith(I, V);
786 if (Instruction *R = commonShiftTransforms(I))
789 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
791 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
792 unsigned ShAmt = Op1C->getZExtValue();
794 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
795 // have a sign-extend idiom.
797 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
798 // If the input is an extension from the shifted amount value, e.g.
799 // %x = zext i8 %A to i32
800 // %y = shl i32 %x, 24
802 // then turn this into "z = sext i8 A to i32".
803 if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
804 uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
805 uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
806 if (Op1C->getZExtValue() == DestBits-SrcBits)
807 return new SExtInst(ZI->getOperand(0), ZI->getType());
811 // If the shifted-out value is known-zero, then this is an exact shift.
813 MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt),
820 // See if we can turn a signed shr into an unsigned shr.
821 if (MaskedValueIsZero(Op0,
822 APInt::getSignBit(I.getType()->getScalarSizeInBits()),
824 return BinaryOperator::CreateLShr(Op0, Op1);