blob: fe91da1b6af4943bc90494b254079c9775acae40 [file] [log] [blame]
Chris Lattner9cdd5f32010-01-05 07:44:46 +00001//===- InstCombineShifts.cpp ----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitShl, visitLShr, and visitAShr functions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
15#include "llvm/Support/PatternMatch.h"
16using namespace llvm;
17using namespace PatternMatch;
18
19Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
20 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
21 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
22
23 // shl X, 0 == X and shr X, 0 == X
24 // shl 0, X == 0 and shr 0, X == 0
25 if (Op1 == Constant::getNullValue(Op1->getType()) ||
26 Op0 == Constant::getNullValue(Op0->getType()))
27 return ReplaceInstUsesWith(I, Op0);
28
29 if (isa<UndefValue>(Op0)) {
30 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
31 return ReplaceInstUsesWith(I, Op0);
32 else // undef << X -> 0, undef >>u X -> 0
33 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
34 }
35 if (isa<UndefValue>(Op1)) {
36 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
37 return ReplaceInstUsesWith(I, Op0);
38 else // X << undef, X >>u undef -> 0
39 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
40 }
41
42 // See if we can fold away this shift.
43 if (SimplifyDemandedInstructionBits(I))
44 return &I;
45
46 // Try to fold constant and into select arguments.
47 if (isa<Constant>(Op0))
48 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
49 if (Instruction *R = FoldOpIntoSelect(I, SI))
50 return R;
51
52 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
53 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
54 return Res;
55 return 0;
56}
57
58Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
59 BinaryOperator &I) {
60 bool isLeftShift = I.getOpcode() == Instruction::Shl;
61
62 // See if we can simplify any instructions used by the instruction whose sole
63 // purpose is to compute bits we don't care about.
64 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
65
66 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
67 // a signed shift.
68 //
69 if (Op1->uge(TypeBits)) {
70 if (I.getOpcode() != Instruction::AShr)
71 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
72 else {
73 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
74 return &I;
75 }
76 }
77
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));
84
85 // Try to fold constant and into select arguments.
86 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
87 if (Instruction *R = FoldOpIntoSelect(I, SI))
88 return R;
89 if (isa<PHINode>(Op0))
90 if (Instruction *NV = FoldOpIntoPhi(I))
91 return NV;
92
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());
107
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));
115
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();
122 else {
123 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
124 MaskV = MaskV.lshr(Op1->getZExtValue());
125 }
126
127 // shift1 & 0x00FF
128 Value *And = Builder->CreateAnd(NSh,
129 ConstantInt::get(I.getContext(), MaskV),
130 TI->getName());
131
132 // Return the value truncated to the interesting size.
133 return new TruncInst(And, I.getType());
134 }
135 }
136
137 if (Op0->hasOneUse()) {
138 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
139 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
140 Value *V1, *V2;
141 ConstantInt *CC;
142 switch (Op0BO->getOpcode()) {
Chris Lattnerabff82d2010-01-10 06:59:55 +0000143 default: break;
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),
152 m_Specific(Op1)))) {
153 Value *YS = // (Y << C)
154 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
155 // (X + (Y << C))
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)));
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000161 }
Chris Lattnerabff82d2010-01-10 06:59:55 +0000162
163 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
164 Value *Op0BOOp1 = Op0BO->getOperand(1);
165 if (isLeftShift && Op0BOOp1->hasOneUse() &&
166 match(Op0BOOp1,
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,
172 Op0BO->getName());
173 // X & (CC << C)
174 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
175 V1->getName()+".mask");
176 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000177 }
178 }
Chris Lattnerabff82d2010-01-10 06:59:55 +0000179
180 // FALL THROUGH.
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),
185 m_Specific(Op1)))) {
186 Value *YS = // (Y << C)
187 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
188 // (X + (Y << C))
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)));
194 }
195
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());
205 // X & (CC << C)
206 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
207 V1->getName()+".mask");
208
209 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
210 }
211
212 break;
213 }
214 }
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000215
216
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?
222
223 switch (Op0BO->getOpcode()) {
Chris Lattnerabff82d2010-01-10 06:59:55 +0000224 default: isValid = false; break; // Do not perform transform!
225 case Instruction::Add:
226 isValid = isLeftShift;
227 break;
228 case Instruction::Or:
229 case Instruction::Xor:
230 highBitSet = false;
231 break;
232 case Instruction::And:
233 highBitSet = true;
234 break;
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000235 }
236
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
241 // operation.
242 //
243 if (isValid && I.getOpcode() == Instruction::AShr)
244 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
245
246 if (isValid) {
247 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
248
249 Value *NewShift =
250 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
251 NewShift->takeName(Op0BO);
252
253 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
254 NewRHS);
255 }
256 }
257 }
258 }
259
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())
263 ShiftOp = 0;
264
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);
272
273 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
274
275 const IntegerType *Ty = cast<IntegerType>(I.getType());
276
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
280 // saturates.
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.
285 }
286
287 return BinaryOperator::Create(I.getOpcode(), X,
288 ConstantInt::get(Ty, AmtSum));
289 }
290
291 if (ShiftOp->getOpcode() == Instruction::LShr &&
292 I.getOpcode() == Instruction::AShr) {
293 if (AmtSum >= TypeBits)
294 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
295
296 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
297 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
298 }
299
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)
304 AmtSum = TypeBits-1;
305
306 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
307
308 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
309 return BinaryOperator::CreateAnd(Shift,
310 ConstantInt::get(I.getContext(), Mask));
311 }
312
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));
321 }
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));
327 }
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000328 } else if (ShiftAmt1 < ShiftAmt2) {
329 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
330
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));
336
337 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
338 return BinaryOperator::CreateAnd(Shift,
339 ConstantInt::get(I.getContext(),Mask));
340 }
341
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));
346
347 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
348 return BinaryOperator::CreateAnd(Shift,
349 ConstantInt::get(I.getContext(),Mask));
350 }
351
352 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
353 } else {
354 assert(ShiftAmt2 < ShiftAmt1);
355 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
356
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));
363
364 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
365 return BinaryOperator::CreateAnd(Shift,
366 ConstantInt::get(I.getContext(),Mask));
367 }
368
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));
373
374 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
375 return BinaryOperator::CreateAnd(Shift,
376 ConstantInt::get(I.getContext(),Mask));
377 }
378
379 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
380 }
381 }
382 return 0;
383}
384
385Instruction *InstCombiner::visitShl(BinaryOperator &I) {
386 return commonShiftTransforms(I);
387}
388
389Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
390 return commonShiftTransforms(I);
391}
392
393Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
394 if (Instruction *R = commonShiftTransforms(I))
395 return R;
396
Chris Lattnera85732f2010-01-08 19:04:21 +0000397 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000398
Chris Lattnera85732f2010-01-08 19:04:21 +0000399 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0)) {
400 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000401 if (CSI->isAllOnesValue())
402 return ReplaceInstUsesWith(I, CSI);
Chris Lattnera85732f2010-01-08 19:04:21 +0000403 }
404
405 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
406 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
407 // have a sign-extend idiom. If the input value is known to already be sign
408 // extended enough, delete the extension.
409 Value *X;
410 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
411 ComputeNumSignBits(X) > Op1C->getZExtValue())
412 return ReplaceInstUsesWith(I, X);
413 }
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000414
415 // See if we can turn a signed shr into an unsigned shr.
416 if (MaskedValueIsZero(Op0,
417 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
Chris Lattnera85732f2010-01-08 19:04:21 +0000418 return BinaryOperator::CreateLShr(Op0, Op1);
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000419
420 // Arithmetic shifting an all-sign-bit value is a no-op.
421 unsigned NumSignBits = ComputeNumSignBits(Op0);
422 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
423 return ReplaceInstUsesWith(I, Op0);
424
425 return 0;
426}
427