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