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