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/Support/PatternMatch.h"
18 using namespace PatternMatch;
20 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
21 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
22 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
24 // shl X, 0 == X and shr X, 0 == X
25 // shl 0, X == 0 and shr 0, X == 0
26 if (Op1 == Constant::getNullValue(Op1->getType()) ||
27 Op0 == Constant::getNullValue(Op0->getType()))
28 return ReplaceInstUsesWith(I, Op0);
30 if (isa<UndefValue>(Op0)) {
31 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
32 return ReplaceInstUsesWith(I, Op0);
33 else // undef << X -> 0, undef >>u X -> 0
34 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
36 if (isa<UndefValue>(Op1)) {
37 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
38 return ReplaceInstUsesWith(I, Op0);
39 else // X << undef, X >>u undef -> 0
40 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
43 // See if we can fold away this shift.
44 if (SimplifyDemandedInstructionBits(I))
47 // Try to fold constant and into select arguments.
48 if (isa<Constant>(Op0))
49 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
50 if (Instruction *R = FoldOpIntoSelect(I, SI))
53 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
54 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
59 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
61 bool isLeftShift = I.getOpcode() == Instruction::Shl;
63 // See if we can simplify any instructions used by the instruction whose sole
64 // purpose is to compute bits we don't care about.
65 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
67 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
70 if (Op1->uge(TypeBits)) {
71 if (I.getOpcode() != Instruction::AShr)
72 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
73 // ashr i32 X, 32 --> ashr i32 X, 31
74 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
78 // ((X*C1) << C2) == (X * (C1 << C2))
79 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
80 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
81 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
82 return BinaryOperator::CreateMul(BO->getOperand(0),
83 ConstantExpr::getShl(BOOp, Op1));
85 // Try to fold constant and into select arguments.
86 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
87 if (Instruction *R = FoldOpIntoSelect(I, SI))
89 if (isa<PHINode>(Op0))
90 if (Instruction *NV = FoldOpIntoPhi(I))
93 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
94 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
95 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
96 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
97 // place. Don't try to do this transformation in this case. Also, we
98 // require that the input operand is a shift-by-constant so that we have
99 // confidence that the shifts will get folded together. We could do this
100 // xform in more cases, but it is unlikely to be profitable.
101 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
102 isa<ConstantInt>(TrOp->getOperand(1))) {
103 // Okay, we'll do this xform. Make the shift of shift.
104 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
105 // (shift2 (shift1 & 0x00FF), c2)
106 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
108 // For logical shifts, the truncation has the effect of making the high
109 // part of the register be zeros. Emulate this by inserting an AND to
110 // clear the top bits as needed. This 'and' will usually be zapped by
111 // other xforms later if dead.
112 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
113 unsigned DstSize = TI->getType()->getScalarSizeInBits();
114 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
116 // The mask we constructed says what the trunc would do if occurring
117 // between the shifts. We want to know the effect *after* the second
118 // shift. We know that it is a logical shift by a constant, so adjust the
119 // mask as appropriate.
120 if (I.getOpcode() == Instruction::Shl)
121 MaskV <<= Op1->getZExtValue();
123 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
124 MaskV = MaskV.lshr(Op1->getZExtValue());
128 Value *And = Builder->CreateAnd(NSh,
129 ConstantInt::get(I.getContext(), MaskV),
132 // Return the value truncated to the interesting size.
133 return new TruncInst(And, I.getType());
137 if (Op0->hasOneUse()) {
138 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
139 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
142 switch (Op0BO->getOpcode()) {
144 case Instruction::Add:
145 case Instruction::And:
146 case Instruction::Or:
147 case Instruction::Xor: {
148 // These operators commute.
149 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
150 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
151 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
153 Value *YS = // (Y << C)
154 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
156 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
157 Op0BO->getOperand(1)->getName());
158 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
159 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
160 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
163 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
164 Value *Op0BOOp1 = Op0BO->getOperand(1);
165 if (isLeftShift && Op0BOOp1->hasOneUse() &&
167 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
168 m_ConstantInt(CC))) &&
169 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
170 Value *YS = // (Y << C)
171 Builder->CreateShl(Op0BO->getOperand(0), Op1,
174 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
175 V1->getName()+".mask");
176 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
181 case Instruction::Sub: {
182 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
183 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
184 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
186 Value *YS = // (Y << C)
187 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
189 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
190 Op0BO->getOperand(0)->getName());
191 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
192 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
193 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
196 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
197 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
198 match(Op0BO->getOperand(0),
199 m_And(m_Shr(m_Value(V1), m_Value(V2)),
200 m_ConstantInt(CC))) && V2 == Op1 &&
201 cast<BinaryOperator>(Op0BO->getOperand(0))
202 ->getOperand(0)->hasOneUse()) {
203 Value *YS = // (Y << C)
204 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
206 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
207 V1->getName()+".mask");
209 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
217 // If the operand is an bitwise operator with a constant RHS, and the
218 // shift is the only use, we can pull it out of the shift.
219 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
220 bool isValid = true; // Valid only for And, Or, Xor
221 bool highBitSet = false; // Transform if high bit of constant set?
223 switch (Op0BO->getOpcode()) {
224 default: isValid = false; break; // Do not perform transform!
225 case Instruction::Add:
226 isValid = isLeftShift;
228 case Instruction::Or:
229 case Instruction::Xor:
232 case Instruction::And:
237 // If this is a signed shift right, and the high bit is modified
238 // by the logical operation, do not perform the transformation.
239 // The highBitSet boolean indicates the value of the high bit of
240 // the constant which would cause it to be modified for this
243 if (isValid && I.getOpcode() == Instruction::AShr)
244 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
247 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
250 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
251 NewShift->takeName(Op0BO);
253 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
260 // Find out if this is a shift of a shift by a constant.
261 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
262 if (ShiftOp && !ShiftOp->isShift())
265 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
266 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
267 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
268 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
269 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
270 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
271 Value *X = ShiftOp->getOperand(0);
273 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
275 const IntegerType *Ty = cast<IntegerType>(I.getType());
277 // Check for (X << c1) << c2 and (X >> c1) >> c2
278 if (I.getOpcode() == ShiftOp->getOpcode()) {
279 // If this is oversized composite shift, then unsigned shifts get 0, ashr
281 if (AmtSum >= TypeBits) {
282 if (I.getOpcode() != Instruction::AShr)
283 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
284 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
287 return BinaryOperator::Create(I.getOpcode(), X,
288 ConstantInt::get(Ty, AmtSum));
291 if (ShiftOp->getOpcode() == Instruction::LShr &&
292 I.getOpcode() == Instruction::AShr) {
293 if (AmtSum >= TypeBits)
294 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
296 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
297 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
300 if (ShiftOp->getOpcode() == Instruction::AShr &&
301 I.getOpcode() == Instruction::LShr) {
302 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
303 if (AmtSum >= TypeBits)
306 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
308 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
309 return BinaryOperator::CreateAnd(Shift,
310 ConstantInt::get(I.getContext(), Mask));
313 // Okay, if we get here, one shift must be left, and the other shift must be
314 // right. See if the amounts are equal.
315 if (ShiftAmt1 == ShiftAmt2) {
316 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
317 if (I.getOpcode() == Instruction::Shl) {
318 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
319 return BinaryOperator::CreateAnd(X,
320 ConstantInt::get(I.getContext(),Mask));
322 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
323 if (I.getOpcode() == Instruction::LShr) {
324 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
325 return BinaryOperator::CreateAnd(X,
326 ConstantInt::get(I.getContext(), Mask));
328 } else if (ShiftAmt1 < ShiftAmt2) {
329 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
331 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
332 if (I.getOpcode() == Instruction::Shl) {
333 assert(ShiftOp->getOpcode() == Instruction::LShr ||
334 ShiftOp->getOpcode() == Instruction::AShr);
335 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
337 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
338 return BinaryOperator::CreateAnd(Shift,
339 ConstantInt::get(I.getContext(),Mask));
342 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
343 if (I.getOpcode() == Instruction::LShr) {
344 assert(ShiftOp->getOpcode() == Instruction::Shl);
345 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
347 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
348 return BinaryOperator::CreateAnd(Shift,
349 ConstantInt::get(I.getContext(),Mask));
352 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
354 assert(ShiftAmt2 < ShiftAmt1);
355 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
357 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
358 if (I.getOpcode() == Instruction::Shl) {
359 assert(ShiftOp->getOpcode() == Instruction::LShr ||
360 ShiftOp->getOpcode() == Instruction::AShr);
361 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
362 ConstantInt::get(Ty, ShiftDiff));
364 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
365 return BinaryOperator::CreateAnd(Shift,
366 ConstantInt::get(I.getContext(),Mask));
369 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
370 if (I.getOpcode() == Instruction::LShr) {
371 assert(ShiftOp->getOpcode() == Instruction::Shl);
372 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
374 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
375 return BinaryOperator::CreateAnd(Shift,
376 ConstantInt::get(I.getContext(),Mask));
379 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
385 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
386 return commonShiftTransforms(I);
389 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
390 if (Instruction *R = commonShiftTransforms(I))
393 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
395 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1))
396 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
397 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
398 // ctlz.i32(x)>>5 --> zext(x == 0)
399 // cttz.i32(x)>>5 --> zext(x == 0)
400 // ctpop.i32(x)>>5 --> zext(x == -1)
401 if ((II->getIntrinsicID() == Intrinsic::ctlz ||
402 II->getIntrinsicID() == Intrinsic::cttz ||
403 II->getIntrinsicID() == Intrinsic::ctpop) &&
404 isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == Op1C->getZExtValue()){
405 bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
406 Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
407 Value *Cmp = Builder->CreateICmpEQ(II->getOperand(1), RHS);
408 return new ZExtInst(Cmp, II->getType());
415 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
416 if (Instruction *R = commonShiftTransforms(I))
419 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
421 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0)) {
422 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
423 if (CSI->isAllOnesValue())
424 return ReplaceInstUsesWith(I, CSI);
427 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
428 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
429 // have a sign-extend idiom.
431 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
432 // If the input value is known to already be sign extended enough, delete
434 if (ComputeNumSignBits(X) > Op1C->getZExtValue())
435 return ReplaceInstUsesWith(I, X);
437 // If the input is an extension from the shifted amount value, e.g.
438 // %x = zext i8 %A to i32
439 // %y = shl i32 %x, 24
441 // then turn this into "z = sext i8 A to i32".
442 if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
443 uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
444 uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
445 if (Op1C->getZExtValue() == DestBits-SrcBits)
446 return new SExtInst(ZI->getOperand(0), ZI->getType());
451 // See if we can turn a signed shr into an unsigned shr.
452 if (MaskedValueIsZero(Op0,
453 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
454 return BinaryOperator::CreateLShr(Op0, Op1);
456 // Arithmetic shifting an all-sign-bit value is a no-op.
457 unsigned NumSignBits = ComputeNumSignBits(Op0);
458 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
459 return ReplaceInstUsesWith(I, Op0);