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 #define DEBUG_TYPE "instcombine"
15 #include "InstCombine.h"
16 #include "llvm/Analysis/ConstantFolding.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/PatternMatch.h"
21 using namespace PatternMatch;
23 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
24 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
25 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
27 // See if we can fold away this shift.
28 if (SimplifyDemandedInstructionBits(I))
31 // Try to fold constant and into select arguments.
32 if (isa<Constant>(Op0))
33 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
34 if (Instruction *R = FoldOpIntoSelect(I, SI))
37 if (Constant *CUI = dyn_cast<Constant>(Op1))
38 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
41 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
42 // Because shifts by negative values (which could occur if A were negative)
44 Value *A; const APInt *B;
45 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
46 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
47 // demand the sign bit (and many others) here??
48 Value *Rem = Builder->CreateAnd(A, ConstantInt::get(I.getType(), *B-1),
57 /// CanEvaluateShifted - See if we can compute the specified value, but shifted
58 /// logically to the left or right by some number of bits. This should return
59 /// true if the expression can be computed for the same cost as the current
60 /// expression tree. This is used to eliminate extraneous shifting from things
62 /// %C = shl i128 %A, 64
63 /// %D = shl i128 %B, 96
64 /// %E = or i128 %C, %D
65 /// %F = lshr i128 %E, 64
66 /// where the client will ask if E can be computed shifted right by 64-bits. If
67 /// this succeeds, the GetShiftedValue function will be called to produce the
69 static bool CanEvaluateShifted(Value *V, unsigned NumBits, bool isLeftShift,
71 // We can always evaluate constants shifted.
75 Instruction *I = dyn_cast<Instruction>(V);
78 // If this is the opposite shift, we can directly reuse the input of the shift
79 // if the needed bits are already zero in the input. This allows us to reuse
80 // the value which means that we don't care if the shift has multiple uses.
81 // TODO: Handle opposite shift by exact value.
83 if ((isLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
84 (!isLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
85 if (CI->getZExtValue() == NumBits) {
86 // TODO: Check that the input bits are already zero with MaskedValueIsZero
88 // If this is a truncate of a logical shr, we can truncate it to a smaller
89 // lshr iff we know that the bits we would otherwise be shifting in are
91 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
92 uint32_t BitWidth = Ty->getScalarSizeInBits();
93 if (MaskedValueIsZero(I->getOperand(0),
94 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
95 CI->getLimitedValue(BitWidth) < BitWidth) {
96 return CanEvaluateTruncated(I->getOperand(0), Ty);
103 // We can't mutate something that has multiple uses: doing so would
104 // require duplicating the instruction in general, which isn't profitable.
105 if (!I->hasOneUse()) return false;
107 switch (I->getOpcode()) {
108 default: return false;
109 case Instruction::And:
110 case Instruction::Or:
111 case Instruction::Xor:
112 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
113 return CanEvaluateShifted(I->getOperand(0), NumBits, isLeftShift, IC) &&
114 CanEvaluateShifted(I->getOperand(1), NumBits, isLeftShift, IC);
116 case Instruction::Shl: {
117 // We can often fold the shift into shifts-by-a-constant.
118 CI = dyn_cast<ConstantInt>(I->getOperand(1));
119 if (CI == 0) return false;
121 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
122 if (isLeftShift) return true;
124 // We can always turn shl(c)+shr(c) -> and(c2).
125 if (CI->getValue() == NumBits) return true;
127 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
129 // We can turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but it isn't
130 // profitable unless we know the and'd out bits are already zero.
131 if (CI->getZExtValue() > NumBits) {
132 unsigned LowBits = TypeWidth - CI->getZExtValue();
133 if (MaskedValueIsZero(I->getOperand(0),
134 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
140 case Instruction::LShr: {
141 // We can often fold the shift into shifts-by-a-constant.
142 CI = dyn_cast<ConstantInt>(I->getOperand(1));
143 if (CI == 0) return false;
145 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
146 if (!isLeftShift) return true;
148 // We can always turn lshr(c)+shl(c) -> and(c2).
149 if (CI->getValue() == NumBits) return true;
151 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
153 // We can always turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but it isn't
154 // profitable unless we know the and'd out bits are already zero.
155 if (CI->getValue().ult(TypeWidth) && CI->getZExtValue() > NumBits) {
156 unsigned LowBits = CI->getZExtValue() - NumBits;
157 if (MaskedValueIsZero(I->getOperand(0),
158 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
164 case Instruction::Select: {
165 SelectInst *SI = cast<SelectInst>(I);
166 return CanEvaluateShifted(SI->getTrueValue(), NumBits, isLeftShift, IC) &&
167 CanEvaluateShifted(SI->getFalseValue(), NumBits, isLeftShift, IC);
169 case Instruction::PHI: {
170 // We can change a phi if we can change all operands. Note that we never
171 // get into trouble with cyclic PHIs here because we only consider
172 // instructions with a single use.
173 PHINode *PN = cast<PHINode>(I);
174 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
175 if (!CanEvaluateShifted(PN->getIncomingValue(i), NumBits, isLeftShift,IC))
182 /// GetShiftedValue - When CanEvaluateShifted returned true for an expression,
183 /// this value inserts the new computation that produces the shifted value.
184 static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
186 // We can always evaluate constants shifted.
187 if (Constant *C = dyn_cast<Constant>(V)) {
189 V = IC.Builder->CreateShl(C, NumBits);
191 V = IC.Builder->CreateLShr(C, NumBits);
192 // If we got a constantexpr back, try to simplify it with TD info.
193 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
194 V = ConstantFoldConstantExpression(CE, IC.getDataLayout(),
195 IC.getTargetLibraryInfo());
199 Instruction *I = cast<Instruction>(V);
202 switch (I->getOpcode()) {
203 default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
204 case Instruction::And:
205 case Instruction::Or:
206 case Instruction::Xor:
207 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
208 I->setOperand(0, GetShiftedValue(I->getOperand(0), NumBits,isLeftShift,IC));
209 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
212 case Instruction::Shl: {
213 BinaryOperator *BO = cast<BinaryOperator>(I);
214 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
216 // We only accept shifts-by-a-constant in CanEvaluateShifted.
217 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
219 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
221 // If this is oversized composite shift, then unsigned shifts get 0.
222 unsigned NewShAmt = NumBits+CI->getZExtValue();
223 if (NewShAmt >= TypeWidth)
224 return Constant::getNullValue(I->getType());
226 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
227 BO->setHasNoUnsignedWrap(false);
228 BO->setHasNoSignedWrap(false);
232 // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
234 if (CI->getValue() == NumBits) {
235 APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
236 V = IC.Builder->CreateAnd(BO->getOperand(0),
237 ConstantInt::get(BO->getContext(), Mask));
238 if (Instruction *VI = dyn_cast<Instruction>(V)) {
245 // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
246 // the and won't be needed.
247 assert(CI->getZExtValue() > NumBits);
248 BO->setOperand(1, ConstantInt::get(BO->getType(),
249 CI->getZExtValue() - NumBits));
250 BO->setHasNoUnsignedWrap(false);
251 BO->setHasNoSignedWrap(false);
254 case Instruction::LShr: {
255 BinaryOperator *BO = cast<BinaryOperator>(I);
256 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
257 // We only accept shifts-by-a-constant in CanEvaluateShifted.
258 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
260 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
262 // If this is oversized composite shift, then unsigned shifts get 0.
263 unsigned NewShAmt = NumBits+CI->getZExtValue();
264 if (NewShAmt >= TypeWidth)
265 return Constant::getNullValue(BO->getType());
267 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
268 BO->setIsExact(false);
272 // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
274 if (CI->getValue() == NumBits) {
275 APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
276 V = IC.Builder->CreateAnd(I->getOperand(0),
277 ConstantInt::get(BO->getContext(), Mask));
278 if (Instruction *VI = dyn_cast<Instruction>(V)) {
285 // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
286 // the and won't be needed.
287 assert(CI->getZExtValue() > NumBits);
288 BO->setOperand(1, ConstantInt::get(BO->getType(),
289 CI->getZExtValue() - NumBits));
290 BO->setIsExact(false);
294 case Instruction::Select:
295 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
296 I->setOperand(2, GetShiftedValue(I->getOperand(2), NumBits,isLeftShift,IC));
298 case Instruction::PHI: {
299 // We can change a phi if we can change all operands. Note that we never
300 // get into trouble with cyclic PHIs here because we only consider
301 // instructions with a single use.
302 PHINode *PN = cast<PHINode>(I);
303 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
304 PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i),
305 NumBits, isLeftShift, IC));
313 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
315 bool isLeftShift = I.getOpcode() == Instruction::Shl;
317 ConstantInt *COp1 = nullptr;
318 if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(Op1))
319 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
320 else if (ConstantVector *CV = dyn_cast<ConstantVector>(Op1))
321 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
323 COp1 = dyn_cast<ConstantInt>(Op1);
328 // See if we can propagate this shift into the input, this covers the trivial
329 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
330 if (I.getOpcode() != Instruction::AShr &&
331 CanEvaluateShifted(Op0, COp1->getZExtValue(), isLeftShift, *this)) {
332 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
333 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
335 return ReplaceInstUsesWith(I,
336 GetShiftedValue(Op0, COp1->getZExtValue(), isLeftShift, *this));
340 // See if we can simplify any instructions used by the instruction whose sole
341 // purpose is to compute bits we don't care about.
342 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
344 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
347 if (COp1->uge(TypeBits)) {
348 if (I.getOpcode() != Instruction::AShr)
349 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
350 // ashr i32 X, 32 --> ashr i32 X, 31
351 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
355 // ((X*C1) << C2) == (X * (C1 << C2))
356 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
357 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
358 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
359 return BinaryOperator::CreateMul(BO->getOperand(0),
360 ConstantExpr::getShl(BOOp, Op1));
362 // Try to fold constant and into select arguments.
363 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
364 if (Instruction *R = FoldOpIntoSelect(I, SI))
366 if (isa<PHINode>(Op0))
367 if (Instruction *NV = FoldOpIntoPhi(I))
370 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
371 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
372 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
373 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
374 // place. Don't try to do this transformation in this case. Also, we
375 // require that the input operand is a shift-by-constant so that we have
376 // confidence that the shifts will get folded together. We could do this
377 // xform in more cases, but it is unlikely to be profitable.
378 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
379 isa<ConstantInt>(TrOp->getOperand(1))) {
380 // Okay, we'll do this xform. Make the shift of shift.
381 Constant *ShAmt = ConstantExpr::getZExt(COp1, TrOp->getType());
382 // (shift2 (shift1 & 0x00FF), c2)
383 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
385 // For logical shifts, the truncation has the effect of making the high
386 // part of the register be zeros. Emulate this by inserting an AND to
387 // clear the top bits as needed. This 'and' will usually be zapped by
388 // other xforms later if dead.
389 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
390 unsigned DstSize = TI->getType()->getScalarSizeInBits();
391 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
393 // The mask we constructed says what the trunc would do if occurring
394 // between the shifts. We want to know the effect *after* the second
395 // shift. We know that it is a logical shift by a constant, so adjust the
396 // mask as appropriate.
397 if (I.getOpcode() == Instruction::Shl)
398 MaskV <<= COp1->getZExtValue();
400 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
401 MaskV = MaskV.lshr(COp1->getZExtValue());
405 Value *And = Builder->CreateAnd(NSh,
406 ConstantInt::get(I.getContext(), MaskV),
409 // Return the value truncated to the interesting size.
410 return new TruncInst(And, I.getType());
414 if (Op0->hasOneUse()) {
415 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
416 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
419 switch (Op0BO->getOpcode()) {
421 case Instruction::Add:
422 case Instruction::And:
423 case Instruction::Or:
424 case Instruction::Xor: {
425 // These operators commute.
426 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
427 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
428 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
430 Value *YS = // (Y << C)
431 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
433 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
434 Op0BO->getOperand(1)->getName());
435 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
437 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
438 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
439 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
440 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
441 return BinaryOperator::CreateAnd(X, Mask);
444 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
445 Value *Op0BOOp1 = Op0BO->getOperand(1);
446 if (isLeftShift && Op0BOOp1->hasOneUse() &&
448 m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
449 m_ConstantInt(CC)))) {
450 Value *YS = // (Y << C)
451 Builder->CreateShl(Op0BO->getOperand(0), Op1,
454 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
455 V1->getName()+".mask");
456 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
461 case Instruction::Sub: {
462 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
463 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
464 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
466 Value *YS = // (Y << C)
467 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
469 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
470 Op0BO->getOperand(0)->getName());
471 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
473 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
474 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
475 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
476 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
477 return BinaryOperator::CreateAnd(X, Mask);
480 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
481 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
482 match(Op0BO->getOperand(0),
483 m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
484 m_ConstantInt(CC))) && V2 == Op1) {
485 Value *YS = // (Y << C)
486 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
488 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
489 V1->getName()+".mask");
491 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
499 // If the operand is an bitwise operator with a constant RHS, and the
500 // shift is the only use, we can pull it out of the shift.
501 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
502 bool isValid = true; // Valid only for And, Or, Xor
503 bool highBitSet = false; // Transform if high bit of constant set?
505 switch (Op0BO->getOpcode()) {
506 default: isValid = false; break; // Do not perform transform!
507 case Instruction::Add:
508 isValid = isLeftShift;
510 case Instruction::Or:
511 case Instruction::Xor:
514 case Instruction::And:
519 // If this is a signed shift right, and the high bit is modified
520 // by the logical operation, do not perform the transformation.
521 // The highBitSet boolean indicates the value of the high bit of
522 // the constant which would cause it to be modified for this
525 if (isValid && I.getOpcode() == Instruction::AShr)
526 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
529 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
532 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
533 NewShift->takeName(Op0BO);
535 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
542 // Find out if this is a shift of a shift by a constant.
543 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
544 if (ShiftOp && !ShiftOp->isShift())
547 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
549 // This is a constant shift of a constant shift. Be careful about hiding
550 // shl instructions behind bit masks. They are used to represent multiplies
551 // by a constant, and it is important that simple arithmetic expressions
552 // are still recognizable by scalar evolution.
554 // The transforms applied to shl are very similar to the transforms applied
555 // to mul by constant. We can be more aggressive about optimizing right
558 // Combinations of right and left shifts will still be optimized in
559 // DAGCombine where scalar evolution no longer applies.
561 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
562 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
563 uint32_t ShiftAmt2 = COp1->getLimitedValue(TypeBits);
564 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
565 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
566 Value *X = ShiftOp->getOperand(0);
568 IntegerType *Ty = cast<IntegerType>(I.getType());
570 // Check for (X << c1) << c2 and (X >> c1) >> c2
571 if (I.getOpcode() == ShiftOp->getOpcode()) {
572 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
573 // If this is oversized composite shift, then unsigned shifts get 0, ashr
575 if (AmtSum >= TypeBits) {
576 if (I.getOpcode() != Instruction::AShr)
577 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
578 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
581 return BinaryOperator::Create(I.getOpcode(), X,
582 ConstantInt::get(Ty, AmtSum));
585 if (ShiftAmt1 == ShiftAmt2) {
586 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
587 if (I.getOpcode() == Instruction::LShr &&
588 ShiftOp->getOpcode() == Instruction::Shl) {
589 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
590 return BinaryOperator::CreateAnd(X,
591 ConstantInt::get(I.getContext(), Mask));
593 } else if (ShiftAmt1 < ShiftAmt2) {
594 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
596 // (X >>?,exact C1) << C2 --> X << (C2-C1)
597 // The inexact version is deferred to DAGCombine so we don't hide shl
598 // behind a bit mask.
599 if (I.getOpcode() == Instruction::Shl &&
600 ShiftOp->getOpcode() != Instruction::Shl &&
601 ShiftOp->isExact()) {
602 assert(ShiftOp->getOpcode() == Instruction::LShr ||
603 ShiftOp->getOpcode() == Instruction::AShr);
604 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
605 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
607 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
608 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
612 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
613 if (I.getOpcode() == Instruction::LShr &&
614 ShiftOp->getOpcode() == Instruction::Shl) {
615 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
616 // (X <<nuw C1) >>u C2 --> X >>u (C2-C1)
617 if (ShiftOp->hasNoUnsignedWrap()) {
618 BinaryOperator *NewLShr = BinaryOperator::Create(Instruction::LShr,
620 NewLShr->setIsExact(I.isExact());
623 Value *Shift = Builder->CreateLShr(X, ShiftDiffCst);
625 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
626 return BinaryOperator::CreateAnd(Shift,
627 ConstantInt::get(I.getContext(),Mask));
630 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
631 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
632 if (I.getOpcode() == Instruction::AShr &&
633 ShiftOp->getOpcode() == Instruction::Shl) {
634 if (ShiftOp->hasNoSignedWrap()) {
635 // (X <<nsw C1) >>s C2 --> X >>s (C2-C1)
636 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
637 BinaryOperator *NewAShr = BinaryOperator::Create(Instruction::AShr,
639 NewAShr->setIsExact(I.isExact());
644 assert(ShiftAmt2 < ShiftAmt1);
645 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
647 // (X >>?exact C1) << C2 --> X >>?exact (C1-C2)
648 // The inexact version is deferred to DAGCombine so we don't hide shl
649 // behind a bit mask.
650 if (I.getOpcode() == Instruction::Shl &&
651 ShiftOp->getOpcode() != Instruction::Shl &&
652 ShiftOp->isExact()) {
653 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
654 BinaryOperator *NewShr = BinaryOperator::Create(ShiftOp->getOpcode(),
656 NewShr->setIsExact(true);
660 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
661 if (I.getOpcode() == Instruction::LShr &&
662 ShiftOp->getOpcode() == Instruction::Shl) {
663 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
664 if (ShiftOp->hasNoUnsignedWrap()) {
665 // (X <<nuw C1) >>u C2 --> X <<nuw (C1-C2)
666 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
668 NewShl->setHasNoUnsignedWrap(true);
671 Value *Shift = Builder->CreateShl(X, ShiftDiffCst);
673 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
674 return BinaryOperator::CreateAnd(Shift,
675 ConstantInt::get(I.getContext(),Mask));
678 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
679 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
680 if (I.getOpcode() == Instruction::AShr &&
681 ShiftOp->getOpcode() == Instruction::Shl) {
682 if (ShiftOp->hasNoSignedWrap()) {
683 // (X <<nsw C1) >>s C2 --> X <<nsw (C1-C2)
684 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
685 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
687 NewShl->setHasNoSignedWrap(true);
696 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
697 if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
698 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
700 return ReplaceInstUsesWith(I, V);
702 if (Instruction *V = commonShiftTransforms(I))
705 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(I.getOperand(1))) {
706 unsigned ShAmt = Op1C->getZExtValue();
708 // If the shifted-out value is known-zero, then this is a NUW shift.
709 if (!I.hasNoUnsignedWrap() &&
710 MaskedValueIsZero(I.getOperand(0),
711 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)) > 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 = SimplifyLShrInst(I.getOperand(0), I.getOperand(1),
737 return ReplaceInstUsesWith(I, V);
739 if (Instruction *R = commonShiftTransforms(I))
742 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
744 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
745 unsigned ShAmt = Op1C->getZExtValue();
747 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
748 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
749 // ctlz.i32(x)>>5 --> zext(x == 0)
750 // cttz.i32(x)>>5 --> zext(x == 0)
751 // ctpop.i32(x)>>5 --> zext(x == -1)
752 if ((II->getIntrinsicID() == Intrinsic::ctlz ||
753 II->getIntrinsicID() == Intrinsic::cttz ||
754 II->getIntrinsicID() == Intrinsic::ctpop) &&
755 isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt) {
756 bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
757 Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
758 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
759 return new ZExtInst(Cmp, II->getType());
763 // If the shifted-out value is known-zero, then this is an exact shift.
765 MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
774 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
775 if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1),
777 return ReplaceInstUsesWith(I, V);
779 if (Instruction *R = commonShiftTransforms(I))
782 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
784 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
785 unsigned ShAmt = Op1C->getZExtValue();
787 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
788 // have a sign-extend idiom.
790 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
791 // If the left shift is just shifting out partial signbits, delete the
793 if (cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
794 return ReplaceInstUsesWith(I, X);
796 // If the input is an extension from the shifted amount value, e.g.
797 // %x = zext i8 %A to i32
798 // %y = shl i32 %x, 24
800 // then turn this into "z = sext i8 A to i32".
801 if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
802 uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
803 uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
804 if (Op1C->getZExtValue() == DestBits-SrcBits)
805 return new SExtInst(ZI->getOperand(0), ZI->getType());
809 // If the shifted-out value is known-zero, then this is an exact shift.
811 MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
817 // See if we can turn a signed shr into an unsigned shr.
818 if (MaskedValueIsZero(Op0,
819 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
820 return BinaryOperator::CreateLShr(Op0, Op1);
822 // Arithmetic shifting an all-sign-bit value is a no-op.
823 unsigned NumSignBits = ComputeNumSignBits(Op0);
824 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
825 return ReplaceInstUsesWith(I, Op0);