1 //===- 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/IntrinsicInst.h"
16 #include "llvm/Analysis/ConstantFolding.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Support/PatternMatch.h"
19 using namespace llvm;
20 using namespace PatternMatch;
21
commonShiftTransforms(BinaryOperator & I)22 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
23 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
24 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
25
26 // See if we can fold away this shift.
27 if (SimplifyDemandedInstructionBits(I))
28 return &I;
29
30 // Try to fold constant and into select arguments.
31 if (isa<Constant>(Op0))
32 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
33 if (Instruction *R = FoldOpIntoSelect(I, SI))
34 return R;
35
36 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
37 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
38 return Res;
39
40 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
41 // Because shifts by negative values (which could occur if A were negative)
42 // are undefined.
43 Value *A; const APInt *B;
44 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
45 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
46 // demand the sign bit (and many others) here??
47 Value *Rem = Builder->CreateAnd(A, ConstantInt::get(I.getType(), *B-1),
48 Op1->getName());
49 I.setOperand(1, Rem);
50 return &I;
51 }
52
53 return 0;
54 }
55
56 /// CanEvaluateShifted - See if we can compute the specified value, but shifted
57 /// logically to the left or right by some number of bits. This should return
58 /// true if the expression can be computed for the same cost as the current
59 /// expression tree. This is used to eliminate extraneous shifting from things
60 /// like:
61 /// %C = shl i128 %A, 64
62 /// %D = shl i128 %B, 96
63 /// %E = or i128 %C, %D
64 /// %F = lshr i128 %E, 64
65 /// where the client will ask if E can be computed shifted right by 64-bits. If
66 /// this succeeds, the GetShiftedValue function will be called to produce the
67 /// value.
CanEvaluateShifted(Value * V,unsigned NumBits,bool isLeftShift,InstCombiner & IC)68 static bool CanEvaluateShifted(Value *V, unsigned NumBits, bool isLeftShift,
69 InstCombiner &IC) {
70 // We can always evaluate constants shifted.
71 if (isa<Constant>(V))
72 return true;
73
74 Instruction *I = dyn_cast<Instruction>(V);
75 if (!I) return false;
76
77 // If this is the opposite shift, we can directly reuse the input of the shift
78 // if the needed bits are already zero in the input. This allows us to reuse
79 // the value which means that we don't care if the shift has multiple uses.
80 // TODO: Handle opposite shift by exact value.
81 ConstantInt *CI = 0;
82 if ((isLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
83 (!isLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
84 if (CI->getZExtValue() == NumBits) {
85 // TODO: Check that the input bits are already zero with MaskedValueIsZero
86 #if 0
87 // If this is a truncate of a logical shr, we can truncate it to a smaller
88 // lshr iff we know that the bits we would otherwise be shifting in are
89 // already zeros.
90 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
91 uint32_t BitWidth = Ty->getScalarSizeInBits();
92 if (MaskedValueIsZero(I->getOperand(0),
93 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
94 CI->getLimitedValue(BitWidth) < BitWidth) {
95 return CanEvaluateTruncated(I->getOperand(0), Ty);
96 }
97 #endif
98
99 }
100 }
101
102 // We can't mutate something that has multiple uses: doing so would
103 // require duplicating the instruction in general, which isn't profitable.
104 if (!I->hasOneUse()) return false;
105
106 switch (I->getOpcode()) {
107 default: return false;
108 case Instruction::And:
109 case Instruction::Or:
110 case Instruction::Xor:
111 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
112 return CanEvaluateShifted(I->getOperand(0), NumBits, isLeftShift, IC) &&
113 CanEvaluateShifted(I->getOperand(1), NumBits, isLeftShift, IC);
114
115 case Instruction::Shl: {
116 // We can often fold the shift into shifts-by-a-constant.
117 CI = dyn_cast<ConstantInt>(I->getOperand(1));
118 if (CI == 0) return false;
119
120 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
121 if (isLeftShift) return true;
122
123 // We can always turn shl(c)+shr(c) -> and(c2).
124 if (CI->getValue() == NumBits) return true;
125
126 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
127
128 // We can turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but it isn't
129 // profitable unless we know the and'd out bits are already zero.
130 if (CI->getZExtValue() > NumBits) {
131 unsigned LowBits = TypeWidth - CI->getZExtValue();
132 if (MaskedValueIsZero(I->getOperand(0),
133 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
134 return true;
135 }
136
137 return false;
138 }
139 case Instruction::LShr: {
140 // We can often fold the shift into shifts-by-a-constant.
141 CI = dyn_cast<ConstantInt>(I->getOperand(1));
142 if (CI == 0) return false;
143
144 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
145 if (!isLeftShift) return true;
146
147 // We can always turn lshr(c)+shl(c) -> and(c2).
148 if (CI->getValue() == NumBits) return true;
149
150 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
151
152 // We can always turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but it isn't
153 // profitable unless we know the and'd out bits are already zero.
154 if (CI->getZExtValue() > NumBits) {
155 unsigned LowBits = CI->getZExtValue() - NumBits;
156 if (MaskedValueIsZero(I->getOperand(0),
157 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
158 return true;
159 }
160
161 return false;
162 }
163 case Instruction::Select: {
164 SelectInst *SI = cast<SelectInst>(I);
165 return CanEvaluateShifted(SI->getTrueValue(), NumBits, isLeftShift, IC) &&
166 CanEvaluateShifted(SI->getFalseValue(), NumBits, isLeftShift, IC);
167 }
168 case Instruction::PHI: {
169 // We can change a phi if we can change all operands. Note that we never
170 // get into trouble with cyclic PHIs here because we only consider
171 // instructions with a single use.
172 PHINode *PN = cast<PHINode>(I);
173 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
174 if (!CanEvaluateShifted(PN->getIncomingValue(i), NumBits, isLeftShift,IC))
175 return false;
176 return true;
177 }
178 }
179 }
180
181 /// GetShiftedValue - When CanEvaluateShifted returned true for an expression,
182 /// this value inserts the new computation that produces the shifted value.
GetShiftedValue(Value * V,unsigned NumBits,bool isLeftShift,InstCombiner & IC)183 static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
184 InstCombiner &IC) {
185 // We can always evaluate constants shifted.
186 if (Constant *C = dyn_cast<Constant>(V)) {
187 if (isLeftShift)
188 V = IC.Builder->CreateShl(C, NumBits);
189 else
190 V = IC.Builder->CreateLShr(C, NumBits);
191 // If we got a constantexpr back, try to simplify it with TD info.
192 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
193 V = ConstantFoldConstantExpression(CE, IC.getTargetData());
194 return V;
195 }
196
197 Instruction *I = cast<Instruction>(V);
198 IC.Worklist.Add(I);
199
200 switch (I->getOpcode()) {
201 default: assert(0 && "Inconsistency with CanEvaluateShifted");
202 case Instruction::And:
203 case Instruction::Or:
204 case Instruction::Xor:
205 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
206 I->setOperand(0, GetShiftedValue(I->getOperand(0), NumBits,isLeftShift,IC));
207 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
208 return I;
209
210 case Instruction::Shl: {
211 BinaryOperator *BO = cast<BinaryOperator>(I);
212 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
213
214 // We only accept shifts-by-a-constant in CanEvaluateShifted.
215 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
216
217 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
218 if (isLeftShift) {
219 // If this is oversized composite shift, then unsigned shifts get 0.
220 unsigned NewShAmt = NumBits+CI->getZExtValue();
221 if (NewShAmt >= TypeWidth)
222 return Constant::getNullValue(I->getType());
223
224 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
225 BO->setHasNoUnsignedWrap(false);
226 BO->setHasNoSignedWrap(false);
227 return I;
228 }
229
230 // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
231 // zeros.
232 if (CI->getValue() == NumBits) {
233 APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
234 V = IC.Builder->CreateAnd(BO->getOperand(0),
235 ConstantInt::get(BO->getContext(), Mask));
236 if (Instruction *VI = dyn_cast<Instruction>(V)) {
237 VI->moveBefore(BO);
238 VI->takeName(BO);
239 }
240 return V;
241 }
242
243 // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
244 // the and won't be needed.
245 assert(CI->getZExtValue() > NumBits);
246 BO->setOperand(1, ConstantInt::get(BO->getType(),
247 CI->getZExtValue() - NumBits));
248 BO->setHasNoUnsignedWrap(false);
249 BO->setHasNoSignedWrap(false);
250 return BO;
251 }
252 case Instruction::LShr: {
253 BinaryOperator *BO = cast<BinaryOperator>(I);
254 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
255 // We only accept shifts-by-a-constant in CanEvaluateShifted.
256 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
257
258 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
259 if (!isLeftShift) {
260 // If this is oversized composite shift, then unsigned shifts get 0.
261 unsigned NewShAmt = NumBits+CI->getZExtValue();
262 if (NewShAmt >= TypeWidth)
263 return Constant::getNullValue(BO->getType());
264
265 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
266 BO->setIsExact(false);
267 return I;
268 }
269
270 // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
271 // zeros.
272 if (CI->getValue() == NumBits) {
273 APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
274 V = IC.Builder->CreateAnd(I->getOperand(0),
275 ConstantInt::get(BO->getContext(), Mask));
276 if (Instruction *VI = dyn_cast<Instruction>(V)) {
277 VI->moveBefore(I);
278 VI->takeName(I);
279 }
280 return V;
281 }
282
283 // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
284 // the and won't be needed.
285 assert(CI->getZExtValue() > NumBits);
286 BO->setOperand(1, ConstantInt::get(BO->getType(),
287 CI->getZExtValue() - NumBits));
288 BO->setIsExact(false);
289 return BO;
290 }
291
292 case Instruction::Select:
293 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
294 I->setOperand(2, GetShiftedValue(I->getOperand(2), NumBits,isLeftShift,IC));
295 return I;
296 case Instruction::PHI: {
297 // We can change a phi if we can change all operands. Note that we never
298 // get into trouble with cyclic PHIs here because we only consider
299 // instructions with a single use.
300 PHINode *PN = cast<PHINode>(I);
301 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
302 PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i),
303 NumBits, isLeftShift, IC));
304 return PN;
305 }
306 }
307 }
308
309
310
FoldShiftByConstant(Value * Op0,ConstantInt * Op1,BinaryOperator & I)311 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
312 BinaryOperator &I) {
313 bool isLeftShift = I.getOpcode() == Instruction::Shl;
314
315
316 // See if we can propagate this shift into the input, this covers the trivial
317 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
318 if (I.getOpcode() != Instruction::AShr &&
319 CanEvaluateShifted(Op0, Op1->getZExtValue(), isLeftShift, *this)) {
320 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
321 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
322
323 return ReplaceInstUsesWith(I,
324 GetShiftedValue(Op0, Op1->getZExtValue(), isLeftShift, *this));
325 }
326
327
328 // See if we can simplify any instructions used by the instruction whose sole
329 // purpose is to compute bits we don't care about.
330 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
331
332 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
333 // a signed shift.
334 //
335 if (Op1->uge(TypeBits)) {
336 if (I.getOpcode() != Instruction::AShr)
337 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
338 // ashr i32 X, 32 --> ashr i32 X, 31
339 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
340 return &I;
341 }
342
343 // ((X*C1) << C2) == (X * (C1 << C2))
344 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
345 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
346 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
347 return BinaryOperator::CreateMul(BO->getOperand(0),
348 ConstantExpr::getShl(BOOp, Op1));
349
350 // Try to fold constant and into select arguments.
351 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
352 if (Instruction *R = FoldOpIntoSelect(I, SI))
353 return R;
354 if (isa<PHINode>(Op0))
355 if (Instruction *NV = FoldOpIntoPhi(I))
356 return NV;
357
358 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
359 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
360 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
361 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
362 // place. Don't try to do this transformation in this case. Also, we
363 // require that the input operand is a shift-by-constant so that we have
364 // confidence that the shifts will get folded together. We could do this
365 // xform in more cases, but it is unlikely to be profitable.
366 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
367 isa<ConstantInt>(TrOp->getOperand(1))) {
368 // Okay, we'll do this xform. Make the shift of shift.
369 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
370 // (shift2 (shift1 & 0x00FF), c2)
371 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
372
373 // For logical shifts, the truncation has the effect of making the high
374 // part of the register be zeros. Emulate this by inserting an AND to
375 // clear the top bits as needed. This 'and' will usually be zapped by
376 // other xforms later if dead.
377 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
378 unsigned DstSize = TI->getType()->getScalarSizeInBits();
379 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
380
381 // The mask we constructed says what the trunc would do if occurring
382 // between the shifts. We want to know the effect *after* the second
383 // shift. We know that it is a logical shift by a constant, so adjust the
384 // mask as appropriate.
385 if (I.getOpcode() == Instruction::Shl)
386 MaskV <<= Op1->getZExtValue();
387 else {
388 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
389 MaskV = MaskV.lshr(Op1->getZExtValue());
390 }
391
392 // shift1 & 0x00FF
393 Value *And = Builder->CreateAnd(NSh,
394 ConstantInt::get(I.getContext(), MaskV),
395 TI->getName());
396
397 // Return the value truncated to the interesting size.
398 return new TruncInst(And, I.getType());
399 }
400 }
401
402 if (Op0->hasOneUse()) {
403 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
404 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
405 Value *V1, *V2;
406 ConstantInt *CC;
407 switch (Op0BO->getOpcode()) {
408 default: break;
409 case Instruction::Add:
410 case Instruction::And:
411 case Instruction::Or:
412 case Instruction::Xor: {
413 // These operators commute.
414 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
415 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
416 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
417 m_Specific(Op1)))) {
418 Value *YS = // (Y << C)
419 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
420 // (X + (Y << C))
421 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
422 Op0BO->getOperand(1)->getName());
423 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
424 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
425 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
426 }
427
428 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
429 Value *Op0BOOp1 = Op0BO->getOperand(1);
430 if (isLeftShift && Op0BOOp1->hasOneUse() &&
431 match(Op0BOOp1,
432 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
433 m_ConstantInt(CC))) &&
434 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
435 Value *YS = // (Y << C)
436 Builder->CreateShl(Op0BO->getOperand(0), Op1,
437 Op0BO->getName());
438 // X & (CC << C)
439 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
440 V1->getName()+".mask");
441 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
442 }
443 }
444
445 // FALL THROUGH.
446 case Instruction::Sub: {
447 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
448 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
449 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
450 m_Specific(Op1)))) {
451 Value *YS = // (Y << C)
452 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
453 // (X + (Y << C))
454 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
455 Op0BO->getOperand(0)->getName());
456 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
457 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
458 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
459 }
460
461 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
462 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
463 match(Op0BO->getOperand(0),
464 m_And(m_Shr(m_Value(V1), m_Value(V2)),
465 m_ConstantInt(CC))) && V2 == Op1 &&
466 cast<BinaryOperator>(Op0BO->getOperand(0))
467 ->getOperand(0)->hasOneUse()) {
468 Value *YS = // (Y << C)
469 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
470 // X & (CC << C)
471 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
472 V1->getName()+".mask");
473
474 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
475 }
476
477 break;
478 }
479 }
480
481
482 // If the operand is an bitwise operator with a constant RHS, and the
483 // shift is the only use, we can pull it out of the shift.
484 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
485 bool isValid = true; // Valid only for And, Or, Xor
486 bool highBitSet = false; // Transform if high bit of constant set?
487
488 switch (Op0BO->getOpcode()) {
489 default: isValid = false; break; // Do not perform transform!
490 case Instruction::Add:
491 isValid = isLeftShift;
492 break;
493 case Instruction::Or:
494 case Instruction::Xor:
495 highBitSet = false;
496 break;
497 case Instruction::And:
498 highBitSet = true;
499 break;
500 }
501
502 // If this is a signed shift right, and the high bit is modified
503 // by the logical operation, do not perform the transformation.
504 // The highBitSet boolean indicates the value of the high bit of
505 // the constant which would cause it to be modified for this
506 // operation.
507 //
508 if (isValid && I.getOpcode() == Instruction::AShr)
509 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
510
511 if (isValid) {
512 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
513
514 Value *NewShift =
515 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
516 NewShift->takeName(Op0BO);
517
518 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
519 NewRHS);
520 }
521 }
522 }
523 }
524
525 // Find out if this is a shift of a shift by a constant.
526 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
527 if (ShiftOp && !ShiftOp->isShift())
528 ShiftOp = 0;
529
530 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
531 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
532 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
533 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
534 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
535 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
536 Value *X = ShiftOp->getOperand(0);
537
538 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
539
540 IntegerType *Ty = cast<IntegerType>(I.getType());
541
542 // Check for (X << c1) << c2 and (X >> c1) >> c2
543 if (I.getOpcode() == ShiftOp->getOpcode()) {
544 // If this is oversized composite shift, then unsigned shifts get 0, ashr
545 // saturates.
546 if (AmtSum >= TypeBits) {
547 if (I.getOpcode() != Instruction::AShr)
548 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
549 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
550 }
551
552 return BinaryOperator::Create(I.getOpcode(), X,
553 ConstantInt::get(Ty, AmtSum));
554 }
555
556 if (ShiftAmt1 == ShiftAmt2) {
557 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
558 if (I.getOpcode() == Instruction::Shl &&
559 ShiftOp->getOpcode() != Instruction::Shl) {
560 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
561 return BinaryOperator::CreateAnd(X,
562 ConstantInt::get(I.getContext(),Mask));
563 }
564 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
565 if (I.getOpcode() == Instruction::LShr &&
566 ShiftOp->getOpcode() == Instruction::Shl) {
567 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
568 return BinaryOperator::CreateAnd(X,
569 ConstantInt::get(I.getContext(), Mask));
570 }
571 } else if (ShiftAmt1 < ShiftAmt2) {
572 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
573
574 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
575 if (I.getOpcode() == Instruction::Shl &&
576 ShiftOp->getOpcode() != Instruction::Shl) {
577 assert(ShiftOp->getOpcode() == Instruction::LShr ||
578 ShiftOp->getOpcode() == Instruction::AShr);
579 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
580
581 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
582 return BinaryOperator::CreateAnd(Shift,
583 ConstantInt::get(I.getContext(),Mask));
584 }
585
586 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
587 if (I.getOpcode() == Instruction::LShr &&
588 ShiftOp->getOpcode() == Instruction::Shl) {
589 assert(ShiftOp->getOpcode() == Instruction::Shl);
590 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
591
592 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
593 return BinaryOperator::CreateAnd(Shift,
594 ConstantInt::get(I.getContext(),Mask));
595 }
596
597 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
598 } else {
599 assert(ShiftAmt2 < ShiftAmt1);
600 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
601
602 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
603 if (I.getOpcode() == Instruction::Shl &&
604 ShiftOp->getOpcode() != Instruction::Shl) {
605 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
606 ConstantInt::get(Ty, ShiftDiff));
607
608 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
609 return BinaryOperator::CreateAnd(Shift,
610 ConstantInt::get(I.getContext(),Mask));
611 }
612
613 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
614 if (I.getOpcode() == Instruction::LShr &&
615 ShiftOp->getOpcode() == Instruction::Shl) {
616 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
617
618 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
619 return BinaryOperator::CreateAnd(Shift,
620 ConstantInt::get(I.getContext(),Mask));
621 }
622
623 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
624 }
625 }
626 return 0;
627 }
628
visitShl(BinaryOperator & I)629 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
630 if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
631 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
632 TD))
633 return ReplaceInstUsesWith(I, V);
634
635 if (Instruction *V = commonShiftTransforms(I))
636 return V;
637
638 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(I.getOperand(1))) {
639 unsigned ShAmt = Op1C->getZExtValue();
640
641 // If the shifted-out value is known-zero, then this is a NUW shift.
642 if (!I.hasNoUnsignedWrap() &&
643 MaskedValueIsZero(I.getOperand(0),
644 APInt::getHighBitsSet(Op1C->getBitWidth(), ShAmt))) {
645 I.setHasNoUnsignedWrap();
646 return &I;
647 }
648
649 // If the shifted out value is all signbits, this is a NSW shift.
650 if (!I.hasNoSignedWrap() &&
651 ComputeNumSignBits(I.getOperand(0)) > ShAmt) {
652 I.setHasNoSignedWrap();
653 return &I;
654 }
655 }
656
657 // (C1 << A) << C2 -> (C1 << C2) << A
658 Constant *C1, *C2;
659 Value *A;
660 if (match(I.getOperand(0), m_OneUse(m_Shl(m_Constant(C1), m_Value(A)))) &&
661 match(I.getOperand(1), m_Constant(C2)))
662 return BinaryOperator::CreateShl(ConstantExpr::getShl(C1, C2), A);
663
664 return 0;
665 }
666
visitLShr(BinaryOperator & I)667 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
668 if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1),
669 I.isExact(), TD))
670 return ReplaceInstUsesWith(I, V);
671
672 if (Instruction *R = commonShiftTransforms(I))
673 return R;
674
675 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
676
677 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
678 unsigned ShAmt = Op1C->getZExtValue();
679
680 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
681 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
682 // ctlz.i32(x)>>5 --> zext(x == 0)
683 // cttz.i32(x)>>5 --> zext(x == 0)
684 // ctpop.i32(x)>>5 --> zext(x == -1)
685 if ((II->getIntrinsicID() == Intrinsic::ctlz ||
686 II->getIntrinsicID() == Intrinsic::cttz ||
687 II->getIntrinsicID() == Intrinsic::ctpop) &&
688 isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt) {
689 bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
690 Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
691 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
692 return new ZExtInst(Cmp, II->getType());
693 }
694 }
695
696 // If the shifted-out value is known-zero, then this is an exact shift.
697 if (!I.isExact() &&
698 MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
699 I.setIsExact();
700 return &I;
701 }
702 }
703
704 return 0;
705 }
706
visitAShr(BinaryOperator & I)707 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
708 if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1),
709 I.isExact(), TD))
710 return ReplaceInstUsesWith(I, V);
711
712 if (Instruction *R = commonShiftTransforms(I))
713 return R;
714
715 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
716
717 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
718 unsigned ShAmt = Op1C->getZExtValue();
719
720 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
721 // have a sign-extend idiom.
722 Value *X;
723 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
724 // If the left shift is just shifting out partial signbits, delete the
725 // extension.
726 if (cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
727 return ReplaceInstUsesWith(I, X);
728
729 // If the input is an extension from the shifted amount value, e.g.
730 // %x = zext i8 %A to i32
731 // %y = shl i32 %x, 24
732 // %z = ashr %y, 24
733 // then turn this into "z = sext i8 A to i32".
734 if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
735 uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
736 uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
737 if (Op1C->getZExtValue() == DestBits-SrcBits)
738 return new SExtInst(ZI->getOperand(0), ZI->getType());
739 }
740 }
741
742 // If the shifted-out value is known-zero, then this is an exact shift.
743 if (!I.isExact() &&
744 MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
745 I.setIsExact();
746 return &I;
747 }
748 }
749
750 // See if we can turn a signed shr into an unsigned shr.
751 if (MaskedValueIsZero(Op0,
752 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
753 return BinaryOperator::CreateLShr(Op0, Op1);
754
755 // Arithmetic shifting an all-sign-bit value is a no-op.
756 unsigned NumSignBits = ComputeNumSignBits(Op0);
757 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
758 return ReplaceInstUsesWith(I, Op0);
759
760 return 0;
761 }
762
763