blob: 7969dbfec04b7abe7c7c8bb11f8a9fe1a20d0059 [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"
Chris Lattner818ff342010-01-23 18:49:30 +000015#include "llvm/IntrinsicInst.h"
Chris Lattner9cdd5f32010-01-05 07:44:46 +000016#include "llvm/Support/PatternMatch.h"
17using namespace llvm;
18using namespace PatternMatch;
19
20Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
21 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
22 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
23
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);
29
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()));
35 }
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()));
41 }
42
43 // See if we can fold away this shift.
44 if (SimplifyDemandedInstructionBits(I))
45 return &I;
46
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))
51 return R;
52
53 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
54 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
55 return Res;
Benjamin Kramerb70ebd22010-11-23 18:52:42 +000056
57 // X shift (A srem B) -> X shift (A urem B) iff B is positive.
58 // Because shifts by negative values are undefined.
59 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op1))
60 if (BO->getOpcode() == Instruction::SRem && BO->getType()->isIntegerTy()) {
61 // Make sure the divisor's sign bit is zero.
62 APInt Mask = APInt::getSignBit(BO->getType()->getPrimitiveSizeInBits());
63 if (MaskedValueIsZero(BO->getOperand(1), Mask)) {
64 Value *URem = Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
65 BO->getName());
66 I.setOperand(1, URem);
67 return &I;
68 }
69 }
70
Chris Lattner9cdd5f32010-01-05 07:44:46 +000071 return 0;
72}
73
Chris Lattner29cc0b32010-08-27 22:24:38 +000074/// CanEvaluateShifted - See if we can compute the specified value, but shifted
75/// logically to the left or right by some number of bits. This should return
76/// true if the expression can be computed for the same cost as the current
77/// expression tree. This is used to eliminate extraneous shifting from things
78/// like:
79/// %C = shl i128 %A, 64
80/// %D = shl i128 %B, 96
81/// %E = or i128 %C, %D
82/// %F = lshr i128 %E, 64
83/// where the client will ask if E can be computed shifted right by 64-bits. If
84/// this succeeds, the GetShiftedValue function will be called to produce the
85/// value.
86static bool CanEvaluateShifted(Value *V, unsigned NumBits, bool isLeftShift,
87 InstCombiner &IC) {
88 // We can always evaluate constants shifted.
89 if (isa<Constant>(V))
90 return true;
91
92 Instruction *I = dyn_cast<Instruction>(V);
93 if (!I) return false;
94
95 // If this is the opposite shift, we can directly reuse the input of the shift
96 // if the needed bits are already zero in the input. This allows us to reuse
97 // the value which means that we don't care if the shift has multiple uses.
98 // TODO: Handle opposite shift by exact value.
99 ConstantInt *CI;
100 if ((isLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
101 (!isLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
102 if (CI->getZExtValue() == NumBits) {
103 // TODO: Check that the input bits are already zero with MaskedValueIsZero
104#if 0
105 // If this is a truncate of a logical shr, we can truncate it to a smaller
106 // lshr iff we know that the bits we would otherwise be shifting in are
107 // already zeros.
108 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
109 uint32_t BitWidth = Ty->getScalarSizeInBits();
110 if (MaskedValueIsZero(I->getOperand(0),
111 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
112 CI->getLimitedValue(BitWidth) < BitWidth) {
113 return CanEvaluateTruncated(I->getOperand(0), Ty);
114 }
115#endif
116
117 }
118 }
119
120 // We can't mutate something that has multiple uses: doing so would
121 // require duplicating the instruction in general, which isn't profitable.
122 if (!I->hasOneUse()) return false;
123
124 switch (I->getOpcode()) {
125 default: return false;
126 case Instruction::And:
127 case Instruction::Or:
128 case Instruction::Xor:
129 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
130 return CanEvaluateShifted(I->getOperand(0), NumBits, isLeftShift, IC) &&
131 CanEvaluateShifted(I->getOperand(1), NumBits, isLeftShift, IC);
132
Chris Lattner4ece5772010-08-27 22:53:44 +0000133 case Instruction::Shl: {
Chris Lattner29cc0b32010-08-27 22:24:38 +0000134 // We can often fold the shift into shifts-by-a-constant.
135 CI = dyn_cast<ConstantInt>(I->getOperand(1));
136 if (CI == 0) return false;
137
138 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
139 if (isLeftShift) return true;
140
141 // We can always turn shl(c)+shr(c) -> and(c2).
142 if (CI->getValue() == NumBits) return true;
Chris Lattner4ece5772010-08-27 22:53:44 +0000143
144 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
145
146 // We can turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but it isn't
Chris Lattner29cc0b32010-08-27 22:24:38 +0000147 // profitable unless we know the and'd out bits are already zero.
Chris Lattner4ece5772010-08-27 22:53:44 +0000148 if (CI->getZExtValue() > NumBits) {
Dale Johannesen201ab3a2010-11-10 01:30:56 +0000149 unsigned LowBits = TypeWidth - CI->getZExtValue();
Chris Lattner4ece5772010-08-27 22:53:44 +0000150 if (MaskedValueIsZero(I->getOperand(0),
Dale Johannesen201ab3a2010-11-10 01:30:56 +0000151 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
Chris Lattner4ece5772010-08-27 22:53:44 +0000152 return true;
153 }
154
Chris Lattner29cc0b32010-08-27 22:24:38 +0000155 return false;
Chris Lattner4ece5772010-08-27 22:53:44 +0000156 }
157 case Instruction::LShr: {
Chris Lattner29cc0b32010-08-27 22:24:38 +0000158 // We can often fold the shift into shifts-by-a-constant.
159 CI = dyn_cast<ConstantInt>(I->getOperand(1));
160 if (CI == 0) return false;
161
162 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
163 if (!isLeftShift) return true;
164
165 // We can always turn lshr(c)+shl(c) -> and(c2).
166 if (CI->getValue() == NumBits) return true;
167
Chris Lattner4ece5772010-08-27 22:53:44 +0000168 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
169
Chris Lattner29cc0b32010-08-27 22:24:38 +0000170 // We can always turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but it isn't
171 // profitable unless we know the and'd out bits are already zero.
Chris Lattner4ece5772010-08-27 22:53:44 +0000172 if (CI->getZExtValue() > NumBits) {
173 unsigned LowBits = CI->getZExtValue() - NumBits;
174 if (MaskedValueIsZero(I->getOperand(0),
Owen Anderson648b20d2010-11-01 21:08:20 +0000175 APInt::getLowBitsSet(TypeWidth, LowBits) << NumBits))
Chris Lattner4ece5772010-08-27 22:53:44 +0000176 return true;
177 }
Chris Lattner29cc0b32010-08-27 22:24:38 +0000178
Chris Lattner4ece5772010-08-27 22:53:44 +0000179 return false;
180 }
Chris Lattner29cc0b32010-08-27 22:24:38 +0000181 case Instruction::Select: {
182 SelectInst *SI = cast<SelectInst>(I);
183 return CanEvaluateShifted(SI->getTrueValue(), NumBits, isLeftShift, IC) &&
184 CanEvaluateShifted(SI->getFalseValue(), NumBits, isLeftShift, IC);
185 }
186 case Instruction::PHI: {
187 // We can change a phi if we can change all operands. Note that we never
188 // get into trouble with cyclic PHIs here because we only consider
189 // instructions with a single use.
190 PHINode *PN = cast<PHINode>(I);
191 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
192 if (!CanEvaluateShifted(PN->getIncomingValue(i), NumBits, isLeftShift,IC))
193 return false;
194 return true;
195 }
196 }
197}
198
199/// GetShiftedValue - When CanEvaluateShifted returned true for an expression,
200/// this value inserts the new computation that produces the shifted value.
201static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
202 InstCombiner &IC) {
203 // We can always evaluate constants shifted.
204 if (Constant *C = dyn_cast<Constant>(V)) {
205 if (isLeftShift)
206 V = IC.Builder->CreateShl(C, NumBits);
207 else
208 V = IC.Builder->CreateLShr(C, NumBits);
209 // If we got a constantexpr back, try to simplify it with TD info.
210 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
211 V = ConstantFoldConstantExpression(CE, IC.getTargetData());
212 return V;
213 }
214
215 Instruction *I = cast<Instruction>(V);
216 IC.Worklist.Add(I);
217
218 switch (I->getOpcode()) {
219 default: assert(0 && "Inconsistency with CanEvaluateShifted");
220 case Instruction::And:
221 case Instruction::Or:
222 case Instruction::Xor:
223 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
224 I->setOperand(0, GetShiftedValue(I->getOperand(0), NumBits,isLeftShift,IC));
225 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
226 return I;
227
228 case Instruction::Shl: {
229 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
230
231 // We only accept shifts-by-a-constant in CanEvaluateShifted.
232 ConstantInt *CI = cast<ConstantInt>(I->getOperand(1));
233
234 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
235 if (isLeftShift) {
236 // If this is oversized composite shift, then unsigned shifts get 0.
237 unsigned NewShAmt = NumBits+CI->getZExtValue();
238 if (NewShAmt >= TypeWidth)
239 return Constant::getNullValue(I->getType());
240
241 I->setOperand(1, ConstantInt::get(I->getType(), NewShAmt));
242 return I;
243 }
244
245 // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
246 // zeros.
Chris Lattner4ece5772010-08-27 22:53:44 +0000247 if (CI->getValue() == NumBits) {
248 APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
249 V = IC.Builder->CreateAnd(I->getOperand(0),
250 ConstantInt::get(I->getContext(), Mask));
251 if (Instruction *VI = dyn_cast<Instruction>(V)) {
252 VI->moveBefore(I);
253 VI->takeName(I);
254 }
255 return V;
Chris Lattner29cc0b32010-08-27 22:24:38 +0000256 }
Chris Lattner4ece5772010-08-27 22:53:44 +0000257
258 // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
259 // the and won't be needed.
260 assert(CI->getZExtValue() > NumBits);
261 I->setOperand(1, ConstantInt::get(I->getType(),
262 CI->getZExtValue() - NumBits));
263 return I;
Chris Lattner29cc0b32010-08-27 22:24:38 +0000264 }
265 case Instruction::LShr: {
266 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
267 // We only accept shifts-by-a-constant in CanEvaluateShifted.
268 ConstantInt *CI = cast<ConstantInt>(I->getOperand(1));
269
270 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
271 if (!isLeftShift) {
272 // If this is oversized composite shift, then unsigned shifts get 0.
273 unsigned NewShAmt = NumBits+CI->getZExtValue();
274 if (NewShAmt >= TypeWidth)
275 return Constant::getNullValue(I->getType());
276
277 I->setOperand(1, ConstantInt::get(I->getType(), NewShAmt));
278 return I;
279 }
280
281 // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
282 // zeros.
Chris Lattner4ece5772010-08-27 22:53:44 +0000283 if (CI->getValue() == NumBits) {
284 APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
285 V = IC.Builder->CreateAnd(I->getOperand(0),
286 ConstantInt::get(I->getContext(), Mask));
287 if (Instruction *VI = dyn_cast<Instruction>(V)) {
288 VI->moveBefore(I);
289 VI->takeName(I);
290 }
291 return V;
Chris Lattner29cc0b32010-08-27 22:24:38 +0000292 }
Chris Lattner4ece5772010-08-27 22:53:44 +0000293
294 // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
295 // the and won't be needed.
296 assert(CI->getZExtValue() > NumBits);
297 I->setOperand(1, ConstantInt::get(I->getType(),
298 CI->getZExtValue() - NumBits));
299 return I;
Chris Lattner29cc0b32010-08-27 22:24:38 +0000300 }
301
302 case Instruction::Select:
303 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
304 I->setOperand(2, GetShiftedValue(I->getOperand(2), NumBits,isLeftShift,IC));
305 return I;
306 case Instruction::PHI: {
307 // We can change a phi if we can change all operands. Note that we never
308 // get into trouble with cyclic PHIs here because we only consider
309 // instructions with a single use.
310 PHINode *PN = cast<PHINode>(I);
311 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
312 PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i),
313 NumBits, isLeftShift, IC));
314 return PN;
315 }
316 }
317}
318
319
320
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000321Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
322 BinaryOperator &I) {
323 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner2d0822a2010-08-27 21:04:34 +0000324
Chris Lattner29cc0b32010-08-27 22:24:38 +0000325
326 // See if we can propagate this shift into the input, this covers the trivial
327 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
328 if (I.getOpcode() != Instruction::AShr &&
329 CanEvaluateShifted(Op0, Op1->getZExtValue(), isLeftShift, *this)) {
Chris Lattner3dd08732010-08-28 01:20:38 +0000330 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
331 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
Chris Lattner29cc0b32010-08-27 22:24:38 +0000332
333 return ReplaceInstUsesWith(I,
334 GetShiftedValue(Op0, Op1->getZExtValue(), isLeftShift, *this));
335 }
336
337
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000338 // See if we can simplify any instructions used by the instruction whose sole
339 // purpose is to compute bits we don't care about.
340 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
341
342 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
343 // a signed shift.
344 //
345 if (Op1->uge(TypeBits)) {
346 if (I.getOpcode() != Instruction::AShr)
347 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner818ff342010-01-23 18:49:30 +0000348 // ashr i32 X, 32 --> ashr i32 X, 31
349 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
350 return &I;
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000351 }
352
353 // ((X*C1) << C2) == (X * (C1 << C2))
354 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
355 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
356 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
357 return BinaryOperator::CreateMul(BO->getOperand(0),
358 ConstantExpr::getShl(BOOp, Op1));
359
360 // Try to fold constant and into select arguments.
361 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
362 if (Instruction *R = FoldOpIntoSelect(I, SI))
363 return R;
364 if (isa<PHINode>(Op0))
365 if (Instruction *NV = FoldOpIntoPhi(I))
366 return NV;
367
368 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
369 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
370 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
371 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
372 // place. Don't try to do this transformation in this case. Also, we
373 // require that the input operand is a shift-by-constant so that we have
374 // confidence that the shifts will get folded together. We could do this
375 // xform in more cases, but it is unlikely to be profitable.
376 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
377 isa<ConstantInt>(TrOp->getOperand(1))) {
378 // Okay, we'll do this xform. Make the shift of shift.
379 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
380 // (shift2 (shift1 & 0x00FF), c2)
381 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
382
383 // For logical shifts, the truncation has the effect of making the high
384 // part of the register be zeros. Emulate this by inserting an AND to
385 // clear the top bits as needed. This 'and' will usually be zapped by
386 // other xforms later if dead.
387 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
388 unsigned DstSize = TI->getType()->getScalarSizeInBits();
389 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
390
391 // The mask we constructed says what the trunc would do if occurring
392 // between the shifts. We want to know the effect *after* the second
393 // shift. We know that it is a logical shift by a constant, so adjust the
394 // mask as appropriate.
395 if (I.getOpcode() == Instruction::Shl)
396 MaskV <<= Op1->getZExtValue();
397 else {
398 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
399 MaskV = MaskV.lshr(Op1->getZExtValue());
400 }
401
402 // shift1 & 0x00FF
403 Value *And = Builder->CreateAnd(NSh,
404 ConstantInt::get(I.getContext(), MaskV),
405 TI->getName());
406
407 // Return the value truncated to the interesting size.
408 return new TruncInst(And, I.getType());
409 }
410 }
411
412 if (Op0->hasOneUse()) {
413 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
414 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
415 Value *V1, *V2;
416 ConstantInt *CC;
417 switch (Op0BO->getOpcode()) {
Chris Lattnerabff82d2010-01-10 06:59:55 +0000418 default: break;
419 case Instruction::Add:
420 case Instruction::And:
421 case Instruction::Or:
422 case Instruction::Xor: {
423 // These operators commute.
424 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
425 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
426 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
427 m_Specific(Op1)))) {
428 Value *YS = // (Y << C)
429 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
430 // (X + (Y << C))
431 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
432 Op0BO->getOperand(1)->getName());
433 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
434 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
435 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000436 }
Chris Lattnerabff82d2010-01-10 06:59:55 +0000437
438 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
439 Value *Op0BOOp1 = Op0BO->getOperand(1);
440 if (isLeftShift && Op0BOOp1->hasOneUse() &&
441 match(Op0BOOp1,
442 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
443 m_ConstantInt(CC))) &&
444 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
445 Value *YS = // (Y << C)
446 Builder->CreateShl(Op0BO->getOperand(0), Op1,
447 Op0BO->getName());
448 // X & (CC << C)
449 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
450 V1->getName()+".mask");
451 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000452 }
453 }
Chris Lattnerabff82d2010-01-10 06:59:55 +0000454
455 // FALL THROUGH.
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),
460 m_Specific(Op1)))) {
461 Value *YS = // (Y << C)
462 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
463 // (X + (Y << C))
464 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
465 Op0BO->getOperand(0)->getName());
466 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
467 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
468 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
469 }
470
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_Shr(m_Value(V1), m_Value(V2)),
475 m_ConstantInt(CC))) && V2 == Op1 &&
476 cast<BinaryOperator>(Op0BO->getOperand(0))
477 ->getOperand(0)->hasOneUse()) {
478 Value *YS = // (Y << C)
479 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
480 // X & (CC << C)
481 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
482 V1->getName()+".mask");
483
484 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
485 }
486
487 break;
488 }
489 }
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000490
491
492 // If the operand is an bitwise operator with a constant RHS, and the
493 // shift is the only use, we can pull it out of the shift.
494 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
495 bool isValid = true; // Valid only for And, Or, Xor
496 bool highBitSet = false; // Transform if high bit of constant set?
497
498 switch (Op0BO->getOpcode()) {
Chris Lattnerabff82d2010-01-10 06:59:55 +0000499 default: isValid = false; break; // Do not perform transform!
500 case Instruction::Add:
501 isValid = isLeftShift;
502 break;
503 case Instruction::Or:
504 case Instruction::Xor:
505 highBitSet = false;
506 break;
507 case Instruction::And:
508 highBitSet = true;
509 break;
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000510 }
511
512 // If this is a signed shift right, and the high bit is modified
513 // by the logical operation, do not perform the transformation.
514 // The highBitSet boolean indicates the value of the high bit of
515 // the constant which would cause it to be modified for this
516 // operation.
517 //
518 if (isValid && I.getOpcode() == Instruction::AShr)
519 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
520
521 if (isValid) {
522 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
523
524 Value *NewShift =
525 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
526 NewShift->takeName(Op0BO);
527
528 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
529 NewRHS);
530 }
531 }
532 }
533 }
534
535 // Find out if this is a shift of a shift by a constant.
536 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
537 if (ShiftOp && !ShiftOp->isShift())
538 ShiftOp = 0;
539
540 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
541 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
542 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
543 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
544 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
545 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
546 Value *X = ShiftOp->getOperand(0);
547
548 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
549
550 const IntegerType *Ty = cast<IntegerType>(I.getType());
551
552 // Check for (X << c1) << c2 and (X >> c1) >> c2
553 if (I.getOpcode() == ShiftOp->getOpcode()) {
554 // If this is oversized composite shift, then unsigned shifts get 0, ashr
555 // saturates.
556 if (AmtSum >= TypeBits) {
557 if (I.getOpcode() != Instruction::AShr)
558 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
559 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
560 }
561
562 return BinaryOperator::Create(I.getOpcode(), X,
563 ConstantInt::get(Ty, AmtSum));
564 }
565
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000566 if (ShiftAmt1 == ShiftAmt2) {
567 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
Chris Lattner2d0822a2010-08-27 21:04:34 +0000568 if (I.getOpcode() == Instruction::Shl &&
569 ShiftOp->getOpcode() != Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000570 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
571 return BinaryOperator::CreateAnd(X,
572 ConstantInt::get(I.getContext(),Mask));
573 }
574 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
Chris Lattner2d0822a2010-08-27 21:04:34 +0000575 if (I.getOpcode() == Instruction::LShr &&
576 ShiftOp->getOpcode() == Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000577 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
578 return BinaryOperator::CreateAnd(X,
579 ConstantInt::get(I.getContext(), Mask));
580 }
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000581 } else if (ShiftAmt1 < ShiftAmt2) {
582 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
583
584 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner2d0822a2010-08-27 21:04:34 +0000585 if (I.getOpcode() == Instruction::Shl &&
586 ShiftOp->getOpcode() != Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000587 assert(ShiftOp->getOpcode() == Instruction::LShr ||
588 ShiftOp->getOpcode() == Instruction::AShr);
589 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
590
591 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
592 return BinaryOperator::CreateAnd(Shift,
593 ConstantInt::get(I.getContext(),Mask));
594 }
595
596 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner2d0822a2010-08-27 21:04:34 +0000597 if (I.getOpcode() == Instruction::LShr &&
598 ShiftOp->getOpcode() == Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000599 assert(ShiftOp->getOpcode() == Instruction::Shl);
600 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
601
602 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
603 return BinaryOperator::CreateAnd(Shift,
604 ConstantInt::get(I.getContext(),Mask));
605 }
606
607 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
608 } else {
609 assert(ShiftAmt2 < ShiftAmt1);
610 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
611
612 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner2d0822a2010-08-27 21:04:34 +0000613 if (I.getOpcode() == Instruction::Shl &&
614 ShiftOp->getOpcode() != Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000615 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
616 ConstantInt::get(Ty, ShiftDiff));
617
618 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
619 return BinaryOperator::CreateAnd(Shift,
620 ConstantInt::get(I.getContext(),Mask));
621 }
622
623 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner2d0822a2010-08-27 21:04:34 +0000624 if (I.getOpcode() == Instruction::LShr &&
625 ShiftOp->getOpcode() == Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000626 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
627
628 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
629 return BinaryOperator::CreateAnd(Shift,
630 ConstantInt::get(I.getContext(),Mask));
631 }
632
633 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
634 }
635 }
636 return 0;
637}
638
639Instruction *InstCombiner::visitShl(BinaryOperator &I) {
640 return commonShiftTransforms(I);
641}
642
643Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
Chris Lattner818ff342010-01-23 18:49:30 +0000644 if (Instruction *R = commonShiftTransforms(I))
645 return R;
646
647 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
648
649 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1))
650 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
Chris Lattnerf7d0d162010-01-23 23:31:46 +0000651 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
Chris Lattner818ff342010-01-23 18:49:30 +0000652 // ctlz.i32(x)>>5 --> zext(x == 0)
653 // cttz.i32(x)>>5 --> zext(x == 0)
654 // ctpop.i32(x)>>5 --> zext(x == -1)
655 if ((II->getIntrinsicID() == Intrinsic::ctlz ||
656 II->getIntrinsicID() == Intrinsic::cttz ||
657 II->getIntrinsicID() == Intrinsic::ctpop) &&
Chris Lattnerf7d0d162010-01-23 23:31:46 +0000658 isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == Op1C->getZExtValue()){
Chris Lattner818ff342010-01-23 18:49:30 +0000659 bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
Chris Lattnerf7d0d162010-01-23 23:31:46 +0000660 Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
Gabor Greifde9f5452010-06-24 00:44:01 +0000661 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
Chris Lattner818ff342010-01-23 18:49:30 +0000662 return new ZExtInst(Cmp, II->getType());
663 }
664 }
665
666 return 0;
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000667}
668
669Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
670 if (Instruction *R = commonShiftTransforms(I))
671 return R;
672
Chris Lattnera85732f2010-01-08 19:04:21 +0000673 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000674
Chris Lattnera85732f2010-01-08 19:04:21 +0000675 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0)) {
676 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000677 if (CSI->isAllOnesValue())
678 return ReplaceInstUsesWith(I, CSI);
Chris Lattnera85732f2010-01-08 19:04:21 +0000679 }
680
681 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
682 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
Chris Lattnercd5adbb2010-01-18 22:19:16 +0000683 // have a sign-extend idiom.
Chris Lattnera85732f2010-01-08 19:04:21 +0000684 Value *X;
Chris Lattnercd5adbb2010-01-18 22:19:16 +0000685 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
686 // If the input value is known to already be sign extended enough, delete
687 // the extension.
688 if (ComputeNumSignBits(X) > Op1C->getZExtValue())
689 return ReplaceInstUsesWith(I, X);
690
691 // If the input is an extension from the shifted amount value, e.g.
692 // %x = zext i8 %A to i32
693 // %y = shl i32 %x, 24
694 // %z = ashr %y, 24
695 // then turn this into "z = sext i8 A to i32".
696 if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
697 uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
698 uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
699 if (Op1C->getZExtValue() == DestBits-SrcBits)
700 return new SExtInst(ZI->getOperand(0), ZI->getType());
701 }
702 }
Chris Lattnera85732f2010-01-08 19:04:21 +0000703 }
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000704
705 // See if we can turn a signed shr into an unsigned shr.
706 if (MaskedValueIsZero(Op0,
707 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
Chris Lattnera85732f2010-01-08 19:04:21 +0000708 return BinaryOperator::CreateLShr(Op0, Op1);
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000709
710 // Arithmetic shifting an all-sign-bit value is a no-op.
711 unsigned NumSignBits = ComputeNumSignBits(Op0);
712 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
713 return ReplaceInstUsesWith(I, Op0);
714
715 return 0;
716}
717