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