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

source code of llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp