1 //===- InstCombineShifts.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitShl, visitLShr, and visitAShr functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/Analysis/ConstantFolding.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/IR/IntrinsicInst.h"
17 #include "llvm/IR/PatternMatch.h"
18 #include "llvm/Transforms/InstCombine/InstCombiner.h"
19 using namespace llvm;
20 using namespace PatternMatch;
21 
22 #define DEBUG_TYPE "instcombine"
23 
24 // Given pattern:
25 //   (x shiftopcode Q) shiftopcode K
26 // we should rewrite it as
27 //   x shiftopcode (Q+K)  iff (Q+K) u< bitwidth(x) and
28 //
29 // This is valid for any shift, but they must be identical, and we must be
30 // careful in case we have (zext(Q)+zext(K)) and look past extensions,
31 // (Q+K) must not overflow or else (Q+K) u< bitwidth(x) is bogus.
32 //
33 // AnalyzeForSignBitExtraction indicates that we will only analyze whether this
34 // pattern has any 2 right-shifts that sum to 1 less than original bit width.
35 Value *InstCombinerImpl::reassociateShiftAmtsOfTwoSameDirectionShifts(
36     BinaryOperator *Sh0, const SimplifyQuery &SQ,
37     bool AnalyzeForSignBitExtraction) {
38   // Look for a shift of some instruction, ignore zext of shift amount if any.
39   Instruction *Sh0Op0;
40   Value *ShAmt0;
41   if (!match(Sh0,
42              m_Shift(m_Instruction(Sh0Op0), m_ZExtOrSelf(m_Value(ShAmt0)))))
43     return nullptr;
44 
45   // If there is a truncation between the two shifts, we must make note of it
46   // and look through it. The truncation imposes additional constraints on the
47   // transform.
48   Instruction *Sh1;
49   Value *Trunc = nullptr;
50   match(Sh0Op0,
51         m_CombineOr(m_CombineAnd(m_Trunc(m_Instruction(Sh1)), m_Value(Trunc)),
52                     m_Instruction(Sh1)));
53 
54   // Inner shift: (x shiftopcode ShAmt1)
55   // Like with other shift, ignore zext of shift amount if any.
56   Value *X, *ShAmt1;
57   if (!match(Sh1, m_Shift(m_Value(X), m_ZExtOrSelf(m_Value(ShAmt1)))))
58     return nullptr;
59 
60   // We have two shift amounts from two different shifts. The types of those
61   // shift amounts may not match. If that's the case let's bailout now..
62   if (ShAmt0->getType() != ShAmt1->getType())
63     return nullptr;
64 
65   // As input, we have the following pattern:
66   //   Sh0 (Sh1 X, Q), K
67   // We want to rewrite that as:
68   //   Sh x, (Q+K)  iff (Q+K) u< bitwidth(x)
69   // While we know that originally (Q+K) would not overflow
70   // (because  2 * (N-1) u<= iN -1), we have looked past extensions of
71   // shift amounts. so it may now overflow in smaller bitwidth.
72   // To ensure that does not happen, we need to ensure that the total maximal
73   // shift amount is still representable in that smaller bit width.
74   unsigned MaximalPossibleTotalShiftAmount =
75       (Sh0->getType()->getScalarSizeInBits() - 1) +
76       (Sh1->getType()->getScalarSizeInBits() - 1);
77   APInt MaximalRepresentableShiftAmount =
78       APInt::getAllOnesValue(ShAmt0->getType()->getScalarSizeInBits());
79   if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
80     return nullptr;
81 
82   // We are only looking for signbit extraction if we have two right shifts.
83   bool HadTwoRightShifts = match(Sh0, m_Shr(m_Value(), m_Value())) &&
84                            match(Sh1, m_Shr(m_Value(), m_Value()));
85   // ... and if it's not two right-shifts, we know the answer already.
86   if (AnalyzeForSignBitExtraction && !HadTwoRightShifts)
87     return nullptr;
88 
89   // The shift opcodes must be identical, unless we are just checking whether
90   // this pattern can be interpreted as a sign-bit-extraction.
91   Instruction::BinaryOps ShiftOpcode = Sh0->getOpcode();
92   bool IdenticalShOpcodes = Sh0->getOpcode() == Sh1->getOpcode();
93   if (!IdenticalShOpcodes && !AnalyzeForSignBitExtraction)
94     return nullptr;
95 
96   // If we saw truncation, we'll need to produce extra instruction,
97   // and for that one of the operands of the shift must be one-use,
98   // unless of course we don't actually plan to produce any instructions here.
99   if (Trunc && !AnalyzeForSignBitExtraction &&
100       !match(Sh0, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
101     return nullptr;
102 
103   // Can we fold (ShAmt0+ShAmt1) ?
104   auto *NewShAmt = dyn_cast_or_null<Constant>(
105       SimplifyAddInst(ShAmt0, ShAmt1, /*isNSW=*/false, /*isNUW=*/false,
106                       SQ.getWithInstruction(Sh0)));
107   if (!NewShAmt)
108     return nullptr; // Did not simplify.
109   unsigned NewShAmtBitWidth = NewShAmt->getType()->getScalarSizeInBits();
110   unsigned XBitWidth = X->getType()->getScalarSizeInBits();
111   // Is the new shift amount smaller than the bit width of inner/new shift?
112   if (!match(NewShAmt, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,
113                                           APInt(NewShAmtBitWidth, XBitWidth))))
114     return nullptr; // FIXME: could perform constant-folding.
115 
116   // If there was a truncation, and we have a right-shift, we can only fold if
117   // we are left with the original sign bit. Likewise, if we were just checking
118   // that this is a sighbit extraction, this is the place to check it.
119   // FIXME: zero shift amount is also legal here, but we can't *easily* check
120   // more than one predicate so it's not really worth it.
121   if (HadTwoRightShifts && (Trunc || AnalyzeForSignBitExtraction)) {
122     // If it's not a sign bit extraction, then we're done.
123     if (!match(NewShAmt,
124                m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
125                                   APInt(NewShAmtBitWidth, XBitWidth - 1))))
126       return nullptr;
127     // If it is, and that was the question, return the base value.
128     if (AnalyzeForSignBitExtraction)
129       return X;
130   }
131 
132   assert(IdenticalShOpcodes && "Should not get here with different shifts.");
133 
134   // All good, we can do this fold.
135   NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, X->getType());
136 
137   BinaryOperator *NewShift = BinaryOperator::Create(ShiftOpcode, X, NewShAmt);
138 
139   // The flags can only be propagated if there wasn't a trunc.
140   if (!Trunc) {
141     // If the pattern did not involve trunc, and both of the original shifts
142     // had the same flag set, preserve the flag.
143     if (ShiftOpcode == Instruction::BinaryOps::Shl) {
144       NewShift->setHasNoUnsignedWrap(Sh0->hasNoUnsignedWrap() &&
145                                      Sh1->hasNoUnsignedWrap());
146       NewShift->setHasNoSignedWrap(Sh0->hasNoSignedWrap() &&
147                                    Sh1->hasNoSignedWrap());
148     } else {
149       NewShift->setIsExact(Sh0->isExact() && Sh1->isExact());
150     }
151   }
152 
153   Instruction *Ret = NewShift;
154   if (Trunc) {
155     Builder.Insert(NewShift);
156     Ret = CastInst::Create(Instruction::Trunc, NewShift, Sh0->getType());
157   }
158 
159   return Ret;
160 }
161 
162 // If we have some pattern that leaves only some low bits set, and then performs
163 // left-shift of those bits, if none of the bits that are left after the final
164 // shift are modified by the mask, we can omit the mask.
165 //
166 // There are many variants to this pattern:
167 //   a)  (x & ((1 << MaskShAmt) - 1)) << ShiftShAmt
168 //   b)  (x & (~(-1 << MaskShAmt))) << ShiftShAmt
169 //   c)  (x & (-1 >> MaskShAmt)) << ShiftShAmt
170 //   d)  (x & ((-1 << MaskShAmt) >> MaskShAmt)) << ShiftShAmt
171 //   e)  ((x << MaskShAmt) l>> MaskShAmt) << ShiftShAmt
172 //   f)  ((x << MaskShAmt) a>> MaskShAmt) << ShiftShAmt
173 // All these patterns can be simplified to just:
174 //   x << ShiftShAmt
175 // iff:
176 //   a,b)     (MaskShAmt+ShiftShAmt) u>= bitwidth(x)
177 //   c,d,e,f) (ShiftShAmt-MaskShAmt) s>= 0 (i.e. ShiftShAmt u>= MaskShAmt)
178 static Instruction *
179 dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift,
180                                      const SimplifyQuery &Q,
181                                      InstCombiner::BuilderTy &Builder) {
182   assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&
183          "The input must be 'shl'!");
184 
185   Value *Masked, *ShiftShAmt;
186   match(OuterShift,
187         m_Shift(m_Value(Masked), m_ZExtOrSelf(m_Value(ShiftShAmt))));
188 
189   // *If* there is a truncation between an outer shift and a possibly-mask,
190   // then said truncation *must* be one-use, else we can't perform the fold.
191   Value *Trunc;
192   if (match(Masked, m_CombineAnd(m_Trunc(m_Value(Masked)), m_Value(Trunc))) &&
193       !Trunc->hasOneUse())
194     return nullptr;
195 
196   Type *NarrowestTy = OuterShift->getType();
197   Type *WidestTy = Masked->getType();
198   bool HadTrunc = WidestTy != NarrowestTy;
199 
200   // The mask must be computed in a type twice as wide to ensure
201   // that no bits are lost if the sum-of-shifts is wider than the base type.
202   Type *ExtendedTy = WidestTy->getExtendedType();
203 
204   Value *MaskShAmt;
205 
206   // ((1 << MaskShAmt) - 1)
207   auto MaskA = m_Add(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes());
208   // (~(-1 << maskNbits))
209   auto MaskB = m_Xor(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_AllOnes());
210   // (-1 >> MaskShAmt)
211   auto MaskC = m_Shr(m_AllOnes(), m_Value(MaskShAmt));
212   // ((-1 << MaskShAmt) >> MaskShAmt)
213   auto MaskD =
214       m_Shr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt));
215 
216   Value *X;
217   Constant *NewMask;
218 
219   if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) {
220     // Peek through an optional zext of the shift amount.
221     match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
222 
223     // We have two shift amounts from two different shifts. The types of those
224     // shift amounts may not match. If that's the case let's bailout now.
225     if (MaskShAmt->getType() != ShiftShAmt->getType())
226       return nullptr;
227 
228     // Can we simplify (MaskShAmt+ShiftShAmt) ?
229     auto *SumOfShAmts = dyn_cast_or_null<Constant>(SimplifyAddInst(
230         MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
231     if (!SumOfShAmts)
232       return nullptr; // Did not simplify.
233     // In this pattern SumOfShAmts correlates with the number of low bits
234     // that shall remain in the root value (OuterShift).
235 
236     // An extend of an undef value becomes zero because the high bits are never
237     // completely unknown. Replace the the `undef` shift amounts with final
238     // shift bitwidth to ensure that the value remains undef when creating the
239     // subsequent shift op.
240     SumOfShAmts = Constant::replaceUndefsWith(
241         SumOfShAmts, ConstantInt::get(SumOfShAmts->getType()->getScalarType(),
242                                       ExtendedTy->getScalarSizeInBits()));
243     auto *ExtendedSumOfShAmts = ConstantExpr::getZExt(SumOfShAmts, ExtendedTy);
244     // And compute the mask as usual: ~(-1 << (SumOfShAmts))
245     auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
246     auto *ExtendedInvertedMask =
247         ConstantExpr::getShl(ExtendedAllOnes, ExtendedSumOfShAmts);
248     NewMask = ConstantExpr::getNot(ExtendedInvertedMask);
249   } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) ||
250              match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)),
251                                  m_Deferred(MaskShAmt)))) {
252     // Peek through an optional zext of the shift amount.
253     match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
254 
255     // We have two shift amounts from two different shifts. The types of those
256     // shift amounts may not match. If that's the case let's bailout now.
257     if (MaskShAmt->getType() != ShiftShAmt->getType())
258       return nullptr;
259 
260     // Can we simplify (ShiftShAmt-MaskShAmt) ?
261     auto *ShAmtsDiff = dyn_cast_or_null<Constant>(SimplifySubInst(
262         ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
263     if (!ShAmtsDiff)
264       return nullptr; // Did not simplify.
265     // In this pattern ShAmtsDiff correlates with the number of high bits that
266     // shall be unset in the root value (OuterShift).
267 
268     // An extend of an undef value becomes zero because the high bits are never
269     // completely unknown. Replace the the `undef` shift amounts with negated
270     // bitwidth of innermost shift to ensure that the value remains undef when
271     // creating the subsequent shift op.
272     unsigned WidestTyBitWidth = WidestTy->getScalarSizeInBits();
273     ShAmtsDiff = Constant::replaceUndefsWith(
274         ShAmtsDiff, ConstantInt::get(ShAmtsDiff->getType()->getScalarType(),
275                                      -WidestTyBitWidth));
276     auto *ExtendedNumHighBitsToClear = ConstantExpr::getZExt(
277         ConstantExpr::getSub(ConstantInt::get(ShAmtsDiff->getType(),
278                                               WidestTyBitWidth,
279                                               /*isSigned=*/false),
280                              ShAmtsDiff),
281         ExtendedTy);
282     // And compute the mask as usual: (-1 l>> (NumHighBitsToClear))
283     auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
284     NewMask =
285         ConstantExpr::getLShr(ExtendedAllOnes, ExtendedNumHighBitsToClear);
286   } else
287     return nullptr; // Don't know anything about this pattern.
288 
289   NewMask = ConstantExpr::getTrunc(NewMask, NarrowestTy);
290 
291   // Does this mask has any unset bits? If not then we can just not apply it.
292   bool NeedMask = !match(NewMask, m_AllOnes());
293 
294   // If we need to apply a mask, there are several more restrictions we have.
295   if (NeedMask) {
296     // The old masking instruction must go away.
297     if (!Masked->hasOneUse())
298       return nullptr;
299     // The original "masking" instruction must not have been`ashr`.
300     if (match(Masked, m_AShr(m_Value(), m_Value())))
301       return nullptr;
302   }
303 
304   // If we need to apply truncation, let's do it first, since we can.
305   // We have already ensured that the old truncation will go away.
306   if (HadTrunc)
307     X = Builder.CreateTrunc(X, NarrowestTy);
308 
309   // No 'NUW'/'NSW'! We no longer know that we won't shift-out non-0 bits.
310   // We didn't change the Type of this outermost shift, so we can just do it.
311   auto *NewShift = BinaryOperator::Create(OuterShift->getOpcode(), X,
312                                           OuterShift->getOperand(1));
313   if (!NeedMask)
314     return NewShift;
315 
316   Builder.Insert(NewShift);
317   return BinaryOperator::Create(Instruction::And, NewShift, NewMask);
318 }
319 
320 /// If we have a shift-by-constant of a bitwise logic op that itself has a
321 /// shift-by-constant operand with identical opcode, we may be able to convert
322 /// that into 2 independent shifts followed by the logic op. This eliminates a
323 /// a use of an intermediate value (reduces dependency chain).
324 static Instruction *foldShiftOfShiftedLogic(BinaryOperator &I,
325                                             InstCombiner::BuilderTy &Builder) {
326   assert(I.isShift() && "Expected a shift as input");
327   auto *LogicInst = dyn_cast<BinaryOperator>(I.getOperand(0));
328   if (!LogicInst || !LogicInst->isBitwiseLogicOp() || !LogicInst->hasOneUse())
329     return nullptr;
330 
331   const APInt *C0, *C1;
332   if (!match(I.getOperand(1), m_APInt(C1)))
333     return nullptr;
334 
335   Instruction::BinaryOps ShiftOpcode = I.getOpcode();
336   Type *Ty = I.getType();
337 
338   // Find a matching one-use shift by constant. The fold is not valid if the sum
339   // of the shift values equals or exceeds bitwidth.
340   // TODO: Remove the one-use check if the other logic operand (Y) is constant.
341   Value *X, *Y;
342   auto matchFirstShift = [&](Value *V) {
343     return !isa<ConstantExpr>(V) &&
344            match(V, m_OneUse(m_Shift(m_Value(X), m_APInt(C0)))) &&
345            cast<BinaryOperator>(V)->getOpcode() == ShiftOpcode &&
346            (*C0 + *C1).ult(Ty->getScalarSizeInBits());
347   };
348 
349   // Logic ops are commutative, so check each operand for a match.
350   if (matchFirstShift(LogicInst->getOperand(0)))
351     Y = LogicInst->getOperand(1);
352   else if (matchFirstShift(LogicInst->getOperand(1)))
353     Y = LogicInst->getOperand(0);
354   else
355     return nullptr;
356 
357   // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1)
358   Constant *ShiftSumC = ConstantInt::get(Ty, *C0 + *C1);
359   Value *NewShift1 = Builder.CreateBinOp(ShiftOpcode, X, ShiftSumC);
360   Value *NewShift2 = Builder.CreateBinOp(ShiftOpcode, Y, I.getOperand(1));
361   return BinaryOperator::Create(LogicInst->getOpcode(), NewShift1, NewShift2);
362 }
363 
364 Instruction *InstCombinerImpl::commonShiftTransforms(BinaryOperator &I) {
365   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
366   assert(Op0->getType() == Op1->getType());
367 
368   // If the shift amount is a one-use `sext`, we can demote it to `zext`.
369   Value *Y;
370   if (match(Op1, m_OneUse(m_SExt(m_Value(Y))))) {
371     Value *NewExt = Builder.CreateZExt(Y, I.getType(), Op1->getName());
372     return BinaryOperator::Create(I.getOpcode(), Op0, NewExt);
373   }
374 
375   // See if we can fold away this shift.
376   if (SimplifyDemandedInstructionBits(I))
377     return &I;
378 
379   // Try to fold constant and into select arguments.
380   if (isa<Constant>(Op0))
381     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
382       if (Instruction *R = FoldOpIntoSelect(I, SI))
383         return R;
384 
385   if (Constant *CUI = dyn_cast<Constant>(Op1))
386     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
387       return Res;
388 
389   if (auto *NewShift = cast_or_null<Instruction>(
390           reassociateShiftAmtsOfTwoSameDirectionShifts(&I, SQ)))
391     return NewShift;
392 
393   // (C1 shift (A add C2)) -> (C1 shift C2) shift A)
394   // iff A and C2 are both positive.
395   Value *A;
396   Constant *C;
397   if (match(Op0, m_Constant()) && match(Op1, m_Add(m_Value(A), m_Constant(C))))
398     if (isKnownNonNegative(A, DL, 0, &AC, &I, &DT) &&
399         isKnownNonNegative(C, DL, 0, &AC, &I, &DT))
400       return BinaryOperator::Create(
401           I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), Op0, C), A);
402 
403   // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
404   // Because shifts by negative values (which could occur if A were negative)
405   // are undefined.
406   const APInt *B;
407   if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
408     // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
409     // demand the sign bit (and many others) here??
410     Value *Rem = Builder.CreateAnd(A, ConstantInt::get(I.getType(), *B - 1),
411                                    Op1->getName());
412     return replaceOperand(I, 1, Rem);
413   }
414 
415   if (Instruction *Logic = foldShiftOfShiftedLogic(I, Builder))
416     return Logic;
417 
418   return nullptr;
419 }
420 
421 /// Return true if we can simplify two logical (either left or right) shifts
422 /// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
423 static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
424                                     Instruction *InnerShift,
425                                     InstCombinerImpl &IC, Instruction *CxtI) {
426   assert(InnerShift->isLogicalShift() && "Unexpected instruction type");
427 
428   // We need constant scalar or constant splat shifts.
429   const APInt *InnerShiftConst;
430   if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst)))
431     return false;
432 
433   // Two logical shifts in the same direction:
434   // shl (shl X, C1), C2 -->  shl X, C1 + C2
435   // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
436   bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
437   if (IsInnerShl == IsOuterShl)
438     return true;
439 
440   // Equal shift amounts in opposite directions become bitwise 'and':
441   // lshr (shl X, C), C --> and X, C'
442   // shl (lshr X, C), C --> and X, C'
443   if (*InnerShiftConst == OuterShAmt)
444     return true;
445 
446   // If the 2nd shift is bigger than the 1st, we can fold:
447   // lshr (shl X, C1), C2 -->  and (shl X, C1 - C2), C3
448   // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
449   // but it isn't profitable unless we know the and'd out bits are already zero.
450   // Also, check that the inner shift is valid (less than the type width) or
451   // we'll crash trying to produce the bit mask for the 'and'.
452   unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
453   if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) {
454     unsigned InnerShAmt = InnerShiftConst->getZExtValue();
455     unsigned MaskShift =
456         IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
457     APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift;
458     if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI))
459       return true;
460   }
461 
462   return false;
463 }
464 
465 /// See if we can compute the specified value, but shifted logically to the left
466 /// or right by some number of bits. This should return true if the expression
467 /// can be computed for the same cost as the current expression tree. This is
468 /// used to eliminate extraneous shifting from things like:
469 ///      %C = shl i128 %A, 64
470 ///      %D = shl i128 %B, 96
471 ///      %E = or i128 %C, %D
472 ///      %F = lshr i128 %E, 64
473 /// where the client will ask if E can be computed shifted right by 64-bits. If
474 /// this succeeds, getShiftedValue() will be called to produce the value.
475 static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
476                                InstCombinerImpl &IC, Instruction *CxtI) {
477   // We can always evaluate constants shifted.
478   if (isa<Constant>(V))
479     return true;
480 
481   Instruction *I = dyn_cast<Instruction>(V);
482   if (!I) return false;
483 
484   // If this is the opposite shift, we can directly reuse the input of the shift
485   // if the needed bits are already zero in the input.  This allows us to reuse
486   // the value which means that we don't care if the shift has multiple uses.
487   //  TODO:  Handle opposite shift by exact value.
488   ConstantInt *CI = nullptr;
489   if ((IsLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
490       (!IsLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
491     if (CI->getValue() == NumBits) {
492       // TODO: Check that the input bits are already zero with MaskedValueIsZero
493 #if 0
494       // If this is a truncate of a logical shr, we can truncate it to a smaller
495       // lshr iff we know that the bits we would otherwise be shifting in are
496       // already zeros.
497       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
498       uint32_t BitWidth = Ty->getScalarSizeInBits();
499       if (MaskedValueIsZero(I->getOperand(0),
500             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
501           CI->getLimitedValue(BitWidth) < BitWidth) {
502         return CanEvaluateTruncated(I->getOperand(0), Ty);
503       }
504 #endif
505 
506     }
507   }
508 
509   // We can't mutate something that has multiple uses: doing so would
510   // require duplicating the instruction in general, which isn't profitable.
511   if (!I->hasOneUse()) return false;
512 
513   switch (I->getOpcode()) {
514   default: return false;
515   case Instruction::And:
516   case Instruction::Or:
517   case Instruction::Xor:
518     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
519     return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
520            canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
521 
522   case Instruction::Shl:
523   case Instruction::LShr:
524     return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
525 
526   case Instruction::Select: {
527     SelectInst *SI = cast<SelectInst>(I);
528     Value *TrueVal = SI->getTrueValue();
529     Value *FalseVal = SI->getFalseValue();
530     return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
531            canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
532   }
533   case Instruction::PHI: {
534     // We can change a phi if we can change all operands.  Note that we never
535     // get into trouble with cyclic PHIs here because we only consider
536     // instructions with a single use.
537     PHINode *PN = cast<PHINode>(I);
538     for (Value *IncValue : PN->incoming_values())
539       if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
540         return false;
541     return true;
542   }
543   }
544 }
545 
546 /// Fold OuterShift (InnerShift X, C1), C2.
547 /// See canEvaluateShiftedShift() for the constraints on these instructions.
548 static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
549                                bool IsOuterShl,
550                                InstCombiner::BuilderTy &Builder) {
551   bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
552   Type *ShType = InnerShift->getType();
553   unsigned TypeWidth = ShType->getScalarSizeInBits();
554 
555   // We only accept shifts-by-a-constant in canEvaluateShifted().
556   const APInt *C1;
557   match(InnerShift->getOperand(1), m_APInt(C1));
558   unsigned InnerShAmt = C1->getZExtValue();
559 
560   // Change the shift amount and clear the appropriate IR flags.
561   auto NewInnerShift = [&](unsigned ShAmt) {
562     InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
563     if (IsInnerShl) {
564       InnerShift->setHasNoUnsignedWrap(false);
565       InnerShift->setHasNoSignedWrap(false);
566     } else {
567       InnerShift->setIsExact(false);
568     }
569     return InnerShift;
570   };
571 
572   // Two logical shifts in the same direction:
573   // shl (shl X, C1), C2 -->  shl X, C1 + C2
574   // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
575   if (IsInnerShl == IsOuterShl) {
576     // If this is an oversized composite shift, then unsigned shifts get 0.
577     if (InnerShAmt + OuterShAmt >= TypeWidth)
578       return Constant::getNullValue(ShType);
579 
580     return NewInnerShift(InnerShAmt + OuterShAmt);
581   }
582 
583   // Equal shift amounts in opposite directions become bitwise 'and':
584   // lshr (shl X, C), C --> and X, C'
585   // shl (lshr X, C), C --> and X, C'
586   if (InnerShAmt == OuterShAmt) {
587     APInt Mask = IsInnerShl
588                      ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
589                      : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
590     Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
591                                    ConstantInt::get(ShType, Mask));
592     if (auto *AndI = dyn_cast<Instruction>(And)) {
593       AndI->moveBefore(InnerShift);
594       AndI->takeName(InnerShift);
595     }
596     return And;
597   }
598 
599   assert(InnerShAmt > OuterShAmt &&
600          "Unexpected opposite direction logical shift pair");
601 
602   // In general, we would need an 'and' for this transform, but
603   // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
604   // lshr (shl X, C1), C2 -->  shl X, C1 - C2
605   // shl (lshr X, C1), C2 --> lshr X, C1 - C2
606   return NewInnerShift(InnerShAmt - OuterShAmt);
607 }
608 
609 /// When canEvaluateShifted() returns true for an expression, this function
610 /// inserts the new computation that produces the shifted value.
611 static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
612                               InstCombinerImpl &IC, const DataLayout &DL) {
613   // We can always evaluate constants shifted.
614   if (Constant *C = dyn_cast<Constant>(V)) {
615     if (isLeftShift)
616       return IC.Builder.CreateShl(C, NumBits);
617     else
618       return IC.Builder.CreateLShr(C, NumBits);
619   }
620 
621   Instruction *I = cast<Instruction>(V);
622   IC.addToWorklist(I);
623 
624   switch (I->getOpcode()) {
625   default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
626   case Instruction::And:
627   case Instruction::Or:
628   case Instruction::Xor:
629     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
630     I->setOperand(
631         0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
632     I->setOperand(
633         1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
634     return I;
635 
636   case Instruction::Shl:
637   case Instruction::LShr:
638     return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
639                             IC.Builder);
640 
641   case Instruction::Select:
642     I->setOperand(
643         1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
644     I->setOperand(
645         2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
646     return I;
647   case Instruction::PHI: {
648     // We can change a phi if we can change all operands.  Note that we never
649     // get into trouble with cyclic PHIs here because we only consider
650     // instructions with a single use.
651     PHINode *PN = cast<PHINode>(I);
652     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
653       PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits,
654                                               isLeftShift, IC, DL));
655     return PN;
656   }
657   }
658 }
659 
660 // If this is a bitwise operator or add with a constant RHS we might be able
661 // to pull it through a shift.
662 static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift,
663                                          BinaryOperator *BO) {
664   switch (BO->getOpcode()) {
665   default:
666     return false; // Do not perform transform!
667   case Instruction::Add:
668     return Shift.getOpcode() == Instruction::Shl;
669   case Instruction::Or:
670   case Instruction::And:
671     return true;
672   case Instruction::Xor:
673     // Do not change a 'not' of logical shift because that would create a normal
674     // 'xor'. The 'not' is likely better for analysis, SCEV, and codegen.
675     return !(Shift.isLogicalShift() && match(BO, m_Not(m_Value())));
676   }
677 }
678 
679 Instruction *InstCombinerImpl::FoldShiftByConstant(Value *Op0, Constant *Op1,
680                                                    BinaryOperator &I) {
681   bool isLeftShift = I.getOpcode() == Instruction::Shl;
682 
683   const APInt *Op1C;
684   if (!match(Op1, m_APInt(Op1C)))
685     return nullptr;
686 
687   // See if we can propagate this shift into the input, this covers the trivial
688   // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
689   if (I.getOpcode() != Instruction::AShr &&
690       canEvaluateShifted(Op0, Op1C->getZExtValue(), isLeftShift, *this, &I)) {
691     LLVM_DEBUG(
692         dbgs() << "ICE: GetShiftedValue propagating shift through expression"
693                   " to eliminate shift:\n  IN: "
694                << *Op0 << "\n  SH: " << I << "\n");
695 
696     return replaceInstUsesWith(
697         I, getShiftedValue(Op0, Op1C->getZExtValue(), isLeftShift, *this, DL));
698   }
699 
700   // See if we can simplify any instructions used by the instruction whose sole
701   // purpose is to compute bits we don't care about.
702   unsigned TypeBits = Op0->getType()->getScalarSizeInBits();
703 
704   assert(!Op1C->uge(TypeBits) &&
705          "Shift over the type width should have been removed already");
706 
707   if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
708     return FoldedShift;
709 
710   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
711   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
712     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
713     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
714     // place.  Don't try to do this transformation in this case.  Also, we
715     // require that the input operand is a shift-by-constant so that we have
716     // confidence that the shifts will get folded together.  We could do this
717     // xform in more cases, but it is unlikely to be profitable.
718     if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
719         isa<ConstantInt>(TrOp->getOperand(1))) {
720       // Okay, we'll do this xform.  Make the shift of shift.
721       Constant *ShAmt =
722           ConstantExpr::getZExt(cast<Constant>(Op1), TrOp->getType());
723       // (shift2 (shift1 & 0x00FF), c2)
724       Value *NSh = Builder.CreateBinOp(I.getOpcode(), TrOp, ShAmt, I.getName());
725 
726       // For logical shifts, the truncation has the effect of making the high
727       // part of the register be zeros.  Emulate this by inserting an AND to
728       // clear the top bits as needed.  This 'and' will usually be zapped by
729       // other xforms later if dead.
730       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
731       unsigned DstSize = TI->getType()->getScalarSizeInBits();
732       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
733 
734       // The mask we constructed says what the trunc would do if occurring
735       // between the shifts.  We want to know the effect *after* the second
736       // shift.  We know that it is a logical shift by a constant, so adjust the
737       // mask as appropriate.
738       if (I.getOpcode() == Instruction::Shl)
739         MaskV <<= Op1C->getZExtValue();
740       else {
741         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
742         MaskV.lshrInPlace(Op1C->getZExtValue());
743       }
744 
745       // shift1 & 0x00FF
746       Value *And = Builder.CreateAnd(NSh,
747                                      ConstantInt::get(I.getContext(), MaskV),
748                                      TI->getName());
749 
750       // Return the value truncated to the interesting size.
751       return new TruncInst(And, I.getType());
752     }
753   }
754 
755   if (Op0->hasOneUse()) {
756     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
757       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
758       Value *V1, *V2;
759       ConstantInt *CC;
760       switch (Op0BO->getOpcode()) {
761       default: break;
762       case Instruction::Add:
763       case Instruction::And:
764       case Instruction::Or:
765       case Instruction::Xor: {
766         // These operators commute.
767         // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
768         if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
769             match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
770                   m_Specific(Op1)))) {
771           Value *YS =         // (Y << C)
772             Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
773           // (X + (Y << C))
774           Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), YS, V1,
775                                          Op0BO->getOperand(1)->getName());
776           unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
777 
778           APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
779           Constant *Mask = ConstantInt::get(I.getContext(), Bits);
780           if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
781             Mask = ConstantVector::getSplat(VT->getElementCount(), Mask);
782           return BinaryOperator::CreateAnd(X, Mask);
783         }
784 
785         // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
786         Value *Op0BOOp1 = Op0BO->getOperand(1);
787         if (isLeftShift && Op0BOOp1->hasOneUse() &&
788             match(Op0BOOp1,
789                   m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
790                         m_ConstantInt(CC)))) {
791           Value *YS =   // (Y << C)
792             Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
793           // X & (CC << C)
794           Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
795                                         V1->getName()+".mask");
796           return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
797         }
798         LLVM_FALLTHROUGH;
799       }
800 
801       case Instruction::Sub: {
802         // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
803         if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
804             match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
805                   m_Specific(Op1)))) {
806           Value *YS =  // (Y << C)
807             Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
808           // (X + (Y << C))
809           Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), V1, YS,
810                                          Op0BO->getOperand(0)->getName());
811           unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
812 
813           APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
814           Constant *Mask = ConstantInt::get(I.getContext(), Bits);
815           if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
816             Mask = ConstantVector::getSplat(VT->getElementCount(), Mask);
817           return BinaryOperator::CreateAnd(X, Mask);
818         }
819 
820         // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
821         if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
822             match(Op0BO->getOperand(0),
823                   m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
824                         m_ConstantInt(CC))) && V2 == Op1) {
825           Value *YS = // (Y << C)
826             Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
827           // X & (CC << C)
828           Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
829                                         V1->getName()+".mask");
830 
831           return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
832         }
833 
834         break;
835       }
836       }
837 
838 
839       // If the operand is a bitwise operator with a constant RHS, and the
840       // shift is the only use, we can pull it out of the shift.
841       const APInt *Op0C;
842       if (match(Op0BO->getOperand(1), m_APInt(Op0C))) {
843         if (canShiftBinOpWithConstantRHS(I, Op0BO)) {
844           Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
845                                      cast<Constant>(Op0BO->getOperand(1)), Op1);
846 
847           Value *NewShift =
848             Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
849           NewShift->takeName(Op0BO);
850 
851           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
852                                         NewRHS);
853         }
854       }
855 
856       // If the operand is a subtract with a constant LHS, and the shift
857       // is the only use, we can pull it out of the shift.
858       // This folds (shl (sub C1, X), C2) -> (sub (C1 << C2), (shl X, C2))
859       if (isLeftShift && Op0BO->getOpcode() == Instruction::Sub &&
860           match(Op0BO->getOperand(0), m_APInt(Op0C))) {
861         Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
862                                    cast<Constant>(Op0BO->getOperand(0)), Op1);
863 
864         Value *NewShift = Builder.CreateShl(Op0BO->getOperand(1), Op1);
865         NewShift->takeName(Op0BO);
866 
867         return BinaryOperator::CreateSub(NewRHS, NewShift);
868       }
869     }
870 
871     // If we have a select that conditionally executes some binary operator,
872     // see if we can pull it the select and operator through the shift.
873     //
874     // For example, turning:
875     //   shl (select C, (add X, C1), X), C2
876     // Into:
877     //   Y = shl X, C2
878     //   select C, (add Y, C1 << C2), Y
879     Value *Cond;
880     BinaryOperator *TBO;
881     Value *FalseVal;
882     if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)),
883                             m_Value(FalseVal)))) {
884       const APInt *C;
885       if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal &&
886           match(TBO->getOperand(1), m_APInt(C)) &&
887           canShiftBinOpWithConstantRHS(I, TBO)) {
888         Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
889                                        cast<Constant>(TBO->getOperand(1)), Op1);
890 
891         Value *NewShift =
892           Builder.CreateBinOp(I.getOpcode(), FalseVal, Op1);
893         Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift,
894                                            NewRHS);
895         return SelectInst::Create(Cond, NewOp, NewShift);
896       }
897     }
898 
899     BinaryOperator *FBO;
900     Value *TrueVal;
901     if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal),
902                             m_OneUse(m_BinOp(FBO))))) {
903       const APInt *C;
904       if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal &&
905           match(FBO->getOperand(1), m_APInt(C)) &&
906           canShiftBinOpWithConstantRHS(I, FBO)) {
907         Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
908                                        cast<Constant>(FBO->getOperand(1)), Op1);
909 
910         Value *NewShift =
911           Builder.CreateBinOp(I.getOpcode(), TrueVal, Op1);
912         Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift,
913                                            NewRHS);
914         return SelectInst::Create(Cond, NewShift, NewOp);
915       }
916     }
917   }
918 
919   return nullptr;
920 }
921 
922 Instruction *InstCombinerImpl::visitShl(BinaryOperator &I) {
923   const SimplifyQuery Q = SQ.getWithInstruction(&I);
924 
925   if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
926                                  I.hasNoSignedWrap(), I.hasNoUnsignedWrap(), Q))
927     return replaceInstUsesWith(I, V);
928 
929   if (Instruction *X = foldVectorBinop(I))
930     return X;
931 
932   if (Instruction *V = commonShiftTransforms(I))
933     return V;
934 
935   if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(&I, Q, Builder))
936     return V;
937 
938   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
939   Type *Ty = I.getType();
940   unsigned BitWidth = Ty->getScalarSizeInBits();
941 
942   const APInt *ShAmtAPInt;
943   if (match(Op1, m_APInt(ShAmtAPInt))) {
944     unsigned ShAmt = ShAmtAPInt->getZExtValue();
945 
946     // shl (zext X), ShAmt --> zext (shl X, ShAmt)
947     // This is only valid if X would have zeros shifted out.
948     Value *X;
949     if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
950       unsigned SrcWidth = X->getType()->getScalarSizeInBits();
951       if (ShAmt < SrcWidth &&
952           MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmt), 0, &I))
953         return new ZExtInst(Builder.CreateShl(X, ShAmt), Ty);
954     }
955 
956     // (X >> C) << C --> X & (-1 << C)
957     if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) {
958       APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt));
959       return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
960     }
961 
962     // FIXME: we do not yet transform non-exact shr's. The backend (DAGCombine)
963     // needs a few fixes for the rotate pattern recognition first.
964     const APInt *ShOp1;
965     if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(ShOp1))))) {
966       unsigned ShrAmt = ShOp1->getZExtValue();
967       if (ShrAmt < ShAmt) {
968         // If C1 < C2: (X >>?,exact C1) << C2 --> X << (C2 - C1)
969         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShrAmt);
970         auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
971         NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
972         NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
973         return NewShl;
974       }
975       if (ShrAmt > ShAmt) {
976         // If C1 > C2: (X >>?exact C1) << C2 --> X >>?exact (C1 - C2)
977         Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmt);
978         auto *NewShr = BinaryOperator::Create(
979             cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff);
980         NewShr->setIsExact(true);
981         return NewShr;
982       }
983     }
984 
985     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1)))) {
986       unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
987       // Oversized shifts are simplified to zero in InstSimplify.
988       if (AmtSum < BitWidth)
989         // (X << C1) << C2 --> X << (C1 + C2)
990         return BinaryOperator::CreateShl(X, ConstantInt::get(Ty, AmtSum));
991     }
992 
993     // If the shifted-out value is known-zero, then this is a NUW shift.
994     if (!I.hasNoUnsignedWrap() &&
995         MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, ShAmt), 0, &I)) {
996       I.setHasNoUnsignedWrap();
997       return &I;
998     }
999 
1000     // If the shifted-out value is all signbits, then this is a NSW shift.
1001     if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmt) {
1002       I.setHasNoSignedWrap();
1003       return &I;
1004     }
1005   }
1006 
1007   // Transform  (x >> y) << y  to  x & (-1 << y)
1008   // Valid for any type of right-shift.
1009   Value *X;
1010   if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
1011     Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
1012     Value *Mask = Builder.CreateShl(AllOnes, Op1);
1013     return BinaryOperator::CreateAnd(Mask, X);
1014   }
1015 
1016   Constant *C1;
1017   if (match(Op1, m_Constant(C1))) {
1018     Constant *C2;
1019     Value *X;
1020     // (C2 << X) << C1 --> (C2 << C1) << X
1021     if (match(Op0, m_OneUse(m_Shl(m_Constant(C2), m_Value(X)))))
1022       return BinaryOperator::CreateShl(ConstantExpr::getShl(C2, C1), X);
1023 
1024     // (X * C2) << C1 --> X * (C2 << C1)
1025     if (match(Op0, m_Mul(m_Value(X), m_Constant(C2))))
1026       return BinaryOperator::CreateMul(X, ConstantExpr::getShl(C2, C1));
1027 
1028     // shl (zext i1 X), C1 --> select (X, 1 << C1, 0)
1029     if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1030       auto *NewC = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C1);
1031       return SelectInst::Create(X, NewC, ConstantInt::getNullValue(Ty));
1032     }
1033   }
1034 
1035   // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
1036   if (match(Op0, m_One()) &&
1037       match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X))))
1038     return BinaryOperator::CreateLShr(
1039         ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X);
1040 
1041   return nullptr;
1042 }
1043 
1044 Instruction *InstCombinerImpl::visitLShr(BinaryOperator &I) {
1045   if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1046                                   SQ.getWithInstruction(&I)))
1047     return replaceInstUsesWith(I, V);
1048 
1049   if (Instruction *X = foldVectorBinop(I))
1050     return X;
1051 
1052   if (Instruction *R = commonShiftTransforms(I))
1053     return R;
1054 
1055   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1056   Type *Ty = I.getType();
1057   const APInt *ShAmtAPInt;
1058   if (match(Op1, m_APInt(ShAmtAPInt))) {
1059     unsigned ShAmt = ShAmtAPInt->getZExtValue();
1060     unsigned BitWidth = Ty->getScalarSizeInBits();
1061     auto *II = dyn_cast<IntrinsicInst>(Op0);
1062     if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt &&
1063         (II->getIntrinsicID() == Intrinsic::ctlz ||
1064          II->getIntrinsicID() == Intrinsic::cttz ||
1065          II->getIntrinsicID() == Intrinsic::ctpop)) {
1066       // ctlz.i32(x)>>5  --> zext(x == 0)
1067       // cttz.i32(x)>>5  --> zext(x == 0)
1068       // ctpop.i32(x)>>5 --> zext(x == -1)
1069       bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
1070       Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
1071       Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS);
1072       return new ZExtInst(Cmp, Ty);
1073     }
1074 
1075     Value *X;
1076     const APInt *ShOp1;
1077     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1))) && ShOp1->ult(BitWidth)) {
1078       if (ShOp1->ult(ShAmt)) {
1079         unsigned ShlAmt = ShOp1->getZExtValue();
1080         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1081         if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1082           // (X <<nuw C1) >>u C2 --> X >>u (C2 - C1)
1083           auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
1084           NewLShr->setIsExact(I.isExact());
1085           return NewLShr;
1086         }
1087         // (X << C1) >>u C2  --> (X >>u (C2 - C1)) & (-1 >> C2)
1088         Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact());
1089         APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
1090         return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
1091       }
1092       if (ShOp1->ugt(ShAmt)) {
1093         unsigned ShlAmt = ShOp1->getZExtValue();
1094         Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1095         if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1096           // (X <<nuw C1) >>u C2 --> X <<nuw (C1 - C2)
1097           auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
1098           NewShl->setHasNoUnsignedWrap(true);
1099           return NewShl;
1100         }
1101         // (X << C1) >>u C2  --> X << (C1 - C2) & (-1 >> C2)
1102         Value *NewShl = Builder.CreateShl(X, ShiftDiff);
1103         APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
1104         return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
1105       }
1106       assert(*ShOp1 == ShAmt);
1107       // (X << C) >>u C --> X & (-1 >>u C)
1108       APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
1109       return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
1110     }
1111 
1112     if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) &&
1113         (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
1114       assert(ShAmt < X->getType()->getScalarSizeInBits() &&
1115              "Big shift not simplified to zero?");
1116       // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
1117       Value *NewLShr = Builder.CreateLShr(X, ShAmt);
1118       return new ZExtInst(NewLShr, Ty);
1119     }
1120 
1121     if (match(Op0, m_SExt(m_Value(X))) &&
1122         (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
1123       // Are we moving the sign bit to the low bit and widening with high zeros?
1124       unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
1125       if (ShAmt == BitWidth - 1) {
1126         // lshr (sext i1 X to iN), N-1 --> zext X to iN
1127         if (SrcTyBitWidth == 1)
1128           return new ZExtInst(X, Ty);
1129 
1130         // lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
1131         if (Op0->hasOneUse()) {
1132           Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1);
1133           return new ZExtInst(NewLShr, Ty);
1134         }
1135       }
1136 
1137       // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
1138       if (ShAmt == BitWidth - SrcTyBitWidth && Op0->hasOneUse()) {
1139         // The new shift amount can't be more than the narrow source type.
1140         unsigned NewShAmt = std::min(ShAmt, SrcTyBitWidth - 1);
1141         Value *AShr = Builder.CreateAShr(X, NewShAmt);
1142         return new ZExtInst(AShr, Ty);
1143       }
1144     }
1145 
1146     if (match(Op0, m_LShr(m_Value(X), m_APInt(ShOp1)))) {
1147       unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1148       // Oversized shifts are simplified to zero in InstSimplify.
1149       if (AmtSum < BitWidth)
1150         // (X >>u C1) >>u C2 --> X >>u (C1 + C2)
1151         return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
1152     }
1153 
1154     // If the shifted-out value is known-zero, then this is an exact shift.
1155     if (!I.isExact() &&
1156         MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
1157       I.setIsExact();
1158       return &I;
1159     }
1160   }
1161 
1162   // Transform  (x << y) >> y  to  x & (-1 >> y)
1163   Value *X;
1164   if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
1165     Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
1166     Value *Mask = Builder.CreateLShr(AllOnes, Op1);
1167     return BinaryOperator::CreateAnd(Mask, X);
1168   }
1169 
1170   return nullptr;
1171 }
1172 
1173 Instruction *
1174 InstCombinerImpl::foldVariableSignZeroExtensionOfVariableHighBitExtract(
1175     BinaryOperator &OldAShr) {
1176   assert(OldAShr.getOpcode() == Instruction::AShr &&
1177          "Must be called with arithmetic right-shift instruction only.");
1178 
1179   // Check that constant C is a splat of the element-wise bitwidth of V.
1180   auto BitWidthSplat = [](Constant *C, Value *V) {
1181     return match(
1182         C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1183                               APInt(C->getType()->getScalarSizeInBits(),
1184                                     V->getType()->getScalarSizeInBits())));
1185   };
1186 
1187   // It should look like variable-length sign-extension on the outside:
1188   //   (Val << (bitwidth(Val)-Nbits)) a>> (bitwidth(Val)-Nbits)
1189   Value *NBits;
1190   Instruction *MaybeTrunc;
1191   Constant *C1, *C2;
1192   if (!match(&OldAShr,
1193              m_AShr(m_Shl(m_Instruction(MaybeTrunc),
1194                           m_ZExtOrSelf(m_Sub(m_Constant(C1),
1195                                              m_ZExtOrSelf(m_Value(NBits))))),
1196                     m_ZExtOrSelf(m_Sub(m_Constant(C2),
1197                                        m_ZExtOrSelf(m_Deferred(NBits)))))) ||
1198       !BitWidthSplat(C1, &OldAShr) || !BitWidthSplat(C2, &OldAShr))
1199     return nullptr;
1200 
1201   // There may or may not be a truncation after outer two shifts.
1202   Instruction *HighBitExtract;
1203   match(MaybeTrunc, m_TruncOrSelf(m_Instruction(HighBitExtract)));
1204   bool HadTrunc = MaybeTrunc != HighBitExtract;
1205 
1206   // And finally, the innermost part of the pattern must be a right-shift.
1207   Value *X, *NumLowBitsToSkip;
1208   if (!match(HighBitExtract, m_Shr(m_Value(X), m_Value(NumLowBitsToSkip))))
1209     return nullptr;
1210 
1211   // Said right-shift must extract high NBits bits - C0 must be it's bitwidth.
1212   Constant *C0;
1213   if (!match(NumLowBitsToSkip,
1214              m_ZExtOrSelf(
1215                  m_Sub(m_Constant(C0), m_ZExtOrSelf(m_Specific(NBits))))) ||
1216       !BitWidthSplat(C0, HighBitExtract))
1217     return nullptr;
1218 
1219   // Since the NBits is identical for all shifts, if the outermost and
1220   // innermost shifts are identical, then outermost shifts are redundant.
1221   // If we had truncation, do keep it though.
1222   if (HighBitExtract->getOpcode() == OldAShr.getOpcode())
1223     return replaceInstUsesWith(OldAShr, MaybeTrunc);
1224 
1225   // Else, if there was a truncation, then we need to ensure that one
1226   // instruction will go away.
1227   if (HadTrunc && !match(&OldAShr, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1228     return nullptr;
1229 
1230   // Finally, bypass two innermost shifts, and perform the outermost shift on
1231   // the operands of the innermost shift.
1232   Instruction *NewAShr =
1233       BinaryOperator::Create(OldAShr.getOpcode(), X, NumLowBitsToSkip);
1234   NewAShr->copyIRFlags(HighBitExtract); // We can preserve 'exact'-ness.
1235   if (!HadTrunc)
1236     return NewAShr;
1237 
1238   Builder.Insert(NewAShr);
1239   return TruncInst::CreateTruncOrBitCast(NewAShr, OldAShr.getType());
1240 }
1241 
1242 Instruction *InstCombinerImpl::visitAShr(BinaryOperator &I) {
1243   if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1244                                   SQ.getWithInstruction(&I)))
1245     return replaceInstUsesWith(I, V);
1246 
1247   if (Instruction *X = foldVectorBinop(I))
1248     return X;
1249 
1250   if (Instruction *R = commonShiftTransforms(I))
1251     return R;
1252 
1253   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1254   Type *Ty = I.getType();
1255   unsigned BitWidth = Ty->getScalarSizeInBits();
1256   const APInt *ShAmtAPInt;
1257   if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) {
1258     unsigned ShAmt = ShAmtAPInt->getZExtValue();
1259 
1260     // If the shift amount equals the difference in width of the destination
1261     // and source scalar types:
1262     // ashr (shl (zext X), C), C --> sext X
1263     Value *X;
1264     if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
1265         ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
1266       return new SExtInst(X, Ty);
1267 
1268     // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
1269     // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
1270     const APInt *ShOp1;
1271     if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) &&
1272         ShOp1->ult(BitWidth)) {
1273       unsigned ShlAmt = ShOp1->getZExtValue();
1274       if (ShlAmt < ShAmt) {
1275         // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
1276         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1277         auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff);
1278         NewAShr->setIsExact(I.isExact());
1279         return NewAShr;
1280       }
1281       if (ShlAmt > ShAmt) {
1282         // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
1283         Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1284         auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff);
1285         NewShl->setHasNoSignedWrap(true);
1286         return NewShl;
1287       }
1288     }
1289 
1290     if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) &&
1291         ShOp1->ult(BitWidth)) {
1292       unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1293       // Oversized arithmetic shifts replicate the sign bit.
1294       AmtSum = std::min(AmtSum, BitWidth - 1);
1295       // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
1296       return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
1297     }
1298 
1299     if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) &&
1300         (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) {
1301       // ashr (sext X), C --> sext (ashr X, C')
1302       Type *SrcTy = X->getType();
1303       ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1);
1304       Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt));
1305       return new SExtInst(NewSh, Ty);
1306     }
1307 
1308     // If the shifted-out value is known-zero, then this is an exact shift.
1309     if (!I.isExact() &&
1310         MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
1311       I.setIsExact();
1312       return &I;
1313     }
1314   }
1315 
1316   if (Instruction *R = foldVariableSignZeroExtensionOfVariableHighBitExtract(I))
1317     return R;
1318 
1319   // See if we can turn a signed shr into an unsigned shr.
1320   if (MaskedValueIsZero(Op0, APInt::getSignMask(BitWidth), 0, &I))
1321     return BinaryOperator::CreateLShr(Op0, Op1);
1322 
1323   return nullptr;
1324 }
1325