1 //===- InstCombineShifts.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitShl, visitLShr, and visitAShr functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/Analysis/ConstantFolding.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/IR/IntrinsicInst.h"
17 #include "llvm/IR/PatternMatch.h"
18 using namespace llvm;
19 using namespace PatternMatch;
20 
21 #define DEBUG_TYPE "instcombine"
22 
23 // Given pattern:
24 //   (x shiftopcode Q) shiftopcode K
25 // we should rewrite it as
26 //   x shiftopcode (Q+K)  iff (Q+K) u< bitwidth(x)
27 // This is valid for any shift, but they must be identical.
28 static Instruction *
29 reassociateShiftAmtsOfTwoSameDirectionShifts(BinaryOperator *Sh0,
30                                              const SimplifyQuery &SQ) {
31   // Look for:  (x shiftopcode ShAmt0) shiftopcode ShAmt1
32   Value *X, *ShAmt1, *ShAmt0;
33   Instruction *Sh1;
34   if (!match(Sh0, m_Shift(m_CombineAnd(m_Shift(m_Value(X), m_Value(ShAmt1)),
35                                        m_Instruction(Sh1)),
36                           m_Value(ShAmt0))))
37     return nullptr;
38 
39   // The shift opcodes must be identical.
40   Instruction::BinaryOps ShiftOpcode = Sh0->getOpcode();
41   if (ShiftOpcode != Sh1->getOpcode())
42     return nullptr;
43   // Can we fold (ShAmt0+ShAmt1) ?
44   Value *NewShAmt = SimplifyBinOp(Instruction::BinaryOps::Add, ShAmt0, ShAmt1,
45                                   SQ.getWithInstruction(Sh0));
46   if (!NewShAmt)
47     return nullptr; // Did not simplify.
48   // Is the new shift amount smaller than the bit width?
49   // FIXME: could also rely on ConstantRange.
50   unsigned BitWidth = X->getType()->getScalarSizeInBits();
51   if (!match(NewShAmt, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,
52                                           APInt(BitWidth, BitWidth))))
53     return nullptr;
54   // All good, we can do this fold.
55   BinaryOperator *NewShift = BinaryOperator::Create(ShiftOpcode, X, NewShAmt);
56   // If both of the original shifts had the same flag set, preserve the flag.
57   if (ShiftOpcode == Instruction::BinaryOps::Shl) {
58     NewShift->setHasNoUnsignedWrap(Sh0->hasNoUnsignedWrap() &&
59                                    Sh1->hasNoUnsignedWrap());
60     NewShift->setHasNoSignedWrap(Sh0->hasNoSignedWrap() &&
61                                  Sh1->hasNoSignedWrap());
62   } else {
63     NewShift->setIsExact(Sh0->isExact() && Sh1->isExact());
64   }
65   return NewShift;
66 }
67 
68 // If we have some pattern that leaves only some low bits set, and then performs
69 // left-shift of those bits, if none of the bits that are left after the final
70 // shift are modified by the mask, we can omit the mask.
71 //
72 // There are many variants to this pattern:
73 //   a)  (x & ((1 << MaskShAmt) - 1)) << ShiftShAmt
74 //   b)  (x & (~(-1 << MaskShAmt))) << ShiftShAmt
75 //   c)  (x & (-1 >> MaskShAmt)) << ShiftShAmt
76 //   d)  (x & ((-1 << MaskShAmt) >> MaskShAmt)) << ShiftShAmt
77 //   e)  ((x << MaskShAmt) l>> MaskShAmt) << ShiftShAmt
78 //   f)  ((x << MaskShAmt) a>> MaskShAmt) << ShiftShAmt
79 // All these patterns can be simplified to just:
80 //   x << ShiftShAmt
81 // iff:
82 //   a,b)     (MaskShAmt+ShiftShAmt) u>= bitwidth(x)
83 //   c,d,e,f) (ShiftShAmt-MaskShAmt) s>= 0 (i.e. ShiftShAmt u>= MaskShAmt)
84 static Instruction *
85 dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift,
86                                      const SimplifyQuery &SQ) {
87   assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&
88          "The input must be 'shl'!");
89 
90   Value *Masked = OuterShift->getOperand(0);
91   Value *ShiftShAmt = OuterShift->getOperand(1);
92 
93   Value *MaskShAmt;
94 
95   // ((1 << MaskShAmt) - 1)
96   auto MaskA = m_Add(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes());
97   // (~(-1 << maskNbits))
98   auto MaskB = m_Xor(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_AllOnes());
99   // (-1 >> MaskShAmt)
100   auto MaskC = m_Shr(m_AllOnes(), m_Value(MaskShAmt));
101   // ((-1 << MaskShAmt) >> MaskShAmt)
102   auto MaskD =
103       m_Shr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt));
104 
105   Value *X;
106   if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) {
107     // Can we simplify (MaskShAmt+ShiftShAmt) ?
108     Value *SumOfShAmts =
109         SimplifyAddInst(MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false,
110                         SQ.getWithInstruction(OuterShift));
111     if (!SumOfShAmts)
112       return nullptr; // Did not simplify.
113     // Is the total shift amount *not* smaller than the bit width?
114     // FIXME: could also rely on ConstantRange.
115     unsigned BitWidth = X->getType()->getScalarSizeInBits();
116     if (!match(SumOfShAmts, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_UGE,
117                                                APInt(BitWidth, BitWidth))))
118       return nullptr;
119     // All good, we can do this fold.
120   } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) ||
121              match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)),
122                                  m_Deferred(MaskShAmt)))) {
123     // Can we simplify (ShiftShAmt-MaskShAmt) ?
124     Value *ShAmtsDiff =
125         SimplifySubInst(ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false,
126                         SQ.getWithInstruction(OuterShift));
127     if (!ShAmtsDiff)
128       return nullptr; // Did not simplify.
129     // Is the difference non-negative? (is ShiftShAmt u>= MaskShAmt ?)
130     // FIXME: could also rely on ConstantRange.
131     if (!match(ShAmtsDiff, m_NonNegative()))
132       return nullptr;
133     // All good, we can do this fold.
134   } else
135     return nullptr; // Don't know anything about this pattern.
136 
137   // No 'NUW'/'NSW'!
138   // We no longer know that we won't shift-out non-0 bits.
139   return BinaryOperator::Create(OuterShift->getOpcode(), X, ShiftShAmt);
140 }
141 
142 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
143   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
144   assert(Op0->getType() == Op1->getType());
145 
146   // See if we can fold away this shift.
147   if (SimplifyDemandedInstructionBits(I))
148     return &I;
149 
150   // Try to fold constant and into select arguments.
151   if (isa<Constant>(Op0))
152     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
153       if (Instruction *R = FoldOpIntoSelect(I, SI))
154         return R;
155 
156   if (Constant *CUI = dyn_cast<Constant>(Op1))
157     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
158       return Res;
159 
160   if (Instruction *NewShift =
161           reassociateShiftAmtsOfTwoSameDirectionShifts(&I, SQ))
162     return NewShift;
163 
164   // (C1 shift (A add C2)) -> (C1 shift C2) shift A)
165   // iff A and C2 are both positive.
166   Value *A;
167   Constant *C;
168   if (match(Op0, m_Constant()) && match(Op1, m_Add(m_Value(A), m_Constant(C))))
169     if (isKnownNonNegative(A, DL, 0, &AC, &I, &DT) &&
170         isKnownNonNegative(C, DL, 0, &AC, &I, &DT))
171       return BinaryOperator::Create(
172           I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), Op0, C), A);
173 
174   // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
175   // Because shifts by negative values (which could occur if A were negative)
176   // are undefined.
177   const APInt *B;
178   if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
179     // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
180     // demand the sign bit (and many others) here??
181     Value *Rem = Builder.CreateAnd(A, ConstantInt::get(I.getType(), *B - 1),
182                                    Op1->getName());
183     I.setOperand(1, Rem);
184     return &I;
185   }
186 
187   return nullptr;
188 }
189 
190 /// Return true if we can simplify two logical (either left or right) shifts
191 /// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
192 static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
193                                     Instruction *InnerShift, InstCombiner &IC,
194                                     Instruction *CxtI) {
195   assert(InnerShift->isLogicalShift() && "Unexpected instruction type");
196 
197   // We need constant scalar or constant splat shifts.
198   const APInt *InnerShiftConst;
199   if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst)))
200     return false;
201 
202   // Two logical shifts in the same direction:
203   // shl (shl X, C1), C2 -->  shl X, C1 + C2
204   // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
205   bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
206   if (IsInnerShl == IsOuterShl)
207     return true;
208 
209   // Equal shift amounts in opposite directions become bitwise 'and':
210   // lshr (shl X, C), C --> and X, C'
211   // shl (lshr X, C), C --> and X, C'
212   if (*InnerShiftConst == OuterShAmt)
213     return true;
214 
215   // If the 2nd shift is bigger than the 1st, we can fold:
216   // lshr (shl X, C1), C2 -->  and (shl X, C1 - C2), C3
217   // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
218   // but it isn't profitable unless we know the and'd out bits are already zero.
219   // Also, check that the inner shift is valid (less than the type width) or
220   // we'll crash trying to produce the bit mask for the 'and'.
221   unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
222   if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) {
223     unsigned InnerShAmt = InnerShiftConst->getZExtValue();
224     unsigned MaskShift =
225         IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
226     APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift;
227     if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI))
228       return true;
229   }
230 
231   return false;
232 }
233 
234 /// See if we can compute the specified value, but shifted logically to the left
235 /// or right by some number of bits. This should return true if the expression
236 /// can be computed for the same cost as the current expression tree. This is
237 /// used to eliminate extraneous shifting from things like:
238 ///      %C = shl i128 %A, 64
239 ///      %D = shl i128 %B, 96
240 ///      %E = or i128 %C, %D
241 ///      %F = lshr i128 %E, 64
242 /// where the client will ask if E can be computed shifted right by 64-bits. If
243 /// this succeeds, getShiftedValue() will be called to produce the value.
244 static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
245                                InstCombiner &IC, Instruction *CxtI) {
246   // We can always evaluate constants shifted.
247   if (isa<Constant>(V))
248     return true;
249 
250   Instruction *I = dyn_cast<Instruction>(V);
251   if (!I) return false;
252 
253   // If this is the opposite shift, we can directly reuse the input of the shift
254   // if the needed bits are already zero in the input.  This allows us to reuse
255   // the value which means that we don't care if the shift has multiple uses.
256   //  TODO:  Handle opposite shift by exact value.
257   ConstantInt *CI = nullptr;
258   if ((IsLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
259       (!IsLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
260     if (CI->getValue() == NumBits) {
261       // TODO: Check that the input bits are already zero with MaskedValueIsZero
262 #if 0
263       // If this is a truncate of a logical shr, we can truncate it to a smaller
264       // lshr iff we know that the bits we would otherwise be shifting in are
265       // already zeros.
266       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
267       uint32_t BitWidth = Ty->getScalarSizeInBits();
268       if (MaskedValueIsZero(I->getOperand(0),
269             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
270           CI->getLimitedValue(BitWidth) < BitWidth) {
271         return CanEvaluateTruncated(I->getOperand(0), Ty);
272       }
273 #endif
274 
275     }
276   }
277 
278   // We can't mutate something that has multiple uses: doing so would
279   // require duplicating the instruction in general, which isn't profitable.
280   if (!I->hasOneUse()) return false;
281 
282   switch (I->getOpcode()) {
283   default: return false;
284   case Instruction::And:
285   case Instruction::Or:
286   case Instruction::Xor:
287     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
288     return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
289            canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
290 
291   case Instruction::Shl:
292   case Instruction::LShr:
293     return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
294 
295   case Instruction::Select: {
296     SelectInst *SI = cast<SelectInst>(I);
297     Value *TrueVal = SI->getTrueValue();
298     Value *FalseVal = SI->getFalseValue();
299     return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
300            canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
301   }
302   case Instruction::PHI: {
303     // We can change a phi if we can change all operands.  Note that we never
304     // get into trouble with cyclic PHIs here because we only consider
305     // instructions with a single use.
306     PHINode *PN = cast<PHINode>(I);
307     for (Value *IncValue : PN->incoming_values())
308       if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
309         return false;
310     return true;
311   }
312   }
313 }
314 
315 /// Fold OuterShift (InnerShift X, C1), C2.
316 /// See canEvaluateShiftedShift() for the constraints on these instructions.
317 static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
318                                bool IsOuterShl,
319                                InstCombiner::BuilderTy &Builder) {
320   bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
321   Type *ShType = InnerShift->getType();
322   unsigned TypeWidth = ShType->getScalarSizeInBits();
323 
324   // We only accept shifts-by-a-constant in canEvaluateShifted().
325   const APInt *C1;
326   match(InnerShift->getOperand(1), m_APInt(C1));
327   unsigned InnerShAmt = C1->getZExtValue();
328 
329   // Change the shift amount and clear the appropriate IR flags.
330   auto NewInnerShift = [&](unsigned ShAmt) {
331     InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
332     if (IsInnerShl) {
333       InnerShift->setHasNoUnsignedWrap(false);
334       InnerShift->setHasNoSignedWrap(false);
335     } else {
336       InnerShift->setIsExact(false);
337     }
338     return InnerShift;
339   };
340 
341   // Two logical shifts in the same direction:
342   // shl (shl X, C1), C2 -->  shl X, C1 + C2
343   // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
344   if (IsInnerShl == IsOuterShl) {
345     // If this is an oversized composite shift, then unsigned shifts get 0.
346     if (InnerShAmt + OuterShAmt >= TypeWidth)
347       return Constant::getNullValue(ShType);
348 
349     return NewInnerShift(InnerShAmt + OuterShAmt);
350   }
351 
352   // Equal shift amounts in opposite directions become bitwise 'and':
353   // lshr (shl X, C), C --> and X, C'
354   // shl (lshr X, C), C --> and X, C'
355   if (InnerShAmt == OuterShAmt) {
356     APInt Mask = IsInnerShl
357                      ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
358                      : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
359     Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
360                                    ConstantInt::get(ShType, Mask));
361     if (auto *AndI = dyn_cast<Instruction>(And)) {
362       AndI->moveBefore(InnerShift);
363       AndI->takeName(InnerShift);
364     }
365     return And;
366   }
367 
368   assert(InnerShAmt > OuterShAmt &&
369          "Unexpected opposite direction logical shift pair");
370 
371   // In general, we would need an 'and' for this transform, but
372   // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
373   // lshr (shl X, C1), C2 -->  shl X, C1 - C2
374   // shl (lshr X, C1), C2 --> lshr X, C1 - C2
375   return NewInnerShift(InnerShAmt - OuterShAmt);
376 }
377 
378 /// When canEvaluateShifted() returns true for an expression, this function
379 /// inserts the new computation that produces the shifted value.
380 static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
381                               InstCombiner &IC, const DataLayout &DL) {
382   // We can always evaluate constants shifted.
383   if (Constant *C = dyn_cast<Constant>(V)) {
384     if (isLeftShift)
385       V = IC.Builder.CreateShl(C, NumBits);
386     else
387       V = IC.Builder.CreateLShr(C, NumBits);
388     // If we got a constantexpr back, try to simplify it with TD info.
389     if (auto *C = dyn_cast<Constant>(V))
390       if (auto *FoldedC =
391               ConstantFoldConstant(C, DL, &IC.getTargetLibraryInfo()))
392         V = FoldedC;
393     return V;
394   }
395 
396   Instruction *I = cast<Instruction>(V);
397   IC.Worklist.Add(I);
398 
399   switch (I->getOpcode()) {
400   default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
401   case Instruction::And:
402   case Instruction::Or:
403   case Instruction::Xor:
404     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
405     I->setOperand(
406         0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
407     I->setOperand(
408         1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
409     return I;
410 
411   case Instruction::Shl:
412   case Instruction::LShr:
413     return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
414                             IC.Builder);
415 
416   case Instruction::Select:
417     I->setOperand(
418         1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
419     I->setOperand(
420         2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
421     return I;
422   case Instruction::PHI: {
423     // We can change a phi if we can change all operands.  Note that we never
424     // get into trouble with cyclic PHIs here because we only consider
425     // instructions with a single use.
426     PHINode *PN = cast<PHINode>(I);
427     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
428       PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits,
429                                               isLeftShift, IC, DL));
430     return PN;
431   }
432   }
433 }
434 
435 // If this is a bitwise operator or add with a constant RHS we might be able
436 // to pull it through a shift.
437 static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift,
438                                          BinaryOperator *BO) {
439   switch (BO->getOpcode()) {
440   default:
441     return false; // Do not perform transform!
442   case Instruction::Add:
443     return Shift.getOpcode() == Instruction::Shl;
444   case Instruction::Or:
445   case Instruction::Xor:
446   case Instruction::And:
447     return true;
448   }
449 }
450 
451 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
452                                                BinaryOperator &I) {
453   bool isLeftShift = I.getOpcode() == Instruction::Shl;
454 
455   const APInt *Op1C;
456   if (!match(Op1, m_APInt(Op1C)))
457     return nullptr;
458 
459   // See if we can propagate this shift into the input, this covers the trivial
460   // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
461   if (I.getOpcode() != Instruction::AShr &&
462       canEvaluateShifted(Op0, Op1C->getZExtValue(), isLeftShift, *this, &I)) {
463     LLVM_DEBUG(
464         dbgs() << "ICE: GetShiftedValue propagating shift through expression"
465                   " to eliminate shift:\n  IN: "
466                << *Op0 << "\n  SH: " << I << "\n");
467 
468     return replaceInstUsesWith(
469         I, getShiftedValue(Op0, Op1C->getZExtValue(), isLeftShift, *this, DL));
470   }
471 
472   // See if we can simplify any instructions used by the instruction whose sole
473   // purpose is to compute bits we don't care about.
474   unsigned TypeBits = Op0->getType()->getScalarSizeInBits();
475 
476   assert(!Op1C->uge(TypeBits) &&
477          "Shift over the type width should have been removed already");
478 
479   if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
480     return FoldedShift;
481 
482   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
483   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
484     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
485     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
486     // place.  Don't try to do this transformation in this case.  Also, we
487     // require that the input operand is a shift-by-constant so that we have
488     // confidence that the shifts will get folded together.  We could do this
489     // xform in more cases, but it is unlikely to be profitable.
490     if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
491         isa<ConstantInt>(TrOp->getOperand(1))) {
492       // Okay, we'll do this xform.  Make the shift of shift.
493       Constant *ShAmt =
494           ConstantExpr::getZExt(cast<Constant>(Op1), TrOp->getType());
495       // (shift2 (shift1 & 0x00FF), c2)
496       Value *NSh = Builder.CreateBinOp(I.getOpcode(), TrOp, ShAmt, I.getName());
497 
498       // For logical shifts, the truncation has the effect of making the high
499       // part of the register be zeros.  Emulate this by inserting an AND to
500       // clear the top bits as needed.  This 'and' will usually be zapped by
501       // other xforms later if dead.
502       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
503       unsigned DstSize = TI->getType()->getScalarSizeInBits();
504       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
505 
506       // The mask we constructed says what the trunc would do if occurring
507       // between the shifts.  We want to know the effect *after* the second
508       // shift.  We know that it is a logical shift by a constant, so adjust the
509       // mask as appropriate.
510       if (I.getOpcode() == Instruction::Shl)
511         MaskV <<= Op1C->getZExtValue();
512       else {
513         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
514         MaskV.lshrInPlace(Op1C->getZExtValue());
515       }
516 
517       // shift1 & 0x00FF
518       Value *And = Builder.CreateAnd(NSh,
519                                      ConstantInt::get(I.getContext(), MaskV),
520                                      TI->getName());
521 
522       // Return the value truncated to the interesting size.
523       return new TruncInst(And, I.getType());
524     }
525   }
526 
527   if (Op0->hasOneUse()) {
528     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
529       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
530       Value *V1, *V2;
531       ConstantInt *CC;
532       switch (Op0BO->getOpcode()) {
533       default: break;
534       case Instruction::Add:
535       case Instruction::And:
536       case Instruction::Or:
537       case Instruction::Xor: {
538         // These operators commute.
539         // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
540         if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
541             match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
542                   m_Specific(Op1)))) {
543           Value *YS =         // (Y << C)
544             Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
545           // (X + (Y << C))
546           Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), YS, V1,
547                                          Op0BO->getOperand(1)->getName());
548           unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
549 
550           APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
551           Constant *Mask = ConstantInt::get(I.getContext(), Bits);
552           if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
553             Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
554           return BinaryOperator::CreateAnd(X, Mask);
555         }
556 
557         // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
558         Value *Op0BOOp1 = Op0BO->getOperand(1);
559         if (isLeftShift && Op0BOOp1->hasOneUse() &&
560             match(Op0BOOp1,
561                   m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
562                         m_ConstantInt(CC)))) {
563           Value *YS =   // (Y << C)
564             Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
565           // X & (CC << C)
566           Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
567                                         V1->getName()+".mask");
568           return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
569         }
570         LLVM_FALLTHROUGH;
571       }
572 
573       case Instruction::Sub: {
574         // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
575         if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
576             match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
577                   m_Specific(Op1)))) {
578           Value *YS =  // (Y << C)
579             Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
580           // (X + (Y << C))
581           Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), V1, YS,
582                                          Op0BO->getOperand(0)->getName());
583           unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
584 
585           APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
586           Constant *Mask = ConstantInt::get(I.getContext(), Bits);
587           if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
588             Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
589           return BinaryOperator::CreateAnd(X, Mask);
590         }
591 
592         // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
593         if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
594             match(Op0BO->getOperand(0),
595                   m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
596                         m_ConstantInt(CC))) && V2 == Op1) {
597           Value *YS = // (Y << C)
598             Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
599           // X & (CC << C)
600           Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
601                                         V1->getName()+".mask");
602 
603           return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
604         }
605 
606         break;
607       }
608       }
609 
610 
611       // If the operand is a bitwise operator with a constant RHS, and the
612       // shift is the only use, we can pull it out of the shift.
613       const APInt *Op0C;
614       if (match(Op0BO->getOperand(1), m_APInt(Op0C))) {
615         if (canShiftBinOpWithConstantRHS(I, Op0BO)) {
616           Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
617                                      cast<Constant>(Op0BO->getOperand(1)), Op1);
618 
619           Value *NewShift =
620             Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
621           NewShift->takeName(Op0BO);
622 
623           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
624                                         NewRHS);
625         }
626       }
627 
628       // If the operand is a subtract with a constant LHS, and the shift
629       // is the only use, we can pull it out of the shift.
630       // This folds (shl (sub C1, X), C2) -> (sub (C1 << C2), (shl X, C2))
631       if (isLeftShift && Op0BO->getOpcode() == Instruction::Sub &&
632           match(Op0BO->getOperand(0), m_APInt(Op0C))) {
633         Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
634                                    cast<Constant>(Op0BO->getOperand(0)), Op1);
635 
636         Value *NewShift = Builder.CreateShl(Op0BO->getOperand(1), Op1);
637         NewShift->takeName(Op0BO);
638 
639         return BinaryOperator::CreateSub(NewRHS, NewShift);
640       }
641     }
642 
643     // If we have a select that conditionally executes some binary operator,
644     // see if we can pull it the select and operator through the shift.
645     //
646     // For example, turning:
647     //   shl (select C, (add X, C1), X), C2
648     // Into:
649     //   Y = shl X, C2
650     //   select C, (add Y, C1 << C2), Y
651     Value *Cond;
652     BinaryOperator *TBO;
653     Value *FalseVal;
654     if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)),
655                             m_Value(FalseVal)))) {
656       const APInt *C;
657       if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal &&
658           match(TBO->getOperand(1), m_APInt(C)) &&
659           canShiftBinOpWithConstantRHS(I, TBO)) {
660         Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
661                                        cast<Constant>(TBO->getOperand(1)), Op1);
662 
663         Value *NewShift =
664           Builder.CreateBinOp(I.getOpcode(), FalseVal, Op1);
665         Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift,
666                                            NewRHS);
667         return SelectInst::Create(Cond, NewOp, NewShift);
668       }
669     }
670 
671     BinaryOperator *FBO;
672     Value *TrueVal;
673     if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal),
674                             m_OneUse(m_BinOp(FBO))))) {
675       const APInt *C;
676       if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal &&
677           match(FBO->getOperand(1), m_APInt(C)) &&
678           canShiftBinOpWithConstantRHS(I, FBO)) {
679         Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
680                                        cast<Constant>(FBO->getOperand(1)), Op1);
681 
682         Value *NewShift =
683           Builder.CreateBinOp(I.getOpcode(), TrueVal, Op1);
684         Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift,
685                                            NewRHS);
686         return SelectInst::Create(Cond, NewShift, NewOp);
687       }
688     }
689   }
690 
691   return nullptr;
692 }
693 
694 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
695   if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
696                                  I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
697                                  SQ.getWithInstruction(&I)))
698     return replaceInstUsesWith(I, V);
699 
700   if (Instruction *X = foldVectorBinop(I))
701     return X;
702 
703   if (Instruction *V = commonShiftTransforms(I))
704     return V;
705 
706   if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(&I, SQ))
707     return V;
708 
709   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
710   Type *Ty = I.getType();
711   unsigned BitWidth = Ty->getScalarSizeInBits();
712 
713   const APInt *ShAmtAPInt;
714   if (match(Op1, m_APInt(ShAmtAPInt))) {
715     unsigned ShAmt = ShAmtAPInt->getZExtValue();
716     unsigned BitWidth = Ty->getScalarSizeInBits();
717 
718     Value *X;
719     if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
720       unsigned SrcWidth = X->getType()->getScalarSizeInBits();
721       // shl (zext X), ShAmt --> zext (shl X, ShAmt)
722       // This is only valid if X would have zeros shifted out.
723       if (ShAmt < SrcWidth &&
724           MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmt), 0, &I))
725         return new ZExtInst(Builder.CreateShl(X, ShAmt), Ty);
726 
727       // shl (zext (mul MulOp, C2)), ShAmt --> mul (zext MulOp), (C2 << ShAmt)
728       // This is valid if the high bits of the wider multiply are shifted out.
729       Value *MulOp;
730       const APInt *C2;
731       if (ShAmt >= (BitWidth - SrcWidth) &&
732           match(X, m_Mul(m_Value(MulOp), m_APInt(C2)))) {
733         Value *Zext = Builder.CreateZExt(MulOp, Ty);
734         Constant *NewMulC = ConstantInt::get(Ty, C2->zext(BitWidth).shl(ShAmt));
735         return BinaryOperator::CreateMul(Zext, NewMulC);
736       }
737     }
738 
739     // (X >> C) << C --> X & (-1 << C)
740     if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) {
741       APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt));
742       return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
743     }
744 
745     // FIXME: we do not yet transform non-exact shr's. The backend (DAGCombine)
746     // needs a few fixes for the rotate pattern recognition first.
747     const APInt *ShOp1;
748     if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(ShOp1))))) {
749       unsigned ShrAmt = ShOp1->getZExtValue();
750       if (ShrAmt < ShAmt) {
751         // If C1 < C2: (X >>?,exact C1) << C2 --> X << (C2 - C1)
752         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShrAmt);
753         auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
754         NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
755         NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
756         return NewShl;
757       }
758       if (ShrAmt > ShAmt) {
759         // If C1 > C2: (X >>?exact C1) << C2 --> X >>?exact (C1 - C2)
760         Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmt);
761         auto *NewShr = BinaryOperator::Create(
762             cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff);
763         NewShr->setIsExact(true);
764         return NewShr;
765       }
766     }
767 
768     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1)))) {
769       unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
770       // Oversized shifts are simplified to zero in InstSimplify.
771       if (AmtSum < BitWidth)
772         // (X << C1) << C2 --> X << (C1 + C2)
773         return BinaryOperator::CreateShl(X, ConstantInt::get(Ty, AmtSum));
774     }
775 
776     // If the shifted-out value is known-zero, then this is a NUW shift.
777     if (!I.hasNoUnsignedWrap() &&
778         MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, ShAmt), 0, &I)) {
779       I.setHasNoUnsignedWrap();
780       return &I;
781     }
782 
783     // If the shifted-out value is all signbits, then this is a NSW shift.
784     if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmt) {
785       I.setHasNoSignedWrap();
786       return &I;
787     }
788   }
789 
790   // Transform  (x >> y) << y  to  x & (-1 << y)
791   // Valid for any type of right-shift.
792   Value *X;
793   if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
794     Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
795     Value *Mask = Builder.CreateShl(AllOnes, Op1);
796     return BinaryOperator::CreateAnd(Mask, X);
797   }
798 
799   Constant *C1;
800   if (match(Op1, m_Constant(C1))) {
801     Constant *C2;
802     Value *X;
803     // (C2 << X) << C1 --> (C2 << C1) << X
804     if (match(Op0, m_OneUse(m_Shl(m_Constant(C2), m_Value(X)))))
805       return BinaryOperator::CreateShl(ConstantExpr::getShl(C2, C1), X);
806 
807     // (X * C2) << C1 --> X * (C2 << C1)
808     if (match(Op0, m_Mul(m_Value(X), m_Constant(C2))))
809       return BinaryOperator::CreateMul(X, ConstantExpr::getShl(C2, C1));
810   }
811 
812   // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
813   if (match(Op0, m_One()) &&
814       match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X))))
815     return BinaryOperator::CreateLShr(
816         ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X);
817 
818   return nullptr;
819 }
820 
821 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
822   if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
823                                   SQ.getWithInstruction(&I)))
824     return replaceInstUsesWith(I, V);
825 
826   if (Instruction *X = foldVectorBinop(I))
827     return X;
828 
829   if (Instruction *R = commonShiftTransforms(I))
830     return R;
831 
832   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
833   Type *Ty = I.getType();
834   const APInt *ShAmtAPInt;
835   if (match(Op1, m_APInt(ShAmtAPInt))) {
836     unsigned ShAmt = ShAmtAPInt->getZExtValue();
837     unsigned BitWidth = Ty->getScalarSizeInBits();
838     auto *II = dyn_cast<IntrinsicInst>(Op0);
839     if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt &&
840         (II->getIntrinsicID() == Intrinsic::ctlz ||
841          II->getIntrinsicID() == Intrinsic::cttz ||
842          II->getIntrinsicID() == Intrinsic::ctpop)) {
843       // ctlz.i32(x)>>5  --> zext(x == 0)
844       // cttz.i32(x)>>5  --> zext(x == 0)
845       // ctpop.i32(x)>>5 --> zext(x == -1)
846       bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
847       Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
848       Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS);
849       return new ZExtInst(Cmp, Ty);
850     }
851 
852     Value *X;
853     const APInt *ShOp1;
854     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1))) && ShOp1->ult(BitWidth)) {
855       if (ShOp1->ult(ShAmt)) {
856         unsigned ShlAmt = ShOp1->getZExtValue();
857         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
858         if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
859           // (X <<nuw C1) >>u C2 --> X >>u (C2 - C1)
860           auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
861           NewLShr->setIsExact(I.isExact());
862           return NewLShr;
863         }
864         // (X << C1) >>u C2  --> (X >>u (C2 - C1)) & (-1 >> C2)
865         Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact());
866         APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
867         return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
868       }
869       if (ShOp1->ugt(ShAmt)) {
870         unsigned ShlAmt = ShOp1->getZExtValue();
871         Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
872         if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
873           // (X <<nuw C1) >>u C2 --> X <<nuw (C1 - C2)
874           auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
875           NewShl->setHasNoUnsignedWrap(true);
876           return NewShl;
877         }
878         // (X << C1) >>u C2  --> X << (C1 - C2) & (-1 >> C2)
879         Value *NewShl = Builder.CreateShl(X, ShiftDiff);
880         APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
881         return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
882       }
883       assert(*ShOp1 == ShAmt);
884       // (X << C) >>u C --> X & (-1 >>u C)
885       APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
886       return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
887     }
888 
889     if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) &&
890         (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
891       assert(ShAmt < X->getType()->getScalarSizeInBits() &&
892              "Big shift not simplified to zero?");
893       // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
894       Value *NewLShr = Builder.CreateLShr(X, ShAmt);
895       return new ZExtInst(NewLShr, Ty);
896     }
897 
898     if (match(Op0, m_SExt(m_Value(X))) &&
899         (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
900       // Are we moving the sign bit to the low bit and widening with high zeros?
901       unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
902       if (ShAmt == BitWidth - 1) {
903         // lshr (sext i1 X to iN), N-1 --> zext X to iN
904         if (SrcTyBitWidth == 1)
905           return new ZExtInst(X, Ty);
906 
907         // lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
908         if (Op0->hasOneUse()) {
909           Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1);
910           return new ZExtInst(NewLShr, Ty);
911         }
912       }
913 
914       // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
915       if (ShAmt == BitWidth - SrcTyBitWidth && Op0->hasOneUse()) {
916         // The new shift amount can't be more than the narrow source type.
917         unsigned NewShAmt = std::min(ShAmt, SrcTyBitWidth - 1);
918         Value *AShr = Builder.CreateAShr(X, NewShAmt);
919         return new ZExtInst(AShr, Ty);
920       }
921     }
922 
923     if (match(Op0, m_LShr(m_Value(X), m_APInt(ShOp1)))) {
924       unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
925       // Oversized shifts are simplified to zero in InstSimplify.
926       if (AmtSum < BitWidth)
927         // (X >>u C1) >>u C2 --> X >>u (C1 + C2)
928         return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
929     }
930 
931     // If the shifted-out value is known-zero, then this is an exact shift.
932     if (!I.isExact() &&
933         MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
934       I.setIsExact();
935       return &I;
936     }
937   }
938 
939   // Transform  (x << y) >> y  to  x & (-1 >> y)
940   Value *X;
941   if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
942     Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
943     Value *Mask = Builder.CreateLShr(AllOnes, Op1);
944     return BinaryOperator::CreateAnd(Mask, X);
945   }
946 
947   return nullptr;
948 }
949 
950 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
951   if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
952                                   SQ.getWithInstruction(&I)))
953     return replaceInstUsesWith(I, V);
954 
955   if (Instruction *X = foldVectorBinop(I))
956     return X;
957 
958   if (Instruction *R = commonShiftTransforms(I))
959     return R;
960 
961   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
962   Type *Ty = I.getType();
963   unsigned BitWidth = Ty->getScalarSizeInBits();
964   const APInt *ShAmtAPInt;
965   if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) {
966     unsigned ShAmt = ShAmtAPInt->getZExtValue();
967 
968     // If the shift amount equals the difference in width of the destination
969     // and source scalar types:
970     // ashr (shl (zext X), C), C --> sext X
971     Value *X;
972     if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
973         ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
974       return new SExtInst(X, Ty);
975 
976     // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
977     // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
978     const APInt *ShOp1;
979     if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) &&
980         ShOp1->ult(BitWidth)) {
981       unsigned ShlAmt = ShOp1->getZExtValue();
982       if (ShlAmt < ShAmt) {
983         // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
984         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
985         auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff);
986         NewAShr->setIsExact(I.isExact());
987         return NewAShr;
988       }
989       if (ShlAmt > ShAmt) {
990         // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
991         Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
992         auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff);
993         NewShl->setHasNoSignedWrap(true);
994         return NewShl;
995       }
996     }
997 
998     if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) &&
999         ShOp1->ult(BitWidth)) {
1000       unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1001       // Oversized arithmetic shifts replicate the sign bit.
1002       AmtSum = std::min(AmtSum, BitWidth - 1);
1003       // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
1004       return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
1005     }
1006 
1007     if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) &&
1008         (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) {
1009       // ashr (sext X), C --> sext (ashr X, C')
1010       Type *SrcTy = X->getType();
1011       ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1);
1012       Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt));
1013       return new SExtInst(NewSh, Ty);
1014     }
1015 
1016     // If the shifted-out value is known-zero, then this is an exact shift.
1017     if (!I.isExact() &&
1018         MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
1019       I.setIsExact();
1020       return &I;
1021     }
1022   }
1023 
1024   // See if we can turn a signed shr into an unsigned shr.
1025   if (MaskedValueIsZero(Op0, APInt::getSignMask(BitWidth), 0, &I))
1026     return BinaryOperator::CreateLShr(Op0, Op1);
1027 
1028   return nullptr;
1029 }
1030