xref: /openbsd-src/gnu/llvm/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===- InstCombineShifts.cpp ----------------------------------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements the visitShl, visitLShr, and visitAShr functions.
1009467b48Spatrick //
1109467b48Spatrick //===----------------------------------------------------------------------===//
1209467b48Spatrick 
1309467b48Spatrick #include "InstCombineInternal.h"
1409467b48Spatrick #include "llvm/Analysis/InstructionSimplify.h"
1509467b48Spatrick #include "llvm/IR/IntrinsicInst.h"
1609467b48Spatrick #include "llvm/IR/PatternMatch.h"
1773471bf0Spatrick #include "llvm/Transforms/InstCombine/InstCombiner.h"
1809467b48Spatrick using namespace llvm;
1909467b48Spatrick using namespace PatternMatch;
2009467b48Spatrick 
2109467b48Spatrick #define DEBUG_TYPE "instcombine"
2209467b48Spatrick 
canTryToConstantAddTwoShiftAmounts(Value * Sh0,Value * ShAmt0,Value * Sh1,Value * ShAmt1)2373471bf0Spatrick bool canTryToConstantAddTwoShiftAmounts(Value *Sh0, Value *ShAmt0, Value *Sh1,
2473471bf0Spatrick                                         Value *ShAmt1) {
2573471bf0Spatrick   // We have two shift amounts from two different shifts. The types of those
2673471bf0Spatrick   // shift amounts may not match. If that's the case let's bailout now..
2773471bf0Spatrick   if (ShAmt0->getType() != ShAmt1->getType())
2873471bf0Spatrick     return false;
2973471bf0Spatrick 
3073471bf0Spatrick   // As input, we have the following pattern:
3173471bf0Spatrick   //   Sh0 (Sh1 X, Q), K
3273471bf0Spatrick   // We want to rewrite that as:
3373471bf0Spatrick   //   Sh x, (Q+K)  iff (Q+K) u< bitwidth(x)
3473471bf0Spatrick   // While we know that originally (Q+K) would not overflow
3573471bf0Spatrick   // (because  2 * (N-1) u<= iN -1), we have looked past extensions of
3673471bf0Spatrick   // shift amounts. so it may now overflow in smaller bitwidth.
3773471bf0Spatrick   // To ensure that does not happen, we need to ensure that the total maximal
3873471bf0Spatrick   // shift amount is still representable in that smaller bit width.
3973471bf0Spatrick   unsigned MaximalPossibleTotalShiftAmount =
4073471bf0Spatrick       (Sh0->getType()->getScalarSizeInBits() - 1) +
4173471bf0Spatrick       (Sh1->getType()->getScalarSizeInBits() - 1);
4273471bf0Spatrick   APInt MaximalRepresentableShiftAmount =
43*d415bd75Srobert       APInt::getAllOnes(ShAmt0->getType()->getScalarSizeInBits());
4473471bf0Spatrick   return MaximalRepresentableShiftAmount.uge(MaximalPossibleTotalShiftAmount);
4573471bf0Spatrick }
4673471bf0Spatrick 
4709467b48Spatrick // Given pattern:
4809467b48Spatrick //   (x shiftopcode Q) shiftopcode K
4909467b48Spatrick // we should rewrite it as
5009467b48Spatrick //   x shiftopcode (Q+K)  iff (Q+K) u< bitwidth(x) and
5109467b48Spatrick //
5209467b48Spatrick // This is valid for any shift, but they must be identical, and we must be
5309467b48Spatrick // careful in case we have (zext(Q)+zext(K)) and look past extensions,
5409467b48Spatrick // (Q+K) must not overflow or else (Q+K) u< bitwidth(x) is bogus.
5509467b48Spatrick //
5609467b48Spatrick // AnalyzeForSignBitExtraction indicates that we will only analyze whether this
5709467b48Spatrick // pattern has any 2 right-shifts that sum to 1 less than original bit width.
reassociateShiftAmtsOfTwoSameDirectionShifts(BinaryOperator * Sh0,const SimplifyQuery & SQ,bool AnalyzeForSignBitExtraction)5873471bf0Spatrick Value *InstCombinerImpl::reassociateShiftAmtsOfTwoSameDirectionShifts(
5909467b48Spatrick     BinaryOperator *Sh0, const SimplifyQuery &SQ,
6009467b48Spatrick     bool AnalyzeForSignBitExtraction) {
6109467b48Spatrick   // Look for a shift of some instruction, ignore zext of shift amount if any.
6209467b48Spatrick   Instruction *Sh0Op0;
6309467b48Spatrick   Value *ShAmt0;
6409467b48Spatrick   if (!match(Sh0,
6509467b48Spatrick              m_Shift(m_Instruction(Sh0Op0), m_ZExtOrSelf(m_Value(ShAmt0)))))
6609467b48Spatrick     return nullptr;
6709467b48Spatrick 
6809467b48Spatrick   // If there is a truncation between the two shifts, we must make note of it
6909467b48Spatrick   // and look through it. The truncation imposes additional constraints on the
7009467b48Spatrick   // transform.
7109467b48Spatrick   Instruction *Sh1;
7209467b48Spatrick   Value *Trunc = nullptr;
7309467b48Spatrick   match(Sh0Op0,
7409467b48Spatrick         m_CombineOr(m_CombineAnd(m_Trunc(m_Instruction(Sh1)), m_Value(Trunc)),
7509467b48Spatrick                     m_Instruction(Sh1)));
7609467b48Spatrick 
7709467b48Spatrick   // Inner shift: (x shiftopcode ShAmt1)
7809467b48Spatrick   // Like with other shift, ignore zext of shift amount if any.
7909467b48Spatrick   Value *X, *ShAmt1;
8009467b48Spatrick   if (!match(Sh1, m_Shift(m_Value(X), m_ZExtOrSelf(m_Value(ShAmt1)))))
8109467b48Spatrick     return nullptr;
8209467b48Spatrick 
8373471bf0Spatrick   // Verify that it would be safe to try to add those two shift amounts.
8473471bf0Spatrick   if (!canTryToConstantAddTwoShiftAmounts(Sh0, ShAmt0, Sh1, ShAmt1))
8509467b48Spatrick     return nullptr;
8609467b48Spatrick 
8709467b48Spatrick   // We are only looking for signbit extraction if we have two right shifts.
8809467b48Spatrick   bool HadTwoRightShifts = match(Sh0, m_Shr(m_Value(), m_Value())) &&
8909467b48Spatrick                            match(Sh1, m_Shr(m_Value(), m_Value()));
9009467b48Spatrick   // ... and if it's not two right-shifts, we know the answer already.
9109467b48Spatrick   if (AnalyzeForSignBitExtraction && !HadTwoRightShifts)
9209467b48Spatrick     return nullptr;
9309467b48Spatrick 
9409467b48Spatrick   // The shift opcodes must be identical, unless we are just checking whether
9509467b48Spatrick   // this pattern can be interpreted as a sign-bit-extraction.
9609467b48Spatrick   Instruction::BinaryOps ShiftOpcode = Sh0->getOpcode();
9709467b48Spatrick   bool IdenticalShOpcodes = Sh0->getOpcode() == Sh1->getOpcode();
9809467b48Spatrick   if (!IdenticalShOpcodes && !AnalyzeForSignBitExtraction)
9909467b48Spatrick     return nullptr;
10009467b48Spatrick 
10109467b48Spatrick   // If we saw truncation, we'll need to produce extra instruction,
10209467b48Spatrick   // and for that one of the operands of the shift must be one-use,
10309467b48Spatrick   // unless of course we don't actually plan to produce any instructions here.
10409467b48Spatrick   if (Trunc && !AnalyzeForSignBitExtraction &&
10509467b48Spatrick       !match(Sh0, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
10609467b48Spatrick     return nullptr;
10709467b48Spatrick 
10809467b48Spatrick   // Can we fold (ShAmt0+ShAmt1) ?
10909467b48Spatrick   auto *NewShAmt = dyn_cast_or_null<Constant>(
110*d415bd75Srobert       simplifyAddInst(ShAmt0, ShAmt1, /*isNSW=*/false, /*isNUW=*/false,
11109467b48Spatrick                       SQ.getWithInstruction(Sh0)));
11209467b48Spatrick   if (!NewShAmt)
11309467b48Spatrick     return nullptr; // Did not simplify.
11409467b48Spatrick   unsigned NewShAmtBitWidth = NewShAmt->getType()->getScalarSizeInBits();
11509467b48Spatrick   unsigned XBitWidth = X->getType()->getScalarSizeInBits();
11609467b48Spatrick   // Is the new shift amount smaller than the bit width of inner/new shift?
11709467b48Spatrick   if (!match(NewShAmt, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,
11809467b48Spatrick                                           APInt(NewShAmtBitWidth, XBitWidth))))
11909467b48Spatrick     return nullptr; // FIXME: could perform constant-folding.
12009467b48Spatrick 
12109467b48Spatrick   // If there was a truncation, and we have a right-shift, we can only fold if
12209467b48Spatrick   // we are left with the original sign bit. Likewise, if we were just checking
12309467b48Spatrick   // that this is a sighbit extraction, this is the place to check it.
12409467b48Spatrick   // FIXME: zero shift amount is also legal here, but we can't *easily* check
12509467b48Spatrick   // more than one predicate so it's not really worth it.
12609467b48Spatrick   if (HadTwoRightShifts && (Trunc || AnalyzeForSignBitExtraction)) {
12709467b48Spatrick     // If it's not a sign bit extraction, then we're done.
12809467b48Spatrick     if (!match(NewShAmt,
12909467b48Spatrick                m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
13009467b48Spatrick                                   APInt(NewShAmtBitWidth, XBitWidth - 1))))
13109467b48Spatrick       return nullptr;
13209467b48Spatrick     // If it is, and that was the question, return the base value.
13309467b48Spatrick     if (AnalyzeForSignBitExtraction)
13409467b48Spatrick       return X;
13509467b48Spatrick   }
13609467b48Spatrick 
13709467b48Spatrick   assert(IdenticalShOpcodes && "Should not get here with different shifts.");
13809467b48Spatrick 
13909467b48Spatrick   // All good, we can do this fold.
14009467b48Spatrick   NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, X->getType());
14109467b48Spatrick 
14209467b48Spatrick   BinaryOperator *NewShift = BinaryOperator::Create(ShiftOpcode, X, NewShAmt);
14309467b48Spatrick 
14409467b48Spatrick   // The flags can only be propagated if there wasn't a trunc.
14509467b48Spatrick   if (!Trunc) {
14609467b48Spatrick     // If the pattern did not involve trunc, and both of the original shifts
14709467b48Spatrick     // had the same flag set, preserve the flag.
14809467b48Spatrick     if (ShiftOpcode == Instruction::BinaryOps::Shl) {
14909467b48Spatrick       NewShift->setHasNoUnsignedWrap(Sh0->hasNoUnsignedWrap() &&
15009467b48Spatrick                                      Sh1->hasNoUnsignedWrap());
15109467b48Spatrick       NewShift->setHasNoSignedWrap(Sh0->hasNoSignedWrap() &&
15209467b48Spatrick                                    Sh1->hasNoSignedWrap());
15309467b48Spatrick     } else {
15409467b48Spatrick       NewShift->setIsExact(Sh0->isExact() && Sh1->isExact());
15509467b48Spatrick     }
15609467b48Spatrick   }
15709467b48Spatrick 
15809467b48Spatrick   Instruction *Ret = NewShift;
15909467b48Spatrick   if (Trunc) {
16009467b48Spatrick     Builder.Insert(NewShift);
16109467b48Spatrick     Ret = CastInst::Create(Instruction::Trunc, NewShift, Sh0->getType());
16209467b48Spatrick   }
16309467b48Spatrick 
16409467b48Spatrick   return Ret;
16509467b48Spatrick }
16609467b48Spatrick 
16709467b48Spatrick // If we have some pattern that leaves only some low bits set, and then performs
16809467b48Spatrick // left-shift of those bits, if none of the bits that are left after the final
16909467b48Spatrick // shift are modified by the mask, we can omit the mask.
17009467b48Spatrick //
17109467b48Spatrick // There are many variants to this pattern:
17209467b48Spatrick //   a)  (x & ((1 << MaskShAmt) - 1)) << ShiftShAmt
17309467b48Spatrick //   b)  (x & (~(-1 << MaskShAmt))) << ShiftShAmt
174*d415bd75Srobert //   c)  (x & (-1 l>> MaskShAmt)) << ShiftShAmt
175*d415bd75Srobert //   d)  (x & ((-1 << MaskShAmt) l>> MaskShAmt)) << ShiftShAmt
17609467b48Spatrick //   e)  ((x << MaskShAmt) l>> MaskShAmt) << ShiftShAmt
17709467b48Spatrick //   f)  ((x << MaskShAmt) a>> MaskShAmt) << ShiftShAmt
17809467b48Spatrick // All these patterns can be simplified to just:
17909467b48Spatrick //   x << ShiftShAmt
18009467b48Spatrick // iff:
18109467b48Spatrick //   a,b)     (MaskShAmt+ShiftShAmt) u>= bitwidth(x)
18209467b48Spatrick //   c,d,e,f) (ShiftShAmt-MaskShAmt) s>= 0 (i.e. ShiftShAmt u>= MaskShAmt)
18309467b48Spatrick static Instruction *
dropRedundantMaskingOfLeftShiftInput(BinaryOperator * OuterShift,const SimplifyQuery & Q,InstCombiner::BuilderTy & Builder)18409467b48Spatrick dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift,
18509467b48Spatrick                                      const SimplifyQuery &Q,
18609467b48Spatrick                                      InstCombiner::BuilderTy &Builder) {
18709467b48Spatrick   assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&
18809467b48Spatrick          "The input must be 'shl'!");
18909467b48Spatrick 
19009467b48Spatrick   Value *Masked, *ShiftShAmt;
19109467b48Spatrick   match(OuterShift,
19209467b48Spatrick         m_Shift(m_Value(Masked), m_ZExtOrSelf(m_Value(ShiftShAmt))));
19309467b48Spatrick 
19409467b48Spatrick   // *If* there is a truncation between an outer shift and a possibly-mask,
19509467b48Spatrick   // then said truncation *must* be one-use, else we can't perform the fold.
19609467b48Spatrick   Value *Trunc;
19709467b48Spatrick   if (match(Masked, m_CombineAnd(m_Trunc(m_Value(Masked)), m_Value(Trunc))) &&
19809467b48Spatrick       !Trunc->hasOneUse())
19909467b48Spatrick     return nullptr;
20009467b48Spatrick 
20109467b48Spatrick   Type *NarrowestTy = OuterShift->getType();
20209467b48Spatrick   Type *WidestTy = Masked->getType();
20309467b48Spatrick   bool HadTrunc = WidestTy != NarrowestTy;
20409467b48Spatrick 
20509467b48Spatrick   // The mask must be computed in a type twice as wide to ensure
20609467b48Spatrick   // that no bits are lost if the sum-of-shifts is wider than the base type.
20709467b48Spatrick   Type *ExtendedTy = WidestTy->getExtendedType();
20809467b48Spatrick 
20909467b48Spatrick   Value *MaskShAmt;
21009467b48Spatrick 
21109467b48Spatrick   // ((1 << MaskShAmt) - 1)
21209467b48Spatrick   auto MaskA = m_Add(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes());
21309467b48Spatrick   // (~(-1 << maskNbits))
21409467b48Spatrick   auto MaskB = m_Xor(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_AllOnes());
215*d415bd75Srobert   // (-1 l>> MaskShAmt)
216*d415bd75Srobert   auto MaskC = m_LShr(m_AllOnes(), m_Value(MaskShAmt));
217*d415bd75Srobert   // ((-1 << MaskShAmt) l>> MaskShAmt)
21809467b48Spatrick   auto MaskD =
219*d415bd75Srobert       m_LShr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt));
22009467b48Spatrick 
22109467b48Spatrick   Value *X;
22209467b48Spatrick   Constant *NewMask;
22309467b48Spatrick 
22409467b48Spatrick   if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) {
22509467b48Spatrick     // Peek through an optional zext of the shift amount.
22609467b48Spatrick     match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
22709467b48Spatrick 
22873471bf0Spatrick     // Verify that it would be safe to try to add those two shift amounts.
22973471bf0Spatrick     if (!canTryToConstantAddTwoShiftAmounts(OuterShift, ShiftShAmt, Masked,
23073471bf0Spatrick                                             MaskShAmt))
23109467b48Spatrick       return nullptr;
23209467b48Spatrick 
23309467b48Spatrick     // Can we simplify (MaskShAmt+ShiftShAmt) ?
234*d415bd75Srobert     auto *SumOfShAmts = dyn_cast_or_null<Constant>(simplifyAddInst(
23509467b48Spatrick         MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
23609467b48Spatrick     if (!SumOfShAmts)
23709467b48Spatrick       return nullptr; // Did not simplify.
23809467b48Spatrick     // In this pattern SumOfShAmts correlates with the number of low bits
23909467b48Spatrick     // that shall remain in the root value (OuterShift).
24009467b48Spatrick 
24109467b48Spatrick     // An extend of an undef value becomes zero because the high bits are never
242*d415bd75Srobert     // completely unknown. Replace the `undef` shift amounts with final
24309467b48Spatrick     // shift bitwidth to ensure that the value remains undef when creating the
24409467b48Spatrick     // subsequent shift op.
24509467b48Spatrick     SumOfShAmts = Constant::replaceUndefsWith(
24609467b48Spatrick         SumOfShAmts, ConstantInt::get(SumOfShAmts->getType()->getScalarType(),
24709467b48Spatrick                                       ExtendedTy->getScalarSizeInBits()));
24809467b48Spatrick     auto *ExtendedSumOfShAmts = ConstantExpr::getZExt(SumOfShAmts, ExtendedTy);
24909467b48Spatrick     // And compute the mask as usual: ~(-1 << (SumOfShAmts))
25009467b48Spatrick     auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
25109467b48Spatrick     auto *ExtendedInvertedMask =
25209467b48Spatrick         ConstantExpr::getShl(ExtendedAllOnes, ExtendedSumOfShAmts);
25309467b48Spatrick     NewMask = ConstantExpr::getNot(ExtendedInvertedMask);
25409467b48Spatrick   } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) ||
25509467b48Spatrick              match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)),
25609467b48Spatrick                                  m_Deferred(MaskShAmt)))) {
25709467b48Spatrick     // Peek through an optional zext of the shift amount.
25809467b48Spatrick     match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
25909467b48Spatrick 
26073471bf0Spatrick     // Verify that it would be safe to try to add those two shift amounts.
26173471bf0Spatrick     if (!canTryToConstantAddTwoShiftAmounts(OuterShift, ShiftShAmt, Masked,
26273471bf0Spatrick                                             MaskShAmt))
26309467b48Spatrick       return nullptr;
26409467b48Spatrick 
26509467b48Spatrick     // Can we simplify (ShiftShAmt-MaskShAmt) ?
266*d415bd75Srobert     auto *ShAmtsDiff = dyn_cast_or_null<Constant>(simplifySubInst(
26709467b48Spatrick         ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
26809467b48Spatrick     if (!ShAmtsDiff)
26909467b48Spatrick       return nullptr; // Did not simplify.
27009467b48Spatrick     // In this pattern ShAmtsDiff correlates with the number of high bits that
27109467b48Spatrick     // shall be unset in the root value (OuterShift).
27209467b48Spatrick 
27309467b48Spatrick     // An extend of an undef value becomes zero because the high bits are never
274*d415bd75Srobert     // completely unknown. Replace the `undef` shift amounts with negated
27509467b48Spatrick     // bitwidth of innermost shift to ensure that the value remains undef when
27609467b48Spatrick     // creating the subsequent shift op.
27709467b48Spatrick     unsigned WidestTyBitWidth = WidestTy->getScalarSizeInBits();
27809467b48Spatrick     ShAmtsDiff = Constant::replaceUndefsWith(
27909467b48Spatrick         ShAmtsDiff, ConstantInt::get(ShAmtsDiff->getType()->getScalarType(),
28009467b48Spatrick                                      -WidestTyBitWidth));
28109467b48Spatrick     auto *ExtendedNumHighBitsToClear = ConstantExpr::getZExt(
28209467b48Spatrick         ConstantExpr::getSub(ConstantInt::get(ShAmtsDiff->getType(),
28309467b48Spatrick                                               WidestTyBitWidth,
28409467b48Spatrick                                               /*isSigned=*/false),
28509467b48Spatrick                              ShAmtsDiff),
28609467b48Spatrick         ExtendedTy);
28709467b48Spatrick     // And compute the mask as usual: (-1 l>> (NumHighBitsToClear))
28809467b48Spatrick     auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
28909467b48Spatrick     NewMask =
29009467b48Spatrick         ConstantExpr::getLShr(ExtendedAllOnes, ExtendedNumHighBitsToClear);
29109467b48Spatrick   } else
29209467b48Spatrick     return nullptr; // Don't know anything about this pattern.
29309467b48Spatrick 
29409467b48Spatrick   NewMask = ConstantExpr::getTrunc(NewMask, NarrowestTy);
29509467b48Spatrick 
29609467b48Spatrick   // Does this mask has any unset bits? If not then we can just not apply it.
29709467b48Spatrick   bool NeedMask = !match(NewMask, m_AllOnes());
29809467b48Spatrick 
29909467b48Spatrick   // If we need to apply a mask, there are several more restrictions we have.
30009467b48Spatrick   if (NeedMask) {
30109467b48Spatrick     // The old masking instruction must go away.
30209467b48Spatrick     if (!Masked->hasOneUse())
30309467b48Spatrick       return nullptr;
30409467b48Spatrick     // The original "masking" instruction must not have been`ashr`.
30509467b48Spatrick     if (match(Masked, m_AShr(m_Value(), m_Value())))
30609467b48Spatrick       return nullptr;
30709467b48Spatrick   }
30809467b48Spatrick 
30909467b48Spatrick   // If we need to apply truncation, let's do it first, since we can.
31009467b48Spatrick   // We have already ensured that the old truncation will go away.
31109467b48Spatrick   if (HadTrunc)
31209467b48Spatrick     X = Builder.CreateTrunc(X, NarrowestTy);
31309467b48Spatrick 
31409467b48Spatrick   // No 'NUW'/'NSW'! We no longer know that we won't shift-out non-0 bits.
31509467b48Spatrick   // We didn't change the Type of this outermost shift, so we can just do it.
31609467b48Spatrick   auto *NewShift = BinaryOperator::Create(OuterShift->getOpcode(), X,
31709467b48Spatrick                                           OuterShift->getOperand(1));
31809467b48Spatrick   if (!NeedMask)
31909467b48Spatrick     return NewShift;
32009467b48Spatrick 
32109467b48Spatrick   Builder.Insert(NewShift);
32209467b48Spatrick   return BinaryOperator::Create(Instruction::And, NewShift, NewMask);
32309467b48Spatrick }
32409467b48Spatrick 
32509467b48Spatrick /// If we have a shift-by-constant of a bitwise logic op that itself has a
32609467b48Spatrick /// shift-by-constant operand with identical opcode, we may be able to convert
32709467b48Spatrick /// that into 2 independent shifts followed by the logic op. This eliminates a
32809467b48Spatrick /// a use of an intermediate value (reduces dependency chain).
foldShiftOfShiftedLogic(BinaryOperator & I,InstCombiner::BuilderTy & Builder)32909467b48Spatrick static Instruction *foldShiftOfShiftedLogic(BinaryOperator &I,
33009467b48Spatrick                                             InstCombiner::BuilderTy &Builder) {
33109467b48Spatrick   assert(I.isShift() && "Expected a shift as input");
33209467b48Spatrick   auto *LogicInst = dyn_cast<BinaryOperator>(I.getOperand(0));
33309467b48Spatrick   if (!LogicInst || !LogicInst->isBitwiseLogicOp() || !LogicInst->hasOneUse())
33409467b48Spatrick     return nullptr;
33509467b48Spatrick 
33673471bf0Spatrick   Constant *C0, *C1;
33773471bf0Spatrick   if (!match(I.getOperand(1), m_Constant(C1)))
33809467b48Spatrick     return nullptr;
33909467b48Spatrick 
34009467b48Spatrick   Instruction::BinaryOps ShiftOpcode = I.getOpcode();
34109467b48Spatrick   Type *Ty = I.getType();
34209467b48Spatrick 
34309467b48Spatrick   // Find a matching one-use shift by constant. The fold is not valid if the sum
34409467b48Spatrick   // of the shift values equals or exceeds bitwidth.
34509467b48Spatrick   // TODO: Remove the one-use check if the other logic operand (Y) is constant.
34609467b48Spatrick   Value *X, *Y;
34709467b48Spatrick   auto matchFirstShift = [&](Value *V) {
34873471bf0Spatrick     APInt Threshold(Ty->getScalarSizeInBits(), Ty->getScalarSizeInBits());
349*d415bd75Srobert     return match(V,
350*d415bd75Srobert                  m_OneUse(m_BinOp(ShiftOpcode, m_Value(X), m_Constant(C0)))) &&
35173471bf0Spatrick            match(ConstantExpr::getAdd(C0, C1),
35273471bf0Spatrick                  m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold));
35309467b48Spatrick   };
35409467b48Spatrick 
35509467b48Spatrick   // Logic ops are commutative, so check each operand for a match.
35609467b48Spatrick   if (matchFirstShift(LogicInst->getOperand(0)))
35709467b48Spatrick     Y = LogicInst->getOperand(1);
35809467b48Spatrick   else if (matchFirstShift(LogicInst->getOperand(1)))
35909467b48Spatrick     Y = LogicInst->getOperand(0);
36009467b48Spatrick   else
36109467b48Spatrick     return nullptr;
36209467b48Spatrick 
36309467b48Spatrick   // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1)
36473471bf0Spatrick   Constant *ShiftSumC = ConstantExpr::getAdd(C0, C1);
36509467b48Spatrick   Value *NewShift1 = Builder.CreateBinOp(ShiftOpcode, X, ShiftSumC);
366*d415bd75Srobert   Value *NewShift2 = Builder.CreateBinOp(ShiftOpcode, Y, C1);
36709467b48Spatrick   return BinaryOperator::Create(LogicInst->getOpcode(), NewShift1, NewShift2);
36809467b48Spatrick }
36909467b48Spatrick 
commonShiftTransforms(BinaryOperator & I)37073471bf0Spatrick Instruction *InstCombinerImpl::commonShiftTransforms(BinaryOperator &I) {
371*d415bd75Srobert   if (Instruction *Phi = foldBinopWithPhiOperands(I))
372*d415bd75Srobert     return Phi;
373*d415bd75Srobert 
37409467b48Spatrick   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
37509467b48Spatrick   assert(Op0->getType() == Op1->getType());
376*d415bd75Srobert   Type *Ty = I.getType();
37709467b48Spatrick 
37809467b48Spatrick   // If the shift amount is a one-use `sext`, we can demote it to `zext`.
37909467b48Spatrick   Value *Y;
38009467b48Spatrick   if (match(Op1, m_OneUse(m_SExt(m_Value(Y))))) {
381*d415bd75Srobert     Value *NewExt = Builder.CreateZExt(Y, Ty, Op1->getName());
38209467b48Spatrick     return BinaryOperator::Create(I.getOpcode(), Op0, NewExt);
38309467b48Spatrick   }
38409467b48Spatrick 
38509467b48Spatrick   // See if we can fold away this shift.
38609467b48Spatrick   if (SimplifyDemandedInstructionBits(I))
38709467b48Spatrick     return &I;
38809467b48Spatrick 
38909467b48Spatrick   // Try to fold constant and into select arguments.
39009467b48Spatrick   if (isa<Constant>(Op0))
39109467b48Spatrick     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
39209467b48Spatrick       if (Instruction *R = FoldOpIntoSelect(I, SI))
39309467b48Spatrick         return R;
39409467b48Spatrick 
39509467b48Spatrick   if (Constant *CUI = dyn_cast<Constant>(Op1))
39609467b48Spatrick     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
39709467b48Spatrick       return Res;
39809467b48Spatrick 
39909467b48Spatrick   if (auto *NewShift = cast_or_null<Instruction>(
40009467b48Spatrick           reassociateShiftAmtsOfTwoSameDirectionShifts(&I, SQ)))
40109467b48Spatrick     return NewShift;
40209467b48Spatrick 
403*d415bd75Srobert   // Pre-shift a constant shifted by a variable amount with constant offset:
404*d415bd75Srobert   // C shift (A add nuw C1) --> (C shift C1) shift A
40509467b48Spatrick   Value *A;
406*d415bd75Srobert   Constant *C, *C1;
407*d415bd75Srobert   if (match(Op0, m_Constant(C)) &&
408*d415bd75Srobert       match(Op1, m_NUWAdd(m_Value(A), m_Constant(C1)))) {
409*d415bd75Srobert     Value *NewC = Builder.CreateBinOp(I.getOpcode(), C, C1);
410*d415bd75Srobert     return BinaryOperator::Create(I.getOpcode(), NewC, A);
411*d415bd75Srobert   }
412*d415bd75Srobert 
413*d415bd75Srobert   unsigned BitWidth = Ty->getScalarSizeInBits();
414*d415bd75Srobert 
415*d415bd75Srobert   const APInt *AC, *AddC;
416*d415bd75Srobert   // Try to pre-shift a constant shifted by a variable amount added with a
417*d415bd75Srobert   // negative number:
418*d415bd75Srobert   // C << (X - AddC) --> (C >> AddC) << X
419*d415bd75Srobert   // and
420*d415bd75Srobert   // C >> (X - AddC) --> (C << AddC) >> X
421*d415bd75Srobert   if (match(Op0, m_APInt(AC)) && match(Op1, m_Add(m_Value(A), m_APInt(AddC))) &&
422*d415bd75Srobert       AddC->isNegative() && (-*AddC).ult(BitWidth)) {
423*d415bd75Srobert     assert(!AC->isZero() && "Expected simplify of shifted zero");
424*d415bd75Srobert     unsigned PosOffset = (-*AddC).getZExtValue();
425*d415bd75Srobert 
426*d415bd75Srobert     auto isSuitableForPreShift = [PosOffset, &I, AC]() {
427*d415bd75Srobert       switch (I.getOpcode()) {
428*d415bd75Srobert       default:
429*d415bd75Srobert         return false;
430*d415bd75Srobert       case Instruction::Shl:
431*d415bd75Srobert         return (I.hasNoSignedWrap() || I.hasNoUnsignedWrap()) &&
432*d415bd75Srobert                AC->eq(AC->lshr(PosOffset).shl(PosOffset));
433*d415bd75Srobert       case Instruction::LShr:
434*d415bd75Srobert         return I.isExact() && AC->eq(AC->shl(PosOffset).lshr(PosOffset));
435*d415bd75Srobert       case Instruction::AShr:
436*d415bd75Srobert         return I.isExact() && AC->eq(AC->shl(PosOffset).ashr(PosOffset));
437*d415bd75Srobert       }
438*d415bd75Srobert     };
439*d415bd75Srobert     if (isSuitableForPreShift()) {
440*d415bd75Srobert       Constant *NewC = ConstantInt::get(Ty, I.getOpcode() == Instruction::Shl
441*d415bd75Srobert                                                 ? AC->lshr(PosOffset)
442*d415bd75Srobert                                                 : AC->shl(PosOffset));
443*d415bd75Srobert       BinaryOperator *NewShiftOp =
444*d415bd75Srobert           BinaryOperator::Create(I.getOpcode(), NewC, A);
445*d415bd75Srobert       if (I.getOpcode() == Instruction::Shl) {
446*d415bd75Srobert         NewShiftOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
447*d415bd75Srobert       } else {
448*d415bd75Srobert         NewShiftOp->setIsExact();
449*d415bd75Srobert       }
450*d415bd75Srobert       return NewShiftOp;
451*d415bd75Srobert     }
452*d415bd75Srobert   }
45309467b48Spatrick 
45473471bf0Spatrick   // X shift (A srem C) -> X shift (A and (C - 1)) iff C is a power of 2.
45509467b48Spatrick   // Because shifts by negative values (which could occur if A were negative)
45609467b48Spatrick   // are undefined.
45773471bf0Spatrick   if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Constant(C))) &&
45873471bf0Spatrick       match(C, m_Power2())) {
45909467b48Spatrick     // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
46009467b48Spatrick     // demand the sign bit (and many others) here??
461*d415bd75Srobert     Constant *Mask = ConstantExpr::getSub(C, ConstantInt::get(Ty, 1));
46273471bf0Spatrick     Value *Rem = Builder.CreateAnd(A, Mask, Op1->getName());
463097a140dSpatrick     return replaceOperand(I, 1, Rem);
46409467b48Spatrick   }
46509467b48Spatrick 
46609467b48Spatrick   if (Instruction *Logic = foldShiftOfShiftedLogic(I, Builder))
46709467b48Spatrick     return Logic;
46809467b48Spatrick 
46909467b48Spatrick   return nullptr;
47009467b48Spatrick }
47109467b48Spatrick 
47209467b48Spatrick /// Return true if we can simplify two logical (either left or right) shifts
47309467b48Spatrick /// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
canEvaluateShiftedShift(unsigned OuterShAmt,bool IsOuterShl,Instruction * InnerShift,InstCombinerImpl & IC,Instruction * CxtI)47409467b48Spatrick static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
47573471bf0Spatrick                                     Instruction *InnerShift,
47673471bf0Spatrick                                     InstCombinerImpl &IC, Instruction *CxtI) {
47709467b48Spatrick   assert(InnerShift->isLogicalShift() && "Unexpected instruction type");
47809467b48Spatrick 
47909467b48Spatrick   // We need constant scalar or constant splat shifts.
48009467b48Spatrick   const APInt *InnerShiftConst;
48109467b48Spatrick   if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst)))
48209467b48Spatrick     return false;
48309467b48Spatrick 
48409467b48Spatrick   // Two logical shifts in the same direction:
48509467b48Spatrick   // shl (shl X, C1), C2 -->  shl X, C1 + C2
48609467b48Spatrick   // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
48709467b48Spatrick   bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
48809467b48Spatrick   if (IsInnerShl == IsOuterShl)
48909467b48Spatrick     return true;
49009467b48Spatrick 
49109467b48Spatrick   // Equal shift amounts in opposite directions become bitwise 'and':
49209467b48Spatrick   // lshr (shl X, C), C --> and X, C'
49309467b48Spatrick   // shl (lshr X, C), C --> and X, C'
49409467b48Spatrick   if (*InnerShiftConst == OuterShAmt)
49509467b48Spatrick     return true;
49609467b48Spatrick 
49709467b48Spatrick   // If the 2nd shift is bigger than the 1st, we can fold:
49809467b48Spatrick   // lshr (shl X, C1), C2 -->  and (shl X, C1 - C2), C3
49909467b48Spatrick   // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
50009467b48Spatrick   // but it isn't profitable unless we know the and'd out bits are already zero.
50109467b48Spatrick   // Also, check that the inner shift is valid (less than the type width) or
50209467b48Spatrick   // we'll crash trying to produce the bit mask for the 'and'.
50309467b48Spatrick   unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
50409467b48Spatrick   if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) {
50509467b48Spatrick     unsigned InnerShAmt = InnerShiftConst->getZExtValue();
50609467b48Spatrick     unsigned MaskShift =
50709467b48Spatrick         IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
50809467b48Spatrick     APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift;
50909467b48Spatrick     if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI))
51009467b48Spatrick       return true;
51109467b48Spatrick   }
51209467b48Spatrick 
51309467b48Spatrick   return false;
51409467b48Spatrick }
51509467b48Spatrick 
51609467b48Spatrick /// See if we can compute the specified value, but shifted logically to the left
51709467b48Spatrick /// or right by some number of bits. This should return true if the expression
51809467b48Spatrick /// can be computed for the same cost as the current expression tree. This is
51909467b48Spatrick /// used to eliminate extraneous shifting from things like:
52009467b48Spatrick ///      %C = shl i128 %A, 64
52109467b48Spatrick ///      %D = shl i128 %B, 96
52209467b48Spatrick ///      %E = or i128 %C, %D
52309467b48Spatrick ///      %F = lshr i128 %E, 64
52409467b48Spatrick /// where the client will ask if E can be computed shifted right by 64-bits. If
52509467b48Spatrick /// this succeeds, getShiftedValue() will be called to produce the value.
canEvaluateShifted(Value * V,unsigned NumBits,bool IsLeftShift,InstCombinerImpl & IC,Instruction * CxtI)52609467b48Spatrick static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
52773471bf0Spatrick                                InstCombinerImpl &IC, Instruction *CxtI) {
52809467b48Spatrick   // We can always evaluate constants shifted.
52909467b48Spatrick   if (isa<Constant>(V))
53009467b48Spatrick     return true;
53109467b48Spatrick 
53209467b48Spatrick   Instruction *I = dyn_cast<Instruction>(V);
53309467b48Spatrick   if (!I) return false;
53409467b48Spatrick 
53509467b48Spatrick   // We can't mutate something that has multiple uses: doing so would
53609467b48Spatrick   // require duplicating the instruction in general, which isn't profitable.
53709467b48Spatrick   if (!I->hasOneUse()) return false;
53809467b48Spatrick 
53909467b48Spatrick   switch (I->getOpcode()) {
54009467b48Spatrick   default: return false;
54109467b48Spatrick   case Instruction::And:
54209467b48Spatrick   case Instruction::Or:
54309467b48Spatrick   case Instruction::Xor:
54409467b48Spatrick     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
54509467b48Spatrick     return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
54609467b48Spatrick            canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
54709467b48Spatrick 
54809467b48Spatrick   case Instruction::Shl:
54909467b48Spatrick   case Instruction::LShr:
55009467b48Spatrick     return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
55109467b48Spatrick 
55209467b48Spatrick   case Instruction::Select: {
55309467b48Spatrick     SelectInst *SI = cast<SelectInst>(I);
55409467b48Spatrick     Value *TrueVal = SI->getTrueValue();
55509467b48Spatrick     Value *FalseVal = SI->getFalseValue();
55609467b48Spatrick     return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
55709467b48Spatrick            canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
55809467b48Spatrick   }
55909467b48Spatrick   case Instruction::PHI: {
56009467b48Spatrick     // We can change a phi if we can change all operands.  Note that we never
56109467b48Spatrick     // get into trouble with cyclic PHIs here because we only consider
56209467b48Spatrick     // instructions with a single use.
56309467b48Spatrick     PHINode *PN = cast<PHINode>(I);
56409467b48Spatrick     for (Value *IncValue : PN->incoming_values())
56509467b48Spatrick       if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
56609467b48Spatrick         return false;
56709467b48Spatrick     return true;
56809467b48Spatrick   }
569*d415bd75Srobert   case Instruction::Mul: {
570*d415bd75Srobert     const APInt *MulConst;
571*d415bd75Srobert     // We can fold (shr (mul X, -(1 << C)), C) -> (and (neg X), C`)
572*d415bd75Srobert     return !IsLeftShift && match(I->getOperand(1), m_APInt(MulConst)) &&
573*d415bd75Srobert            MulConst->isNegatedPowerOf2() &&
574*d415bd75Srobert            MulConst->countTrailingZeros() == NumBits;
575*d415bd75Srobert   }
57609467b48Spatrick   }
57709467b48Spatrick }
57809467b48Spatrick 
57909467b48Spatrick /// Fold OuterShift (InnerShift X, C1), C2.
58009467b48Spatrick /// See canEvaluateShiftedShift() for the constraints on these instructions.
foldShiftedShift(BinaryOperator * InnerShift,unsigned OuterShAmt,bool IsOuterShl,InstCombiner::BuilderTy & Builder)58109467b48Spatrick static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
58209467b48Spatrick                                bool IsOuterShl,
58309467b48Spatrick                                InstCombiner::BuilderTy &Builder) {
58409467b48Spatrick   bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
58509467b48Spatrick   Type *ShType = InnerShift->getType();
58609467b48Spatrick   unsigned TypeWidth = ShType->getScalarSizeInBits();
58709467b48Spatrick 
58809467b48Spatrick   // We only accept shifts-by-a-constant in canEvaluateShifted().
58909467b48Spatrick   const APInt *C1;
59009467b48Spatrick   match(InnerShift->getOperand(1), m_APInt(C1));
59109467b48Spatrick   unsigned InnerShAmt = C1->getZExtValue();
59209467b48Spatrick 
59309467b48Spatrick   // Change the shift amount and clear the appropriate IR flags.
59409467b48Spatrick   auto NewInnerShift = [&](unsigned ShAmt) {
59509467b48Spatrick     InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
59609467b48Spatrick     if (IsInnerShl) {
59709467b48Spatrick       InnerShift->setHasNoUnsignedWrap(false);
59809467b48Spatrick       InnerShift->setHasNoSignedWrap(false);
59909467b48Spatrick     } else {
60009467b48Spatrick       InnerShift->setIsExact(false);
60109467b48Spatrick     }
60209467b48Spatrick     return InnerShift;
60309467b48Spatrick   };
60409467b48Spatrick 
60509467b48Spatrick   // Two logical shifts in the same direction:
60609467b48Spatrick   // shl (shl X, C1), C2 -->  shl X, C1 + C2
60709467b48Spatrick   // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
60809467b48Spatrick   if (IsInnerShl == IsOuterShl) {
60909467b48Spatrick     // If this is an oversized composite shift, then unsigned shifts get 0.
61009467b48Spatrick     if (InnerShAmt + OuterShAmt >= TypeWidth)
61109467b48Spatrick       return Constant::getNullValue(ShType);
61209467b48Spatrick 
61309467b48Spatrick     return NewInnerShift(InnerShAmt + OuterShAmt);
61409467b48Spatrick   }
61509467b48Spatrick 
61609467b48Spatrick   // Equal shift amounts in opposite directions become bitwise 'and':
61709467b48Spatrick   // lshr (shl X, C), C --> and X, C'
61809467b48Spatrick   // shl (lshr X, C), C --> and X, C'
61909467b48Spatrick   if (InnerShAmt == OuterShAmt) {
62009467b48Spatrick     APInt Mask = IsInnerShl
62109467b48Spatrick                      ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
62209467b48Spatrick                      : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
62309467b48Spatrick     Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
62409467b48Spatrick                                    ConstantInt::get(ShType, Mask));
62509467b48Spatrick     if (auto *AndI = dyn_cast<Instruction>(And)) {
62609467b48Spatrick       AndI->moveBefore(InnerShift);
62709467b48Spatrick       AndI->takeName(InnerShift);
62809467b48Spatrick     }
62909467b48Spatrick     return And;
63009467b48Spatrick   }
63109467b48Spatrick 
63209467b48Spatrick   assert(InnerShAmt > OuterShAmt &&
63309467b48Spatrick          "Unexpected opposite direction logical shift pair");
63409467b48Spatrick 
63509467b48Spatrick   // In general, we would need an 'and' for this transform, but
63609467b48Spatrick   // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
63709467b48Spatrick   // lshr (shl X, C1), C2 -->  shl X, C1 - C2
63809467b48Spatrick   // shl (lshr X, C1), C2 --> lshr X, C1 - C2
63909467b48Spatrick   return NewInnerShift(InnerShAmt - OuterShAmt);
64009467b48Spatrick }
64109467b48Spatrick 
64209467b48Spatrick /// When canEvaluateShifted() returns true for an expression, this function
64309467b48Spatrick /// inserts the new computation that produces the shifted value.
getShiftedValue(Value * V,unsigned NumBits,bool isLeftShift,InstCombinerImpl & IC,const DataLayout & DL)64409467b48Spatrick static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
64573471bf0Spatrick                               InstCombinerImpl &IC, const DataLayout &DL) {
64609467b48Spatrick   // We can always evaluate constants shifted.
64709467b48Spatrick   if (Constant *C = dyn_cast<Constant>(V)) {
64809467b48Spatrick     if (isLeftShift)
649097a140dSpatrick       return IC.Builder.CreateShl(C, NumBits);
65009467b48Spatrick     else
651097a140dSpatrick       return IC.Builder.CreateLShr(C, NumBits);
65209467b48Spatrick   }
65309467b48Spatrick 
65409467b48Spatrick   Instruction *I = cast<Instruction>(V);
65573471bf0Spatrick   IC.addToWorklist(I);
65609467b48Spatrick 
65709467b48Spatrick   switch (I->getOpcode()) {
65809467b48Spatrick   default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
65909467b48Spatrick   case Instruction::And:
66009467b48Spatrick   case Instruction::Or:
66109467b48Spatrick   case Instruction::Xor:
66209467b48Spatrick     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
66309467b48Spatrick     I->setOperand(
66409467b48Spatrick         0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
66509467b48Spatrick     I->setOperand(
66609467b48Spatrick         1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
66709467b48Spatrick     return I;
66809467b48Spatrick 
66909467b48Spatrick   case Instruction::Shl:
67009467b48Spatrick   case Instruction::LShr:
67109467b48Spatrick     return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
67209467b48Spatrick                             IC.Builder);
67309467b48Spatrick 
67409467b48Spatrick   case Instruction::Select:
67509467b48Spatrick     I->setOperand(
67609467b48Spatrick         1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
67709467b48Spatrick     I->setOperand(
67809467b48Spatrick         2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
67909467b48Spatrick     return I;
68009467b48Spatrick   case Instruction::PHI: {
68109467b48Spatrick     // We can change a phi if we can change all operands.  Note that we never
68209467b48Spatrick     // get into trouble with cyclic PHIs here because we only consider
68309467b48Spatrick     // instructions with a single use.
68409467b48Spatrick     PHINode *PN = cast<PHINode>(I);
68509467b48Spatrick     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
68609467b48Spatrick       PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits,
68709467b48Spatrick                                               isLeftShift, IC, DL));
68809467b48Spatrick     return PN;
68909467b48Spatrick   }
690*d415bd75Srobert   case Instruction::Mul: {
691*d415bd75Srobert     assert(!isLeftShift && "Unexpected shift direction!");
692*d415bd75Srobert     auto *Neg = BinaryOperator::CreateNeg(I->getOperand(0));
693*d415bd75Srobert     IC.InsertNewInstWith(Neg, *I);
694*d415bd75Srobert     unsigned TypeWidth = I->getType()->getScalarSizeInBits();
695*d415bd75Srobert     APInt Mask = APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits);
696*d415bd75Srobert     auto *And = BinaryOperator::CreateAnd(Neg,
697*d415bd75Srobert                                           ConstantInt::get(I->getType(), Mask));
698*d415bd75Srobert     And->takeName(I);
699*d415bd75Srobert     return IC.InsertNewInstWith(And, *I);
700*d415bd75Srobert   }
70109467b48Spatrick   }
70209467b48Spatrick }
70309467b48Spatrick 
70409467b48Spatrick // If this is a bitwise operator or add with a constant RHS we might be able
70509467b48Spatrick // to pull it through a shift.
canShiftBinOpWithConstantRHS(BinaryOperator & Shift,BinaryOperator * BO)70609467b48Spatrick static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift,
70709467b48Spatrick                                          BinaryOperator *BO) {
70809467b48Spatrick   switch (BO->getOpcode()) {
70909467b48Spatrick   default:
71009467b48Spatrick     return false; // Do not perform transform!
71109467b48Spatrick   case Instruction::Add:
71209467b48Spatrick     return Shift.getOpcode() == Instruction::Shl;
71309467b48Spatrick   case Instruction::Or:
71409467b48Spatrick   case Instruction::And:
71509467b48Spatrick     return true;
71673471bf0Spatrick   case Instruction::Xor:
71773471bf0Spatrick     // Do not change a 'not' of logical shift because that would create a normal
71873471bf0Spatrick     // 'xor'. The 'not' is likely better for analysis, SCEV, and codegen.
71973471bf0Spatrick     return !(Shift.isLogicalShift() && match(BO, m_Not(m_Value())));
72009467b48Spatrick   }
72109467b48Spatrick }
72209467b48Spatrick 
FoldShiftByConstant(Value * Op0,Constant * C1,BinaryOperator & I)723*d415bd75Srobert Instruction *InstCombinerImpl::FoldShiftByConstant(Value *Op0, Constant *C1,
72409467b48Spatrick                                                    BinaryOperator &I) {
725*d415bd75Srobert   // (C2 << X) << C1 --> (C2 << C1) << X
726*d415bd75Srobert   // (C2 >> X) >> C1 --> (C2 >> C1) >> X
727*d415bd75Srobert   Constant *C2;
728*d415bd75Srobert   Value *X;
729*d415bd75Srobert   if (match(Op0, m_BinOp(I.getOpcode(), m_Constant(C2), m_Value(X))))
730*d415bd75Srobert     return BinaryOperator::Create(
731*d415bd75Srobert         I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), C2, C1), X);
732*d415bd75Srobert 
733*d415bd75Srobert   bool IsLeftShift = I.getOpcode() == Instruction::Shl;
734*d415bd75Srobert   Type *Ty = I.getType();
735*d415bd75Srobert   unsigned TypeBits = Ty->getScalarSizeInBits();
736*d415bd75Srobert 
737*d415bd75Srobert   // (X / +DivC) >> (Width - 1) --> ext (X <= -DivC)
738*d415bd75Srobert   // (X / -DivC) >> (Width - 1) --> ext (X >= +DivC)
739*d415bd75Srobert   const APInt *DivC;
740*d415bd75Srobert   if (!IsLeftShift && match(C1, m_SpecificIntAllowUndef(TypeBits - 1)) &&
741*d415bd75Srobert       match(Op0, m_SDiv(m_Value(X), m_APInt(DivC))) && !DivC->isZero() &&
742*d415bd75Srobert       !DivC->isMinSignedValue()) {
743*d415bd75Srobert     Constant *NegDivC = ConstantInt::get(Ty, -(*DivC));
744*d415bd75Srobert     ICmpInst::Predicate Pred =
745*d415bd75Srobert         DivC->isNegative() ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SLE;
746*d415bd75Srobert     Value *Cmp = Builder.CreateICmp(Pred, X, NegDivC);
747*d415bd75Srobert     auto ExtOpcode = (I.getOpcode() == Instruction::AShr) ? Instruction::SExt
748*d415bd75Srobert                                                           : Instruction::ZExt;
749*d415bd75Srobert     return CastInst::Create(ExtOpcode, Cmp, Ty);
750*d415bd75Srobert   }
75109467b48Spatrick 
75209467b48Spatrick   const APInt *Op1C;
753*d415bd75Srobert   if (!match(C1, m_APInt(Op1C)))
75409467b48Spatrick     return nullptr;
75509467b48Spatrick 
756*d415bd75Srobert   assert(!Op1C->uge(TypeBits) &&
757*d415bd75Srobert          "Shift over the type width should have been removed already");
758*d415bd75Srobert 
75909467b48Spatrick   // See if we can propagate this shift into the input, this covers the trivial
76009467b48Spatrick   // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
76109467b48Spatrick   if (I.getOpcode() != Instruction::AShr &&
762*d415bd75Srobert       canEvaluateShifted(Op0, Op1C->getZExtValue(), IsLeftShift, *this, &I)) {
76309467b48Spatrick     LLVM_DEBUG(
76409467b48Spatrick         dbgs() << "ICE: GetShiftedValue propagating shift through expression"
76509467b48Spatrick                   " to eliminate shift:\n  IN: "
76609467b48Spatrick                << *Op0 << "\n  SH: " << I << "\n");
76709467b48Spatrick 
76809467b48Spatrick     return replaceInstUsesWith(
769*d415bd75Srobert         I, getShiftedValue(Op0, Op1C->getZExtValue(), IsLeftShift, *this, DL));
77009467b48Spatrick   }
77109467b48Spatrick 
77209467b48Spatrick   if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
77309467b48Spatrick     return FoldedShift;
77409467b48Spatrick 
775*d415bd75Srobert   if (!Op0->hasOneUse())
776*d415bd75Srobert     return nullptr;
77773471bf0Spatrick 
778*d415bd75Srobert   if (auto *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
77909467b48Spatrick     // If the operand is a bitwise operator with a constant RHS, and the
78009467b48Spatrick     // shift is the only use, we can pull it out of the shift.
78109467b48Spatrick     const APInt *Op0C;
78209467b48Spatrick     if (match(Op0BO->getOperand(1), m_APInt(Op0C))) {
78309467b48Spatrick       if (canShiftBinOpWithConstantRHS(I, Op0BO)) {
784*d415bd75Srobert         Value *NewRHS =
785*d415bd75Srobert             Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(1), C1);
78609467b48Spatrick 
78709467b48Spatrick         Value *NewShift =
788*d415bd75Srobert             Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), C1);
78909467b48Spatrick         NewShift->takeName(Op0BO);
79009467b48Spatrick 
791*d415bd75Srobert         return BinaryOperator::Create(Op0BO->getOpcode(), NewShift, NewRHS);
79209467b48Spatrick       }
79309467b48Spatrick     }
79409467b48Spatrick   }
79509467b48Spatrick 
79609467b48Spatrick   // If we have a select that conditionally executes some binary operator,
79709467b48Spatrick   // see if we can pull it the select and operator through the shift.
79809467b48Spatrick   //
79909467b48Spatrick   // For example, turning:
80009467b48Spatrick   //   shl (select C, (add X, C1), X), C2
80109467b48Spatrick   // Into:
80209467b48Spatrick   //   Y = shl X, C2
80309467b48Spatrick   //   select C, (add Y, C1 << C2), Y
80409467b48Spatrick   Value *Cond;
80509467b48Spatrick   BinaryOperator *TBO;
80609467b48Spatrick   Value *FalseVal;
80709467b48Spatrick   if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)),
80809467b48Spatrick                           m_Value(FalseVal)))) {
80909467b48Spatrick     const APInt *C;
81009467b48Spatrick     if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal &&
81109467b48Spatrick         match(TBO->getOperand(1), m_APInt(C)) &&
81209467b48Spatrick         canShiftBinOpWithConstantRHS(I, TBO)) {
813*d415bd75Srobert       Value *NewRHS =
814*d415bd75Srobert           Builder.CreateBinOp(I.getOpcode(), TBO->getOperand(1), C1);
81509467b48Spatrick 
816*d415bd75Srobert       Value *NewShift = Builder.CreateBinOp(I.getOpcode(), FalseVal, C1);
817*d415bd75Srobert       Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift, NewRHS);
81809467b48Spatrick       return SelectInst::Create(Cond, NewOp, NewShift);
81909467b48Spatrick     }
82009467b48Spatrick   }
82109467b48Spatrick 
82209467b48Spatrick   BinaryOperator *FBO;
82309467b48Spatrick   Value *TrueVal;
82409467b48Spatrick   if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal),
82509467b48Spatrick                           m_OneUse(m_BinOp(FBO))))) {
82609467b48Spatrick     const APInt *C;
82709467b48Spatrick     if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal &&
82809467b48Spatrick         match(FBO->getOperand(1), m_APInt(C)) &&
82909467b48Spatrick         canShiftBinOpWithConstantRHS(I, FBO)) {
830*d415bd75Srobert       Value *NewRHS =
831*d415bd75Srobert           Builder.CreateBinOp(I.getOpcode(), FBO->getOperand(1), C1);
83209467b48Spatrick 
833*d415bd75Srobert       Value *NewShift = Builder.CreateBinOp(I.getOpcode(), TrueVal, C1);
834*d415bd75Srobert       Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift, NewRHS);
83509467b48Spatrick       return SelectInst::Create(Cond, NewShift, NewOp);
83609467b48Spatrick     }
83709467b48Spatrick   }
83809467b48Spatrick 
83909467b48Spatrick   return nullptr;
84009467b48Spatrick }
84109467b48Spatrick 
842*d415bd75Srobert // Tries to perform
843*d415bd75Srobert //    (lshr (add (zext X), (zext Y)), K)
844*d415bd75Srobert //      -> (icmp ult (add X, Y), X)
845*d415bd75Srobert //    where
846*d415bd75Srobert //      - The add's operands are zexts from a K-bits integer to a bigger type.
847*d415bd75Srobert //      - The add is only used by the shr, or by iK (or narrower) truncates.
848*d415bd75Srobert //      - The lshr type has more than 2 bits (other types are boolean math).
849*d415bd75Srobert //      - K > 1
850*d415bd75Srobert //    note that
851*d415bd75Srobert //      - The resulting add cannot have nuw/nsw, else on overflow we get a
852*d415bd75Srobert //        poison value and the transform isn't legal anymore.
foldLShrOverflowBit(BinaryOperator & I)853*d415bd75Srobert Instruction *InstCombinerImpl::foldLShrOverflowBit(BinaryOperator &I) {
854*d415bd75Srobert   assert(I.getOpcode() == Instruction::LShr);
855*d415bd75Srobert 
856*d415bd75Srobert   Value *Add = I.getOperand(0);
857*d415bd75Srobert   Value *ShiftAmt = I.getOperand(1);
858*d415bd75Srobert   Type *Ty = I.getType();
859*d415bd75Srobert 
860*d415bd75Srobert   if (Ty->getScalarSizeInBits() < 3)
861*d415bd75Srobert     return nullptr;
862*d415bd75Srobert 
863*d415bd75Srobert   const APInt *ShAmtAPInt = nullptr;
864*d415bd75Srobert   Value *X = nullptr, *Y = nullptr;
865*d415bd75Srobert   if (!match(ShiftAmt, m_APInt(ShAmtAPInt)) ||
866*d415bd75Srobert       !match(Add,
867*d415bd75Srobert              m_Add(m_OneUse(m_ZExt(m_Value(X))), m_OneUse(m_ZExt(m_Value(Y))))))
868*d415bd75Srobert     return nullptr;
869*d415bd75Srobert 
870*d415bd75Srobert   const unsigned ShAmt = ShAmtAPInt->getZExtValue();
871*d415bd75Srobert   if (ShAmt == 1)
872*d415bd75Srobert     return nullptr;
873*d415bd75Srobert 
874*d415bd75Srobert   // X/Y are zexts from `ShAmt`-sized ints.
875*d415bd75Srobert   if (X->getType()->getScalarSizeInBits() != ShAmt ||
876*d415bd75Srobert       Y->getType()->getScalarSizeInBits() != ShAmt)
877*d415bd75Srobert     return nullptr;
878*d415bd75Srobert 
879*d415bd75Srobert   // Make sure that `Add` is only used by `I` and `ShAmt`-truncates.
880*d415bd75Srobert   if (!Add->hasOneUse()) {
881*d415bd75Srobert     for (User *U : Add->users()) {
882*d415bd75Srobert       if (U == &I)
883*d415bd75Srobert         continue;
884*d415bd75Srobert 
885*d415bd75Srobert       TruncInst *Trunc = dyn_cast<TruncInst>(U);
886*d415bd75Srobert       if (!Trunc || Trunc->getType()->getScalarSizeInBits() > ShAmt)
887*d415bd75Srobert         return nullptr;
888*d415bd75Srobert     }
889*d415bd75Srobert   }
890*d415bd75Srobert 
891*d415bd75Srobert   // Insert at Add so that the newly created `NarrowAdd` will dominate it's
892*d415bd75Srobert   // users (i.e. `Add`'s users).
893*d415bd75Srobert   Instruction *AddInst = cast<Instruction>(Add);
894*d415bd75Srobert   Builder.SetInsertPoint(AddInst);
895*d415bd75Srobert 
896*d415bd75Srobert   Value *NarrowAdd = Builder.CreateAdd(X, Y, "add.narrowed");
897*d415bd75Srobert   Value *Overflow =
898*d415bd75Srobert       Builder.CreateICmpULT(NarrowAdd, X, "add.narrowed.overflow");
899*d415bd75Srobert 
900*d415bd75Srobert   // Replace the uses of the original add with a zext of the
901*d415bd75Srobert   // NarrowAdd's result. Note that all users at this stage are known to
902*d415bd75Srobert   // be ShAmt-sized truncs, or the lshr itself.
903*d415bd75Srobert   if (!Add->hasOneUse())
904*d415bd75Srobert     replaceInstUsesWith(*AddInst, Builder.CreateZExt(NarrowAdd, Ty));
905*d415bd75Srobert 
906*d415bd75Srobert   // Replace the LShr with a zext of the overflow check.
907*d415bd75Srobert   return new ZExtInst(Overflow, Ty);
908*d415bd75Srobert }
909*d415bd75Srobert 
visitShl(BinaryOperator & I)91073471bf0Spatrick Instruction *InstCombinerImpl::visitShl(BinaryOperator &I) {
91109467b48Spatrick   const SimplifyQuery Q = SQ.getWithInstruction(&I);
91209467b48Spatrick 
913*d415bd75Srobert   if (Value *V = simplifyShlInst(I.getOperand(0), I.getOperand(1),
91409467b48Spatrick                                  I.hasNoSignedWrap(), I.hasNoUnsignedWrap(), Q))
91509467b48Spatrick     return replaceInstUsesWith(I, V);
91609467b48Spatrick 
91709467b48Spatrick   if (Instruction *X = foldVectorBinop(I))
91809467b48Spatrick     return X;
91909467b48Spatrick 
92009467b48Spatrick   if (Instruction *V = commonShiftTransforms(I))
92109467b48Spatrick     return V;
92209467b48Spatrick 
92309467b48Spatrick   if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(&I, Q, Builder))
92409467b48Spatrick     return V;
92509467b48Spatrick 
92609467b48Spatrick   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
92709467b48Spatrick   Type *Ty = I.getType();
92809467b48Spatrick   unsigned BitWidth = Ty->getScalarSizeInBits();
92909467b48Spatrick 
930*d415bd75Srobert   const APInt *C;
931*d415bd75Srobert   if (match(Op1, m_APInt(C))) {
932*d415bd75Srobert     unsigned ShAmtC = C->getZExtValue();
93309467b48Spatrick 
934*d415bd75Srobert     // shl (zext X), C --> zext (shl X, C)
93509467b48Spatrick     // This is only valid if X would have zeros shifted out.
93609467b48Spatrick     Value *X;
93709467b48Spatrick     if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
93809467b48Spatrick       unsigned SrcWidth = X->getType()->getScalarSizeInBits();
939*d415bd75Srobert       if (ShAmtC < SrcWidth &&
940*d415bd75Srobert           MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmtC), 0, &I))
941*d415bd75Srobert         return new ZExtInst(Builder.CreateShl(X, ShAmtC), Ty);
94209467b48Spatrick     }
94309467b48Spatrick 
94409467b48Spatrick     // (X >> C) << C --> X & (-1 << C)
94509467b48Spatrick     if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) {
946*d415bd75Srobert       APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmtC));
94709467b48Spatrick       return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
94809467b48Spatrick     }
94909467b48Spatrick 
950*d415bd75Srobert     const APInt *C1;
951*d415bd75Srobert     if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(C1)))) &&
952*d415bd75Srobert         C1->ult(BitWidth)) {
953*d415bd75Srobert       unsigned ShrAmt = C1->getZExtValue();
954*d415bd75Srobert       if (ShrAmt < ShAmtC) {
955*d415bd75Srobert         // If C1 < C: (X >>?,exact C1) << C --> X << (C - C1)
956*d415bd75Srobert         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShrAmt);
95709467b48Spatrick         auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
95809467b48Spatrick         NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
95909467b48Spatrick         NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
96009467b48Spatrick         return NewShl;
96109467b48Spatrick       }
962*d415bd75Srobert       if (ShrAmt > ShAmtC) {
963*d415bd75Srobert         // If C1 > C: (X >>?exact C1) << C --> X >>?exact (C1 - C)
964*d415bd75Srobert         Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmtC);
96509467b48Spatrick         auto *NewShr = BinaryOperator::Create(
96609467b48Spatrick             cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff);
96709467b48Spatrick         NewShr->setIsExact(true);
96809467b48Spatrick         return NewShr;
96909467b48Spatrick       }
97009467b48Spatrick     }
97109467b48Spatrick 
972*d415bd75Srobert     if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_APInt(C1)))) &&
973*d415bd75Srobert         C1->ult(BitWidth)) {
974*d415bd75Srobert       unsigned ShrAmt = C1->getZExtValue();
975*d415bd75Srobert       if (ShrAmt < ShAmtC) {
976*d415bd75Srobert         // If C1 < C: (X >>? C1) << C --> (X << (C - C1)) & (-1 << C)
977*d415bd75Srobert         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShrAmt);
97873471bf0Spatrick         auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
97973471bf0Spatrick         NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
98073471bf0Spatrick         NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
98173471bf0Spatrick         Builder.Insert(NewShl);
982*d415bd75Srobert         APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmtC));
98373471bf0Spatrick         return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
98473471bf0Spatrick       }
985*d415bd75Srobert       if (ShrAmt > ShAmtC) {
986*d415bd75Srobert         // If C1 > C: (X >>? C1) << C --> (X >>? (C1 - C)) & (-1 << C)
987*d415bd75Srobert         Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmtC);
98873471bf0Spatrick         auto *OldShr = cast<BinaryOperator>(Op0);
98973471bf0Spatrick         auto *NewShr =
99073471bf0Spatrick             BinaryOperator::Create(OldShr->getOpcode(), X, ShiftDiff);
99173471bf0Spatrick         NewShr->setIsExact(OldShr->isExact());
99273471bf0Spatrick         Builder.Insert(NewShr);
993*d415bd75Srobert         APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmtC));
99473471bf0Spatrick         return BinaryOperator::CreateAnd(NewShr, ConstantInt::get(Ty, Mask));
99573471bf0Spatrick       }
99673471bf0Spatrick     }
99773471bf0Spatrick 
998*d415bd75Srobert     // Similar to above, but look through an intermediate trunc instruction.
999*d415bd75Srobert     BinaryOperator *Shr;
1000*d415bd75Srobert     if (match(Op0, m_OneUse(m_Trunc(m_OneUse(m_BinOp(Shr))))) &&
1001*d415bd75Srobert         match(Shr, m_Shr(m_Value(X), m_APInt(C1)))) {
1002*d415bd75Srobert       // The larger shift direction survives through the transform.
1003*d415bd75Srobert       unsigned ShrAmtC = C1->getZExtValue();
1004*d415bd75Srobert       unsigned ShDiff = ShrAmtC > ShAmtC ? ShrAmtC - ShAmtC : ShAmtC - ShrAmtC;
1005*d415bd75Srobert       Constant *ShiftDiffC = ConstantInt::get(X->getType(), ShDiff);
1006*d415bd75Srobert       auto ShiftOpc = ShrAmtC > ShAmtC ? Shr->getOpcode() : Instruction::Shl;
1007*d415bd75Srobert 
1008*d415bd75Srobert       // If C1 > C:
1009*d415bd75Srobert       // (trunc (X >> C1)) << C --> (trunc (X >> (C1 - C))) && (-1 << C)
1010*d415bd75Srobert       // If C > C1:
1011*d415bd75Srobert       // (trunc (X >> C1)) << C --> (trunc (X << (C - C1))) && (-1 << C)
1012*d415bd75Srobert       Value *NewShift = Builder.CreateBinOp(ShiftOpc, X, ShiftDiffC, "sh.diff");
1013*d415bd75Srobert       Value *Trunc = Builder.CreateTrunc(NewShift, Ty, "tr.sh.diff");
1014*d415bd75Srobert       APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmtC));
1015*d415bd75Srobert       return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Ty, Mask));
1016*d415bd75Srobert     }
1017*d415bd75Srobert 
1018*d415bd75Srobert     if (match(Op0, m_Shl(m_Value(X), m_APInt(C1))) && C1->ult(BitWidth)) {
1019*d415bd75Srobert       unsigned AmtSum = ShAmtC + C1->getZExtValue();
102009467b48Spatrick       // Oversized shifts are simplified to zero in InstSimplify.
102109467b48Spatrick       if (AmtSum < BitWidth)
102209467b48Spatrick         // (X << C1) << C2 --> X << (C1 + C2)
102309467b48Spatrick         return BinaryOperator::CreateShl(X, ConstantInt::get(Ty, AmtSum));
102409467b48Spatrick     }
102509467b48Spatrick 
1026*d415bd75Srobert     // If we have an opposite shift by the same amount, we may be able to
1027*d415bd75Srobert     // reorder binops and shifts to eliminate math/logic.
1028*d415bd75Srobert     auto isSuitableBinOpcode = [](Instruction::BinaryOps BinOpcode) {
1029*d415bd75Srobert       switch (BinOpcode) {
1030*d415bd75Srobert       default:
1031*d415bd75Srobert         return false;
1032*d415bd75Srobert       case Instruction::Add:
1033*d415bd75Srobert       case Instruction::And:
1034*d415bd75Srobert       case Instruction::Or:
1035*d415bd75Srobert       case Instruction::Xor:
1036*d415bd75Srobert       case Instruction::Sub:
1037*d415bd75Srobert         // NOTE: Sub is not commutable and the tranforms below may not be valid
1038*d415bd75Srobert         //       when the shift-right is operand 1 (RHS) of the sub.
1039*d415bd75Srobert         return true;
1040*d415bd75Srobert       }
1041*d415bd75Srobert     };
1042*d415bd75Srobert     BinaryOperator *Op0BO;
1043*d415bd75Srobert     if (match(Op0, m_OneUse(m_BinOp(Op0BO))) &&
1044*d415bd75Srobert         isSuitableBinOpcode(Op0BO->getOpcode())) {
1045*d415bd75Srobert       // Commute so shift-right is on LHS of the binop.
1046*d415bd75Srobert       // (Y bop (X >> C)) << C         ->  ((X >> C) bop Y) << C
1047*d415bd75Srobert       // (Y bop ((X >> C) & CC)) << C  ->  (((X >> C) & CC) bop Y) << C
1048*d415bd75Srobert       Value *Shr = Op0BO->getOperand(0);
1049*d415bd75Srobert       Value *Y = Op0BO->getOperand(1);
1050*d415bd75Srobert       Value *X;
1051*d415bd75Srobert       const APInt *CC;
1052*d415bd75Srobert       if (Op0BO->isCommutative() && Y->hasOneUse() &&
1053*d415bd75Srobert           (match(Y, m_Shr(m_Value(), m_Specific(Op1))) ||
1054*d415bd75Srobert            match(Y, m_And(m_OneUse(m_Shr(m_Value(), m_Specific(Op1))),
1055*d415bd75Srobert                           m_APInt(CC)))))
1056*d415bd75Srobert         std::swap(Shr, Y);
1057*d415bd75Srobert 
1058*d415bd75Srobert       // ((X >> C) bop Y) << C  ->  (X bop (Y << C)) & (~0 << C)
1059*d415bd75Srobert       if (match(Shr, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
1060*d415bd75Srobert         // Y << C
1061*d415bd75Srobert         Value *YS = Builder.CreateShl(Y, Op1, Op0BO->getName());
1062*d415bd75Srobert         // (X bop (Y << C))
1063*d415bd75Srobert         Value *B =
1064*d415bd75Srobert             Builder.CreateBinOp(Op0BO->getOpcode(), X, YS, Shr->getName());
1065*d415bd75Srobert         unsigned Op1Val = C->getLimitedValue(BitWidth);
1066*d415bd75Srobert         APInt Bits = APInt::getHighBitsSet(BitWidth, BitWidth - Op1Val);
1067*d415bd75Srobert         Constant *Mask = ConstantInt::get(Ty, Bits);
1068*d415bd75Srobert         return BinaryOperator::CreateAnd(B, Mask);
1069*d415bd75Srobert       }
1070*d415bd75Srobert 
1071*d415bd75Srobert       // (((X >> C) & CC) bop Y) << C  ->  (X & (CC << C)) bop (Y << C)
1072*d415bd75Srobert       if (match(Shr,
1073*d415bd75Srobert                 m_OneUse(m_And(m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))),
1074*d415bd75Srobert                                m_APInt(CC))))) {
1075*d415bd75Srobert         // Y << C
1076*d415bd75Srobert         Value *YS = Builder.CreateShl(Y, Op1, Op0BO->getName());
1077*d415bd75Srobert         // X & (CC << C)
1078*d415bd75Srobert         Value *M = Builder.CreateAnd(X, ConstantInt::get(Ty, CC->shl(*C)),
1079*d415bd75Srobert                                      X->getName() + ".mask");
1080*d415bd75Srobert         return BinaryOperator::Create(Op0BO->getOpcode(), M, YS);
1081*d415bd75Srobert       }
1082*d415bd75Srobert     }
1083*d415bd75Srobert 
1084*d415bd75Srobert     // (C1 - X) << C --> (C1 << C) - (X << C)
1085*d415bd75Srobert     if (match(Op0, m_OneUse(m_Sub(m_APInt(C1), m_Value(X))))) {
1086*d415bd75Srobert       Constant *NewLHS = ConstantInt::get(Ty, C1->shl(*C));
1087*d415bd75Srobert       Value *NewShift = Builder.CreateShl(X, Op1);
1088*d415bd75Srobert       return BinaryOperator::CreateSub(NewLHS, NewShift);
1089*d415bd75Srobert     }
1090*d415bd75Srobert 
109109467b48Spatrick     // If the shifted-out value is known-zero, then this is a NUW shift.
109209467b48Spatrick     if (!I.hasNoUnsignedWrap() &&
1093*d415bd75Srobert         MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, ShAmtC), 0,
1094*d415bd75Srobert                           &I)) {
109509467b48Spatrick       I.setHasNoUnsignedWrap();
109609467b48Spatrick       return &I;
109709467b48Spatrick     }
109809467b48Spatrick 
109909467b48Spatrick     // If the shifted-out value is all signbits, then this is a NSW shift.
1100*d415bd75Srobert     if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmtC) {
110109467b48Spatrick       I.setHasNoSignedWrap();
110209467b48Spatrick       return &I;
110309467b48Spatrick     }
110409467b48Spatrick   }
110509467b48Spatrick 
110609467b48Spatrick   // Transform  (x >> y) << y  to  x & (-1 << y)
110709467b48Spatrick   // Valid for any type of right-shift.
110809467b48Spatrick   Value *X;
110909467b48Spatrick   if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
111009467b48Spatrick     Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
111109467b48Spatrick     Value *Mask = Builder.CreateShl(AllOnes, Op1);
111209467b48Spatrick     return BinaryOperator::CreateAnd(Mask, X);
111309467b48Spatrick   }
111409467b48Spatrick 
111509467b48Spatrick   Constant *C1;
111609467b48Spatrick   if (match(Op1, m_Constant(C1))) {
111709467b48Spatrick     Constant *C2;
111809467b48Spatrick     Value *X;
111909467b48Spatrick     // (X * C2) << C1 --> X * (C2 << C1)
112009467b48Spatrick     if (match(Op0, m_Mul(m_Value(X), m_Constant(C2))))
112109467b48Spatrick       return BinaryOperator::CreateMul(X, ConstantExpr::getShl(C2, C1));
112209467b48Spatrick 
112309467b48Spatrick     // shl (zext i1 X), C1 --> select (X, 1 << C1, 0)
112409467b48Spatrick     if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
112509467b48Spatrick       auto *NewC = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C1);
112609467b48Spatrick       return SelectInst::Create(X, NewC, ConstantInt::getNullValue(Ty));
112709467b48Spatrick     }
112809467b48Spatrick   }
112909467b48Spatrick 
1130*d415bd75Srobert   if (match(Op0, m_One())) {
113109467b48Spatrick     // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
1132*d415bd75Srobert     if (match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X))))
113309467b48Spatrick       return BinaryOperator::CreateLShr(
113409467b48Spatrick           ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X);
113509467b48Spatrick 
1136*d415bd75Srobert     // The only way to shift out the 1 is with an over-shift, so that would
1137*d415bd75Srobert     // be poison with or without "nuw". Undef is excluded because (undef << X)
1138*d415bd75Srobert     // is not undef (it is zero).
1139*d415bd75Srobert     Constant *ConstantOne = cast<Constant>(Op0);
1140*d415bd75Srobert     if (!I.hasNoUnsignedWrap() && !ConstantOne->containsUndefElement()) {
1141*d415bd75Srobert       I.setHasNoUnsignedWrap();
1142*d415bd75Srobert       return &I;
1143*d415bd75Srobert     }
1144*d415bd75Srobert   }
1145*d415bd75Srobert 
114609467b48Spatrick   return nullptr;
114709467b48Spatrick }
114809467b48Spatrick 
visitLShr(BinaryOperator & I)114973471bf0Spatrick Instruction *InstCombinerImpl::visitLShr(BinaryOperator &I) {
1150*d415bd75Srobert   if (Value *V = simplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
115109467b48Spatrick                                   SQ.getWithInstruction(&I)))
115209467b48Spatrick     return replaceInstUsesWith(I, V);
115309467b48Spatrick 
115409467b48Spatrick   if (Instruction *X = foldVectorBinop(I))
115509467b48Spatrick     return X;
115609467b48Spatrick 
115709467b48Spatrick   if (Instruction *R = commonShiftTransforms(I))
115809467b48Spatrick     return R;
115909467b48Spatrick 
116009467b48Spatrick   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
116109467b48Spatrick   Type *Ty = I.getType();
1162*d415bd75Srobert   Value *X;
1163*d415bd75Srobert   const APInt *C;
116409467b48Spatrick   unsigned BitWidth = Ty->getScalarSizeInBits();
1165*d415bd75Srobert 
1166*d415bd75Srobert   // (iN (~X) u>> (N - 1)) --> zext (X > -1)
1167*d415bd75Srobert   if (match(Op0, m_OneUse(m_Not(m_Value(X)))) &&
1168*d415bd75Srobert       match(Op1, m_SpecificIntAllowUndef(BitWidth - 1)))
1169*d415bd75Srobert     return new ZExtInst(Builder.CreateIsNotNeg(X, "isnotneg"), Ty);
1170*d415bd75Srobert 
1171*d415bd75Srobert   if (match(Op1, m_APInt(C))) {
1172*d415bd75Srobert     unsigned ShAmtC = C->getZExtValue();
117309467b48Spatrick     auto *II = dyn_cast<IntrinsicInst>(Op0);
1174*d415bd75Srobert     if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmtC &&
117509467b48Spatrick         (II->getIntrinsicID() == Intrinsic::ctlz ||
117609467b48Spatrick          II->getIntrinsicID() == Intrinsic::cttz ||
117709467b48Spatrick          II->getIntrinsicID() == Intrinsic::ctpop)) {
117809467b48Spatrick       // ctlz.i32(x)>>5  --> zext(x == 0)
117909467b48Spatrick       // cttz.i32(x)>>5  --> zext(x == 0)
118009467b48Spatrick       // ctpop.i32(x)>>5 --> zext(x == -1)
118109467b48Spatrick       bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
118209467b48Spatrick       Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
118309467b48Spatrick       Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS);
118409467b48Spatrick       return new ZExtInst(Cmp, Ty);
118509467b48Spatrick     }
118609467b48Spatrick 
118709467b48Spatrick     Value *X;
1188*d415bd75Srobert     const APInt *C1;
1189*d415bd75Srobert     if (match(Op0, m_Shl(m_Value(X), m_APInt(C1))) && C1->ult(BitWidth)) {
1190*d415bd75Srobert       if (C1->ult(ShAmtC)) {
1191*d415bd75Srobert         unsigned ShlAmtC = C1->getZExtValue();
1192*d415bd75Srobert         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShlAmtC);
119309467b48Spatrick         if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1194*d415bd75Srobert           // (X <<nuw C1) >>u C --> X >>u (C - C1)
119509467b48Spatrick           auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
119609467b48Spatrick           NewLShr->setIsExact(I.isExact());
119709467b48Spatrick           return NewLShr;
119809467b48Spatrick         }
1199*d415bd75Srobert         if (Op0->hasOneUse()) {
1200*d415bd75Srobert           // (X << C1) >>u C  --> (X >>u (C - C1)) & (-1 >> C)
120109467b48Spatrick           Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact());
1202*d415bd75Srobert           APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
120309467b48Spatrick           return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
120409467b48Spatrick         }
1205*d415bd75Srobert       } else if (C1->ugt(ShAmtC)) {
1206*d415bd75Srobert         unsigned ShlAmtC = C1->getZExtValue();
1207*d415bd75Srobert         Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmtC - ShAmtC);
120809467b48Spatrick         if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1209*d415bd75Srobert           // (X <<nuw C1) >>u C --> X <<nuw (C1 - C)
121009467b48Spatrick           auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
121109467b48Spatrick           NewShl->setHasNoUnsignedWrap(true);
121209467b48Spatrick           return NewShl;
121309467b48Spatrick         }
1214*d415bd75Srobert         if (Op0->hasOneUse()) {
1215*d415bd75Srobert           // (X << C1) >>u C  --> X << (C1 - C) & (-1 >> C)
121609467b48Spatrick           Value *NewShl = Builder.CreateShl(X, ShiftDiff);
1217*d415bd75Srobert           APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
121809467b48Spatrick           return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
121909467b48Spatrick         }
1220*d415bd75Srobert       } else {
1221*d415bd75Srobert         assert(*C1 == ShAmtC);
122209467b48Spatrick         // (X << C) >>u C --> X & (-1 >>u C)
1223*d415bd75Srobert         APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
122409467b48Spatrick         return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
122509467b48Spatrick       }
1226*d415bd75Srobert     }
1227*d415bd75Srobert 
1228*d415bd75Srobert     // ((X << C) + Y) >>u C --> (X + (Y >>u C)) & (-1 >>u C)
1229*d415bd75Srobert     // TODO: Consolidate with the more general transform that starts from shl
1230*d415bd75Srobert     //       (the shifts are in the opposite order).
1231*d415bd75Srobert     Value *Y;
1232*d415bd75Srobert     if (match(Op0,
1233*d415bd75Srobert               m_OneUse(m_c_Add(m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))),
1234*d415bd75Srobert                                m_Value(Y))))) {
1235*d415bd75Srobert       Value *NewLshr = Builder.CreateLShr(Y, Op1);
1236*d415bd75Srobert       Value *NewAdd = Builder.CreateAdd(NewLshr, X);
1237*d415bd75Srobert       unsigned Op1Val = C->getLimitedValue(BitWidth);
1238*d415bd75Srobert       APInt Bits = APInt::getLowBitsSet(BitWidth, BitWidth - Op1Val);
1239*d415bd75Srobert       Constant *Mask = ConstantInt::get(Ty, Bits);
1240*d415bd75Srobert       return BinaryOperator::CreateAnd(NewAdd, Mask);
1241*d415bd75Srobert     }
124209467b48Spatrick 
124309467b48Spatrick     if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) &&
124409467b48Spatrick         (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
1245*d415bd75Srobert       assert(ShAmtC < X->getType()->getScalarSizeInBits() &&
124609467b48Spatrick              "Big shift not simplified to zero?");
124709467b48Spatrick       // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
1248*d415bd75Srobert       Value *NewLShr = Builder.CreateLShr(X, ShAmtC);
124909467b48Spatrick       return new ZExtInst(NewLShr, Ty);
125009467b48Spatrick     }
125109467b48Spatrick 
1252*d415bd75Srobert     if (match(Op0, m_SExt(m_Value(X)))) {
125309467b48Spatrick       unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
1254*d415bd75Srobert       // lshr (sext i1 X to iN), C --> select (X, -1 >> C, 0)
1255*d415bd75Srobert       if (SrcTyBitWidth == 1) {
1256*d415bd75Srobert         auto *NewC = ConstantInt::get(
1257*d415bd75Srobert             Ty, APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
1258*d415bd75Srobert         return SelectInst::Create(X, NewC, ConstantInt::getNullValue(Ty));
1259*d415bd75Srobert       }
126009467b48Spatrick 
1261*d415bd75Srobert       if ((!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType())) &&
1262*d415bd75Srobert           Op0->hasOneUse()) {
1263*d415bd75Srobert         // Are we moving the sign bit to the low bit and widening with high
1264*d415bd75Srobert         // zeros? lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
1265*d415bd75Srobert         if (ShAmtC == BitWidth - 1) {
126609467b48Spatrick           Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1);
126709467b48Spatrick           return new ZExtInst(NewLShr, Ty);
126809467b48Spatrick         }
126909467b48Spatrick 
127009467b48Spatrick         // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
1271*d415bd75Srobert         if (ShAmtC == BitWidth - SrcTyBitWidth) {
127209467b48Spatrick           // The new shift amount can't be more than the narrow source type.
1273*d415bd75Srobert           unsigned NewShAmt = std::min(ShAmtC, SrcTyBitWidth - 1);
127409467b48Spatrick           Value *AShr = Builder.CreateAShr(X, NewShAmt);
127509467b48Spatrick           return new ZExtInst(AShr, Ty);
127609467b48Spatrick         }
127709467b48Spatrick       }
1278*d415bd75Srobert     }
127909467b48Spatrick 
1280*d415bd75Srobert     if (ShAmtC == BitWidth - 1) {
128173471bf0Spatrick       // lshr i32 or(X,-X), 31 --> zext (X != 0)
128273471bf0Spatrick       if (match(Op0, m_OneUse(m_c_Or(m_Neg(m_Value(X)), m_Deferred(X)))))
128373471bf0Spatrick         return new ZExtInst(Builder.CreateIsNotNull(X), Ty);
128473471bf0Spatrick 
128573471bf0Spatrick       // lshr i32 (X -nsw Y), 31 --> zext (X < Y)
128673471bf0Spatrick       if (match(Op0, m_OneUse(m_NSWSub(m_Value(X), m_Value(Y)))))
128773471bf0Spatrick         return new ZExtInst(Builder.CreateICmpSLT(X, Y), Ty);
128873471bf0Spatrick 
128973471bf0Spatrick       // Check if a number is negative and odd:
129073471bf0Spatrick       // lshr i32 (srem X, 2), 31 --> and (X >> 31), X
129173471bf0Spatrick       if (match(Op0, m_OneUse(m_SRem(m_Value(X), m_SpecificInt(2))))) {
1292*d415bd75Srobert         Value *Signbit = Builder.CreateLShr(X, ShAmtC);
129373471bf0Spatrick         return BinaryOperator::CreateAnd(Signbit, X);
129473471bf0Spatrick       }
129573471bf0Spatrick     }
129673471bf0Spatrick 
1297*d415bd75Srobert     // (X >>u C1) >>u C --> X >>u (C1 + C)
1298*d415bd75Srobert     if (match(Op0, m_LShr(m_Value(X), m_APInt(C1)))) {
129909467b48Spatrick       // Oversized shifts are simplified to zero in InstSimplify.
1300*d415bd75Srobert       unsigned AmtSum = ShAmtC + C1->getZExtValue();
130109467b48Spatrick       if (AmtSum < BitWidth)
130209467b48Spatrick         return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
130309467b48Spatrick     }
130409467b48Spatrick 
1305*d415bd75Srobert     Instruction *TruncSrc;
1306*d415bd75Srobert     if (match(Op0, m_OneUse(m_Trunc(m_Instruction(TruncSrc)))) &&
1307*d415bd75Srobert         match(TruncSrc, m_LShr(m_Value(X), m_APInt(C1)))) {
1308*d415bd75Srobert       unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1309*d415bd75Srobert       unsigned AmtSum = ShAmtC + C1->getZExtValue();
1310*d415bd75Srobert 
1311*d415bd75Srobert       // If the combined shift fits in the source width:
1312*d415bd75Srobert       // (trunc (X >>u C1)) >>u C --> and (trunc (X >>u (C1 + C)), MaskC
1313*d415bd75Srobert       //
1314*d415bd75Srobert       // If the first shift covers the number of bits truncated, then the
1315*d415bd75Srobert       // mask instruction is eliminated (and so the use check is relaxed).
1316*d415bd75Srobert       if (AmtSum < SrcWidth &&
1317*d415bd75Srobert           (TruncSrc->hasOneUse() || C1->uge(SrcWidth - BitWidth))) {
1318*d415bd75Srobert         Value *SumShift = Builder.CreateLShr(X, AmtSum, "sum.shift");
1319*d415bd75Srobert         Value *Trunc = Builder.CreateTrunc(SumShift, Ty, I.getName());
1320*d415bd75Srobert 
1321*d415bd75Srobert         // If the first shift does not cover the number of bits truncated, then
1322*d415bd75Srobert         // we require a mask to get rid of high bits in the result.
1323*d415bd75Srobert         APInt MaskC = APInt::getAllOnes(BitWidth).lshr(ShAmtC);
1324*d415bd75Srobert         return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Ty, MaskC));
1325*d415bd75Srobert       }
1326*d415bd75Srobert     }
1327*d415bd75Srobert 
1328*d415bd75Srobert     const APInt *MulC;
1329*d415bd75Srobert     if (match(Op0, m_NUWMul(m_Value(X), m_APInt(MulC)))) {
133073471bf0Spatrick       // Look for a "splat" mul pattern - it replicates bits across each half of
133173471bf0Spatrick       // a value, so a right shift is just a mask of the low bits:
1332*d415bd75Srobert       // lshr i[2N] (mul nuw X, (2^N)+1), N --> and iN X, (2^N)-1
133373471bf0Spatrick       // TODO: Generalize to allow more than just half-width shifts?
1334*d415bd75Srobert       if (BitWidth > 2 && ShAmtC * 2 == BitWidth && (*MulC - 1).isPowerOf2() &&
1335*d415bd75Srobert           MulC->logBase2() == ShAmtC)
133673471bf0Spatrick         return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, *MulC - 2));
133773471bf0Spatrick 
1338*d415bd75Srobert       // The one-use check is not strictly necessary, but codegen may not be
1339*d415bd75Srobert       // able to invert the transform and perf may suffer with an extra mul
1340*d415bd75Srobert       // instruction.
1341*d415bd75Srobert       if (Op0->hasOneUse()) {
1342*d415bd75Srobert         APInt NewMulC = MulC->lshr(ShAmtC);
1343*d415bd75Srobert         // if c is divisible by (1 << ShAmtC):
1344*d415bd75Srobert         // lshr (mul nuw x, MulC), ShAmtC -> mul nuw x, (MulC >> ShAmtC)
1345*d415bd75Srobert         if (MulC->eq(NewMulC.shl(ShAmtC))) {
1346*d415bd75Srobert           auto *NewMul =
1347*d415bd75Srobert               BinaryOperator::CreateNUWMul(X, ConstantInt::get(Ty, NewMulC));
1348*d415bd75Srobert           BinaryOperator *OrigMul = cast<BinaryOperator>(Op0);
1349*d415bd75Srobert           NewMul->setHasNoSignedWrap(OrigMul->hasNoSignedWrap());
1350*d415bd75Srobert           return NewMul;
1351*d415bd75Srobert         }
1352*d415bd75Srobert       }
1353*d415bd75Srobert     }
1354*d415bd75Srobert 
1355*d415bd75Srobert     // Try to narrow bswap.
1356*d415bd75Srobert     // In the case where the shift amount equals the bitwidth difference, the
1357*d415bd75Srobert     // shift is eliminated.
1358*d415bd75Srobert     if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::bswap>(
1359*d415bd75Srobert                        m_OneUse(m_ZExt(m_Value(X))))))) {
1360*d415bd75Srobert       unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1361*d415bd75Srobert       unsigned WidthDiff = BitWidth - SrcWidth;
1362*d415bd75Srobert       if (SrcWidth % 16 == 0) {
1363*d415bd75Srobert         Value *NarrowSwap = Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X);
1364*d415bd75Srobert         if (ShAmtC >= WidthDiff) {
1365*d415bd75Srobert           // (bswap (zext X)) >> C --> zext (bswap X >> C')
1366*d415bd75Srobert           Value *NewShift = Builder.CreateLShr(NarrowSwap, ShAmtC - WidthDiff);
1367*d415bd75Srobert           return new ZExtInst(NewShift, Ty);
1368*d415bd75Srobert         } else {
1369*d415bd75Srobert           // (bswap (zext X)) >> C --> (zext (bswap X)) << C'
1370*d415bd75Srobert           Value *NewZExt = Builder.CreateZExt(NarrowSwap, Ty);
1371*d415bd75Srobert           Constant *ShiftDiff = ConstantInt::get(Ty, WidthDiff - ShAmtC);
1372*d415bd75Srobert           return BinaryOperator::CreateShl(NewZExt, ShiftDiff);
1373*d415bd75Srobert         }
1374*d415bd75Srobert       }
1375*d415bd75Srobert     }
1376*d415bd75Srobert 
1377*d415bd75Srobert     // Reduce add-carry of bools to logic:
1378*d415bd75Srobert     // ((zext BoolX) + (zext BoolY)) >> 1 --> zext (BoolX && BoolY)
1379*d415bd75Srobert     Value *BoolX, *BoolY;
1380*d415bd75Srobert     if (ShAmtC == 1 && match(Op0, m_Add(m_Value(X), m_Value(Y))) &&
1381*d415bd75Srobert         match(X, m_ZExt(m_Value(BoolX))) && match(Y, m_ZExt(m_Value(BoolY))) &&
1382*d415bd75Srobert         BoolX->getType()->isIntOrIntVectorTy(1) &&
1383*d415bd75Srobert         BoolY->getType()->isIntOrIntVectorTy(1) &&
1384*d415bd75Srobert         (X->hasOneUse() || Y->hasOneUse() || Op0->hasOneUse())) {
1385*d415bd75Srobert       Value *And = Builder.CreateAnd(BoolX, BoolY);
1386*d415bd75Srobert       return new ZExtInst(And, Ty);
1387*d415bd75Srobert     }
1388*d415bd75Srobert 
138909467b48Spatrick     // If the shifted-out value is known-zero, then this is an exact shift.
139009467b48Spatrick     if (!I.isExact() &&
1391*d415bd75Srobert         MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmtC), 0, &I)) {
139209467b48Spatrick       I.setIsExact();
139309467b48Spatrick       return &I;
139409467b48Spatrick     }
139509467b48Spatrick   }
139609467b48Spatrick 
139709467b48Spatrick   // Transform  (x << y) >> y  to  x & (-1 >> y)
139809467b48Spatrick   if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
139909467b48Spatrick     Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
140009467b48Spatrick     Value *Mask = Builder.CreateLShr(AllOnes, Op1);
140109467b48Spatrick     return BinaryOperator::CreateAnd(Mask, X);
140209467b48Spatrick   }
140309467b48Spatrick 
1404*d415bd75Srobert   if (Instruction *Overflow = foldLShrOverflowBit(I))
1405*d415bd75Srobert     return Overflow;
1406*d415bd75Srobert 
140709467b48Spatrick   return nullptr;
140809467b48Spatrick }
140909467b48Spatrick 
141009467b48Spatrick Instruction *
foldVariableSignZeroExtensionOfVariableHighBitExtract(BinaryOperator & OldAShr)141173471bf0Spatrick InstCombinerImpl::foldVariableSignZeroExtensionOfVariableHighBitExtract(
141209467b48Spatrick     BinaryOperator &OldAShr) {
141309467b48Spatrick   assert(OldAShr.getOpcode() == Instruction::AShr &&
141409467b48Spatrick          "Must be called with arithmetic right-shift instruction only.");
141509467b48Spatrick 
141609467b48Spatrick   // Check that constant C is a splat of the element-wise bitwidth of V.
141709467b48Spatrick   auto BitWidthSplat = [](Constant *C, Value *V) {
141809467b48Spatrick     return match(
141909467b48Spatrick         C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
142009467b48Spatrick                               APInt(C->getType()->getScalarSizeInBits(),
142109467b48Spatrick                                     V->getType()->getScalarSizeInBits())));
142209467b48Spatrick   };
142309467b48Spatrick 
142409467b48Spatrick   // It should look like variable-length sign-extension on the outside:
142509467b48Spatrick   //   (Val << (bitwidth(Val)-Nbits)) a>> (bitwidth(Val)-Nbits)
142609467b48Spatrick   Value *NBits;
142709467b48Spatrick   Instruction *MaybeTrunc;
142809467b48Spatrick   Constant *C1, *C2;
142909467b48Spatrick   if (!match(&OldAShr,
143009467b48Spatrick              m_AShr(m_Shl(m_Instruction(MaybeTrunc),
143109467b48Spatrick                           m_ZExtOrSelf(m_Sub(m_Constant(C1),
143209467b48Spatrick                                              m_ZExtOrSelf(m_Value(NBits))))),
143309467b48Spatrick                     m_ZExtOrSelf(m_Sub(m_Constant(C2),
143409467b48Spatrick                                        m_ZExtOrSelf(m_Deferred(NBits)))))) ||
143509467b48Spatrick       !BitWidthSplat(C1, &OldAShr) || !BitWidthSplat(C2, &OldAShr))
143609467b48Spatrick     return nullptr;
143709467b48Spatrick 
143809467b48Spatrick   // There may or may not be a truncation after outer two shifts.
143909467b48Spatrick   Instruction *HighBitExtract;
144009467b48Spatrick   match(MaybeTrunc, m_TruncOrSelf(m_Instruction(HighBitExtract)));
144109467b48Spatrick   bool HadTrunc = MaybeTrunc != HighBitExtract;
144209467b48Spatrick 
144309467b48Spatrick   // And finally, the innermost part of the pattern must be a right-shift.
144409467b48Spatrick   Value *X, *NumLowBitsToSkip;
144509467b48Spatrick   if (!match(HighBitExtract, m_Shr(m_Value(X), m_Value(NumLowBitsToSkip))))
144609467b48Spatrick     return nullptr;
144709467b48Spatrick 
144809467b48Spatrick   // Said right-shift must extract high NBits bits - C0 must be it's bitwidth.
144909467b48Spatrick   Constant *C0;
145009467b48Spatrick   if (!match(NumLowBitsToSkip,
145109467b48Spatrick              m_ZExtOrSelf(
145209467b48Spatrick                  m_Sub(m_Constant(C0), m_ZExtOrSelf(m_Specific(NBits))))) ||
145309467b48Spatrick       !BitWidthSplat(C0, HighBitExtract))
145409467b48Spatrick     return nullptr;
145509467b48Spatrick 
145609467b48Spatrick   // Since the NBits is identical for all shifts, if the outermost and
145709467b48Spatrick   // innermost shifts are identical, then outermost shifts are redundant.
145809467b48Spatrick   // If we had truncation, do keep it though.
145909467b48Spatrick   if (HighBitExtract->getOpcode() == OldAShr.getOpcode())
146009467b48Spatrick     return replaceInstUsesWith(OldAShr, MaybeTrunc);
146109467b48Spatrick 
146209467b48Spatrick   // Else, if there was a truncation, then we need to ensure that one
146309467b48Spatrick   // instruction will go away.
146409467b48Spatrick   if (HadTrunc && !match(&OldAShr, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
146509467b48Spatrick     return nullptr;
146609467b48Spatrick 
146709467b48Spatrick   // Finally, bypass two innermost shifts, and perform the outermost shift on
146809467b48Spatrick   // the operands of the innermost shift.
146909467b48Spatrick   Instruction *NewAShr =
147009467b48Spatrick       BinaryOperator::Create(OldAShr.getOpcode(), X, NumLowBitsToSkip);
147109467b48Spatrick   NewAShr->copyIRFlags(HighBitExtract); // We can preserve 'exact'-ness.
147209467b48Spatrick   if (!HadTrunc)
147309467b48Spatrick     return NewAShr;
147409467b48Spatrick 
147509467b48Spatrick   Builder.Insert(NewAShr);
147609467b48Spatrick   return TruncInst::CreateTruncOrBitCast(NewAShr, OldAShr.getType());
147709467b48Spatrick }
147809467b48Spatrick 
visitAShr(BinaryOperator & I)147973471bf0Spatrick Instruction *InstCombinerImpl::visitAShr(BinaryOperator &I) {
1480*d415bd75Srobert   if (Value *V = simplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
148109467b48Spatrick                                   SQ.getWithInstruction(&I)))
148209467b48Spatrick     return replaceInstUsesWith(I, V);
148309467b48Spatrick 
148409467b48Spatrick   if (Instruction *X = foldVectorBinop(I))
148509467b48Spatrick     return X;
148609467b48Spatrick 
148709467b48Spatrick   if (Instruction *R = commonShiftTransforms(I))
148809467b48Spatrick     return R;
148909467b48Spatrick 
149009467b48Spatrick   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
149109467b48Spatrick   Type *Ty = I.getType();
149209467b48Spatrick   unsigned BitWidth = Ty->getScalarSizeInBits();
149309467b48Spatrick   const APInt *ShAmtAPInt;
149409467b48Spatrick   if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) {
149509467b48Spatrick     unsigned ShAmt = ShAmtAPInt->getZExtValue();
149609467b48Spatrick 
149709467b48Spatrick     // If the shift amount equals the difference in width of the destination
149809467b48Spatrick     // and source scalar types:
149909467b48Spatrick     // ashr (shl (zext X), C), C --> sext X
150009467b48Spatrick     Value *X;
150109467b48Spatrick     if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
150209467b48Spatrick         ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
150309467b48Spatrick       return new SExtInst(X, Ty);
150409467b48Spatrick 
150509467b48Spatrick     // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
150609467b48Spatrick     // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
150709467b48Spatrick     const APInt *ShOp1;
150809467b48Spatrick     if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) &&
150909467b48Spatrick         ShOp1->ult(BitWidth)) {
151009467b48Spatrick       unsigned ShlAmt = ShOp1->getZExtValue();
151109467b48Spatrick       if (ShlAmt < ShAmt) {
151209467b48Spatrick         // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
151309467b48Spatrick         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
151409467b48Spatrick         auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff);
151509467b48Spatrick         NewAShr->setIsExact(I.isExact());
151609467b48Spatrick         return NewAShr;
151709467b48Spatrick       }
151809467b48Spatrick       if (ShlAmt > ShAmt) {
151909467b48Spatrick         // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
152009467b48Spatrick         Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
152109467b48Spatrick         auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff);
152209467b48Spatrick         NewShl->setHasNoSignedWrap(true);
152309467b48Spatrick         return NewShl;
152409467b48Spatrick       }
152509467b48Spatrick     }
152609467b48Spatrick 
152709467b48Spatrick     if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) &&
152809467b48Spatrick         ShOp1->ult(BitWidth)) {
152909467b48Spatrick       unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
153009467b48Spatrick       // Oversized arithmetic shifts replicate the sign bit.
153109467b48Spatrick       AmtSum = std::min(AmtSum, BitWidth - 1);
153209467b48Spatrick       // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
153309467b48Spatrick       return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
153409467b48Spatrick     }
153509467b48Spatrick 
153609467b48Spatrick     if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) &&
153709467b48Spatrick         (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) {
153809467b48Spatrick       // ashr (sext X), C --> sext (ashr X, C')
153909467b48Spatrick       Type *SrcTy = X->getType();
154009467b48Spatrick       ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1);
154109467b48Spatrick       Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt));
154209467b48Spatrick       return new SExtInst(NewSh, Ty);
154309467b48Spatrick     }
154409467b48Spatrick 
154573471bf0Spatrick     if (ShAmt == BitWidth - 1) {
154673471bf0Spatrick       // ashr i32 or(X,-X), 31 --> sext (X != 0)
154773471bf0Spatrick       if (match(Op0, m_OneUse(m_c_Or(m_Neg(m_Value(X)), m_Deferred(X)))))
154873471bf0Spatrick         return new SExtInst(Builder.CreateIsNotNull(X), Ty);
154973471bf0Spatrick 
155073471bf0Spatrick       // ashr i32 (X -nsw Y), 31 --> sext (X < Y)
155173471bf0Spatrick       Value *Y;
155273471bf0Spatrick       if (match(Op0, m_OneUse(m_NSWSub(m_Value(X), m_Value(Y)))))
155373471bf0Spatrick         return new SExtInst(Builder.CreateICmpSLT(X, Y), Ty);
155473471bf0Spatrick     }
155573471bf0Spatrick 
155609467b48Spatrick     // If the shifted-out value is known-zero, then this is an exact shift.
155709467b48Spatrick     if (!I.isExact() &&
155809467b48Spatrick         MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
155909467b48Spatrick       I.setIsExact();
156009467b48Spatrick       return &I;
156109467b48Spatrick     }
156209467b48Spatrick   }
156309467b48Spatrick 
1564*d415bd75Srobert   // Prefer `-(x & 1)` over `(x << (bitwidth(x)-1)) a>> (bitwidth(x)-1)`
1565*d415bd75Srobert   // as the pattern to splat the lowest bit.
1566*d415bd75Srobert   // FIXME: iff X is already masked, we don't need the one-use check.
1567*d415bd75Srobert   Value *X;
1568*d415bd75Srobert   if (match(Op1, m_SpecificIntAllowUndef(BitWidth - 1)) &&
1569*d415bd75Srobert       match(Op0, m_OneUse(m_Shl(m_Value(X),
1570*d415bd75Srobert                                 m_SpecificIntAllowUndef(BitWidth - 1))))) {
1571*d415bd75Srobert     Constant *Mask = ConstantInt::get(Ty, 1);
1572*d415bd75Srobert     // Retain the knowledge about the ignored lanes.
1573*d415bd75Srobert     Mask = Constant::mergeUndefsWith(
1574*d415bd75Srobert         Constant::mergeUndefsWith(Mask, cast<Constant>(Op1)),
1575*d415bd75Srobert         cast<Constant>(cast<Instruction>(Op0)->getOperand(1)));
1576*d415bd75Srobert     X = Builder.CreateAnd(X, Mask);
1577*d415bd75Srobert     return BinaryOperator::CreateNeg(X);
1578*d415bd75Srobert   }
1579*d415bd75Srobert 
158009467b48Spatrick   if (Instruction *R = foldVariableSignZeroExtensionOfVariableHighBitExtract(I))
158109467b48Spatrick     return R;
158209467b48Spatrick 
158309467b48Spatrick   // See if we can turn a signed shr into an unsigned shr.
1584*d415bd75Srobert   if (MaskedValueIsZero(Op0, APInt::getSignMask(BitWidth), 0, &I)) {
1585*d415bd75Srobert     Instruction *Lshr = BinaryOperator::CreateLShr(Op0, Op1);
1586*d415bd75Srobert     Lshr->setIsExact(I.isExact());
1587*d415bd75Srobert     return Lshr;
1588*d415bd75Srobert   }
158909467b48Spatrick 
159073471bf0Spatrick   // ashr (xor %x, -1), %y  -->  xor (ashr %x, %y), -1
159173471bf0Spatrick   if (match(Op0, m_OneUse(m_Not(m_Value(X))))) {
159273471bf0Spatrick     // Note that we must drop 'exact'-ness of the shift!
159373471bf0Spatrick     // Note that we can't keep undef's in -1 vector constant!
159473471bf0Spatrick     auto *NewAShr = Builder.CreateAShr(X, Op1, Op0->getName() + ".not");
159573471bf0Spatrick     return BinaryOperator::CreateNot(NewAShr);
159673471bf0Spatrick   }
159773471bf0Spatrick 
159809467b48Spatrick   return nullptr;
159909467b48Spatrick }
1600