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/IntrinsicInst.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Support/PatternMatch.h"
19 using namespace PatternMatch;
21 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
22 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
23 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
25 // See if we can fold away this shift.
26 if (SimplifyDemandedInstructionBits(I))
29 // Try to fold constant and into select arguments.
30 if (isa<Constant>(Op0))
31 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
32 if (Instruction *R = FoldOpIntoSelect(I, SI))
35 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
36 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
39 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
40 // Because shifts by negative values are undefined.
41 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op1))
42 if (BO->hasOneUse() && BO->getOpcode() == Instruction::SRem)
43 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
44 if (CI->getValue().isPowerOf2()) {
45 Constant *C = ConstantInt::get(BO->getType(), CI->getValue()-1);
46 Value *Rem = Builder->CreateAnd(BO->getOperand(0), C, BO->getName());
54 /// CanEvaluateShifted - See if we can compute the specified value, but shifted
55 /// logically to the left or right by some number of bits. This should return
56 /// true if the expression can be computed for the same cost as the current
57 /// expression tree. This is used to eliminate extraneous shifting from things
59 /// %C = shl i128 %A, 64
60 /// %D = shl i128 %B, 96
61 /// %E = or i128 %C, %D
62 /// %F = lshr i128 %E, 64
63 /// where the client will ask if E can be computed shifted right by 64-bits. If
64 /// this succeeds, the GetShiftedValue function will be called to produce the
66 static bool CanEvaluateShifted(Value *V, unsigned NumBits, bool isLeftShift,
68 // We can always evaluate constants shifted.
72 Instruction *I = dyn_cast<Instruction>(V);
75 // If this is the opposite shift, we can directly reuse the input of the shift
76 // if the needed bits are already zero in the input. This allows us to reuse
77 // the value which means that we don't care if the shift has multiple uses.
78 // TODO: Handle opposite shift by exact value.
80 if ((isLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
81 (!isLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
82 if (CI->getZExtValue() == NumBits) {
83 // TODO: Check that the input bits are already zero with MaskedValueIsZero
85 // If this is a truncate of a logical shr, we can truncate it to a smaller
86 // lshr iff we know that the bits we would otherwise be shifting in are
88 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
89 uint32_t BitWidth = Ty->getScalarSizeInBits();
90 if (MaskedValueIsZero(I->getOperand(0),
91 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
92 CI->getLimitedValue(BitWidth) < BitWidth) {
93 return CanEvaluateTruncated(I->getOperand(0), Ty);
100 // We can't mutate something that has multiple uses: doing so would
101 // require duplicating the instruction in general, which isn't profitable.
102 if (!I->hasOneUse()) return false;
104 switch (I->getOpcode()) {
105 default: return false;
106 case Instruction::And:
107 case Instruction::Or:
108 case Instruction::Xor:
109 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
110 return CanEvaluateShifted(I->getOperand(0), NumBits, isLeftShift, IC) &&
111 CanEvaluateShifted(I->getOperand(1), NumBits, isLeftShift, IC);
113 case Instruction::Shl: {
114 // We can often fold the shift into shifts-by-a-constant.
115 CI = dyn_cast<ConstantInt>(I->getOperand(1));
116 if (CI == 0) return false;
118 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
119 if (isLeftShift) return true;
121 // We can always turn shl(c)+shr(c) -> and(c2).
122 if (CI->getValue() == NumBits) return true;
124 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
126 // We can turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but it isn't
127 // profitable unless we know the and'd out bits are already zero.
128 if (CI->getZExtValue() > NumBits) {
129 unsigned LowBits = TypeWidth - CI->getZExtValue();
130 if (MaskedValueIsZero(I->getOperand(0),
131 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
137 case Instruction::LShr: {
138 // We can often fold the shift into shifts-by-a-constant.
139 CI = dyn_cast<ConstantInt>(I->getOperand(1));
140 if (CI == 0) return false;
142 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
143 if (!isLeftShift) return true;
145 // We can always turn lshr(c)+shl(c) -> and(c2).
146 if (CI->getValue() == NumBits) return true;
148 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
150 // We can always turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but it isn't
151 // profitable unless we know the and'd out bits are already zero.
152 if (CI->getZExtValue() > NumBits) {
153 unsigned LowBits = CI->getZExtValue() - NumBits;
154 if (MaskedValueIsZero(I->getOperand(0),
155 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
161 case Instruction::Select: {
162 SelectInst *SI = cast<SelectInst>(I);
163 return CanEvaluateShifted(SI->getTrueValue(), NumBits, isLeftShift, IC) &&
164 CanEvaluateShifted(SI->getFalseValue(), NumBits, isLeftShift, IC);
166 case Instruction::PHI: {
167 // We can change a phi if we can change all operands. Note that we never
168 // get into trouble with cyclic PHIs here because we only consider
169 // instructions with a single use.
170 PHINode *PN = cast<PHINode>(I);
171 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
172 if (!CanEvaluateShifted(PN->getIncomingValue(i), NumBits, isLeftShift,IC))
179 /// GetShiftedValue - When CanEvaluateShifted returned true for an expression,
180 /// this value inserts the new computation that produces the shifted value.
181 static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
183 // We can always evaluate constants shifted.
184 if (Constant *C = dyn_cast<Constant>(V)) {
186 V = IC.Builder->CreateShl(C, NumBits);
188 V = IC.Builder->CreateLShr(C, NumBits);
189 // If we got a constantexpr back, try to simplify it with TD info.
190 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
191 V = ConstantFoldConstantExpression(CE, IC.getTargetData());
195 Instruction *I = cast<Instruction>(V);
198 switch (I->getOpcode()) {
199 default: assert(0 && "Inconsistency with CanEvaluateShifted");
200 case Instruction::And:
201 case Instruction::Or:
202 case Instruction::Xor:
203 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
204 I->setOperand(0, GetShiftedValue(I->getOperand(0), NumBits,isLeftShift,IC));
205 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
208 case Instruction::Shl: {
209 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
211 // We only accept shifts-by-a-constant in CanEvaluateShifted.
212 ConstantInt *CI = cast<ConstantInt>(I->getOperand(1));
214 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
216 // If this is oversized composite shift, then unsigned shifts get 0.
217 unsigned NewShAmt = NumBits+CI->getZExtValue();
218 if (NewShAmt >= TypeWidth)
219 return Constant::getNullValue(I->getType());
221 I->setOperand(1, ConstantInt::get(I->getType(), NewShAmt));
225 // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
227 if (CI->getValue() == NumBits) {
228 APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
229 V = IC.Builder->CreateAnd(I->getOperand(0),
230 ConstantInt::get(I->getContext(), Mask));
231 if (Instruction *VI = dyn_cast<Instruction>(V)) {
238 // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
239 // the and won't be needed.
240 assert(CI->getZExtValue() > NumBits);
241 I->setOperand(1, ConstantInt::get(I->getType(),
242 CI->getZExtValue() - NumBits));
245 case Instruction::LShr: {
246 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
247 // We only accept shifts-by-a-constant in CanEvaluateShifted.
248 ConstantInt *CI = cast<ConstantInt>(I->getOperand(1));
250 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
252 // If this is oversized composite shift, then unsigned shifts get 0.
253 unsigned NewShAmt = NumBits+CI->getZExtValue();
254 if (NewShAmt >= TypeWidth)
255 return Constant::getNullValue(I->getType());
257 I->setOperand(1, ConstantInt::get(I->getType(), NewShAmt));
261 // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
263 if (CI->getValue() == NumBits) {
264 APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
265 V = IC.Builder->CreateAnd(I->getOperand(0),
266 ConstantInt::get(I->getContext(), Mask));
267 if (Instruction *VI = dyn_cast<Instruction>(V)) {
274 // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
275 // the and won't be needed.
276 assert(CI->getZExtValue() > NumBits);
277 I->setOperand(1, ConstantInt::get(I->getType(),
278 CI->getZExtValue() - NumBits));
282 case Instruction::Select:
283 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
284 I->setOperand(2, GetShiftedValue(I->getOperand(2), NumBits,isLeftShift,IC));
286 case Instruction::PHI: {
287 // We can change a phi if we can change all operands. Note that we never
288 // get into trouble with cyclic PHIs here because we only consider
289 // instructions with a single use.
290 PHINode *PN = cast<PHINode>(I);
291 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
292 PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i),
293 NumBits, isLeftShift, IC));
301 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
303 bool isLeftShift = I.getOpcode() == Instruction::Shl;
306 // See if we can propagate this shift into the input, this covers the trivial
307 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
308 if (I.getOpcode() != Instruction::AShr &&
309 CanEvaluateShifted(Op0, Op1->getZExtValue(), isLeftShift, *this)) {
310 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
311 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
313 return ReplaceInstUsesWith(I,
314 GetShiftedValue(Op0, Op1->getZExtValue(), isLeftShift, *this));
318 // See if we can simplify any instructions used by the instruction whose sole
319 // purpose is to compute bits we don't care about.
320 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
322 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
325 if (Op1->uge(TypeBits)) {
326 if (I.getOpcode() != Instruction::AShr)
327 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
328 // ashr i32 X, 32 --> ashr i32 X, 31
329 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
333 // ((X*C1) << C2) == (X * (C1 << C2))
334 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
335 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
336 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
337 return BinaryOperator::CreateMul(BO->getOperand(0),
338 ConstantExpr::getShl(BOOp, Op1));
340 // Try to fold constant and into select arguments.
341 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
342 if (Instruction *R = FoldOpIntoSelect(I, SI))
344 if (isa<PHINode>(Op0))
345 if (Instruction *NV = FoldOpIntoPhi(I))
348 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
349 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
350 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
351 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
352 // place. Don't try to do this transformation in this case. Also, we
353 // require that the input operand is a shift-by-constant so that we have
354 // confidence that the shifts will get folded together. We could do this
355 // xform in more cases, but it is unlikely to be profitable.
356 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
357 isa<ConstantInt>(TrOp->getOperand(1))) {
358 // Okay, we'll do this xform. Make the shift of shift.
359 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
360 // (shift2 (shift1 & 0x00FF), c2)
361 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
363 // For logical shifts, the truncation has the effect of making the high
364 // part of the register be zeros. Emulate this by inserting an AND to
365 // clear the top bits as needed. This 'and' will usually be zapped by
366 // other xforms later if dead.
367 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
368 unsigned DstSize = TI->getType()->getScalarSizeInBits();
369 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
371 // The mask we constructed says what the trunc would do if occurring
372 // between the shifts. We want to know the effect *after* the second
373 // shift. We know that it is a logical shift by a constant, so adjust the
374 // mask as appropriate.
375 if (I.getOpcode() == Instruction::Shl)
376 MaskV <<= Op1->getZExtValue();
378 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
379 MaskV = MaskV.lshr(Op1->getZExtValue());
383 Value *And = Builder->CreateAnd(NSh,
384 ConstantInt::get(I.getContext(), MaskV),
387 // Return the value truncated to the interesting size.
388 return new TruncInst(And, I.getType());
392 if (Op0->hasOneUse()) {
393 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
394 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
397 switch (Op0BO->getOpcode()) {
399 case Instruction::Add:
400 case Instruction::And:
401 case Instruction::Or:
402 case Instruction::Xor: {
403 // These operators commute.
404 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
405 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
406 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
408 Value *YS = // (Y << C)
409 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
411 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
412 Op0BO->getOperand(1)->getName());
413 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
414 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
415 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
418 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
419 Value *Op0BOOp1 = Op0BO->getOperand(1);
420 if (isLeftShift && Op0BOOp1->hasOneUse() &&
422 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
423 m_ConstantInt(CC))) &&
424 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
425 Value *YS = // (Y << C)
426 Builder->CreateShl(Op0BO->getOperand(0), Op1,
429 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
430 V1->getName()+".mask");
431 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
436 case Instruction::Sub: {
437 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
438 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
439 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
441 Value *YS = // (Y << C)
442 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
444 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
445 Op0BO->getOperand(0)->getName());
446 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
447 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
448 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
451 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
452 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
453 match(Op0BO->getOperand(0),
454 m_And(m_Shr(m_Value(V1), m_Value(V2)),
455 m_ConstantInt(CC))) && V2 == Op1 &&
456 cast<BinaryOperator>(Op0BO->getOperand(0))
457 ->getOperand(0)->hasOneUse()) {
458 Value *YS = // (Y << C)
459 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
461 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
462 V1->getName()+".mask");
464 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
472 // If the operand is an bitwise operator with a constant RHS, and the
473 // shift is the only use, we can pull it out of the shift.
474 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
475 bool isValid = true; // Valid only for And, Or, Xor
476 bool highBitSet = false; // Transform if high bit of constant set?
478 switch (Op0BO->getOpcode()) {
479 default: isValid = false; break; // Do not perform transform!
480 case Instruction::Add:
481 isValid = isLeftShift;
483 case Instruction::Or:
484 case Instruction::Xor:
487 case Instruction::And:
492 // If this is a signed shift right, and the high bit is modified
493 // by the logical operation, do not perform the transformation.
494 // The highBitSet boolean indicates the value of the high bit of
495 // the constant which would cause it to be modified for this
498 if (isValid && I.getOpcode() == Instruction::AShr)
499 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
502 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
505 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
506 NewShift->takeName(Op0BO);
508 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
515 // Find out if this is a shift of a shift by a constant.
516 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
517 if (ShiftOp && !ShiftOp->isShift())
520 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
521 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
522 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
523 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
524 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
525 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
526 Value *X = ShiftOp->getOperand(0);
528 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
530 const IntegerType *Ty = cast<IntegerType>(I.getType());
532 // Check for (X << c1) << c2 and (X >> c1) >> c2
533 if (I.getOpcode() == ShiftOp->getOpcode()) {
534 // If this is oversized composite shift, then unsigned shifts get 0, ashr
536 if (AmtSum >= TypeBits) {
537 if (I.getOpcode() != Instruction::AShr)
538 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
539 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
542 return BinaryOperator::Create(I.getOpcode(), X,
543 ConstantInt::get(Ty, AmtSum));
546 if (ShiftAmt1 == ShiftAmt2) {
547 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
548 if (I.getOpcode() == Instruction::Shl &&
549 ShiftOp->getOpcode() != Instruction::Shl) {
550 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
551 return BinaryOperator::CreateAnd(X,
552 ConstantInt::get(I.getContext(),Mask));
554 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
555 if (I.getOpcode() == Instruction::LShr &&
556 ShiftOp->getOpcode() == Instruction::Shl) {
557 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
558 return BinaryOperator::CreateAnd(X,
559 ConstantInt::get(I.getContext(), Mask));
561 } else if (ShiftAmt1 < ShiftAmt2) {
562 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
564 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
565 if (I.getOpcode() == Instruction::Shl &&
566 ShiftOp->getOpcode() != Instruction::Shl) {
567 assert(ShiftOp->getOpcode() == Instruction::LShr ||
568 ShiftOp->getOpcode() == Instruction::AShr);
569 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
571 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
572 return BinaryOperator::CreateAnd(Shift,
573 ConstantInt::get(I.getContext(),Mask));
576 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
577 if (I.getOpcode() == Instruction::LShr &&
578 ShiftOp->getOpcode() == Instruction::Shl) {
579 assert(ShiftOp->getOpcode() == Instruction::Shl);
580 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
582 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
583 return BinaryOperator::CreateAnd(Shift,
584 ConstantInt::get(I.getContext(),Mask));
587 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
589 assert(ShiftAmt2 < ShiftAmt1);
590 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
592 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
593 if (I.getOpcode() == Instruction::Shl &&
594 ShiftOp->getOpcode() != Instruction::Shl) {
595 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
596 ConstantInt::get(Ty, ShiftDiff));
598 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
599 return BinaryOperator::CreateAnd(Shift,
600 ConstantInt::get(I.getContext(),Mask));
603 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
604 if (I.getOpcode() == Instruction::LShr &&
605 ShiftOp->getOpcode() == Instruction::Shl) {
606 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
608 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
609 return BinaryOperator::CreateAnd(Shift,
610 ConstantInt::get(I.getContext(),Mask));
613 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
619 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
620 if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
621 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
623 return ReplaceInstUsesWith(I, V);
624 return commonShiftTransforms(I);
627 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
628 if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1),
630 return ReplaceInstUsesWith(I, V);
632 if (Instruction *R = commonShiftTransforms(I))
635 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
637 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1))
638 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
639 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
640 // ctlz.i32(x)>>5 --> zext(x == 0)
641 // cttz.i32(x)>>5 --> zext(x == 0)
642 // ctpop.i32(x)>>5 --> zext(x == -1)
643 if ((II->getIntrinsicID() == Intrinsic::ctlz ||
644 II->getIntrinsicID() == Intrinsic::cttz ||
645 II->getIntrinsicID() == Intrinsic::ctpop) &&
646 isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == Op1C->getZExtValue()){
647 bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
648 Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
649 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
650 return new ZExtInst(Cmp, II->getType());
657 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
658 if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1),
660 return ReplaceInstUsesWith(I, V);
662 if (Instruction *R = commonShiftTransforms(I))
665 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
667 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
668 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
669 // have a sign-extend idiom.
671 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
672 // If the input value is known to already be sign extended enough, delete
674 if (ComputeNumSignBits(X) > Op1C->getZExtValue())
675 return ReplaceInstUsesWith(I, X);
677 // If the input is an extension from the shifted amount value, e.g.
678 // %x = zext i8 %A to i32
679 // %y = shl i32 %x, 24
681 // then turn this into "z = sext i8 A to i32".
682 if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
683 uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
684 uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
685 if (Op1C->getZExtValue() == DestBits-SrcBits)
686 return new SExtInst(ZI->getOperand(0), ZI->getType());
691 // See if we can turn a signed shr into an unsigned shr.
692 if (MaskedValueIsZero(Op0,
693 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
694 return BinaryOperator::CreateLShr(Op0, Op1);
696 // Arithmetic shifting an all-sign-bit value is a no-op.
697 unsigned NumSignBits = ComputeNumSignBits(Op0);
698 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
699 return ReplaceInstUsesWith(I, Op0);