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