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