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 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
23 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
24 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
26 // See if we can fold away this shift.
27 if (SimplifyDemandedInstructionBits(I))
30 // Try to fold constant and into select arguments.
31 if (isa<Constant>(Op0))
32 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
33 if (Instruction *R = FoldOpIntoSelect(I, SI))
36 if (Constant *CUI = dyn_cast<Constant>(Op1))
37 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
40 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
41 // Because shifts by negative values (which could occur if A were negative)
43 Value *A; const APInt *B;
44 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
45 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
46 // demand the sign bit (and many others) here??
47 Value *Rem = Builder->CreateAnd(A, ConstantInt::get(I.getType(), *B-1),
56 /// CanEvaluateShifted - See if we can compute the specified value, but shifted
57 /// logically to the left or right by some number of bits. This should return
58 /// true if the expression can be computed for the same cost as the current
59 /// expression tree. This is used to eliminate extraneous shifting from things
61 /// %C = shl i128 %A, 64
62 /// %D = shl i128 %B, 96
63 /// %E = or i128 %C, %D
64 /// %F = lshr i128 %E, 64
65 /// where the client will ask if E can be computed shifted right by 64-bits. If
66 /// this succeeds, the GetShiftedValue function will be called to produce the
68 static bool CanEvaluateShifted(Value *V, unsigned NumBits, bool isLeftShift,
70 // We can always evaluate constants shifted.
74 Instruction *I = dyn_cast<Instruction>(V);
77 // If this is the opposite shift, we can directly reuse the input of the shift
78 // if the needed bits are already zero in the input. This allows us to reuse
79 // the value which means that we don't care if the shift has multiple uses.
80 // TODO: Handle opposite shift by exact value.
82 if ((isLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
83 (!isLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
84 if (CI->getZExtValue() == NumBits) {
85 // TODO: Check that the input bits are already zero with MaskedValueIsZero
87 // If this is a truncate of a logical shr, we can truncate it to a smaller
88 // lshr iff we know that the bits we would otherwise be shifting in are
90 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
91 uint32_t BitWidth = Ty->getScalarSizeInBits();
92 if (MaskedValueIsZero(I->getOperand(0),
93 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
94 CI->getLimitedValue(BitWidth) < BitWidth) {
95 return CanEvaluateTruncated(I->getOperand(0), Ty);
102 // We can't mutate something that has multiple uses: doing so would
103 // require duplicating the instruction in general, which isn't profitable.
104 if (!I->hasOneUse()) return false;
106 switch (I->getOpcode()) {
107 default: return false;
108 case Instruction::And:
109 case Instruction::Or:
110 case Instruction::Xor:
111 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
112 return CanEvaluateShifted(I->getOperand(0), NumBits, isLeftShift, IC) &&
113 CanEvaluateShifted(I->getOperand(1), NumBits, isLeftShift, IC);
115 case Instruction::Shl: {
116 // We can often fold the shift into shifts-by-a-constant.
117 CI = dyn_cast<ConstantInt>(I->getOperand(1));
118 if (CI == 0) return false;
120 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
121 if (isLeftShift) return true;
123 // We can always turn shl(c)+shr(c) -> and(c2).
124 if (CI->getValue() == NumBits) return true;
126 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
128 // We can turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but it isn't
129 // profitable unless we know the and'd out bits are already zero.
130 if (CI->getZExtValue() > NumBits) {
131 unsigned LowBits = TypeWidth - CI->getZExtValue();
132 if (MaskedValueIsZero(I->getOperand(0),
133 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
139 case Instruction::LShr: {
140 // We can often fold the shift into shifts-by-a-constant.
141 CI = dyn_cast<ConstantInt>(I->getOperand(1));
142 if (CI == 0) return false;
144 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
145 if (!isLeftShift) return true;
147 // We can always turn lshr(c)+shl(c) -> and(c2).
148 if (CI->getValue() == NumBits) return true;
150 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
152 // We can always turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but it isn't
153 // profitable unless we know the and'd out bits are already zero.
154 if (CI->getValue().ult(TypeWidth) && CI->getZExtValue() > NumBits) {
155 unsigned LowBits = CI->getZExtValue() - NumBits;
156 if (MaskedValueIsZero(I->getOperand(0),
157 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
163 case Instruction::Select: {
164 SelectInst *SI = cast<SelectInst>(I);
165 return CanEvaluateShifted(SI->getTrueValue(), NumBits, isLeftShift, IC) &&
166 CanEvaluateShifted(SI->getFalseValue(), NumBits, isLeftShift, IC);
168 case Instruction::PHI: {
169 // We can change a phi if we can change all operands. Note that we never
170 // get into trouble with cyclic PHIs here because we only consider
171 // instructions with a single use.
172 PHINode *PN = cast<PHINode>(I);
173 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
174 if (!CanEvaluateShifted(PN->getIncomingValue(i), NumBits, isLeftShift,IC))
181 /// GetShiftedValue - When CanEvaluateShifted returned true for an expression,
182 /// this value inserts the new computation that produces the shifted value.
183 static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
185 // We can always evaluate constants shifted.
186 if (Constant *C = dyn_cast<Constant>(V)) {
188 V = IC.Builder->CreateShl(C, NumBits);
190 V = IC.Builder->CreateLShr(C, NumBits);
191 // If we got a constantexpr back, try to simplify it with TD info.
192 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
193 V = ConstantFoldConstantExpression(CE, IC.getDataLayout(),
194 IC.getTargetLibraryInfo());
198 Instruction *I = cast<Instruction>(V);
201 switch (I->getOpcode()) {
202 default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
203 case Instruction::And:
204 case Instruction::Or:
205 case Instruction::Xor:
206 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
207 I->setOperand(0, GetShiftedValue(I->getOperand(0), NumBits,isLeftShift,IC));
208 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
211 case Instruction::Shl: {
212 BinaryOperator *BO = cast<BinaryOperator>(I);
213 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
215 // We only accept shifts-by-a-constant in CanEvaluateShifted.
216 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
218 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
220 // If this is oversized composite shift, then unsigned shifts get 0.
221 unsigned NewShAmt = NumBits+CI->getZExtValue();
222 if (NewShAmt >= TypeWidth)
223 return Constant::getNullValue(I->getType());
225 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
226 BO->setHasNoUnsignedWrap(false);
227 BO->setHasNoSignedWrap(false);
231 // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
233 if (CI->getValue() == NumBits) {
234 APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
235 V = IC.Builder->CreateAnd(BO->getOperand(0),
236 ConstantInt::get(BO->getContext(), Mask));
237 if (Instruction *VI = dyn_cast<Instruction>(V)) {
244 // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
245 // the and won't be needed.
246 assert(CI->getZExtValue() > NumBits);
247 BO->setOperand(1, ConstantInt::get(BO->getType(),
248 CI->getZExtValue() - NumBits));
249 BO->setHasNoUnsignedWrap(false);
250 BO->setHasNoSignedWrap(false);
253 case Instruction::LShr: {
254 BinaryOperator *BO = cast<BinaryOperator>(I);
255 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
256 // We only accept shifts-by-a-constant in CanEvaluateShifted.
257 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
259 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
261 // If this is oversized composite shift, then unsigned shifts get 0.
262 unsigned NewShAmt = NumBits+CI->getZExtValue();
263 if (NewShAmt >= TypeWidth)
264 return Constant::getNullValue(BO->getType());
266 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
267 BO->setIsExact(false);
271 // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
273 if (CI->getValue() == NumBits) {
274 APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
275 V = IC.Builder->CreateAnd(I->getOperand(0),
276 ConstantInt::get(BO->getContext(), Mask));
277 if (Instruction *VI = dyn_cast<Instruction>(V)) {
284 // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
285 // the and won't be needed.
286 assert(CI->getZExtValue() > NumBits);
287 BO->setOperand(1, ConstantInt::get(BO->getType(),
288 CI->getZExtValue() - NumBits));
289 BO->setIsExact(false);
293 case Instruction::Select:
294 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
295 I->setOperand(2, GetShiftedValue(I->getOperand(2), NumBits,isLeftShift,IC));
297 case Instruction::PHI: {
298 // We can change a phi if we can change all operands. Note that we never
299 // get into trouble with cyclic PHIs here because we only consider
300 // instructions with a single use.
301 PHINode *PN = cast<PHINode>(I);
302 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
303 PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i),
304 NumBits, isLeftShift, IC));
312 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
314 bool isLeftShift = I.getOpcode() == Instruction::Shl;
316 ConstantInt *COp1 = nullptr;
317 if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(Op1))
318 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
319 else if (ConstantVector *CV = dyn_cast<ConstantVector>(Op1))
320 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
322 COp1 = dyn_cast<ConstantInt>(Op1);
327 // See if we can propagate this shift into the input, this covers the trivial
328 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
329 if (I.getOpcode() != Instruction::AShr &&
330 CanEvaluateShifted(Op0, COp1->getZExtValue(), isLeftShift, *this)) {
331 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
332 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
334 return ReplaceInstUsesWith(I,
335 GetShiftedValue(Op0, COp1->getZExtValue(), isLeftShift, *this));
339 // See if we can simplify any instructions used by the instruction whose sole
340 // purpose is to compute bits we don't care about.
341 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
343 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
346 if (COp1->uge(TypeBits)) {
347 if (I.getOpcode() != Instruction::AShr)
348 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
349 // ashr i32 X, 32 --> ashr i32 X, 31
350 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
354 // ((X*C1) << C2) == (X * (C1 << C2))
355 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
356 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
357 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
358 return BinaryOperator::CreateMul(BO->getOperand(0),
359 ConstantExpr::getShl(BOOp, COp1));
361 // Try to fold constant and into select arguments.
362 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
363 if (Instruction *R = FoldOpIntoSelect(I, SI))
365 if (isa<PHINode>(Op0))
366 if (Instruction *NV = FoldOpIntoPhi(I))
369 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
370 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
371 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
372 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
373 // place. Don't try to do this transformation in this case. Also, we
374 // require that the input operand is a shift-by-constant so that we have
375 // confidence that the shifts will get folded together. We could do this
376 // xform in more cases, but it is unlikely to be profitable.
377 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
378 isa<ConstantInt>(TrOp->getOperand(1))) {
379 // Okay, we'll do this xform. Make the shift of shift.
380 Constant *ShAmt = ConstantExpr::getZExt(COp1, TrOp->getType());
381 // (shift2 (shift1 & 0x00FF), c2)
382 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
384 // For logical shifts, the truncation has the effect of making the high
385 // part of the register be zeros. Emulate this by inserting an AND to
386 // clear the top bits as needed. This 'and' will usually be zapped by
387 // other xforms later if dead.
388 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
389 unsigned DstSize = TI->getType()->getScalarSizeInBits();
390 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
392 // The mask we constructed says what the trunc would do if occurring
393 // between the shifts. We want to know the effect *after* the second
394 // shift. We know that it is a logical shift by a constant, so adjust the
395 // mask as appropriate.
396 if (I.getOpcode() == Instruction::Shl)
397 MaskV <<= COp1->getZExtValue();
399 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
400 MaskV = MaskV.lshr(COp1->getZExtValue());
404 Value *And = Builder->CreateAnd(NSh,
405 ConstantInt::get(I.getContext(), MaskV),
408 // Return the value truncated to the interesting size.
409 return new TruncInst(And, I.getType());
413 if (Op0->hasOneUse()) {
414 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
415 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
418 switch (Op0BO->getOpcode()) {
420 case Instruction::Add:
421 case Instruction::And:
422 case Instruction::Or:
423 case Instruction::Xor: {
424 // These operators commute.
425 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
426 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
427 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
429 Value *YS = // (Y << C)
430 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
432 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
433 Op0BO->getOperand(1)->getName());
434 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
435 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
436 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
439 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
440 Value *Op0BOOp1 = Op0BO->getOperand(1);
441 if (isLeftShift && Op0BOOp1->hasOneUse() &&
443 m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
444 m_ConstantInt(CC)))) {
445 Value *YS = // (Y << C)
446 Builder->CreateShl(Op0BO->getOperand(0), Op1,
449 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
450 V1->getName()+".mask");
451 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
456 case Instruction::Sub: {
457 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
458 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
459 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
461 Value *YS = // (Y << C)
462 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
464 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
465 Op0BO->getOperand(0)->getName());
466 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
467 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
468 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
471 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
472 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
473 match(Op0BO->getOperand(0),
474 m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
475 m_ConstantInt(CC))) && V2 == Op1) {
476 Value *YS = // (Y << C)
477 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
479 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
480 V1->getName()+".mask");
482 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
490 // If the operand is an bitwise operator with a constant RHS, and the
491 // shift is the only use, we can pull it out of the shift.
492 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
493 bool isValid = true; // Valid only for And, Or, Xor
494 bool highBitSet = false; // Transform if high bit of constant set?
496 switch (Op0BO->getOpcode()) {
497 default: isValid = false; break; // Do not perform transform!
498 case Instruction::Add:
499 isValid = isLeftShift;
501 case Instruction::Or:
502 case Instruction::Xor:
505 case Instruction::And:
510 // If this is a signed shift right, and the high bit is modified
511 // by the logical operation, do not perform the transformation.
512 // The highBitSet boolean indicates the value of the high bit of
513 // the constant which would cause it to be modified for this
516 if (isValid && I.getOpcode() == Instruction::AShr)
517 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
520 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
523 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
524 NewShift->takeName(Op0BO);
526 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
533 // Find out if this is a shift of a shift by a constant.
534 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
535 if (ShiftOp && !ShiftOp->isShift())
538 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
540 // This is a constant shift of a constant shift. Be careful about hiding
541 // shl instructions behind bit masks. They are used to represent multiplies
542 // by a constant, and it is important that simple arithmetic expressions
543 // are still recognizable by scalar evolution.
545 // The transforms applied to shl are very similar to the transforms applied
546 // to mul by constant. We can be more aggressive about optimizing right
549 // Combinations of right and left shifts will still be optimized in
550 // DAGCombine where scalar evolution no longer applies.
552 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
553 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
554 uint32_t ShiftAmt2 = COp1->getLimitedValue(TypeBits);
555 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
556 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
557 Value *X = ShiftOp->getOperand(0);
559 IntegerType *Ty = cast<IntegerType>(I.getType());
561 // Check for (X << c1) << c2 and (X >> c1) >> c2
562 if (I.getOpcode() == ShiftOp->getOpcode()) {
563 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
564 // If this is oversized composite shift, then unsigned shifts get 0, ashr
566 if (AmtSum >= TypeBits) {
567 if (I.getOpcode() != Instruction::AShr)
568 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
569 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
572 return BinaryOperator::Create(I.getOpcode(), X,
573 ConstantInt::get(Ty, AmtSum));
576 if (ShiftAmt1 == ShiftAmt2) {
577 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
578 if (I.getOpcode() == Instruction::LShr &&
579 ShiftOp->getOpcode() == Instruction::Shl) {
580 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
581 return BinaryOperator::CreateAnd(X,
582 ConstantInt::get(I.getContext(), Mask));
584 } else if (ShiftAmt1 < ShiftAmt2) {
585 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
587 // (X >>?,exact C1) << C2 --> X << (C2-C1)
588 // The inexact version is deferred to DAGCombine so we don't hide shl
589 // behind a bit mask.
590 if (I.getOpcode() == Instruction::Shl &&
591 ShiftOp->getOpcode() != Instruction::Shl &&
592 ShiftOp->isExact()) {
593 assert(ShiftOp->getOpcode() == Instruction::LShr ||
594 ShiftOp->getOpcode() == Instruction::AShr);
595 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
596 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
598 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
599 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
603 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
604 if (I.getOpcode() == Instruction::LShr &&
605 ShiftOp->getOpcode() == Instruction::Shl) {
606 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
607 // (X <<nuw C1) >>u C2 --> X >>u (C2-C1)
608 if (ShiftOp->hasNoUnsignedWrap()) {
609 BinaryOperator *NewLShr = BinaryOperator::Create(Instruction::LShr,
611 NewLShr->setIsExact(I.isExact());
614 Value *Shift = Builder->CreateLShr(X, ShiftDiffCst);
616 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
617 return BinaryOperator::CreateAnd(Shift,
618 ConstantInt::get(I.getContext(),Mask));
621 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
622 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
623 if (I.getOpcode() == Instruction::AShr &&
624 ShiftOp->getOpcode() == Instruction::Shl) {
625 if (ShiftOp->hasNoSignedWrap()) {
626 // (X <<nsw C1) >>s C2 --> X >>s (C2-C1)
627 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
628 BinaryOperator *NewAShr = BinaryOperator::Create(Instruction::AShr,
630 NewAShr->setIsExact(I.isExact());
635 assert(ShiftAmt2 < ShiftAmt1);
636 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
638 // (X >>?exact C1) << C2 --> X >>?exact (C1-C2)
639 // The inexact version is deferred to DAGCombine so we don't hide shl
640 // behind a bit mask.
641 if (I.getOpcode() == Instruction::Shl &&
642 ShiftOp->getOpcode() != Instruction::Shl &&
643 ShiftOp->isExact()) {
644 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
645 BinaryOperator *NewShr = BinaryOperator::Create(ShiftOp->getOpcode(),
647 NewShr->setIsExact(true);
651 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
652 if (I.getOpcode() == Instruction::LShr &&
653 ShiftOp->getOpcode() == Instruction::Shl) {
654 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
655 if (ShiftOp->hasNoUnsignedWrap()) {
656 // (X <<nuw C1) >>u C2 --> X <<nuw (C1-C2)
657 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
659 NewShl->setHasNoUnsignedWrap(true);
662 Value *Shift = Builder->CreateShl(X, ShiftDiffCst);
664 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
665 return BinaryOperator::CreateAnd(Shift,
666 ConstantInt::get(I.getContext(),Mask));
669 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
670 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
671 if (I.getOpcode() == Instruction::AShr &&
672 ShiftOp->getOpcode() == Instruction::Shl) {
673 if (ShiftOp->hasNoSignedWrap()) {
674 // (X <<nsw C1) >>s C2 --> X <<nsw (C1-C2)
675 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
676 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
678 NewShl->setHasNoSignedWrap(true);
687 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
688 if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
689 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
691 return ReplaceInstUsesWith(I, V);
693 if (Instruction *V = commonShiftTransforms(I))
696 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(I.getOperand(1))) {
697 unsigned ShAmt = Op1C->getZExtValue();
699 // If the shifted-out value is known-zero, then this is a NUW shift.
700 if (!I.hasNoUnsignedWrap() &&
701 MaskedValueIsZero(I.getOperand(0),
702 APInt::getHighBitsSet(Op1C->getBitWidth(), ShAmt))) {
703 I.setHasNoUnsignedWrap();
707 // If the shifted out value is all signbits, this is a NSW shift.
708 if (!I.hasNoSignedWrap() &&
709 ComputeNumSignBits(I.getOperand(0)) > ShAmt) {
710 I.setHasNoSignedWrap();
715 // (C1 << A) << C2 -> (C1 << C2) << A
718 if (match(I.getOperand(0), m_OneUse(m_Shl(m_Constant(C1), m_Value(A)))) &&
719 match(I.getOperand(1), m_Constant(C2)))
720 return BinaryOperator::CreateShl(ConstantExpr::getShl(C1, C2), A);
725 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
726 if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1),
728 return ReplaceInstUsesWith(I, V);
730 if (Instruction *R = commonShiftTransforms(I))
733 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
735 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
736 unsigned ShAmt = Op1C->getZExtValue();
738 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
739 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
740 // ctlz.i32(x)>>5 --> zext(x == 0)
741 // cttz.i32(x)>>5 --> zext(x == 0)
742 // ctpop.i32(x)>>5 --> zext(x == -1)
743 if ((II->getIntrinsicID() == Intrinsic::ctlz ||
744 II->getIntrinsicID() == Intrinsic::cttz ||
745 II->getIntrinsicID() == Intrinsic::ctpop) &&
746 isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt) {
747 bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
748 Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
749 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
750 return new ZExtInst(Cmp, II->getType());
754 // If the shifted-out value is known-zero, then this is an exact shift.
756 MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
765 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
766 if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1),
768 return ReplaceInstUsesWith(I, V);
770 if (Instruction *R = commonShiftTransforms(I))
773 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
775 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
776 unsigned ShAmt = Op1C->getZExtValue();
778 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
779 // have a sign-extend idiom.
781 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
782 // If the left shift is just shifting out partial signbits, delete the
784 if (cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
785 return ReplaceInstUsesWith(I, X);
787 // If the input is an extension from the shifted amount value, e.g.
788 // %x = zext i8 %A to i32
789 // %y = shl i32 %x, 24
791 // then turn this into "z = sext i8 A to i32".
792 if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
793 uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
794 uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
795 if (Op1C->getZExtValue() == DestBits-SrcBits)
796 return new SExtInst(ZI->getOperand(0), ZI->getType());
800 // If the shifted-out value is known-zero, then this is an exact shift.
802 MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
808 // See if we can turn a signed shr into an unsigned shr.
809 if (MaskedValueIsZero(Op0,
810 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
811 return BinaryOperator::CreateLShr(Op0, Op1);
813 // Arithmetic shifting an all-sign-bit value is a no-op.
814 unsigned NumSignBits = ComputeNumSignBits(Op0);
815 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
816 return ReplaceInstUsesWith(I, Op0);