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,
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.
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) &&
115 CanEvaluateShifted(I->getOperand(1), NumBits, isLeftShift, IC);
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 == 0) 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 (MaskedValueIsZero(I->getOperand(0),
135 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
141 case Instruction::LShr: {
142 // We can often fold the shift into shifts-by-a-constant.
143 CI = dyn_cast<ConstantInt>(I->getOperand(1));
144 if (CI == 0) return false;
146 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
147 if (!isLeftShift) return true;
149 // We can always turn lshr(c)+shl(c) -> and(c2).
150 if (CI->getValue() == NumBits) return true;
152 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
154 // We can always turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but it isn't
155 // profitable unless we know the and'd out bits are already zero.
156 if (CI->getValue().ult(TypeWidth) && CI->getZExtValue() > NumBits) {
157 unsigned LowBits = CI->getZExtValue() - NumBits;
158 if (MaskedValueIsZero(I->getOperand(0),
159 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
165 case Instruction::Select: {
166 SelectInst *SI = cast<SelectInst>(I);
167 return CanEvaluateShifted(SI->getTrueValue(), NumBits, isLeftShift, IC) &&
168 CanEvaluateShifted(SI->getFalseValue(), NumBits, isLeftShift, IC);
170 case Instruction::PHI: {
171 // We can change a phi if we can change all operands. Note that we never
172 // get into trouble with cyclic PHIs here because we only consider
173 // instructions with a single use.
174 PHINode *PN = cast<PHINode>(I);
175 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
176 if (!CanEvaluateShifted(PN->getIncomingValue(i), NumBits, isLeftShift,IC))
183 /// GetShiftedValue - When CanEvaluateShifted returned true for an expression,
184 /// this value inserts the new computation that produces the shifted value.
185 static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
187 // We can always evaluate constants shifted.
188 if (Constant *C = dyn_cast<Constant>(V)) {
190 V = IC.Builder->CreateShl(C, NumBits);
192 V = IC.Builder->CreateLShr(C, NumBits);
193 // If we got a constantexpr back, try to simplify it with TD info.
194 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
195 V = ConstantFoldConstantExpression(CE, IC.getDataLayout(),
196 IC.getTargetLibraryInfo());
200 Instruction *I = cast<Instruction>(V);
203 switch (I->getOpcode()) {
204 default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
205 case Instruction::And:
206 case Instruction::Or:
207 case Instruction::Xor:
208 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
209 I->setOperand(0, GetShiftedValue(I->getOperand(0), NumBits,isLeftShift,IC));
210 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
213 case Instruction::Shl: {
214 BinaryOperator *BO = cast<BinaryOperator>(I);
215 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
217 // We only accept shifts-by-a-constant in CanEvaluateShifted.
218 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
220 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
222 // If this is oversized composite shift, then unsigned shifts get 0.
223 unsigned NewShAmt = NumBits+CI->getZExtValue();
224 if (NewShAmt >= TypeWidth)
225 return Constant::getNullValue(I->getType());
227 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
228 BO->setHasNoUnsignedWrap(false);
229 BO->setHasNoSignedWrap(false);
233 // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
235 if (CI->getValue() == NumBits) {
236 APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
237 V = IC.Builder->CreateAnd(BO->getOperand(0),
238 ConstantInt::get(BO->getContext(), Mask));
239 if (Instruction *VI = dyn_cast<Instruction>(V)) {
246 // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
247 // the and won't be needed.
248 assert(CI->getZExtValue() > NumBits);
249 BO->setOperand(1, ConstantInt::get(BO->getType(),
250 CI->getZExtValue() - NumBits));
251 BO->setHasNoUnsignedWrap(false);
252 BO->setHasNoSignedWrap(false);
255 case Instruction::LShr: {
256 BinaryOperator *BO = cast<BinaryOperator>(I);
257 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
258 // We only accept shifts-by-a-constant in CanEvaluateShifted.
259 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
261 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
263 // If this is oversized composite shift, then unsigned shifts get 0.
264 unsigned NewShAmt = NumBits+CI->getZExtValue();
265 if (NewShAmt >= TypeWidth)
266 return Constant::getNullValue(BO->getType());
268 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
269 BO->setIsExact(false);
273 // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
275 if (CI->getValue() == NumBits) {
276 APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
277 V = IC.Builder->CreateAnd(I->getOperand(0),
278 ConstantInt::get(BO->getContext(), Mask));
279 if (Instruction *VI = dyn_cast<Instruction>(V)) {
286 // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
287 // the and won't be needed.
288 assert(CI->getZExtValue() > NumBits);
289 BO->setOperand(1, ConstantInt::get(BO->getType(),
290 CI->getZExtValue() - NumBits));
291 BO->setIsExact(false);
295 case Instruction::Select:
296 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
297 I->setOperand(2, GetShiftedValue(I->getOperand(2), NumBits,isLeftShift,IC));
299 case Instruction::PHI: {
300 // We can change a phi if we can change all operands. Note that we never
301 // get into trouble with cyclic PHIs here because we only consider
302 // instructions with a single use.
303 PHINode *PN = cast<PHINode>(I);
304 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
305 PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i),
306 NumBits, isLeftShift, IC));
314 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
316 bool isLeftShift = I.getOpcode() == Instruction::Shl;
318 ConstantInt *COp1 = nullptr;
319 if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(Op1))
320 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
321 else if (ConstantVector *CV = dyn_cast<ConstantVector>(Op1))
322 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
324 COp1 = dyn_cast<ConstantInt>(Op1);
329 // See if we can propagate this shift into the input, this covers the trivial
330 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
331 if (I.getOpcode() != Instruction::AShr &&
332 CanEvaluateShifted(Op0, COp1->getZExtValue(), isLeftShift, *this)) {
333 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
334 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
336 return ReplaceInstUsesWith(I,
337 GetShiftedValue(Op0, COp1->getZExtValue(), isLeftShift, *this));
341 // See if we can simplify any instructions used by the instruction whose sole
342 // purpose is to compute bits we don't care about.
343 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
345 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
348 if (COp1->uge(TypeBits)) {
349 if (I.getOpcode() != Instruction::AShr)
350 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
351 // ashr i32 X, 32 --> ashr i32 X, 31
352 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
356 // ((X*C1) << C2) == (X * (C1 << C2))
357 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
358 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
359 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
360 return BinaryOperator::CreateMul(BO->getOperand(0),
361 ConstantExpr::getShl(BOOp, Op1));
363 // Try to fold constant and into select arguments.
364 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
365 if (Instruction *R = FoldOpIntoSelect(I, SI))
367 if (isa<PHINode>(Op0))
368 if (Instruction *NV = FoldOpIntoPhi(I))
371 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
372 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
373 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
374 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
375 // place. Don't try to do this transformation in this case. Also, we
376 // require that the input operand is a shift-by-constant so that we have
377 // confidence that the shifts will get folded together. We could do this
378 // xform in more cases, but it is unlikely to be profitable.
379 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
380 isa<ConstantInt>(TrOp->getOperand(1))) {
381 // Okay, we'll do this xform. Make the shift of shift.
382 Constant *ShAmt = ConstantExpr::getZExt(COp1, TrOp->getType());
383 // (shift2 (shift1 & 0x00FF), c2)
384 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
386 // For logical shifts, the truncation has the effect of making the high
387 // part of the register be zeros. Emulate this by inserting an AND to
388 // clear the top bits as needed. This 'and' will usually be zapped by
389 // other xforms later if dead.
390 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
391 unsigned DstSize = TI->getType()->getScalarSizeInBits();
392 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
394 // The mask we constructed says what the trunc would do if occurring
395 // between the shifts. We want to know the effect *after* the second
396 // shift. We know that it is a logical shift by a constant, so adjust the
397 // mask as appropriate.
398 if (I.getOpcode() == Instruction::Shl)
399 MaskV <<= COp1->getZExtValue();
401 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
402 MaskV = MaskV.lshr(COp1->getZExtValue());
406 Value *And = Builder->CreateAnd(NSh,
407 ConstantInt::get(I.getContext(), MaskV),
410 // Return the value truncated to the interesting size.
411 return new TruncInst(And, I.getType());
415 if (Op0->hasOneUse()) {
416 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
417 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
420 switch (Op0BO->getOpcode()) {
422 case Instruction::Add:
423 case Instruction::And:
424 case Instruction::Or:
425 case Instruction::Xor: {
426 // These operators commute.
427 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
428 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
429 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
431 Value *YS = // (Y << C)
432 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
434 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
435 Op0BO->getOperand(1)->getName());
436 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
438 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
439 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
440 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
441 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
442 return BinaryOperator::CreateAnd(X, Mask);
445 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
446 Value *Op0BOOp1 = Op0BO->getOperand(1);
447 if (isLeftShift && Op0BOOp1->hasOneUse() &&
449 m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
450 m_ConstantInt(CC)))) {
451 Value *YS = // (Y << C)
452 Builder->CreateShl(Op0BO->getOperand(0), Op1,
455 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
456 V1->getName()+".mask");
457 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
462 case Instruction::Sub: {
463 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
464 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
465 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
467 Value *YS = // (Y << C)
468 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
470 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
471 Op0BO->getOperand(0)->getName());
472 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
474 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
475 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
476 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
477 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
478 return BinaryOperator::CreateAnd(X, Mask);
481 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
482 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
483 match(Op0BO->getOperand(0),
484 m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
485 m_ConstantInt(CC))) && V2 == Op1) {
486 Value *YS = // (Y << C)
487 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
489 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
490 V1->getName()+".mask");
492 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
500 // If the operand is an bitwise operator with a constant RHS, and the
501 // shift is the only use, we can pull it out of the shift.
502 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
503 bool isValid = true; // Valid only for And, Or, Xor
504 bool highBitSet = false; // Transform if high bit of constant set?
506 switch (Op0BO->getOpcode()) {
507 default: isValid = false; break; // Do not perform transform!
508 case Instruction::Add:
509 isValid = isLeftShift;
511 case Instruction::Or:
512 case Instruction::Xor:
515 case Instruction::And:
520 // If this is a signed shift right, and the high bit is modified
521 // by the logical operation, do not perform the transformation.
522 // The highBitSet boolean indicates the value of the high bit of
523 // the constant which would cause it to be modified for this
526 if (isValid && I.getOpcode() == Instruction::AShr)
527 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
530 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
533 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
534 NewShift->takeName(Op0BO);
536 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
543 // Find out if this is a shift of a shift by a constant.
544 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
545 if (ShiftOp && !ShiftOp->isShift())
548 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
550 // This is a constant shift of a constant shift. Be careful about hiding
551 // shl instructions behind bit masks. They are used to represent multiplies
552 // by a constant, and it is important that simple arithmetic expressions
553 // are still recognizable by scalar evolution.
555 // The transforms applied to shl are very similar to the transforms applied
556 // to mul by constant. We can be more aggressive about optimizing right
559 // Combinations of right and left shifts will still be optimized in
560 // DAGCombine where scalar evolution no longer applies.
562 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
563 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
564 uint32_t ShiftAmt2 = COp1->getLimitedValue(TypeBits);
565 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
566 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
567 Value *X = ShiftOp->getOperand(0);
569 IntegerType *Ty = cast<IntegerType>(I.getType());
571 // Check for (X << c1) << c2 and (X >> c1) >> c2
572 if (I.getOpcode() == ShiftOp->getOpcode()) {
573 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
574 // If this is oversized composite shift, then unsigned shifts get 0, ashr
576 if (AmtSum >= TypeBits) {
577 if (I.getOpcode() != Instruction::AShr)
578 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
579 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
582 return BinaryOperator::Create(I.getOpcode(), X,
583 ConstantInt::get(Ty, AmtSum));
586 if (ShiftAmt1 == ShiftAmt2) {
587 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
588 if (I.getOpcode() == Instruction::LShr &&
589 ShiftOp->getOpcode() == Instruction::Shl) {
590 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
591 return BinaryOperator::CreateAnd(X,
592 ConstantInt::get(I.getContext(), Mask));
594 } else if (ShiftAmt1 < ShiftAmt2) {
595 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
597 // (X >>?,exact C1) << C2 --> X << (C2-C1)
598 // The inexact version is deferred to DAGCombine so we don't hide shl
599 // behind a bit mask.
600 if (I.getOpcode() == Instruction::Shl &&
601 ShiftOp->getOpcode() != Instruction::Shl &&
602 ShiftOp->isExact()) {
603 assert(ShiftOp->getOpcode() == Instruction::LShr ||
604 ShiftOp->getOpcode() == Instruction::AShr);
605 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
606 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
608 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
609 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
613 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
614 if (I.getOpcode() == Instruction::LShr &&
615 ShiftOp->getOpcode() == Instruction::Shl) {
616 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
617 // (X <<nuw C1) >>u C2 --> X >>u (C2-C1)
618 if (ShiftOp->hasNoUnsignedWrap()) {
619 BinaryOperator *NewLShr = BinaryOperator::Create(Instruction::LShr,
621 NewLShr->setIsExact(I.isExact());
624 Value *Shift = Builder->CreateLShr(X, ShiftDiffCst);
626 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
627 return BinaryOperator::CreateAnd(Shift,
628 ConstantInt::get(I.getContext(),Mask));
631 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
632 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
633 if (I.getOpcode() == Instruction::AShr &&
634 ShiftOp->getOpcode() == Instruction::Shl) {
635 if (ShiftOp->hasNoSignedWrap()) {
636 // (X <<nsw C1) >>s C2 --> X >>s (C2-C1)
637 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
638 BinaryOperator *NewAShr = BinaryOperator::Create(Instruction::AShr,
640 NewAShr->setIsExact(I.isExact());
645 assert(ShiftAmt2 < ShiftAmt1);
646 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
648 // (X >>?exact C1) << C2 --> X >>?exact (C1-C2)
649 // The inexact version is deferred to DAGCombine so we don't hide shl
650 // behind a bit mask.
651 if (I.getOpcode() == Instruction::Shl &&
652 ShiftOp->getOpcode() != Instruction::Shl &&
653 ShiftOp->isExact()) {
654 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
655 BinaryOperator *NewShr = BinaryOperator::Create(ShiftOp->getOpcode(),
657 NewShr->setIsExact(true);
661 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
662 if (I.getOpcode() == Instruction::LShr &&
663 ShiftOp->getOpcode() == Instruction::Shl) {
664 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
665 if (ShiftOp->hasNoUnsignedWrap()) {
666 // (X <<nuw C1) >>u C2 --> X <<nuw (C1-C2)
667 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
669 NewShl->setHasNoUnsignedWrap(true);
672 Value *Shift = Builder->CreateShl(X, ShiftDiffCst);
674 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
675 return BinaryOperator::CreateAnd(Shift,
676 ConstantInt::get(I.getContext(),Mask));
679 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
680 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
681 if (I.getOpcode() == Instruction::AShr &&
682 ShiftOp->getOpcode() == Instruction::Shl) {
683 if (ShiftOp->hasNoSignedWrap()) {
684 // (X <<nsw C1) >>s C2 --> X <<nsw (C1-C2)
685 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
686 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
688 NewShl->setHasNoSignedWrap(true);
697 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
698 if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
699 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
701 return ReplaceInstUsesWith(I, V);
703 if (Instruction *V = commonShiftTransforms(I))
706 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(I.getOperand(1))) {
707 unsigned ShAmt = Op1C->getZExtValue();
709 // If the shifted-out value is known-zero, then this is a NUW shift.
710 if (!I.hasNoUnsignedWrap() &&
711 MaskedValueIsZero(I.getOperand(0),
712 APInt::getHighBitsSet(Op1C->getBitWidth(), ShAmt))) {
713 I.setHasNoUnsignedWrap();
717 // If the shifted out value is all signbits, this is a NSW shift.
718 if (!I.hasNoSignedWrap() &&
719 ComputeNumSignBits(I.getOperand(0)) > ShAmt) {
720 I.setHasNoSignedWrap();
725 // (C1 << A) << C2 -> (C1 << C2) << A
728 if (match(I.getOperand(0), m_OneUse(m_Shl(m_Constant(C1), m_Value(A)))) &&
729 match(I.getOperand(1), m_Constant(C2)))
730 return BinaryOperator::CreateShl(ConstantExpr::getShl(C1, C2), A);
735 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
736 if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1),
738 return ReplaceInstUsesWith(I, V);
740 if (Instruction *R = commonShiftTransforms(I))
743 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
745 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
746 unsigned ShAmt = Op1C->getZExtValue();
748 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
749 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
750 // ctlz.i32(x)>>5 --> zext(x == 0)
751 // cttz.i32(x)>>5 --> zext(x == 0)
752 // ctpop.i32(x)>>5 --> zext(x == -1)
753 if ((II->getIntrinsicID() == Intrinsic::ctlz ||
754 II->getIntrinsicID() == Intrinsic::cttz ||
755 II->getIntrinsicID() == Intrinsic::ctpop) &&
756 isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt) {
757 bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
758 Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
759 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
760 return new ZExtInst(Cmp, II->getType());
764 // If the shifted-out value is known-zero, then this is an exact shift.
766 MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
775 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
776 if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1),
778 return ReplaceInstUsesWith(I, V);
780 if (Instruction *R = commonShiftTransforms(I))
783 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
785 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
786 unsigned ShAmt = Op1C->getZExtValue();
788 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
789 // have a sign-extend idiom.
791 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
792 // If the left shift is just shifting out partial signbits, delete the
794 if (cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
795 return ReplaceInstUsesWith(I, X);
797 // If the input is an extension from the shifted amount value, e.g.
798 // %x = zext i8 %A to i32
799 // %y = shl i32 %x, 24
801 // then turn this into "z = sext i8 A to i32".
802 if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
803 uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
804 uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
805 if (Op1C->getZExtValue() == DestBits-SrcBits)
806 return new SExtInst(ZI->getOperand(0), ZI->getType());
810 // If the shifted-out value is known-zero, then this is an exact shift.
812 MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
818 // See if we can turn a signed shr into an unsigned shr.
819 if (MaskedValueIsZero(Op0,
820 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
821 return BinaryOperator::CreateLShr(Op0, Op1);
823 // Arithmetic shifting an all-sign-bit value is a no-op.
824 unsigned NumSignBits = ComputeNumSignBits(Op0);
825 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
826 return ReplaceInstUsesWith(I, Op0);