blob: e3232a491b7c6e170dab999b669282982c4c4016 [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
Benjamin Kramerc21a8212010-11-23 20:33:57 +000057 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
Benjamin Kramerb70ebd22010-11-23 18:52:42 +000058 // Because shifts by negative values are undefined.
59 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op1))
Benjamin Kramerc21a8212010-11-23 20:33:57 +000060 if (BO->hasOneUse() && BO->getOpcode() == Instruction::SRem)
61 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
62 if (CI->getValue().isPowerOf2()) {
63 Constant *C = ConstantInt::get(BO->getType(), CI->getValue()-1);
64 Value *Rem = Builder->CreateAnd(BO->getOperand(0), C, BO->getName());
65 I.setOperand(1, Rem);
66 return &I;
67 }
Benjamin Kramerb70ebd22010-11-23 18:52:42 +000068
Chris Lattner9cdd5f32010-01-05 07:44:46 +000069 return 0;
70}
71
Chris Lattner29cc0b32010-08-27 22:24:38 +000072/// CanEvaluateShifted - See if we can compute the specified value, but shifted
73/// logically to the left or right by some number of bits. This should return
74/// true if the expression can be computed for the same cost as the current
75/// expression tree. This is used to eliminate extraneous shifting from things
76/// like:
77/// %C = shl i128 %A, 64
78/// %D = shl i128 %B, 96
79/// %E = or i128 %C, %D
80/// %F = lshr i128 %E, 64
81/// where the client will ask if E can be computed shifted right by 64-bits. If
82/// this succeeds, the GetShiftedValue function will be called to produce the
83/// value.
84static bool CanEvaluateShifted(Value *V, unsigned NumBits, bool isLeftShift,
85 InstCombiner &IC) {
86 // We can always evaluate constants shifted.
87 if (isa<Constant>(V))
88 return true;
89
90 Instruction *I = dyn_cast<Instruction>(V);
91 if (!I) return false;
92
93 // If this is the opposite shift, we can directly reuse the input of the shift
94 // if the needed bits are already zero in the input. This allows us to reuse
95 // the value which means that we don't care if the shift has multiple uses.
96 // TODO: Handle opposite shift by exact value.
97 ConstantInt *CI;
98 if ((isLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
99 (!isLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
100 if (CI->getZExtValue() == NumBits) {
101 // TODO: Check that the input bits are already zero with MaskedValueIsZero
102#if 0
103 // If this is a truncate of a logical shr, we can truncate it to a smaller
104 // lshr iff we know that the bits we would otherwise be shifting in are
105 // already zeros.
106 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
107 uint32_t BitWidth = Ty->getScalarSizeInBits();
108 if (MaskedValueIsZero(I->getOperand(0),
109 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
110 CI->getLimitedValue(BitWidth) < BitWidth) {
111 return CanEvaluateTruncated(I->getOperand(0), Ty);
112 }
113#endif
114
115 }
116 }
117
118 // We can't mutate something that has multiple uses: doing so would
119 // require duplicating the instruction in general, which isn't profitable.
120 if (!I->hasOneUse()) return false;
121
122 switch (I->getOpcode()) {
123 default: return false;
124 case Instruction::And:
125 case Instruction::Or:
126 case Instruction::Xor:
127 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
128 return CanEvaluateShifted(I->getOperand(0), NumBits, isLeftShift, IC) &&
129 CanEvaluateShifted(I->getOperand(1), NumBits, isLeftShift, IC);
130
Chris Lattner4ece5772010-08-27 22:53:44 +0000131 case Instruction::Shl: {
Chris Lattner29cc0b32010-08-27 22:24:38 +0000132 // We can often fold the shift into shifts-by-a-constant.
133 CI = dyn_cast<ConstantInt>(I->getOperand(1));
134 if (CI == 0) return false;
135
136 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
137 if (isLeftShift) return true;
138
139 // We can always turn shl(c)+shr(c) -> and(c2).
140 if (CI->getValue() == NumBits) return true;
Chris Lattner4ece5772010-08-27 22:53:44 +0000141
142 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
143
144 // We can turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but it isn't
Chris Lattner29cc0b32010-08-27 22:24:38 +0000145 // profitable unless we know the and'd out bits are already zero.
Chris Lattner4ece5772010-08-27 22:53:44 +0000146 if (CI->getZExtValue() > NumBits) {
Dale Johannesen201ab3a2010-11-10 01:30:56 +0000147 unsigned LowBits = TypeWidth - CI->getZExtValue();
Chris Lattner4ece5772010-08-27 22:53:44 +0000148 if (MaskedValueIsZero(I->getOperand(0),
Dale Johannesen201ab3a2010-11-10 01:30:56 +0000149 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
Chris Lattner4ece5772010-08-27 22:53:44 +0000150 return true;
151 }
152
Chris Lattner29cc0b32010-08-27 22:24:38 +0000153 return false;
Chris Lattner4ece5772010-08-27 22:53:44 +0000154 }
155 case Instruction::LShr: {
Chris Lattner29cc0b32010-08-27 22:24:38 +0000156 // We can often fold the shift into shifts-by-a-constant.
157 CI = dyn_cast<ConstantInt>(I->getOperand(1));
158 if (CI == 0) return false;
159
160 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
161 if (!isLeftShift) return true;
162
163 // We can always turn lshr(c)+shl(c) -> and(c2).
164 if (CI->getValue() == NumBits) return true;
165
Chris Lattner4ece5772010-08-27 22:53:44 +0000166 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
167
Chris Lattner29cc0b32010-08-27 22:24:38 +0000168 // We can always turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but it isn't
169 // profitable unless we know the and'd out bits are already zero.
Chris Lattner4ece5772010-08-27 22:53:44 +0000170 if (CI->getZExtValue() > NumBits) {
Chris Lattner4ece5772010-08-27 22:53:44 +0000171 if (MaskedValueIsZero(I->getOperand(0),
Dan Gohmand8e0c042010-12-09 02:52:17 +0000172 APInt::getLowBitsSet(TypeWidth, NumBits)))
Chris Lattner4ece5772010-08-27 22:53:44 +0000173 return true;
174 }
Chris Lattner29cc0b32010-08-27 22:24:38 +0000175
Chris Lattner4ece5772010-08-27 22:53:44 +0000176 return false;
177 }
Chris Lattner29cc0b32010-08-27 22:24:38 +0000178 case Instruction::Select: {
179 SelectInst *SI = cast<SelectInst>(I);
180 return CanEvaluateShifted(SI->getTrueValue(), NumBits, isLeftShift, IC) &&
181 CanEvaluateShifted(SI->getFalseValue(), NumBits, isLeftShift, IC);
182 }
183 case Instruction::PHI: {
184 // We can change a phi if we can change all operands. Note that we never
185 // get into trouble with cyclic PHIs here because we only consider
186 // instructions with a single use.
187 PHINode *PN = cast<PHINode>(I);
188 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
189 if (!CanEvaluateShifted(PN->getIncomingValue(i), NumBits, isLeftShift,IC))
190 return false;
191 return true;
192 }
193 }
194}
195
196/// GetShiftedValue - When CanEvaluateShifted returned true for an expression,
197/// this value inserts the new computation that produces the shifted value.
198static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
199 InstCombiner &IC) {
200 // We can always evaluate constants shifted.
201 if (Constant *C = dyn_cast<Constant>(V)) {
202 if (isLeftShift)
203 V = IC.Builder->CreateShl(C, NumBits);
204 else
205 V = IC.Builder->CreateLShr(C, NumBits);
206 // If we got a constantexpr back, try to simplify it with TD info.
207 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
208 V = ConstantFoldConstantExpression(CE, IC.getTargetData());
209 return V;
210 }
211
212 Instruction *I = cast<Instruction>(V);
213 IC.Worklist.Add(I);
214
215 switch (I->getOpcode()) {
216 default: assert(0 && "Inconsistency with CanEvaluateShifted");
217 case Instruction::And:
218 case Instruction::Or:
219 case Instruction::Xor:
220 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
221 I->setOperand(0, GetShiftedValue(I->getOperand(0), NumBits,isLeftShift,IC));
222 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
223 return I;
224
225 case Instruction::Shl: {
226 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
227
228 // We only accept shifts-by-a-constant in CanEvaluateShifted.
229 ConstantInt *CI = cast<ConstantInt>(I->getOperand(1));
230
231 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
232 if (isLeftShift) {
233 // If this is oversized composite shift, then unsigned shifts get 0.
234 unsigned NewShAmt = NumBits+CI->getZExtValue();
235 if (NewShAmt >= TypeWidth)
236 return Constant::getNullValue(I->getType());
237
238 I->setOperand(1, ConstantInt::get(I->getType(), NewShAmt));
239 return I;
240 }
241
242 // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
243 // zeros.
Chris Lattner4ece5772010-08-27 22:53:44 +0000244 if (CI->getValue() == NumBits) {
245 APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
246 V = IC.Builder->CreateAnd(I->getOperand(0),
247 ConstantInt::get(I->getContext(), Mask));
248 if (Instruction *VI = dyn_cast<Instruction>(V)) {
249 VI->moveBefore(I);
250 VI->takeName(I);
251 }
252 return V;
Chris Lattner29cc0b32010-08-27 22:24:38 +0000253 }
Chris Lattner4ece5772010-08-27 22:53:44 +0000254
255 // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
256 // the and won't be needed.
257 assert(CI->getZExtValue() > NumBits);
258 I->setOperand(1, ConstantInt::get(I->getType(),
259 CI->getZExtValue() - NumBits));
260 return I;
Chris Lattner29cc0b32010-08-27 22:24:38 +0000261 }
262 case Instruction::LShr: {
263 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
264 // We only accept shifts-by-a-constant in CanEvaluateShifted.
265 ConstantInt *CI = cast<ConstantInt>(I->getOperand(1));
266
267 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
268 if (!isLeftShift) {
269 // If this is oversized composite shift, then unsigned shifts get 0.
270 unsigned NewShAmt = NumBits+CI->getZExtValue();
271 if (NewShAmt >= TypeWidth)
272 return Constant::getNullValue(I->getType());
273
274 I->setOperand(1, ConstantInt::get(I->getType(), NewShAmt));
275 return I;
276 }
277
278 // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
279 // zeros.
Chris Lattner4ece5772010-08-27 22:53:44 +0000280 if (CI->getValue() == NumBits) {
281 APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
282 V = IC.Builder->CreateAnd(I->getOperand(0),
283 ConstantInt::get(I->getContext(), Mask));
284 if (Instruction *VI = dyn_cast<Instruction>(V)) {
285 VI->moveBefore(I);
286 VI->takeName(I);
287 }
288 return V;
Chris Lattner29cc0b32010-08-27 22:24:38 +0000289 }
Chris Lattner4ece5772010-08-27 22:53:44 +0000290
291 // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
292 // the and won't be needed.
293 assert(CI->getZExtValue() > NumBits);
294 I->setOperand(1, ConstantInt::get(I->getType(),
295 CI->getZExtValue() - NumBits));
296 return I;
Chris Lattner29cc0b32010-08-27 22:24:38 +0000297 }
298
299 case Instruction::Select:
300 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
301 I->setOperand(2, GetShiftedValue(I->getOperand(2), NumBits,isLeftShift,IC));
302 return I;
303 case Instruction::PHI: {
304 // We can change a phi if we can change all operands. Note that we never
305 // get into trouble with cyclic PHIs here because we only consider
306 // instructions with a single use.
307 PHINode *PN = cast<PHINode>(I);
308 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
309 PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i),
310 NumBits, isLeftShift, IC));
311 return PN;
312 }
313 }
314}
315
316
317
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000318Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
319 BinaryOperator &I) {
320 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner2d0822a2010-08-27 21:04:34 +0000321
Chris Lattner29cc0b32010-08-27 22:24:38 +0000322
323 // See if we can propagate this shift into the input, this covers the trivial
324 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
325 if (I.getOpcode() != Instruction::AShr &&
326 CanEvaluateShifted(Op0, Op1->getZExtValue(), isLeftShift, *this)) {
Chris Lattner3dd08732010-08-28 01:20:38 +0000327 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
328 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
Chris Lattner29cc0b32010-08-27 22:24:38 +0000329
330 return ReplaceInstUsesWith(I,
331 GetShiftedValue(Op0, Op1->getZExtValue(), isLeftShift, *this));
332 }
333
334
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000335 // See if we can simplify any instructions used by the instruction whose sole
336 // purpose is to compute bits we don't care about.
337 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
338
339 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
340 // a signed shift.
341 //
342 if (Op1->uge(TypeBits)) {
343 if (I.getOpcode() != Instruction::AShr)
344 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner818ff342010-01-23 18:49:30 +0000345 // ashr i32 X, 32 --> ashr i32 X, 31
346 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
347 return &I;
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000348 }
349
350 // ((X*C1) << C2) == (X * (C1 << C2))
351 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
352 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
353 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
354 return BinaryOperator::CreateMul(BO->getOperand(0),
355 ConstantExpr::getShl(BOOp, Op1));
356
357 // Try to fold constant and into select arguments.
358 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
359 if (Instruction *R = FoldOpIntoSelect(I, SI))
360 return R;
361 if (isa<PHINode>(Op0))
362 if (Instruction *NV = FoldOpIntoPhi(I))
363 return NV;
364
365 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
366 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
367 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
368 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
369 // place. Don't try to do this transformation in this case. Also, we
370 // require that the input operand is a shift-by-constant so that we have
371 // confidence that the shifts will get folded together. We could do this
372 // xform in more cases, but it is unlikely to be profitable.
373 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
374 isa<ConstantInt>(TrOp->getOperand(1))) {
375 // Okay, we'll do this xform. Make the shift of shift.
376 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
377 // (shift2 (shift1 & 0x00FF), c2)
378 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
379
380 // For logical shifts, the truncation has the effect of making the high
381 // part of the register be zeros. Emulate this by inserting an AND to
382 // clear the top bits as needed. This 'and' will usually be zapped by
383 // other xforms later if dead.
384 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
385 unsigned DstSize = TI->getType()->getScalarSizeInBits();
386 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
387
388 // The mask we constructed says what the trunc would do if occurring
389 // between the shifts. We want to know the effect *after* the second
390 // shift. We know that it is a logical shift by a constant, so adjust the
391 // mask as appropriate.
392 if (I.getOpcode() == Instruction::Shl)
393 MaskV <<= Op1->getZExtValue();
394 else {
395 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
396 MaskV = MaskV.lshr(Op1->getZExtValue());
397 }
398
399 // shift1 & 0x00FF
400 Value *And = Builder->CreateAnd(NSh,
401 ConstantInt::get(I.getContext(), MaskV),
402 TI->getName());
403
404 // Return the value truncated to the interesting size.
405 return new TruncInst(And, I.getType());
406 }
407 }
408
409 if (Op0->hasOneUse()) {
410 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
411 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
412 Value *V1, *V2;
413 ConstantInt *CC;
414 switch (Op0BO->getOpcode()) {
Chris Lattnerabff82d2010-01-10 06:59:55 +0000415 default: break;
416 case Instruction::Add:
417 case Instruction::And:
418 case Instruction::Or:
419 case Instruction::Xor: {
420 // These operators commute.
421 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
422 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
423 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
424 m_Specific(Op1)))) {
425 Value *YS = // (Y << C)
426 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
427 // (X + (Y << C))
428 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
429 Op0BO->getOperand(1)->getName());
430 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
431 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
432 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000433 }
Chris Lattnerabff82d2010-01-10 06:59:55 +0000434
435 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
436 Value *Op0BOOp1 = Op0BO->getOperand(1);
437 if (isLeftShift && Op0BOOp1->hasOneUse() &&
438 match(Op0BOOp1,
439 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
440 m_ConstantInt(CC))) &&
441 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
442 Value *YS = // (Y << C)
443 Builder->CreateShl(Op0BO->getOperand(0), Op1,
444 Op0BO->getName());
445 // X & (CC << C)
446 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
447 V1->getName()+".mask");
448 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000449 }
450 }
Chris Lattnerabff82d2010-01-10 06:59:55 +0000451
452 // FALL THROUGH.
453 case Instruction::Sub: {
454 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
455 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
456 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
457 m_Specific(Op1)))) {
458 Value *YS = // (Y << C)
459 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
460 // (X + (Y << C))
461 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
462 Op0BO->getOperand(0)->getName());
463 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
464 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
465 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
466 }
467
468 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
469 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
470 match(Op0BO->getOperand(0),
471 m_And(m_Shr(m_Value(V1), m_Value(V2)),
472 m_ConstantInt(CC))) && V2 == Op1 &&
473 cast<BinaryOperator>(Op0BO->getOperand(0))
474 ->getOperand(0)->hasOneUse()) {
475 Value *YS = // (Y << C)
476 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
477 // X & (CC << C)
478 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
479 V1->getName()+".mask");
480
481 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
482 }
483
484 break;
485 }
486 }
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000487
488
489 // If the operand is an bitwise operator with a constant RHS, and the
490 // shift is the only use, we can pull it out of the shift.
491 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
492 bool isValid = true; // Valid only for And, Or, Xor
493 bool highBitSet = false; // Transform if high bit of constant set?
494
495 switch (Op0BO->getOpcode()) {
Chris Lattnerabff82d2010-01-10 06:59:55 +0000496 default: isValid = false; break; // Do not perform transform!
497 case Instruction::Add:
498 isValid = isLeftShift;
499 break;
500 case Instruction::Or:
501 case Instruction::Xor:
502 highBitSet = false;
503 break;
504 case Instruction::And:
505 highBitSet = true;
506 break;
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000507 }
508
509 // If this is a signed shift right, and the high bit is modified
510 // by the logical operation, do not perform the transformation.
511 // The highBitSet boolean indicates the value of the high bit of
512 // the constant which would cause it to be modified for this
513 // operation.
514 //
515 if (isValid && I.getOpcode() == Instruction::AShr)
516 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
517
518 if (isValid) {
519 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
520
521 Value *NewShift =
522 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
523 NewShift->takeName(Op0BO);
524
525 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
526 NewRHS);
527 }
528 }
529 }
530 }
531
532 // Find out if this is a shift of a shift by a constant.
533 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
534 if (ShiftOp && !ShiftOp->isShift())
535 ShiftOp = 0;
536
537 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
538 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
539 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
540 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
541 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
542 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
543 Value *X = ShiftOp->getOperand(0);
544
545 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
546
547 const IntegerType *Ty = cast<IntegerType>(I.getType());
548
549 // Check for (X << c1) << c2 and (X >> c1) >> c2
550 if (I.getOpcode() == ShiftOp->getOpcode()) {
551 // If this is oversized composite shift, then unsigned shifts get 0, ashr
552 // saturates.
553 if (AmtSum >= TypeBits) {
554 if (I.getOpcode() != Instruction::AShr)
555 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
556 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
557 }
558
559 return BinaryOperator::Create(I.getOpcode(), X,
560 ConstantInt::get(Ty, AmtSum));
561 }
562
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000563 if (ShiftAmt1 == ShiftAmt2) {
564 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
Chris Lattner2d0822a2010-08-27 21:04:34 +0000565 if (I.getOpcode() == Instruction::Shl &&
566 ShiftOp->getOpcode() != Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000567 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
568 return BinaryOperator::CreateAnd(X,
569 ConstantInt::get(I.getContext(),Mask));
570 }
571 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
Chris Lattner2d0822a2010-08-27 21:04:34 +0000572 if (I.getOpcode() == Instruction::LShr &&
573 ShiftOp->getOpcode() == Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000574 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
575 return BinaryOperator::CreateAnd(X,
576 ConstantInt::get(I.getContext(), Mask));
577 }
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000578 } else if (ShiftAmt1 < ShiftAmt2) {
579 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
580
581 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner2d0822a2010-08-27 21:04:34 +0000582 if (I.getOpcode() == Instruction::Shl &&
583 ShiftOp->getOpcode() != Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000584 assert(ShiftOp->getOpcode() == Instruction::LShr ||
585 ShiftOp->getOpcode() == Instruction::AShr);
586 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
587
588 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
589 return BinaryOperator::CreateAnd(Shift,
590 ConstantInt::get(I.getContext(),Mask));
591 }
592
593 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner2d0822a2010-08-27 21:04:34 +0000594 if (I.getOpcode() == Instruction::LShr &&
595 ShiftOp->getOpcode() == Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000596 assert(ShiftOp->getOpcode() == Instruction::Shl);
597 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
598
599 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
600 return BinaryOperator::CreateAnd(Shift,
601 ConstantInt::get(I.getContext(),Mask));
602 }
603
604 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
605 } else {
606 assert(ShiftAmt2 < ShiftAmt1);
607 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
608
609 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner2d0822a2010-08-27 21:04:34 +0000610 if (I.getOpcode() == Instruction::Shl &&
611 ShiftOp->getOpcode() != Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000612 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
613 ConstantInt::get(Ty, ShiftDiff));
614
615 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
616 return BinaryOperator::CreateAnd(Shift,
617 ConstantInt::get(I.getContext(),Mask));
618 }
619
620 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner2d0822a2010-08-27 21:04:34 +0000621 if (I.getOpcode() == Instruction::LShr &&
622 ShiftOp->getOpcode() == Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000623 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
624
625 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
626 return BinaryOperator::CreateAnd(Shift,
627 ConstantInt::get(I.getContext(),Mask));
628 }
629
630 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
631 }
632 }
633 return 0;
634}
635
636Instruction *InstCombiner::visitShl(BinaryOperator &I) {
637 return commonShiftTransforms(I);
638}
639
640Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
Chris Lattner818ff342010-01-23 18:49:30 +0000641 if (Instruction *R = commonShiftTransforms(I))
642 return R;
643
644 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
645
646 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1))
647 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
Chris Lattnerf7d0d162010-01-23 23:31:46 +0000648 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
Chris Lattner818ff342010-01-23 18:49:30 +0000649 // ctlz.i32(x)>>5 --> zext(x == 0)
650 // cttz.i32(x)>>5 --> zext(x == 0)
651 // ctpop.i32(x)>>5 --> zext(x == -1)
652 if ((II->getIntrinsicID() == Intrinsic::ctlz ||
653 II->getIntrinsicID() == Intrinsic::cttz ||
654 II->getIntrinsicID() == Intrinsic::ctpop) &&
Chris Lattnerf7d0d162010-01-23 23:31:46 +0000655 isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == Op1C->getZExtValue()){
Chris Lattner818ff342010-01-23 18:49:30 +0000656 bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
Chris Lattnerf7d0d162010-01-23 23:31:46 +0000657 Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
Gabor Greifde9f5452010-06-24 00:44:01 +0000658 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
Chris Lattner818ff342010-01-23 18:49:30 +0000659 return new ZExtInst(Cmp, II->getType());
660 }
661 }
662
663 return 0;
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000664}
665
666Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
667 if (Instruction *R = commonShiftTransforms(I))
668 return R;
669
Chris Lattnera85732f2010-01-08 19:04:21 +0000670 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000671
Chris Lattnera85732f2010-01-08 19:04:21 +0000672 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0)) {
673 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000674 if (CSI->isAllOnesValue())
675 return ReplaceInstUsesWith(I, CSI);
Chris Lattnera85732f2010-01-08 19:04:21 +0000676 }
677
678 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
679 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
Chris Lattnercd5adbb2010-01-18 22:19:16 +0000680 // have a sign-extend idiom.
Chris Lattnera85732f2010-01-08 19:04:21 +0000681 Value *X;
Chris Lattnercd5adbb2010-01-18 22:19:16 +0000682 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
683 // If the input value is known to already be sign extended enough, delete
684 // the extension.
685 if (ComputeNumSignBits(X) > Op1C->getZExtValue())
686 return ReplaceInstUsesWith(I, X);
687
688 // If the input is an extension from the shifted amount value, e.g.
689 // %x = zext i8 %A to i32
690 // %y = shl i32 %x, 24
691 // %z = ashr %y, 24
692 // then turn this into "z = sext i8 A to i32".
693 if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
694 uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
695 uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
696 if (Op1C->getZExtValue() == DestBits-SrcBits)
697 return new SExtInst(ZI->getOperand(0), ZI->getType());
698 }
699 }
Chris Lattnera85732f2010-01-08 19:04:21 +0000700 }
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000701
702 // See if we can turn a signed shr into an unsigned shr.
703 if (MaskedValueIsZero(Op0,
704 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
Chris Lattnera85732f2010-01-08 19:04:21 +0000705 return BinaryOperator::CreateLShr(Op0, Op1);
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000706
707 // Arithmetic shifting an all-sign-bit value is a no-op.
708 unsigned NumSignBits = ComputeNumSignBits(Op0);
709 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
710 return ReplaceInstUsesWith(I, Op0);
711
712 return 0;
713}
714