xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp (revision 5fb307d29b364982acbde82cbf77db3cae486f8c)
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/InstructionSimplify.h"
15 #include "llvm/IR/IntrinsicInst.h"
16 #include "llvm/IR/PatternMatch.h"
17 #include "llvm/Transforms/InstCombine/InstCombiner.h"
18 using namespace llvm;
19 using namespace PatternMatch;
20 
21 #define DEBUG_TYPE "instcombine"
22 
23 bool canTryToConstantAddTwoShiftAmounts(Value *Sh0, Value *ShAmt0, Value *Sh1,
24                                         Value *ShAmt1) {
25   // We have two shift amounts from two different shifts. The types of those
26   // shift amounts may not match. If that's the case let's bailout now..
27   if (ShAmt0->getType() != ShAmt1->getType())
28     return false;
29 
30   // As input, we have the following pattern:
31   //   Sh0 (Sh1 X, Q), K
32   // We want to rewrite that as:
33   //   Sh x, (Q+K)  iff (Q+K) u< bitwidth(x)
34   // While we know that originally (Q+K) would not overflow
35   // (because  2 * (N-1) u<= iN -1), we have looked past extensions of
36   // shift amounts. so it may now overflow in smaller bitwidth.
37   // To ensure that does not happen, we need to ensure that the total maximal
38   // shift amount is still representable in that smaller bit width.
39   unsigned MaximalPossibleTotalShiftAmount =
40       (Sh0->getType()->getScalarSizeInBits() - 1) +
41       (Sh1->getType()->getScalarSizeInBits() - 1);
42   APInt MaximalRepresentableShiftAmount =
43       APInt::getAllOnes(ShAmt0->getType()->getScalarSizeInBits());
44   return MaximalRepresentableShiftAmount.uge(MaximalPossibleTotalShiftAmount);
45 }
46 
47 // Given pattern:
48 //   (x shiftopcode Q) shiftopcode K
49 // we should rewrite it as
50 //   x shiftopcode (Q+K)  iff (Q+K) u< bitwidth(x) and
51 //
52 // This is valid for any shift, but they must be identical, and we must be
53 // careful in case we have (zext(Q)+zext(K)) and look past extensions,
54 // (Q+K) must not overflow or else (Q+K) u< bitwidth(x) is bogus.
55 //
56 // AnalyzeForSignBitExtraction indicates that we will only analyze whether this
57 // pattern has any 2 right-shifts that sum to 1 less than original bit width.
58 Value *InstCombinerImpl::reassociateShiftAmtsOfTwoSameDirectionShifts(
59     BinaryOperator *Sh0, const SimplifyQuery &SQ,
60     bool AnalyzeForSignBitExtraction) {
61   // Look for a shift of some instruction, ignore zext of shift amount if any.
62   Instruction *Sh0Op0;
63   Value *ShAmt0;
64   if (!match(Sh0,
65              m_Shift(m_Instruction(Sh0Op0), m_ZExtOrSelf(m_Value(ShAmt0)))))
66     return nullptr;
67 
68   // If there is a truncation between the two shifts, we must make note of it
69   // and look through it. The truncation imposes additional constraints on the
70   // transform.
71   Instruction *Sh1;
72   Value *Trunc = nullptr;
73   match(Sh0Op0,
74         m_CombineOr(m_CombineAnd(m_Trunc(m_Instruction(Sh1)), m_Value(Trunc)),
75                     m_Instruction(Sh1)));
76 
77   // Inner shift: (x shiftopcode ShAmt1)
78   // Like with other shift, ignore zext of shift amount if any.
79   Value *X, *ShAmt1;
80   if (!match(Sh1, m_Shift(m_Value(X), m_ZExtOrSelf(m_Value(ShAmt1)))))
81     return nullptr;
82 
83   // Verify that it would be safe to try to add those two shift amounts.
84   if (!canTryToConstantAddTwoShiftAmounts(Sh0, ShAmt0, Sh1, ShAmt1))
85     return nullptr;
86 
87   // We are only looking for signbit extraction if we have two right shifts.
88   bool HadTwoRightShifts = match(Sh0, m_Shr(m_Value(), m_Value())) &&
89                            match(Sh1, m_Shr(m_Value(), m_Value()));
90   // ... and if it's not two right-shifts, we know the answer already.
91   if (AnalyzeForSignBitExtraction && !HadTwoRightShifts)
92     return nullptr;
93 
94   // The shift opcodes must be identical, unless we are just checking whether
95   // this pattern can be interpreted as a sign-bit-extraction.
96   Instruction::BinaryOps ShiftOpcode = Sh0->getOpcode();
97   bool IdenticalShOpcodes = Sh0->getOpcode() == Sh1->getOpcode();
98   if (!IdenticalShOpcodes && !AnalyzeForSignBitExtraction)
99     return nullptr;
100 
101   // If we saw truncation, we'll need to produce extra instruction,
102   // and for that one of the operands of the shift must be one-use,
103   // unless of course we don't actually plan to produce any instructions here.
104   if (Trunc && !AnalyzeForSignBitExtraction &&
105       !match(Sh0, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
106     return nullptr;
107 
108   // Can we fold (ShAmt0+ShAmt1) ?
109   auto *NewShAmt = dyn_cast_or_null<Constant>(
110       simplifyAddInst(ShAmt0, ShAmt1, /*isNSW=*/false, /*isNUW=*/false,
111                       SQ.getWithInstruction(Sh0)));
112   if (!NewShAmt)
113     return nullptr; // Did not simplify.
114   unsigned NewShAmtBitWidth = NewShAmt->getType()->getScalarSizeInBits();
115   unsigned XBitWidth = X->getType()->getScalarSizeInBits();
116   // Is the new shift amount smaller than the bit width of inner/new shift?
117   if (!match(NewShAmt, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,
118                                           APInt(NewShAmtBitWidth, XBitWidth))))
119     return nullptr; // FIXME: could perform constant-folding.
120 
121   // If there was a truncation, and we have a right-shift, we can only fold if
122   // we are left with the original sign bit. Likewise, if we were just checking
123   // that this is a sighbit extraction, this is the place to check it.
124   // FIXME: zero shift amount is also legal here, but we can't *easily* check
125   // more than one predicate so it's not really worth it.
126   if (HadTwoRightShifts && (Trunc || AnalyzeForSignBitExtraction)) {
127     // If it's not a sign bit extraction, then we're done.
128     if (!match(NewShAmt,
129                m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
130                                   APInt(NewShAmtBitWidth, XBitWidth - 1))))
131       return nullptr;
132     // If it is, and that was the question, return the base value.
133     if (AnalyzeForSignBitExtraction)
134       return X;
135   }
136 
137   assert(IdenticalShOpcodes && "Should not get here with different shifts.");
138 
139   // All good, we can do this fold.
140   NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, X->getType());
141 
142   BinaryOperator *NewShift = BinaryOperator::Create(ShiftOpcode, X, NewShAmt);
143 
144   // The flags can only be propagated if there wasn't a trunc.
145   if (!Trunc) {
146     // If the pattern did not involve trunc, and both of the original shifts
147     // had the same flag set, preserve the flag.
148     if (ShiftOpcode == Instruction::BinaryOps::Shl) {
149       NewShift->setHasNoUnsignedWrap(Sh0->hasNoUnsignedWrap() &&
150                                      Sh1->hasNoUnsignedWrap());
151       NewShift->setHasNoSignedWrap(Sh0->hasNoSignedWrap() &&
152                                    Sh1->hasNoSignedWrap());
153     } else {
154       NewShift->setIsExact(Sh0->isExact() && Sh1->isExact());
155     }
156   }
157 
158   Instruction *Ret = NewShift;
159   if (Trunc) {
160     Builder.Insert(NewShift);
161     Ret = CastInst::Create(Instruction::Trunc, NewShift, Sh0->getType());
162   }
163 
164   return Ret;
165 }
166 
167 // If we have some pattern that leaves only some low bits set, and then performs
168 // left-shift of those bits, if none of the bits that are left after the final
169 // shift are modified by the mask, we can omit the mask.
170 //
171 // There are many variants to this pattern:
172 //   a)  (x & ((1 << MaskShAmt) - 1)) << ShiftShAmt
173 //   b)  (x & (~(-1 << MaskShAmt))) << ShiftShAmt
174 //   c)  (x & (-1 l>> MaskShAmt)) << ShiftShAmt
175 //   d)  (x & ((-1 << MaskShAmt) l>> MaskShAmt)) << ShiftShAmt
176 //   e)  ((x << MaskShAmt) l>> MaskShAmt) << ShiftShAmt
177 //   f)  ((x << MaskShAmt) a>> MaskShAmt) << ShiftShAmt
178 // All these patterns can be simplified to just:
179 //   x << ShiftShAmt
180 // iff:
181 //   a,b)     (MaskShAmt+ShiftShAmt) u>= bitwidth(x)
182 //   c,d,e,f) (ShiftShAmt-MaskShAmt) s>= 0 (i.e. ShiftShAmt u>= MaskShAmt)
183 static Instruction *
184 dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift,
185                                      const SimplifyQuery &Q,
186                                      InstCombiner::BuilderTy &Builder) {
187   assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&
188          "The input must be 'shl'!");
189 
190   Value *Masked, *ShiftShAmt;
191   match(OuterShift,
192         m_Shift(m_Value(Masked), m_ZExtOrSelf(m_Value(ShiftShAmt))));
193 
194   // *If* there is a truncation between an outer shift and a possibly-mask,
195   // then said truncation *must* be one-use, else we can't perform the fold.
196   Value *Trunc;
197   if (match(Masked, m_CombineAnd(m_Trunc(m_Value(Masked)), m_Value(Trunc))) &&
198       !Trunc->hasOneUse())
199     return nullptr;
200 
201   Type *NarrowestTy = OuterShift->getType();
202   Type *WidestTy = Masked->getType();
203   bool HadTrunc = WidestTy != NarrowestTy;
204 
205   // The mask must be computed in a type twice as wide to ensure
206   // that no bits are lost if the sum-of-shifts is wider than the base type.
207   Type *ExtendedTy = WidestTy->getExtendedType();
208 
209   Value *MaskShAmt;
210 
211   // ((1 << MaskShAmt) - 1)
212   auto MaskA = m_Add(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes());
213   // (~(-1 << maskNbits))
214   auto MaskB = m_Xor(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_AllOnes());
215   // (-1 l>> MaskShAmt)
216   auto MaskC = m_LShr(m_AllOnes(), m_Value(MaskShAmt));
217   // ((-1 << MaskShAmt) l>> MaskShAmt)
218   auto MaskD =
219       m_LShr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt));
220 
221   Value *X;
222   Constant *NewMask;
223 
224   if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) {
225     // Peek through an optional zext of the shift amount.
226     match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
227 
228     // Verify that it would be safe to try to add those two shift amounts.
229     if (!canTryToConstantAddTwoShiftAmounts(OuterShift, ShiftShAmt, Masked,
230                                             MaskShAmt))
231       return nullptr;
232 
233     // Can we simplify (MaskShAmt+ShiftShAmt) ?
234     auto *SumOfShAmts = dyn_cast_or_null<Constant>(simplifyAddInst(
235         MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
236     if (!SumOfShAmts)
237       return nullptr; // Did not simplify.
238     // In this pattern SumOfShAmts correlates with the number of low bits
239     // that shall remain in the root value (OuterShift).
240 
241     // An extend of an undef value becomes zero because the high bits are never
242     // completely unknown. Replace the `undef` shift amounts with final
243     // shift bitwidth to ensure that the value remains undef when creating the
244     // subsequent shift op.
245     SumOfShAmts = Constant::replaceUndefsWith(
246         SumOfShAmts, ConstantInt::get(SumOfShAmts->getType()->getScalarType(),
247                                       ExtendedTy->getScalarSizeInBits()));
248     auto *ExtendedSumOfShAmts = ConstantExpr::getZExt(SumOfShAmts, ExtendedTy);
249     // And compute the mask as usual: ~(-1 << (SumOfShAmts))
250     auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
251     auto *ExtendedInvertedMask =
252         ConstantExpr::getShl(ExtendedAllOnes, ExtendedSumOfShAmts);
253     NewMask = ConstantExpr::getNot(ExtendedInvertedMask);
254   } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) ||
255              match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)),
256                                  m_Deferred(MaskShAmt)))) {
257     // Peek through an optional zext of the shift amount.
258     match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
259 
260     // Verify that it would be safe to try to add those two shift amounts.
261     if (!canTryToConstantAddTwoShiftAmounts(OuterShift, ShiftShAmt, Masked,
262                                             MaskShAmt))
263       return nullptr;
264 
265     // Can we simplify (ShiftShAmt-MaskShAmt) ?
266     auto *ShAmtsDiff = dyn_cast_or_null<Constant>(simplifySubInst(
267         ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
268     if (!ShAmtsDiff)
269       return nullptr; // Did not simplify.
270     // In this pattern ShAmtsDiff correlates with the number of high bits that
271     // shall be unset in the root value (OuterShift).
272 
273     // An extend of an undef value becomes zero because the high bits are never
274     // completely unknown. Replace the `undef` shift amounts with negated
275     // bitwidth of innermost shift to ensure that the value remains undef when
276     // creating the subsequent shift op.
277     unsigned WidestTyBitWidth = WidestTy->getScalarSizeInBits();
278     ShAmtsDiff = Constant::replaceUndefsWith(
279         ShAmtsDiff, ConstantInt::get(ShAmtsDiff->getType()->getScalarType(),
280                                      -WidestTyBitWidth));
281     auto *ExtendedNumHighBitsToClear = ConstantExpr::getZExt(
282         ConstantExpr::getSub(ConstantInt::get(ShAmtsDiff->getType(),
283                                               WidestTyBitWidth,
284                                               /*isSigned=*/false),
285                              ShAmtsDiff),
286         ExtendedTy);
287     // And compute the mask as usual: (-1 l>> (NumHighBitsToClear))
288     auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
289     NewMask =
290         ConstantExpr::getLShr(ExtendedAllOnes, ExtendedNumHighBitsToClear);
291   } else
292     return nullptr; // Don't know anything about this pattern.
293 
294   NewMask = ConstantExpr::getTrunc(NewMask, NarrowestTy);
295 
296   // Does this mask has any unset bits? If not then we can just not apply it.
297   bool NeedMask = !match(NewMask, m_AllOnes());
298 
299   // If we need to apply a mask, there are several more restrictions we have.
300   if (NeedMask) {
301     // The old masking instruction must go away.
302     if (!Masked->hasOneUse())
303       return nullptr;
304     // The original "masking" instruction must not have been`ashr`.
305     if (match(Masked, m_AShr(m_Value(), m_Value())))
306       return nullptr;
307   }
308 
309   // If we need to apply truncation, let's do it first, since we can.
310   // We have already ensured that the old truncation will go away.
311   if (HadTrunc)
312     X = Builder.CreateTrunc(X, NarrowestTy);
313 
314   // No 'NUW'/'NSW'! We no longer know that we won't shift-out non-0 bits.
315   // We didn't change the Type of this outermost shift, so we can just do it.
316   auto *NewShift = BinaryOperator::Create(OuterShift->getOpcode(), X,
317                                           OuterShift->getOperand(1));
318   if (!NeedMask)
319     return NewShift;
320 
321   Builder.Insert(NewShift);
322   return BinaryOperator::Create(Instruction::And, NewShift, NewMask);
323 }
324 
325 /// If we have a shift-by-constant of a bin op (bitwise logic op or add/sub w/
326 /// shl) that itself has a shift-by-constant operand with identical opcode, we
327 /// may be able to convert that into 2 independent shifts followed by the logic
328 /// op. This eliminates a use of an intermediate value (reduces dependency
329 /// chain).
330 static Instruction *foldShiftOfShiftedBinOp(BinaryOperator &I,
331                                             InstCombiner::BuilderTy &Builder) {
332   assert(I.isShift() && "Expected a shift as input");
333   auto *BinInst = dyn_cast<BinaryOperator>(I.getOperand(0));
334   if (!BinInst ||
335       (!BinInst->isBitwiseLogicOp() &&
336        BinInst->getOpcode() != Instruction::Add &&
337        BinInst->getOpcode() != Instruction::Sub) ||
338       !BinInst->hasOneUse())
339     return nullptr;
340 
341   Constant *C0, *C1;
342   if (!match(I.getOperand(1), m_Constant(C1)))
343     return nullptr;
344 
345   Instruction::BinaryOps ShiftOpcode = I.getOpcode();
346   // Transform for add/sub only works with shl.
347   if ((BinInst->getOpcode() == Instruction::Add ||
348        BinInst->getOpcode() == Instruction::Sub) &&
349       ShiftOpcode != Instruction::Shl)
350     return nullptr;
351 
352   Type *Ty = I.getType();
353 
354   // Find a matching one-use shift by constant. The fold is not valid if the sum
355   // of the shift values equals or exceeds bitwidth.
356   // TODO: Remove the one-use check if the other logic operand (Y) is constant.
357   Value *X, *Y;
358   auto matchFirstShift = [&](Value *V) {
359     APInt Threshold(Ty->getScalarSizeInBits(), Ty->getScalarSizeInBits());
360     return match(V,
361                  m_OneUse(m_BinOp(ShiftOpcode, m_Value(X), m_Constant(C0)))) &&
362            match(ConstantExpr::getAdd(C0, C1),
363                  m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold));
364   };
365 
366   // Logic ops and Add are commutative, so check each operand for a match. Sub
367   // is not so we cannot reoder if we match operand(1) and need to keep the
368   // operands in their original positions.
369   bool FirstShiftIsOp1 = false;
370   if (matchFirstShift(BinInst->getOperand(0)))
371     Y = BinInst->getOperand(1);
372   else if (matchFirstShift(BinInst->getOperand(1))) {
373     Y = BinInst->getOperand(0);
374     FirstShiftIsOp1 = BinInst->getOpcode() == Instruction::Sub;
375   } else
376     return nullptr;
377 
378   // shift (binop (shift X, C0), Y), C1 -> binop (shift X, C0+C1), (shift Y, C1)
379   Constant *ShiftSumC = ConstantExpr::getAdd(C0, C1);
380   Value *NewShift1 = Builder.CreateBinOp(ShiftOpcode, X, ShiftSumC);
381   Value *NewShift2 = Builder.CreateBinOp(ShiftOpcode, Y, C1);
382   Value *Op1 = FirstShiftIsOp1 ? NewShift2 : NewShift1;
383   Value *Op2 = FirstShiftIsOp1 ? NewShift1 : NewShift2;
384   return BinaryOperator::Create(BinInst->getOpcode(), Op1, Op2);
385 }
386 
387 Instruction *InstCombinerImpl::commonShiftTransforms(BinaryOperator &I) {
388   if (Instruction *Phi = foldBinopWithPhiOperands(I))
389     return Phi;
390 
391   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
392   assert(Op0->getType() == Op1->getType());
393   Type *Ty = I.getType();
394 
395   // If the shift amount is a one-use `sext`, we can demote it to `zext`.
396   Value *Y;
397   if (match(Op1, m_OneUse(m_SExt(m_Value(Y))))) {
398     Value *NewExt = Builder.CreateZExt(Y, Ty, Op1->getName());
399     return BinaryOperator::Create(I.getOpcode(), Op0, NewExt);
400   }
401 
402   // See if we can fold away this shift.
403   if (SimplifyDemandedInstructionBits(I))
404     return &I;
405 
406   // Try to fold constant and into select arguments.
407   if (isa<Constant>(Op0))
408     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
409       if (Instruction *R = FoldOpIntoSelect(I, SI))
410         return R;
411 
412   if (Constant *CUI = dyn_cast<Constant>(Op1))
413     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
414       return Res;
415 
416   if (auto *NewShift = cast_or_null<Instruction>(
417           reassociateShiftAmtsOfTwoSameDirectionShifts(&I, SQ)))
418     return NewShift;
419 
420   // Pre-shift a constant shifted by a variable amount with constant offset:
421   // C shift (A add nuw C1) --> (C shift C1) shift A
422   Value *A;
423   Constant *C, *C1;
424   if (match(Op0, m_Constant(C)) &&
425       match(Op1, m_NUWAdd(m_Value(A), m_Constant(C1)))) {
426     Value *NewC = Builder.CreateBinOp(I.getOpcode(), C, C1);
427     return BinaryOperator::Create(I.getOpcode(), NewC, A);
428   }
429 
430   unsigned BitWidth = Ty->getScalarSizeInBits();
431 
432   const APInt *AC, *AddC;
433   // Try to pre-shift a constant shifted by a variable amount added with a
434   // negative number:
435   // C << (X - AddC) --> (C >> AddC) << X
436   // and
437   // C >> (X - AddC) --> (C << AddC) >> X
438   if (match(Op0, m_APInt(AC)) && match(Op1, m_Add(m_Value(A), m_APInt(AddC))) &&
439       AddC->isNegative() && (-*AddC).ult(BitWidth)) {
440     assert(!AC->isZero() && "Expected simplify of shifted zero");
441     unsigned PosOffset = (-*AddC).getZExtValue();
442 
443     auto isSuitableForPreShift = [PosOffset, &I, AC]() {
444       switch (I.getOpcode()) {
445       default:
446         return false;
447       case Instruction::Shl:
448         return (I.hasNoSignedWrap() || I.hasNoUnsignedWrap()) &&
449                AC->eq(AC->lshr(PosOffset).shl(PosOffset));
450       case Instruction::LShr:
451         return I.isExact() && AC->eq(AC->shl(PosOffset).lshr(PosOffset));
452       case Instruction::AShr:
453         return I.isExact() && AC->eq(AC->shl(PosOffset).ashr(PosOffset));
454       }
455     };
456     if (isSuitableForPreShift()) {
457       Constant *NewC = ConstantInt::get(Ty, I.getOpcode() == Instruction::Shl
458                                                 ? AC->lshr(PosOffset)
459                                                 : AC->shl(PosOffset));
460       BinaryOperator *NewShiftOp =
461           BinaryOperator::Create(I.getOpcode(), NewC, A);
462       if (I.getOpcode() == Instruction::Shl) {
463         NewShiftOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
464       } else {
465         NewShiftOp->setIsExact();
466       }
467       return NewShiftOp;
468     }
469   }
470 
471   // X shift (A srem C) -> X shift (A and (C - 1)) iff C is a power of 2.
472   // Because shifts by negative values (which could occur if A were negative)
473   // are undefined.
474   if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Constant(C))) &&
475       match(C, m_Power2())) {
476     // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
477     // demand the sign bit (and many others) here??
478     Constant *Mask = ConstantExpr::getSub(C, ConstantInt::get(Ty, 1));
479     Value *Rem = Builder.CreateAnd(A, Mask, Op1->getName());
480     return replaceOperand(I, 1, Rem);
481   }
482 
483   if (Instruction *Logic = foldShiftOfShiftedBinOp(I, Builder))
484     return Logic;
485 
486   if (match(Op1, m_Or(m_Value(), m_SpecificInt(BitWidth - 1))))
487     return replaceOperand(I, 1, ConstantInt::get(Ty, BitWidth - 1));
488 
489   return nullptr;
490 }
491 
492 /// Return true if we can simplify two logical (either left or right) shifts
493 /// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
494 static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
495                                     Instruction *InnerShift,
496                                     InstCombinerImpl &IC, Instruction *CxtI) {
497   assert(InnerShift->isLogicalShift() && "Unexpected instruction type");
498 
499   // We need constant scalar or constant splat shifts.
500   const APInt *InnerShiftConst;
501   if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst)))
502     return false;
503 
504   // Two logical shifts in the same direction:
505   // shl (shl X, C1), C2 -->  shl X, C1 + C2
506   // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
507   bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
508   if (IsInnerShl == IsOuterShl)
509     return true;
510 
511   // Equal shift amounts in opposite directions become bitwise 'and':
512   // lshr (shl X, C), C --> and X, C'
513   // shl (lshr X, C), C --> and X, C'
514   if (*InnerShiftConst == OuterShAmt)
515     return true;
516 
517   // If the 2nd shift is bigger than the 1st, we can fold:
518   // lshr (shl X, C1), C2 -->  and (shl X, C1 - C2), C3
519   // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
520   // but it isn't profitable unless we know the and'd out bits are already zero.
521   // Also, check that the inner shift is valid (less than the type width) or
522   // we'll crash trying to produce the bit mask for the 'and'.
523   unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
524   if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) {
525     unsigned InnerShAmt = InnerShiftConst->getZExtValue();
526     unsigned MaskShift =
527         IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
528     APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift;
529     if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI))
530       return true;
531   }
532 
533   return false;
534 }
535 
536 /// See if we can compute the specified value, but shifted logically to the left
537 /// or right by some number of bits. This should return true if the expression
538 /// can be computed for the same cost as the current expression tree. This is
539 /// used to eliminate extraneous shifting from things like:
540 ///      %C = shl i128 %A, 64
541 ///      %D = shl i128 %B, 96
542 ///      %E = or i128 %C, %D
543 ///      %F = lshr i128 %E, 64
544 /// where the client will ask if E can be computed shifted right by 64-bits. If
545 /// this succeeds, getShiftedValue() will be called to produce the value.
546 static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
547                                InstCombinerImpl &IC, Instruction *CxtI) {
548   // We can always evaluate constants shifted.
549   if (isa<Constant>(V))
550     return true;
551 
552   Instruction *I = dyn_cast<Instruction>(V);
553   if (!I) return false;
554 
555   // We can't mutate something that has multiple uses: doing so would
556   // require duplicating the instruction in general, which isn't profitable.
557   if (!I->hasOneUse()) return false;
558 
559   switch (I->getOpcode()) {
560   default: return false;
561   case Instruction::And:
562   case Instruction::Or:
563   case Instruction::Xor:
564     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
565     return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
566            canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
567 
568   case Instruction::Shl:
569   case Instruction::LShr:
570     return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
571 
572   case Instruction::Select: {
573     SelectInst *SI = cast<SelectInst>(I);
574     Value *TrueVal = SI->getTrueValue();
575     Value *FalseVal = SI->getFalseValue();
576     return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
577            canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
578   }
579   case Instruction::PHI: {
580     // We can change a phi if we can change all operands.  Note that we never
581     // get into trouble with cyclic PHIs here because we only consider
582     // instructions with a single use.
583     PHINode *PN = cast<PHINode>(I);
584     for (Value *IncValue : PN->incoming_values())
585       if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
586         return false;
587     return true;
588   }
589   case Instruction::Mul: {
590     const APInt *MulConst;
591     // We can fold (shr (mul X, -(1 << C)), C) -> (and (neg X), C`)
592     return !IsLeftShift && match(I->getOperand(1), m_APInt(MulConst)) &&
593            MulConst->isNegatedPowerOf2() && MulConst->countr_zero() == NumBits;
594   }
595   }
596 }
597 
598 /// Fold OuterShift (InnerShift X, C1), C2.
599 /// See canEvaluateShiftedShift() for the constraints on these instructions.
600 static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
601                                bool IsOuterShl,
602                                InstCombiner::BuilderTy &Builder) {
603   bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
604   Type *ShType = InnerShift->getType();
605   unsigned TypeWidth = ShType->getScalarSizeInBits();
606 
607   // We only accept shifts-by-a-constant in canEvaluateShifted().
608   const APInt *C1;
609   match(InnerShift->getOperand(1), m_APInt(C1));
610   unsigned InnerShAmt = C1->getZExtValue();
611 
612   // Change the shift amount and clear the appropriate IR flags.
613   auto NewInnerShift = [&](unsigned ShAmt) {
614     InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
615     if (IsInnerShl) {
616       InnerShift->setHasNoUnsignedWrap(false);
617       InnerShift->setHasNoSignedWrap(false);
618     } else {
619       InnerShift->setIsExact(false);
620     }
621     return InnerShift;
622   };
623 
624   // Two logical shifts in the same direction:
625   // shl (shl X, C1), C2 -->  shl X, C1 + C2
626   // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
627   if (IsInnerShl == IsOuterShl) {
628     // If this is an oversized composite shift, then unsigned shifts get 0.
629     if (InnerShAmt + OuterShAmt >= TypeWidth)
630       return Constant::getNullValue(ShType);
631 
632     return NewInnerShift(InnerShAmt + OuterShAmt);
633   }
634 
635   // Equal shift amounts in opposite directions become bitwise 'and':
636   // lshr (shl X, C), C --> and X, C'
637   // shl (lshr X, C), C --> and X, C'
638   if (InnerShAmt == OuterShAmt) {
639     APInt Mask = IsInnerShl
640                      ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
641                      : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
642     Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
643                                    ConstantInt::get(ShType, Mask));
644     if (auto *AndI = dyn_cast<Instruction>(And)) {
645       AndI->moveBefore(InnerShift);
646       AndI->takeName(InnerShift);
647     }
648     return And;
649   }
650 
651   assert(InnerShAmt > OuterShAmt &&
652          "Unexpected opposite direction logical shift pair");
653 
654   // In general, we would need an 'and' for this transform, but
655   // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
656   // lshr (shl X, C1), C2 -->  shl X, C1 - C2
657   // shl (lshr X, C1), C2 --> lshr X, C1 - C2
658   return NewInnerShift(InnerShAmt - OuterShAmt);
659 }
660 
661 /// When canEvaluateShifted() returns true for an expression, this function
662 /// inserts the new computation that produces the shifted value.
663 static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
664                               InstCombinerImpl &IC, const DataLayout &DL) {
665   // We can always evaluate constants shifted.
666   if (Constant *C = dyn_cast<Constant>(V)) {
667     if (isLeftShift)
668       return IC.Builder.CreateShl(C, NumBits);
669     else
670       return IC.Builder.CreateLShr(C, NumBits);
671   }
672 
673   Instruction *I = cast<Instruction>(V);
674   IC.addToWorklist(I);
675 
676   switch (I->getOpcode()) {
677   default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
678   case Instruction::And:
679   case Instruction::Or:
680   case Instruction::Xor:
681     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
682     I->setOperand(
683         0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
684     I->setOperand(
685         1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
686     return I;
687 
688   case Instruction::Shl:
689   case Instruction::LShr:
690     return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
691                             IC.Builder);
692 
693   case Instruction::Select:
694     I->setOperand(
695         1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
696     I->setOperand(
697         2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
698     return I;
699   case Instruction::PHI: {
700     // We can change a phi if we can change all operands.  Note that we never
701     // get into trouble with cyclic PHIs here because we only consider
702     // instructions with a single use.
703     PHINode *PN = cast<PHINode>(I);
704     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
705       PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits,
706                                               isLeftShift, IC, DL));
707     return PN;
708   }
709   case Instruction::Mul: {
710     assert(!isLeftShift && "Unexpected shift direction!");
711     auto *Neg = BinaryOperator::CreateNeg(I->getOperand(0));
712     IC.InsertNewInstWith(Neg, *I);
713     unsigned TypeWidth = I->getType()->getScalarSizeInBits();
714     APInt Mask = APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits);
715     auto *And = BinaryOperator::CreateAnd(Neg,
716                                           ConstantInt::get(I->getType(), Mask));
717     And->takeName(I);
718     return IC.InsertNewInstWith(And, *I);
719   }
720   }
721 }
722 
723 // If this is a bitwise operator or add with a constant RHS we might be able
724 // to pull it through a shift.
725 static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift,
726                                          BinaryOperator *BO) {
727   switch (BO->getOpcode()) {
728   default:
729     return false; // Do not perform transform!
730   case Instruction::Add:
731     return Shift.getOpcode() == Instruction::Shl;
732   case Instruction::Or:
733   case Instruction::And:
734     return true;
735   case Instruction::Xor:
736     // Do not change a 'not' of logical shift because that would create a normal
737     // 'xor'. The 'not' is likely better for analysis, SCEV, and codegen.
738     return !(Shift.isLogicalShift() && match(BO, m_Not(m_Value())));
739   }
740 }
741 
742 Instruction *InstCombinerImpl::FoldShiftByConstant(Value *Op0, Constant *C1,
743                                                    BinaryOperator &I) {
744   // (C2 << X) << C1 --> (C2 << C1) << X
745   // (C2 >> X) >> C1 --> (C2 >> C1) >> X
746   Constant *C2;
747   Value *X;
748   if (match(Op0, m_BinOp(I.getOpcode(), m_Constant(C2), m_Value(X))))
749     return BinaryOperator::Create(
750         I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), C2, C1), X);
751 
752   bool IsLeftShift = I.getOpcode() == Instruction::Shl;
753   Type *Ty = I.getType();
754   unsigned TypeBits = Ty->getScalarSizeInBits();
755 
756   // (X / +DivC) >> (Width - 1) --> ext (X <= -DivC)
757   // (X / -DivC) >> (Width - 1) --> ext (X >= +DivC)
758   const APInt *DivC;
759   if (!IsLeftShift && match(C1, m_SpecificIntAllowUndef(TypeBits - 1)) &&
760       match(Op0, m_SDiv(m_Value(X), m_APInt(DivC))) && !DivC->isZero() &&
761       !DivC->isMinSignedValue()) {
762     Constant *NegDivC = ConstantInt::get(Ty, -(*DivC));
763     ICmpInst::Predicate Pred =
764         DivC->isNegative() ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SLE;
765     Value *Cmp = Builder.CreateICmp(Pred, X, NegDivC);
766     auto ExtOpcode = (I.getOpcode() == Instruction::AShr) ? Instruction::SExt
767                                                           : Instruction::ZExt;
768     return CastInst::Create(ExtOpcode, Cmp, Ty);
769   }
770 
771   const APInt *Op1C;
772   if (!match(C1, m_APInt(Op1C)))
773     return nullptr;
774 
775   assert(!Op1C->uge(TypeBits) &&
776          "Shift over the type width should have been removed already");
777 
778   // See if we can propagate this shift into the input, this covers the trivial
779   // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
780   if (I.getOpcode() != Instruction::AShr &&
781       canEvaluateShifted(Op0, Op1C->getZExtValue(), IsLeftShift, *this, &I)) {
782     LLVM_DEBUG(
783         dbgs() << "ICE: GetShiftedValue propagating shift through expression"
784                   " to eliminate shift:\n  IN: "
785                << *Op0 << "\n  SH: " << I << "\n");
786 
787     return replaceInstUsesWith(
788         I, getShiftedValue(Op0, Op1C->getZExtValue(), IsLeftShift, *this, DL));
789   }
790 
791   if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
792     return FoldedShift;
793 
794   if (!Op0->hasOneUse())
795     return nullptr;
796 
797   if (auto *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
798     // If the operand is a bitwise operator with a constant RHS, and the
799     // shift is the only use, we can pull it out of the shift.
800     const APInt *Op0C;
801     if (match(Op0BO->getOperand(1), m_APInt(Op0C))) {
802       if (canShiftBinOpWithConstantRHS(I, Op0BO)) {
803         Value *NewRHS =
804             Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(1), C1);
805 
806         Value *NewShift =
807             Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), C1);
808         NewShift->takeName(Op0BO);
809 
810         return BinaryOperator::Create(Op0BO->getOpcode(), NewShift, NewRHS);
811       }
812     }
813   }
814 
815   // If we have a select that conditionally executes some binary operator,
816   // see if we can pull it the select and operator through the shift.
817   //
818   // For example, turning:
819   //   shl (select C, (add X, C1), X), C2
820   // Into:
821   //   Y = shl X, C2
822   //   select C, (add Y, C1 << C2), Y
823   Value *Cond;
824   BinaryOperator *TBO;
825   Value *FalseVal;
826   if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)),
827                           m_Value(FalseVal)))) {
828     const APInt *C;
829     if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal &&
830         match(TBO->getOperand(1), m_APInt(C)) &&
831         canShiftBinOpWithConstantRHS(I, TBO)) {
832       Value *NewRHS =
833           Builder.CreateBinOp(I.getOpcode(), TBO->getOperand(1), C1);
834 
835       Value *NewShift = Builder.CreateBinOp(I.getOpcode(), FalseVal, C1);
836       Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift, NewRHS);
837       return SelectInst::Create(Cond, NewOp, NewShift);
838     }
839   }
840 
841   BinaryOperator *FBO;
842   Value *TrueVal;
843   if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal),
844                           m_OneUse(m_BinOp(FBO))))) {
845     const APInt *C;
846     if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal &&
847         match(FBO->getOperand(1), m_APInt(C)) &&
848         canShiftBinOpWithConstantRHS(I, FBO)) {
849       Value *NewRHS =
850           Builder.CreateBinOp(I.getOpcode(), FBO->getOperand(1), C1);
851 
852       Value *NewShift = Builder.CreateBinOp(I.getOpcode(), TrueVal, C1);
853       Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift, NewRHS);
854       return SelectInst::Create(Cond, NewShift, NewOp);
855     }
856   }
857 
858   return nullptr;
859 }
860 
861 // Tries to perform
862 //    (lshr (add (zext X), (zext Y)), K)
863 //      -> (icmp ult (add X, Y), X)
864 //    where
865 //      - The add's operands are zexts from a K-bits integer to a bigger type.
866 //      - The add is only used by the shr, or by iK (or narrower) truncates.
867 //      - The lshr type has more than 2 bits (other types are boolean math).
868 //      - K > 1
869 //    note that
870 //      - The resulting add cannot have nuw/nsw, else on overflow we get a
871 //        poison value and the transform isn't legal anymore.
872 Instruction *InstCombinerImpl::foldLShrOverflowBit(BinaryOperator &I) {
873   assert(I.getOpcode() == Instruction::LShr);
874 
875   Value *Add = I.getOperand(0);
876   Value *ShiftAmt = I.getOperand(1);
877   Type *Ty = I.getType();
878 
879   if (Ty->getScalarSizeInBits() < 3)
880     return nullptr;
881 
882   const APInt *ShAmtAPInt = nullptr;
883   Value *X = nullptr, *Y = nullptr;
884   if (!match(ShiftAmt, m_APInt(ShAmtAPInt)) ||
885       !match(Add,
886              m_Add(m_OneUse(m_ZExt(m_Value(X))), m_OneUse(m_ZExt(m_Value(Y))))))
887     return nullptr;
888 
889   const unsigned ShAmt = ShAmtAPInt->getZExtValue();
890   if (ShAmt == 1)
891     return nullptr;
892 
893   // X/Y are zexts from `ShAmt`-sized ints.
894   if (X->getType()->getScalarSizeInBits() != ShAmt ||
895       Y->getType()->getScalarSizeInBits() != ShAmt)
896     return nullptr;
897 
898   // Make sure that `Add` is only used by `I` and `ShAmt`-truncates.
899   if (!Add->hasOneUse()) {
900     for (User *U : Add->users()) {
901       if (U == &I)
902         continue;
903 
904       TruncInst *Trunc = dyn_cast<TruncInst>(U);
905       if (!Trunc || Trunc->getType()->getScalarSizeInBits() > ShAmt)
906         return nullptr;
907     }
908   }
909 
910   // Insert at Add so that the newly created `NarrowAdd` will dominate it's
911   // users (i.e. `Add`'s users).
912   Instruction *AddInst = cast<Instruction>(Add);
913   Builder.SetInsertPoint(AddInst);
914 
915   Value *NarrowAdd = Builder.CreateAdd(X, Y, "add.narrowed");
916   Value *Overflow =
917       Builder.CreateICmpULT(NarrowAdd, X, "add.narrowed.overflow");
918 
919   // Replace the uses of the original add with a zext of the
920   // NarrowAdd's result. Note that all users at this stage are known to
921   // be ShAmt-sized truncs, or the lshr itself.
922   if (!Add->hasOneUse()) {
923     replaceInstUsesWith(*AddInst, Builder.CreateZExt(NarrowAdd, Ty));
924     eraseInstFromFunction(*AddInst);
925   }
926 
927   // Replace the LShr with a zext of the overflow check.
928   return new ZExtInst(Overflow, Ty);
929 }
930 
931 Instruction *InstCombinerImpl::visitShl(BinaryOperator &I) {
932   const SimplifyQuery Q = SQ.getWithInstruction(&I);
933 
934   if (Value *V = simplifyShlInst(I.getOperand(0), I.getOperand(1),
935                                  I.hasNoSignedWrap(), I.hasNoUnsignedWrap(), Q))
936     return replaceInstUsesWith(I, V);
937 
938   if (Instruction *X = foldVectorBinop(I))
939     return X;
940 
941   if (Instruction *V = commonShiftTransforms(I))
942     return V;
943 
944   if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(&I, Q, Builder))
945     return V;
946 
947   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
948   Type *Ty = I.getType();
949   unsigned BitWidth = Ty->getScalarSizeInBits();
950 
951   const APInt *C;
952   if (match(Op1, m_APInt(C))) {
953     unsigned ShAmtC = C->getZExtValue();
954 
955     // shl (zext X), C --> zext (shl X, C)
956     // This is only valid if X would have zeros shifted out.
957     Value *X;
958     if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
959       unsigned SrcWidth = X->getType()->getScalarSizeInBits();
960       if (ShAmtC < SrcWidth &&
961           MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmtC), 0, &I))
962         return new ZExtInst(Builder.CreateShl(X, ShAmtC), Ty);
963     }
964 
965     // (X >> C) << C --> X & (-1 << C)
966     if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) {
967       APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmtC));
968       return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
969     }
970 
971     const APInt *C1;
972     if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(C1)))) &&
973         C1->ult(BitWidth)) {
974       unsigned ShrAmt = C1->getZExtValue();
975       if (ShrAmt < ShAmtC) {
976         // If C1 < C: (X >>?,exact C1) << C --> X << (C - C1)
977         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShrAmt);
978         auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
979         NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
980         NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
981         return NewShl;
982       }
983       if (ShrAmt > ShAmtC) {
984         // If C1 > C: (X >>?exact C1) << C --> X >>?exact (C1 - C)
985         Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmtC);
986         auto *NewShr = BinaryOperator::Create(
987             cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff);
988         NewShr->setIsExact(true);
989         return NewShr;
990       }
991     }
992 
993     if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_APInt(C1)))) &&
994         C1->ult(BitWidth)) {
995       unsigned ShrAmt = C1->getZExtValue();
996       if (ShrAmt < ShAmtC) {
997         // If C1 < C: (X >>? C1) << C --> (X << (C - C1)) & (-1 << C)
998         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShrAmt);
999         auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
1000         NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1001         NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
1002         Builder.Insert(NewShl);
1003         APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmtC));
1004         return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
1005       }
1006       if (ShrAmt > ShAmtC) {
1007         // If C1 > C: (X >>? C1) << C --> (X >>? (C1 - C)) & (-1 << C)
1008         Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmtC);
1009         auto *OldShr = cast<BinaryOperator>(Op0);
1010         auto *NewShr =
1011             BinaryOperator::Create(OldShr->getOpcode(), X, ShiftDiff);
1012         NewShr->setIsExact(OldShr->isExact());
1013         Builder.Insert(NewShr);
1014         APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmtC));
1015         return BinaryOperator::CreateAnd(NewShr, ConstantInt::get(Ty, Mask));
1016       }
1017     }
1018 
1019     // Similar to above, but look through an intermediate trunc instruction.
1020     BinaryOperator *Shr;
1021     if (match(Op0, m_OneUse(m_Trunc(m_OneUse(m_BinOp(Shr))))) &&
1022         match(Shr, m_Shr(m_Value(X), m_APInt(C1)))) {
1023       // The larger shift direction survives through the transform.
1024       unsigned ShrAmtC = C1->getZExtValue();
1025       unsigned ShDiff = ShrAmtC > ShAmtC ? ShrAmtC - ShAmtC : ShAmtC - ShrAmtC;
1026       Constant *ShiftDiffC = ConstantInt::get(X->getType(), ShDiff);
1027       auto ShiftOpc = ShrAmtC > ShAmtC ? Shr->getOpcode() : Instruction::Shl;
1028 
1029       // If C1 > C:
1030       // (trunc (X >> C1)) << C --> (trunc (X >> (C1 - C))) && (-1 << C)
1031       // If C > C1:
1032       // (trunc (X >> C1)) << C --> (trunc (X << (C - C1))) && (-1 << C)
1033       Value *NewShift = Builder.CreateBinOp(ShiftOpc, X, ShiftDiffC, "sh.diff");
1034       Value *Trunc = Builder.CreateTrunc(NewShift, Ty, "tr.sh.diff");
1035       APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmtC));
1036       return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Ty, Mask));
1037     }
1038 
1039     if (match(Op0, m_Shl(m_Value(X), m_APInt(C1))) && C1->ult(BitWidth)) {
1040       unsigned AmtSum = ShAmtC + C1->getZExtValue();
1041       // Oversized shifts are simplified to zero in InstSimplify.
1042       if (AmtSum < BitWidth)
1043         // (X << C1) << C2 --> X << (C1 + C2)
1044         return BinaryOperator::CreateShl(X, ConstantInt::get(Ty, AmtSum));
1045     }
1046 
1047     // If we have an opposite shift by the same amount, we may be able to
1048     // reorder binops and shifts to eliminate math/logic.
1049     auto isSuitableBinOpcode = [](Instruction::BinaryOps BinOpcode) {
1050       switch (BinOpcode) {
1051       default:
1052         return false;
1053       case Instruction::Add:
1054       case Instruction::And:
1055       case Instruction::Or:
1056       case Instruction::Xor:
1057       case Instruction::Sub:
1058         // NOTE: Sub is not commutable and the tranforms below may not be valid
1059         //       when the shift-right is operand 1 (RHS) of the sub.
1060         return true;
1061       }
1062     };
1063     BinaryOperator *Op0BO;
1064     if (match(Op0, m_OneUse(m_BinOp(Op0BO))) &&
1065         isSuitableBinOpcode(Op0BO->getOpcode())) {
1066       // Commute so shift-right is on LHS of the binop.
1067       // (Y bop (X >> C)) << C         ->  ((X >> C) bop Y) << C
1068       // (Y bop ((X >> C) & CC)) << C  ->  (((X >> C) & CC) bop Y) << C
1069       Value *Shr = Op0BO->getOperand(0);
1070       Value *Y = Op0BO->getOperand(1);
1071       Value *X;
1072       const APInt *CC;
1073       if (Op0BO->isCommutative() && Y->hasOneUse() &&
1074           (match(Y, m_Shr(m_Value(), m_Specific(Op1))) ||
1075            match(Y, m_And(m_OneUse(m_Shr(m_Value(), m_Specific(Op1))),
1076                           m_APInt(CC)))))
1077         std::swap(Shr, Y);
1078 
1079       // ((X >> C) bop Y) << C  ->  (X bop (Y << C)) & (~0 << C)
1080       if (match(Shr, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
1081         // Y << C
1082         Value *YS = Builder.CreateShl(Y, Op1, Op0BO->getName());
1083         // (X bop (Y << C))
1084         Value *B =
1085             Builder.CreateBinOp(Op0BO->getOpcode(), X, YS, Shr->getName());
1086         unsigned Op1Val = C->getLimitedValue(BitWidth);
1087         APInt Bits = APInt::getHighBitsSet(BitWidth, BitWidth - Op1Val);
1088         Constant *Mask = ConstantInt::get(Ty, Bits);
1089         return BinaryOperator::CreateAnd(B, Mask);
1090       }
1091 
1092       // (((X >> C) & CC) bop Y) << C  ->  (X & (CC << C)) bop (Y << C)
1093       if (match(Shr,
1094                 m_OneUse(m_And(m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))),
1095                                m_APInt(CC))))) {
1096         // Y << C
1097         Value *YS = Builder.CreateShl(Y, Op1, Op0BO->getName());
1098         // X & (CC << C)
1099         Value *M = Builder.CreateAnd(X, ConstantInt::get(Ty, CC->shl(*C)),
1100                                      X->getName() + ".mask");
1101         return BinaryOperator::Create(Op0BO->getOpcode(), M, YS);
1102       }
1103     }
1104 
1105     // (C1 - X) << C --> (C1 << C) - (X << C)
1106     if (match(Op0, m_OneUse(m_Sub(m_APInt(C1), m_Value(X))))) {
1107       Constant *NewLHS = ConstantInt::get(Ty, C1->shl(*C));
1108       Value *NewShift = Builder.CreateShl(X, Op1);
1109       return BinaryOperator::CreateSub(NewLHS, NewShift);
1110     }
1111 
1112     // If the shifted-out value is known-zero, then this is a NUW shift.
1113     if (!I.hasNoUnsignedWrap() &&
1114         MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, ShAmtC), 0,
1115                           &I)) {
1116       I.setHasNoUnsignedWrap();
1117       return &I;
1118     }
1119 
1120     // If the shifted-out value is all signbits, then this is a NSW shift.
1121     if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmtC) {
1122       I.setHasNoSignedWrap();
1123       return &I;
1124     }
1125   }
1126 
1127   // Transform  (x >> y) << y  to  x & (-1 << y)
1128   // Valid for any type of right-shift.
1129   Value *X;
1130   if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
1131     Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
1132     Value *Mask = Builder.CreateShl(AllOnes, Op1);
1133     return BinaryOperator::CreateAnd(Mask, X);
1134   }
1135 
1136   Constant *C1;
1137   if (match(Op1, m_Constant(C1))) {
1138     Constant *C2;
1139     Value *X;
1140     // (X * C2) << C1 --> X * (C2 << C1)
1141     if (match(Op0, m_Mul(m_Value(X), m_Constant(C2))))
1142       return BinaryOperator::CreateMul(X, ConstantExpr::getShl(C2, C1));
1143 
1144     // shl (zext i1 X), C1 --> select (X, 1 << C1, 0)
1145     if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1146       auto *NewC = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C1);
1147       return SelectInst::Create(X, NewC, ConstantInt::getNullValue(Ty));
1148     }
1149   }
1150 
1151   if (match(Op0, m_One())) {
1152     // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
1153     if (match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X))))
1154       return BinaryOperator::CreateLShr(
1155           ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X);
1156 
1157     // Canonicalize "extract lowest set bit" using cttz to and-with-negate:
1158     // 1 << (cttz X) --> -X & X
1159     if (match(Op1,
1160               m_OneUse(m_Intrinsic<Intrinsic::cttz>(m_Value(X), m_Value())))) {
1161       Value *NegX = Builder.CreateNeg(X, "neg");
1162       return BinaryOperator::CreateAnd(NegX, X);
1163     }
1164 
1165     // The only way to shift out the 1 is with an over-shift, so that would
1166     // be poison with or without "nuw". Undef is excluded because (undef << X)
1167     // is not undef (it is zero).
1168     Constant *ConstantOne = cast<Constant>(Op0);
1169     if (!I.hasNoUnsignedWrap() && !ConstantOne->containsUndefElement()) {
1170       I.setHasNoUnsignedWrap();
1171       return &I;
1172     }
1173   }
1174 
1175   return nullptr;
1176 }
1177 
1178 Instruction *InstCombinerImpl::visitLShr(BinaryOperator &I) {
1179   if (Value *V = simplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1180                                   SQ.getWithInstruction(&I)))
1181     return replaceInstUsesWith(I, V);
1182 
1183   if (Instruction *X = foldVectorBinop(I))
1184     return X;
1185 
1186   if (Instruction *R = commonShiftTransforms(I))
1187     return R;
1188 
1189   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1190   Type *Ty = I.getType();
1191   Value *X;
1192   const APInt *C;
1193   unsigned BitWidth = Ty->getScalarSizeInBits();
1194 
1195   // (iN (~X) u>> (N - 1)) --> zext (X > -1)
1196   if (match(Op0, m_OneUse(m_Not(m_Value(X)))) &&
1197       match(Op1, m_SpecificIntAllowUndef(BitWidth - 1)))
1198     return new ZExtInst(Builder.CreateIsNotNeg(X, "isnotneg"), Ty);
1199 
1200   if (match(Op1, m_APInt(C))) {
1201     unsigned ShAmtC = C->getZExtValue();
1202     auto *II = dyn_cast<IntrinsicInst>(Op0);
1203     if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmtC &&
1204         (II->getIntrinsicID() == Intrinsic::ctlz ||
1205          II->getIntrinsicID() == Intrinsic::cttz ||
1206          II->getIntrinsicID() == Intrinsic::ctpop)) {
1207       // ctlz.i32(x)>>5  --> zext(x == 0)
1208       // cttz.i32(x)>>5  --> zext(x == 0)
1209       // ctpop.i32(x)>>5 --> zext(x == -1)
1210       bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
1211       Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
1212       Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS);
1213       return new ZExtInst(Cmp, Ty);
1214     }
1215 
1216     Value *X;
1217     const APInt *C1;
1218     if (match(Op0, m_Shl(m_Value(X), m_APInt(C1))) && C1->ult(BitWidth)) {
1219       if (C1->ult(ShAmtC)) {
1220         unsigned ShlAmtC = C1->getZExtValue();
1221         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShlAmtC);
1222         if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1223           // (X <<nuw C1) >>u C --> X >>u (C - C1)
1224           auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
1225           NewLShr->setIsExact(I.isExact());
1226           return NewLShr;
1227         }
1228         if (Op0->hasOneUse()) {
1229           // (X << C1) >>u C  --> (X >>u (C - C1)) & (-1 >> C)
1230           Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact());
1231           APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
1232           return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
1233         }
1234       } else if (C1->ugt(ShAmtC)) {
1235         unsigned ShlAmtC = C1->getZExtValue();
1236         Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmtC - ShAmtC);
1237         if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1238           // (X <<nuw C1) >>u C --> X <<nuw (C1 - C)
1239           auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
1240           NewShl->setHasNoUnsignedWrap(true);
1241           return NewShl;
1242         }
1243         if (Op0->hasOneUse()) {
1244           // (X << C1) >>u C  --> X << (C1 - C) & (-1 >> C)
1245           Value *NewShl = Builder.CreateShl(X, ShiftDiff);
1246           APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
1247           return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
1248         }
1249       } else {
1250         assert(*C1 == ShAmtC);
1251         // (X << C) >>u C --> X & (-1 >>u C)
1252         APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
1253         return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
1254       }
1255     }
1256 
1257     // ((X << C) + Y) >>u C --> (X + (Y >>u C)) & (-1 >>u C)
1258     // TODO: Consolidate with the more general transform that starts from shl
1259     //       (the shifts are in the opposite order).
1260     Value *Y;
1261     if (match(Op0,
1262               m_OneUse(m_c_Add(m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))),
1263                                m_Value(Y))))) {
1264       Value *NewLshr = Builder.CreateLShr(Y, Op1);
1265       Value *NewAdd = Builder.CreateAdd(NewLshr, X);
1266       unsigned Op1Val = C->getLimitedValue(BitWidth);
1267       APInt Bits = APInt::getLowBitsSet(BitWidth, BitWidth - Op1Val);
1268       Constant *Mask = ConstantInt::get(Ty, Bits);
1269       return BinaryOperator::CreateAnd(NewAdd, Mask);
1270     }
1271 
1272     if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) &&
1273         (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
1274       assert(ShAmtC < X->getType()->getScalarSizeInBits() &&
1275              "Big shift not simplified to zero?");
1276       // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
1277       Value *NewLShr = Builder.CreateLShr(X, ShAmtC);
1278       return new ZExtInst(NewLShr, Ty);
1279     }
1280 
1281     if (match(Op0, m_SExt(m_Value(X)))) {
1282       unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
1283       // lshr (sext i1 X to iN), C --> select (X, -1 >> C, 0)
1284       if (SrcTyBitWidth == 1) {
1285         auto *NewC = ConstantInt::get(
1286             Ty, APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
1287         return SelectInst::Create(X, NewC, ConstantInt::getNullValue(Ty));
1288       }
1289 
1290       if ((!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType())) &&
1291           Op0->hasOneUse()) {
1292         // Are we moving the sign bit to the low bit and widening with high
1293         // zeros? lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
1294         if (ShAmtC == BitWidth - 1) {
1295           Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1);
1296           return new ZExtInst(NewLShr, Ty);
1297         }
1298 
1299         // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
1300         if (ShAmtC == BitWidth - SrcTyBitWidth) {
1301           // The new shift amount can't be more than the narrow source type.
1302           unsigned NewShAmt = std::min(ShAmtC, SrcTyBitWidth - 1);
1303           Value *AShr = Builder.CreateAShr(X, NewShAmt);
1304           return new ZExtInst(AShr, Ty);
1305         }
1306       }
1307     }
1308 
1309     if (ShAmtC == BitWidth - 1) {
1310       // lshr i32 or(X,-X), 31 --> zext (X != 0)
1311       if (match(Op0, m_OneUse(m_c_Or(m_Neg(m_Value(X)), m_Deferred(X)))))
1312         return new ZExtInst(Builder.CreateIsNotNull(X), Ty);
1313 
1314       // lshr i32 (X -nsw Y), 31 --> zext (X < Y)
1315       if (match(Op0, m_OneUse(m_NSWSub(m_Value(X), m_Value(Y)))))
1316         return new ZExtInst(Builder.CreateICmpSLT(X, Y), Ty);
1317 
1318       // Check if a number is negative and odd:
1319       // lshr i32 (srem X, 2), 31 --> and (X >> 31), X
1320       if (match(Op0, m_OneUse(m_SRem(m_Value(X), m_SpecificInt(2))))) {
1321         Value *Signbit = Builder.CreateLShr(X, ShAmtC);
1322         return BinaryOperator::CreateAnd(Signbit, X);
1323       }
1324     }
1325 
1326     // (X >>u C1) >>u C --> X >>u (C1 + C)
1327     if (match(Op0, m_LShr(m_Value(X), m_APInt(C1)))) {
1328       // Oversized shifts are simplified to zero in InstSimplify.
1329       unsigned AmtSum = ShAmtC + C1->getZExtValue();
1330       if (AmtSum < BitWidth)
1331         return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
1332     }
1333 
1334     Instruction *TruncSrc;
1335     if (match(Op0, m_OneUse(m_Trunc(m_Instruction(TruncSrc)))) &&
1336         match(TruncSrc, m_LShr(m_Value(X), m_APInt(C1)))) {
1337       unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1338       unsigned AmtSum = ShAmtC + C1->getZExtValue();
1339 
1340       // If the combined shift fits in the source width:
1341       // (trunc (X >>u C1)) >>u C --> and (trunc (X >>u (C1 + C)), MaskC
1342       //
1343       // If the first shift covers the number of bits truncated, then the
1344       // mask instruction is eliminated (and so the use check is relaxed).
1345       if (AmtSum < SrcWidth &&
1346           (TruncSrc->hasOneUse() || C1->uge(SrcWidth - BitWidth))) {
1347         Value *SumShift = Builder.CreateLShr(X, AmtSum, "sum.shift");
1348         Value *Trunc = Builder.CreateTrunc(SumShift, Ty, I.getName());
1349 
1350         // If the first shift does not cover the number of bits truncated, then
1351         // we require a mask to get rid of high bits in the result.
1352         APInt MaskC = APInt::getAllOnes(BitWidth).lshr(ShAmtC);
1353         return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Ty, MaskC));
1354       }
1355     }
1356 
1357     const APInt *MulC;
1358     if (match(Op0, m_NUWMul(m_Value(X), m_APInt(MulC)))) {
1359       // Look for a "splat" mul pattern - it replicates bits across each half of
1360       // a value, so a right shift is just a mask of the low bits:
1361       // lshr i[2N] (mul nuw X, (2^N)+1), N --> and iN X, (2^N)-1
1362       // TODO: Generalize to allow more than just half-width shifts?
1363       if (BitWidth > 2 && ShAmtC * 2 == BitWidth && (*MulC - 1).isPowerOf2() &&
1364           MulC->logBase2() == ShAmtC)
1365         return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, *MulC - 2));
1366 
1367       // The one-use check is not strictly necessary, but codegen may not be
1368       // able to invert the transform and perf may suffer with an extra mul
1369       // instruction.
1370       if (Op0->hasOneUse()) {
1371         APInt NewMulC = MulC->lshr(ShAmtC);
1372         // if c is divisible by (1 << ShAmtC):
1373         // lshr (mul nuw x, MulC), ShAmtC -> mul nuw x, (MulC >> ShAmtC)
1374         if (MulC->eq(NewMulC.shl(ShAmtC))) {
1375           auto *NewMul =
1376               BinaryOperator::CreateNUWMul(X, ConstantInt::get(Ty, NewMulC));
1377           BinaryOperator *OrigMul = cast<BinaryOperator>(Op0);
1378           NewMul->setHasNoSignedWrap(OrigMul->hasNoSignedWrap());
1379           return NewMul;
1380         }
1381       }
1382     }
1383 
1384     // Try to narrow bswap.
1385     // In the case where the shift amount equals the bitwidth difference, the
1386     // shift is eliminated.
1387     if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::bswap>(
1388                        m_OneUse(m_ZExt(m_Value(X))))))) {
1389       unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1390       unsigned WidthDiff = BitWidth - SrcWidth;
1391       if (SrcWidth % 16 == 0) {
1392         Value *NarrowSwap = Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X);
1393         if (ShAmtC >= WidthDiff) {
1394           // (bswap (zext X)) >> C --> zext (bswap X >> C')
1395           Value *NewShift = Builder.CreateLShr(NarrowSwap, ShAmtC - WidthDiff);
1396           return new ZExtInst(NewShift, Ty);
1397         } else {
1398           // (bswap (zext X)) >> C --> (zext (bswap X)) << C'
1399           Value *NewZExt = Builder.CreateZExt(NarrowSwap, Ty);
1400           Constant *ShiftDiff = ConstantInt::get(Ty, WidthDiff - ShAmtC);
1401           return BinaryOperator::CreateShl(NewZExt, ShiftDiff);
1402         }
1403       }
1404     }
1405 
1406     // Reduce add-carry of bools to logic:
1407     // ((zext BoolX) + (zext BoolY)) >> 1 --> zext (BoolX && BoolY)
1408     Value *BoolX, *BoolY;
1409     if (ShAmtC == 1 && match(Op0, m_Add(m_Value(X), m_Value(Y))) &&
1410         match(X, m_ZExt(m_Value(BoolX))) && match(Y, m_ZExt(m_Value(BoolY))) &&
1411         BoolX->getType()->isIntOrIntVectorTy(1) &&
1412         BoolY->getType()->isIntOrIntVectorTy(1) &&
1413         (X->hasOneUse() || Y->hasOneUse() || Op0->hasOneUse())) {
1414       Value *And = Builder.CreateAnd(BoolX, BoolY);
1415       return new ZExtInst(And, Ty);
1416     }
1417 
1418     // If the shifted-out value is known-zero, then this is an exact shift.
1419     if (!I.isExact() &&
1420         MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmtC), 0, &I)) {
1421       I.setIsExact();
1422       return &I;
1423     }
1424   }
1425 
1426   // Transform  (x << y) >> y  to  x & (-1 >> y)
1427   if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
1428     Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
1429     Value *Mask = Builder.CreateLShr(AllOnes, Op1);
1430     return BinaryOperator::CreateAnd(Mask, X);
1431   }
1432 
1433   if (Instruction *Overflow = foldLShrOverflowBit(I))
1434     return Overflow;
1435 
1436   return nullptr;
1437 }
1438 
1439 Instruction *
1440 InstCombinerImpl::foldVariableSignZeroExtensionOfVariableHighBitExtract(
1441     BinaryOperator &OldAShr) {
1442   assert(OldAShr.getOpcode() == Instruction::AShr &&
1443          "Must be called with arithmetic right-shift instruction only.");
1444 
1445   // Check that constant C is a splat of the element-wise bitwidth of V.
1446   auto BitWidthSplat = [](Constant *C, Value *V) {
1447     return match(
1448         C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1449                               APInt(C->getType()->getScalarSizeInBits(),
1450                                     V->getType()->getScalarSizeInBits())));
1451   };
1452 
1453   // It should look like variable-length sign-extension on the outside:
1454   //   (Val << (bitwidth(Val)-Nbits)) a>> (bitwidth(Val)-Nbits)
1455   Value *NBits;
1456   Instruction *MaybeTrunc;
1457   Constant *C1, *C2;
1458   if (!match(&OldAShr,
1459              m_AShr(m_Shl(m_Instruction(MaybeTrunc),
1460                           m_ZExtOrSelf(m_Sub(m_Constant(C1),
1461                                              m_ZExtOrSelf(m_Value(NBits))))),
1462                     m_ZExtOrSelf(m_Sub(m_Constant(C2),
1463                                        m_ZExtOrSelf(m_Deferred(NBits)))))) ||
1464       !BitWidthSplat(C1, &OldAShr) || !BitWidthSplat(C2, &OldAShr))
1465     return nullptr;
1466 
1467   // There may or may not be a truncation after outer two shifts.
1468   Instruction *HighBitExtract;
1469   match(MaybeTrunc, m_TruncOrSelf(m_Instruction(HighBitExtract)));
1470   bool HadTrunc = MaybeTrunc != HighBitExtract;
1471 
1472   // And finally, the innermost part of the pattern must be a right-shift.
1473   Value *X, *NumLowBitsToSkip;
1474   if (!match(HighBitExtract, m_Shr(m_Value(X), m_Value(NumLowBitsToSkip))))
1475     return nullptr;
1476 
1477   // Said right-shift must extract high NBits bits - C0 must be it's bitwidth.
1478   Constant *C0;
1479   if (!match(NumLowBitsToSkip,
1480              m_ZExtOrSelf(
1481                  m_Sub(m_Constant(C0), m_ZExtOrSelf(m_Specific(NBits))))) ||
1482       !BitWidthSplat(C0, HighBitExtract))
1483     return nullptr;
1484 
1485   // Since the NBits is identical for all shifts, if the outermost and
1486   // innermost shifts are identical, then outermost shifts are redundant.
1487   // If we had truncation, do keep it though.
1488   if (HighBitExtract->getOpcode() == OldAShr.getOpcode())
1489     return replaceInstUsesWith(OldAShr, MaybeTrunc);
1490 
1491   // Else, if there was a truncation, then we need to ensure that one
1492   // instruction will go away.
1493   if (HadTrunc && !match(&OldAShr, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1494     return nullptr;
1495 
1496   // Finally, bypass two innermost shifts, and perform the outermost shift on
1497   // the operands of the innermost shift.
1498   Instruction *NewAShr =
1499       BinaryOperator::Create(OldAShr.getOpcode(), X, NumLowBitsToSkip);
1500   NewAShr->copyIRFlags(HighBitExtract); // We can preserve 'exact'-ness.
1501   if (!HadTrunc)
1502     return NewAShr;
1503 
1504   Builder.Insert(NewAShr);
1505   return TruncInst::CreateTruncOrBitCast(NewAShr, OldAShr.getType());
1506 }
1507 
1508 Instruction *InstCombinerImpl::visitAShr(BinaryOperator &I) {
1509   if (Value *V = simplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1510                                   SQ.getWithInstruction(&I)))
1511     return replaceInstUsesWith(I, V);
1512 
1513   if (Instruction *X = foldVectorBinop(I))
1514     return X;
1515 
1516   if (Instruction *R = commonShiftTransforms(I))
1517     return R;
1518 
1519   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1520   Type *Ty = I.getType();
1521   unsigned BitWidth = Ty->getScalarSizeInBits();
1522   const APInt *ShAmtAPInt;
1523   if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) {
1524     unsigned ShAmt = ShAmtAPInt->getZExtValue();
1525 
1526     // If the shift amount equals the difference in width of the destination
1527     // and source scalar types:
1528     // ashr (shl (zext X), C), C --> sext X
1529     Value *X;
1530     if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
1531         ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
1532       return new SExtInst(X, Ty);
1533 
1534     // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
1535     // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
1536     const APInt *ShOp1;
1537     if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) &&
1538         ShOp1->ult(BitWidth)) {
1539       unsigned ShlAmt = ShOp1->getZExtValue();
1540       if (ShlAmt < ShAmt) {
1541         // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
1542         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1543         auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff);
1544         NewAShr->setIsExact(I.isExact());
1545         return NewAShr;
1546       }
1547       if (ShlAmt > ShAmt) {
1548         // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
1549         Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1550         auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff);
1551         NewShl->setHasNoSignedWrap(true);
1552         return NewShl;
1553       }
1554     }
1555 
1556     if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) &&
1557         ShOp1->ult(BitWidth)) {
1558       unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1559       // Oversized arithmetic shifts replicate the sign bit.
1560       AmtSum = std::min(AmtSum, BitWidth - 1);
1561       // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
1562       return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
1563     }
1564 
1565     if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) &&
1566         (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) {
1567       // ashr (sext X), C --> sext (ashr X, C')
1568       Type *SrcTy = X->getType();
1569       ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1);
1570       Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt));
1571       return new SExtInst(NewSh, Ty);
1572     }
1573 
1574     if (ShAmt == BitWidth - 1) {
1575       // ashr i32 or(X,-X), 31 --> sext (X != 0)
1576       if (match(Op0, m_OneUse(m_c_Or(m_Neg(m_Value(X)), m_Deferred(X)))))
1577         return new SExtInst(Builder.CreateIsNotNull(X), Ty);
1578 
1579       // ashr i32 (X -nsw Y), 31 --> sext (X < Y)
1580       Value *Y;
1581       if (match(Op0, m_OneUse(m_NSWSub(m_Value(X), m_Value(Y)))))
1582         return new SExtInst(Builder.CreateICmpSLT(X, Y), Ty);
1583     }
1584 
1585     // If the shifted-out value is known-zero, then this is an exact shift.
1586     if (!I.isExact() &&
1587         MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
1588       I.setIsExact();
1589       return &I;
1590     }
1591   }
1592 
1593   // Prefer `-(x & 1)` over `(x << (bitwidth(x)-1)) a>> (bitwidth(x)-1)`
1594   // as the pattern to splat the lowest bit.
1595   // FIXME: iff X is already masked, we don't need the one-use check.
1596   Value *X;
1597   if (match(Op1, m_SpecificIntAllowUndef(BitWidth - 1)) &&
1598       match(Op0, m_OneUse(m_Shl(m_Value(X),
1599                                 m_SpecificIntAllowUndef(BitWidth - 1))))) {
1600     Constant *Mask = ConstantInt::get(Ty, 1);
1601     // Retain the knowledge about the ignored lanes.
1602     Mask = Constant::mergeUndefsWith(
1603         Constant::mergeUndefsWith(Mask, cast<Constant>(Op1)),
1604         cast<Constant>(cast<Instruction>(Op0)->getOperand(1)));
1605     X = Builder.CreateAnd(X, Mask);
1606     return BinaryOperator::CreateNeg(X);
1607   }
1608 
1609   if (Instruction *R = foldVariableSignZeroExtensionOfVariableHighBitExtract(I))
1610     return R;
1611 
1612   // See if we can turn a signed shr into an unsigned shr.
1613   if (MaskedValueIsZero(Op0, APInt::getSignMask(BitWidth), 0, &I)) {
1614     Instruction *Lshr = BinaryOperator::CreateLShr(Op0, Op1);
1615     Lshr->setIsExact(I.isExact());
1616     return Lshr;
1617   }
1618 
1619   // ashr (xor %x, -1), %y  -->  xor (ashr %x, %y), -1
1620   if (match(Op0, m_OneUse(m_Not(m_Value(X))))) {
1621     // Note that we must drop 'exact'-ness of the shift!
1622     // Note that we can't keep undef's in -1 vector constant!
1623     auto *NewAShr = Builder.CreateAShr(X, Op1, Op0->getName() + ".not");
1624     return BinaryOperator::CreateNot(NewAShr);
1625   }
1626 
1627   return nullptr;
1628 }
1629