LLVM 20.0.0git
InstCombineShifts.cpp
Go to the documentation of this file.
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"
18using namespace llvm;
19using namespace PatternMatch;
20
21#define DEBUG_TYPE "instcombine"
22
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 =
44 return MaximalRepresentableShiftAmount.uge(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.
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(Sh0,
65 m_Shift(m_Instruction(Sh0Op0), m_ZExtOrSelf(m_Value(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(Sh0Op0,
75 m_Instruction(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(Sh1, m_Shift(m_Value(X), m_ZExtOrSelf(m_Value(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(Sh0, m_Shr(m_Value(), m_Value())) &&
89 match(Sh1, m_Shr(m_Value(), 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(Sh0, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
106 return nullptr;
107
108 // Can we fold (ShAmt0+ShAmt1) ?
109 auto *NewShAmt = dyn_cast_or_null<Constant>(
110 simplifyAddInst(ShAmt0, ShAmt1, /*isNSW=*/false, /*isNUW=*/false,
111 SQ.getWithInstruction(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?
118 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(NewShAmt,
130 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(Instruction::ZExt, NewShAmt,
141 X->getType(), SQ.DL);
142 if (!NewShAmt)
143 return nullptr;
144 }
145
146 // All good, we can do this fold.
147 BinaryOperator *NewShift = BinaryOperator::Create(ShiftOpcode, X, 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(NewShift);
166 Ret = CastInst::Create(Instruction::Trunc, NewShift, 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 *
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(OuterShift,
197 m_Shift(m_Value(Masked), m_ZExtOrSelf(m_Value(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;
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(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes());
218 // (~(-1 << maskNbits))
219 auto MaskB = m_Not(m_Shl(m_AllOnes(), m_Value(MaskShAmt)));
220 // (-1 l>> MaskShAmt)
221 auto MaskC = m_LShr(m_AllOnes(), m_Value(MaskShAmt));
222 // ((-1 << MaskShAmt) l>> MaskShAmt)
223 auto MaskD =
224 m_LShr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt));
225
226 Value *X;
227 Constant *NewMask;
228
229 if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) {
230 // Peek through an optional zext of the shift amount.
231 match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
232
233 // Verify that it would be safe to try to add those two shift amounts.
234 if (!canTryToConstantAddTwoShiftAmounts(OuterShift, ShiftShAmt, Masked,
235 MaskShAmt))
236 return nullptr;
237
238 // Can we simplify (MaskShAmt+ShiftShAmt) ?
239 auto *SumOfShAmts = dyn_cast_or_null<Constant>(simplifyAddInst(
240 MaskShAmt, 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 SumOfShAmts, ConstantInt::get(SumOfShAmts->getType()->getScalarType(),
252 ExtendedTy->getScalarSizeInBits()));
253 auto *ExtendedSumOfShAmts = ConstantFoldCastOperand(
254 Instruction::ZExt, SumOfShAmts, ExtendedTy, Q.DL);
255 if (!ExtendedSumOfShAmts)
256 return nullptr;
257
258 // And compute the mask as usual: ~(-1 << (SumOfShAmts))
259 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
260 Constant *ExtendedInvertedMask = ConstantFoldBinaryOpOperands(
261 Instruction::Shl, ExtendedAllOnes, ExtendedSumOfShAmts, Q.DL);
262 if (!ExtendedInvertedMask)
263 return nullptr;
264
265 NewMask = ConstantExpr::getNot(ExtendedInvertedMask);
266 } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) ||
267 match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)),
268 m_Deferred(MaskShAmt)))) {
269 // Peek through an optional zext of the shift amount.
270 match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
271
272 // Verify that it would be safe to try to add those two shift amounts.
273 if (!canTryToConstantAddTwoShiftAmounts(OuterShift, ShiftShAmt, Masked,
274 MaskShAmt))
275 return nullptr;
276
277 // Can we simplify (ShiftShAmt-MaskShAmt) ?
278 auto *ShAmtsDiff = dyn_cast_or_null<Constant>(simplifySubInst(
279 ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
280 if (!ShAmtsDiff)
281 return nullptr; // Did not simplify.
282 // In this pattern ShAmtsDiff correlates with the number of high bits that
283 // shall be unset in the root value (OuterShift).
284
285 // An extend of an undef value becomes zero because the high bits are never
286 // completely unknown. Replace the `undef` shift amounts with negated
287 // bitwidth of innermost shift to ensure that the value remains undef when
288 // creating the subsequent shift op.
289 unsigned WidestTyBitWidth = WidestTy->getScalarSizeInBits();
290 ShAmtsDiff = Constant::replaceUndefsWith(
291 ShAmtsDiff, ConstantInt::get(ShAmtsDiff->getType()->getScalarType(),
292 -WidestTyBitWidth));
293 auto *ExtendedNumHighBitsToClear = ConstantFoldCastOperand(
294 Instruction::ZExt,
295 ConstantExpr::getSub(ConstantInt::get(ShAmtsDiff->getType(),
296 WidestTyBitWidth,
297 /*isSigned=*/false),
298 ShAmtsDiff),
299 ExtendedTy, Q.DL);
300 if (!ExtendedNumHighBitsToClear)
301 return nullptr;
302
303 // And compute the mask as usual: (-1 l>> (NumHighBitsToClear))
304 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
305 NewMask = ConstantFoldBinaryOpOperands(Instruction::LShr, ExtendedAllOnes,
306 ExtendedNumHighBitsToClear, Q.DL);
307 if (!NewMask)
308 return nullptr;
309 } else
310 return nullptr; // Don't know anything about this pattern.
311
312 NewMask = ConstantExpr::getTrunc(NewMask, NarrowestTy);
313
314 // Does this mask has any unset bits? If not then we can just not apply it.
315 bool NeedMask = !match(NewMask, m_AllOnes());
316
317 // If we need to apply a mask, there are several more restrictions we have.
318 if (NeedMask) {
319 // The old masking instruction must go away.
320 if (!Masked->hasOneUse())
321 return nullptr;
322 // The original "masking" instruction must not have been`ashr`.
323 if (match(Masked, m_AShr(m_Value(), m_Value())))
324 return nullptr;
325 }
326
327 // If we need to apply truncation, let's do it first, since we can.
328 // We have already ensured that the old truncation will go away.
329 if (HadTrunc)
330 X = Builder.CreateTrunc(X, NarrowestTy);
331
332 // No 'NUW'/'NSW'! We no longer know that we won't shift-out non-0 bits.
333 // We didn't change the Type of this outermost shift, so we can just do it.
334 auto *NewShift = BinaryOperator::Create(OuterShift->getOpcode(), X,
335 OuterShift->getOperand(1));
336 if (!NeedMask)
337 return NewShift;
338
339 Builder.Insert(NewShift);
340 return BinaryOperator::Create(Instruction::And, NewShift, NewMask);
341}
342
343/// If we have a shift-by-constant of a bin op (bitwise logic op or add/sub w/
344/// shl) that itself has a shift-by-constant operand with identical opcode, we
345/// may be able to convert that into 2 independent shifts followed by the logic
346/// op. This eliminates a use of an intermediate value (reduces dependency
347/// chain).
349 InstCombiner::BuilderTy &Builder) {
350 assert(I.isShift() && "Expected a shift as input");
351 auto *BinInst = dyn_cast<BinaryOperator>(I.getOperand(0));
352 if (!BinInst ||
353 (!BinInst->isBitwiseLogicOp() &&
354 BinInst->getOpcode() != Instruction::Add &&
355 BinInst->getOpcode() != Instruction::Sub) ||
356 !BinInst->hasOneUse())
357 return nullptr;
358
359 Constant *C0, *C1;
360 if (!match(I.getOperand(1), m_Constant(C1)))
361 return nullptr;
362
363 Instruction::BinaryOps ShiftOpcode = I.getOpcode();
364 // Transform for add/sub only works with shl.
365 if ((BinInst->getOpcode() == Instruction::Add ||
366 BinInst->getOpcode() == Instruction::Sub) &&
367 ShiftOpcode != Instruction::Shl)
368 return nullptr;
369
370 Type *Ty = I.getType();
371
372 // Find a matching shift by constant. The fold is not valid if the sum
373 // of the shift values equals or exceeds bitwidth.
374 Value *X, *Y;
375 auto matchFirstShift = [&](Value *V, Value *W) {
376 unsigned Size = Ty->getScalarSizeInBits();
377 APInt Threshold(Size, Size);
378 return match(V, m_BinOp(ShiftOpcode, m_Value(X), m_Constant(C0))) &&
379 (V->hasOneUse() || match(W, m_ImmConstant())) &&
382 };
383
384 // Logic ops and Add are commutative, so check each operand for a match. Sub
385 // is not so we cannot reoder if we match operand(1) and need to keep the
386 // operands in their original positions.
387 bool FirstShiftIsOp1 = false;
388 if (matchFirstShift(BinInst->getOperand(0), BinInst->getOperand(1)))
389 Y = BinInst->getOperand(1);
390 else if (matchFirstShift(BinInst->getOperand(1), BinInst->getOperand(0))) {
391 Y = BinInst->getOperand(0);
392 FirstShiftIsOp1 = BinInst->getOpcode() == Instruction::Sub;
393 } else
394 return nullptr;
395
396 // shift (binop (shift X, C0), Y), C1 -> binop (shift X, C0+C1), (shift Y, C1)
397 Constant *ShiftSumC = ConstantExpr::getAdd(C0, C1);
398 Value *NewShift1 = Builder.CreateBinOp(ShiftOpcode, X, ShiftSumC);
399 Value *NewShift2 = Builder.CreateBinOp(ShiftOpcode, Y, C1);
400 Value *Op1 = FirstShiftIsOp1 ? NewShift2 : NewShift1;
401 Value *Op2 = FirstShiftIsOp1 ? NewShift1 : NewShift2;
402 return BinaryOperator::Create(BinInst->getOpcode(), Op1, Op2);
403}
404
407 return Phi;
408
409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
410 assert(Op0->getType() == Op1->getType());
411 Type *Ty = I.getType();
412
413 // If the shift amount is a one-use `sext`, we can demote it to `zext`.
414 Value *Y;
415 if (match(Op1, m_OneUse(m_SExt(m_Value(Y))))) {
416 Value *NewExt = Builder.CreateZExt(Y, Ty, Op1->getName());
417 return BinaryOperator::Create(I.getOpcode(), Op0, NewExt);
418 }
419
420 // See if we can fold away this shift.
422 return &I;
423
424 // Try to fold constant and into select arguments.
425 if (isa<Constant>(Op0))
426 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
427 if (Instruction *R = FoldOpIntoSelect(I, SI))
428 return R;
429
430 if (Constant *CUI = dyn_cast<Constant>(Op1))
431 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
432 return Res;
433
434 if (auto *NewShift = cast_or_null<Instruction>(
436 return NewShift;
437
438 // Pre-shift a constant shifted by a variable amount with constant offset:
439 // C shift (A add nuw C1) --> (C shift C1) shift A
440 Value *A;
441 Constant *C, *C1;
442 if (match(Op0, m_Constant(C)) &&
443 match(Op1, m_NUWAddLike(m_Value(A), m_Constant(C1)))) {
444 Value *NewC = Builder.CreateBinOp(I.getOpcode(), C, C1);
445 BinaryOperator *NewShiftOp = BinaryOperator::Create(I.getOpcode(), NewC, A);
446 if (I.getOpcode() == Instruction::Shl) {
447 NewShiftOp->setHasNoSignedWrap(I.hasNoSignedWrap());
448 NewShiftOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
449 } else {
450 NewShiftOp->setIsExact(I.isExact());
451 }
452 return NewShiftOp;
453 }
454
455 unsigned BitWidth = Ty->getScalarSizeInBits();
456
457 const APInt *AC, *AddC;
458 // Try to pre-shift a constant shifted by a variable amount added with a
459 // negative number:
460 // C << (X - AddC) --> (C >> AddC) << X
461 // and
462 // C >> (X - AddC) --> (C << AddC) >> X
463 if (match(Op0, m_APInt(AC)) && match(Op1, m_Add(m_Value(A), m_APInt(AddC))) &&
464 AddC->isNegative() && (-*AddC).ult(BitWidth)) {
465 assert(!AC->isZero() && "Expected simplify of shifted zero");
466 unsigned PosOffset = (-*AddC).getZExtValue();
467
468 auto isSuitableForPreShift = [PosOffset, &I, AC]() {
469 switch (I.getOpcode()) {
470 default:
471 return false;
472 case Instruction::Shl:
473 return (I.hasNoSignedWrap() || I.hasNoUnsignedWrap()) &&
474 AC->eq(AC->lshr(PosOffset).shl(PosOffset));
475 case Instruction::LShr:
476 return I.isExact() && AC->eq(AC->shl(PosOffset).lshr(PosOffset));
477 case Instruction::AShr:
478 return I.isExact() && AC->eq(AC->shl(PosOffset).ashr(PosOffset));
479 }
480 };
481 if (isSuitableForPreShift()) {
482 Constant *NewC = ConstantInt::get(Ty, I.getOpcode() == Instruction::Shl
483 ? AC->lshr(PosOffset)
484 : AC->shl(PosOffset));
485 BinaryOperator *NewShiftOp =
486 BinaryOperator::Create(I.getOpcode(), NewC, A);
487 if (I.getOpcode() == Instruction::Shl) {
488 NewShiftOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
489 } else {
490 NewShiftOp->setIsExact();
491 }
492 return NewShiftOp;
493 }
494 }
495
496 // X shift (A srem C) -> X shift (A and (C - 1)) iff C is a power of 2.
497 // Because shifts by negative values (which could occur if A were negative)
498 // are undefined.
499 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Constant(C))) &&
500 match(C, m_Power2())) {
501 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
502 // demand the sign bit (and many others) here??
503 Constant *Mask = ConstantExpr::getSub(C, ConstantInt::get(Ty, 1));
504 Value *Rem = Builder.CreateAnd(A, Mask, Op1->getName());
505 return replaceOperand(I, 1, Rem);
506 }
507
509 return Logic;
510
511 if (match(Op1, m_Or(m_Value(), m_SpecificInt(BitWidth - 1))))
512 return replaceOperand(I, 1, ConstantInt::get(Ty, BitWidth - 1));
513
514 Instruction *CmpIntr;
515 if ((I.getOpcode() == Instruction::LShr ||
516 I.getOpcode() == Instruction::AShr) &&
517 match(Op0, m_OneUse(m_Instruction(CmpIntr))) &&
518 isa<CmpIntrinsic>(CmpIntr) &&
519 match(Op1, m_SpecificInt(Ty->getScalarSizeInBits() - 1))) {
520 Value *Cmp =
521 Builder.CreateICmp(cast<CmpIntrinsic>(CmpIntr)->getLTPredicate(),
522 CmpIntr->getOperand(0), CmpIntr->getOperand(1));
523 return CastInst::Create(I.getOpcode() == Instruction::LShr
524 ? Instruction::ZExt
525 : Instruction::SExt,
526 Cmp, Ty);
527 }
528
529 return nullptr;
530}
531
532/// Return true if we can simplify two logical (either left or right) shifts
533/// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
534static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
535 Instruction *InnerShift,
536 InstCombinerImpl &IC, Instruction *CxtI) {
537 assert(InnerShift->isLogicalShift() && "Unexpected instruction type");
538
539 // We need constant scalar or constant splat shifts.
540 const APInt *InnerShiftConst;
541 if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst)))
542 return false;
543
544 // Two logical shifts in the same direction:
545 // shl (shl X, C1), C2 --> shl X, C1 + C2
546 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
547 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
548 if (IsInnerShl == IsOuterShl)
549 return true;
550
551 // Equal shift amounts in opposite directions become bitwise 'and':
552 // lshr (shl X, C), C --> and X, C'
553 // shl (lshr X, C), C --> and X, C'
554 if (*InnerShiftConst == OuterShAmt)
555 return true;
556
557 // If the 2nd shift is bigger than the 1st, we can fold:
558 // lshr (shl X, C1), C2 --> and (shl X, C1 - C2), C3
559 // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
560 // but it isn't profitable unless we know the and'd out bits are already zero.
561 // Also, check that the inner shift is valid (less than the type width) or
562 // we'll crash trying to produce the bit mask for the 'and'.
563 unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
564 if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) {
565 unsigned InnerShAmt = InnerShiftConst->getZExtValue();
566 unsigned MaskShift =
567 IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
568 APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift;
569 if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI))
570 return true;
571 }
572
573 return false;
574}
575
576/// See if we can compute the specified value, but shifted logically to the left
577/// or right by some number of bits. This should return true if the expression
578/// can be computed for the same cost as the current expression tree. This is
579/// used to eliminate extraneous shifting from things like:
580/// %C = shl i128 %A, 64
581/// %D = shl i128 %B, 96
582/// %E = or i128 %C, %D
583/// %F = lshr i128 %E, 64
584/// where the client will ask if E can be computed shifted right by 64-bits. If
585/// this succeeds, getShiftedValue() will be called to produce the value.
586static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
587 InstCombinerImpl &IC, Instruction *CxtI) {
588 // We can always evaluate immediate constants.
589 if (match(V, m_ImmConstant()))
590 return true;
591
592 Instruction *I = dyn_cast<Instruction>(V);
593 if (!I) return false;
594
595 // We can't mutate something that has multiple uses: doing so would
596 // require duplicating the instruction in general, which isn't profitable.
597 if (!I->hasOneUse()) return false;
598
599 switch (I->getOpcode()) {
600 default: return false;
601 case Instruction::And:
602 case Instruction::Or:
603 case Instruction::Xor:
604 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
605 return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
606 canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
607
608 case Instruction::Shl:
609 case Instruction::LShr:
610 return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
611
612 case Instruction::Select: {
613 SelectInst *SI = cast<SelectInst>(I);
614 Value *TrueVal = SI->getTrueValue();
615 Value *FalseVal = SI->getFalseValue();
616 return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
617 canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
618 }
619 case Instruction::PHI: {
620 // We can change a phi if we can change all operands. Note that we never
621 // get into trouble with cyclic PHIs here because we only consider
622 // instructions with a single use.
623 PHINode *PN = cast<PHINode>(I);
624 for (Value *IncValue : PN->incoming_values())
625 if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
626 return false;
627 return true;
628 }
629 case Instruction::Mul: {
630 const APInt *MulConst;
631 // We can fold (shr (mul X, -(1 << C)), C) -> (and (neg X), C`)
632 return !IsLeftShift && match(I->getOperand(1), m_APInt(MulConst)) &&
633 MulConst->isNegatedPowerOf2() && MulConst->countr_zero() == NumBits;
634 }
635 }
636}
637
638/// Fold OuterShift (InnerShift X, C1), C2.
639/// See canEvaluateShiftedShift() for the constraints on these instructions.
640static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
641 bool IsOuterShl,
642 InstCombiner::BuilderTy &Builder) {
643 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
644 Type *ShType = InnerShift->getType();
645 unsigned TypeWidth = ShType->getScalarSizeInBits();
646
647 // We only accept shifts-by-a-constant in canEvaluateShifted().
648 const APInt *C1;
649 match(InnerShift->getOperand(1), m_APInt(C1));
650 unsigned InnerShAmt = C1->getZExtValue();
651
652 // Change the shift amount and clear the appropriate IR flags.
653 auto NewInnerShift = [&](unsigned ShAmt) {
654 InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
655 if (IsInnerShl) {
656 InnerShift->setHasNoUnsignedWrap(false);
657 InnerShift->setHasNoSignedWrap(false);
658 } else {
659 InnerShift->setIsExact(false);
660 }
661 return InnerShift;
662 };
663
664 // Two logical shifts in the same direction:
665 // shl (shl X, C1), C2 --> shl X, C1 + C2
666 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
667 if (IsInnerShl == IsOuterShl) {
668 // If this is an oversized composite shift, then unsigned shifts get 0.
669 if (InnerShAmt + OuterShAmt >= TypeWidth)
670 return Constant::getNullValue(ShType);
671
672 return NewInnerShift(InnerShAmt + OuterShAmt);
673 }
674
675 // Equal shift amounts in opposite directions become bitwise 'and':
676 // lshr (shl X, C), C --> and X, C'
677 // shl (lshr X, C), C --> and X, C'
678 if (InnerShAmt == OuterShAmt) {
679 APInt Mask = IsInnerShl
680 ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
681 : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
682 Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
683 ConstantInt::get(ShType, Mask));
684 if (auto *AndI = dyn_cast<Instruction>(And)) {
685 AndI->moveBefore(InnerShift);
686 AndI->takeName(InnerShift);
687 }
688 return And;
689 }
690
691 assert(InnerShAmt > OuterShAmt &&
692 "Unexpected opposite direction logical shift pair");
693
694 // In general, we would need an 'and' for this transform, but
695 // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
696 // lshr (shl X, C1), C2 --> shl X, C1 - C2
697 // shl (lshr X, C1), C2 --> lshr X, C1 - C2
698 return NewInnerShift(InnerShAmt - OuterShAmt);
699}
700
701/// When canEvaluateShifted() returns true for an expression, this function
702/// inserts the new computation that produces the shifted value.
703static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
704 InstCombinerImpl &IC, const DataLayout &DL) {
705 // We can always evaluate constants shifted.
706 if (Constant *C = dyn_cast<Constant>(V)) {
707 if (isLeftShift)
708 return IC.Builder.CreateShl(C, NumBits);
709 else
710 return IC.Builder.CreateLShr(C, NumBits);
711 }
712
713 Instruction *I = cast<Instruction>(V);
714 IC.addToWorklist(I);
715
716 switch (I->getOpcode()) {
717 default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
718 case Instruction::And:
719 case Instruction::Or:
720 case Instruction::Xor:
721 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
722 I->setOperand(
723 0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
724 I->setOperand(
725 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
726 return I;
727
728 case Instruction::Shl:
729 case Instruction::LShr:
730 return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
731 IC.Builder);
732
733 case Instruction::Select:
734 I->setOperand(
735 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
736 I->setOperand(
737 2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
738 return I;
739 case Instruction::PHI: {
740 // We can change a phi if we can change all operands. Note that we never
741 // get into trouble with cyclic PHIs here because we only consider
742 // instructions with a single use.
743 PHINode *PN = cast<PHINode>(I);
744 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
746 isLeftShift, IC, DL));
747 return PN;
748 }
749 case Instruction::Mul: {
750 assert(!isLeftShift && "Unexpected shift direction!");
751 auto *Neg = BinaryOperator::CreateNeg(I->getOperand(0));
752 IC.InsertNewInstWith(Neg, I->getIterator());
753 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
754 APInt Mask = APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits);
755 auto *And = BinaryOperator::CreateAnd(Neg,
756 ConstantInt::get(I->getType(), Mask));
757 And->takeName(I);
758 return IC.InsertNewInstWith(And, I->getIterator());
759 }
760 }
761}
762
763// If this is a bitwise operator or add with a constant RHS we might be able
764// to pull it through a shift.
766 BinaryOperator *BO) {
767 switch (BO->getOpcode()) {
768 default:
769 return false; // Do not perform transform!
770 case Instruction::Add:
771 return Shift.getOpcode() == Instruction::Shl;
772 case Instruction::Or:
773 case Instruction::And:
774 return true;
775 case Instruction::Xor:
776 // Do not change a 'not' of logical shift because that would create a normal
777 // 'xor'. The 'not' is likely better for analysis, SCEV, and codegen.
778 return !(Shift.isLogicalShift() && match(BO, m_Not(m_Value())));
779 }
780}
781
783 BinaryOperator &I) {
784 // (C2 << X) << C1 --> (C2 << C1) << X
785 // (C2 >> X) >> C1 --> (C2 >> C1) >> X
786 Constant *C2;
787 Value *X;
788 bool IsLeftShift = I.getOpcode() == Instruction::Shl;
789 if (match(Op0, m_BinOp(I.getOpcode(), m_ImmConstant(C2), m_Value(X)))) {
791 I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), C2, C1), X);
792 BinaryOperator *BO0 = cast<BinaryOperator>(Op0);
793 if (IsLeftShift) {
794 R->setHasNoUnsignedWrap(I.hasNoUnsignedWrap() &&
795 BO0->hasNoUnsignedWrap());
796 R->setHasNoSignedWrap(I.hasNoSignedWrap() && BO0->hasNoSignedWrap());
797 } else
798 R->setIsExact(I.isExact() && BO0->isExact());
799 return R;
800 }
801
802 Type *Ty = I.getType();
803 unsigned TypeBits = Ty->getScalarSizeInBits();
804
805 // (X / +DivC) >> (Width - 1) --> ext (X <= -DivC)
806 // (X / -DivC) >> (Width - 1) --> ext (X >= +DivC)
807 const APInt *DivC;
808 if (!IsLeftShift && match(C1, m_SpecificIntAllowPoison(TypeBits - 1)) &&
809 match(Op0, m_SDiv(m_Value(X), m_APInt(DivC))) && !DivC->isZero() &&
810 !DivC->isMinSignedValue()) {
811 Constant *NegDivC = ConstantInt::get(Ty, -(*DivC));
814 Value *Cmp = Builder.CreateICmp(Pred, X, NegDivC);
815 auto ExtOpcode = (I.getOpcode() == Instruction::AShr) ? Instruction::SExt
816 : Instruction::ZExt;
817 return CastInst::Create(ExtOpcode, Cmp, Ty);
818 }
819
820 const APInt *Op1C;
821 if (!match(C1, m_APInt(Op1C)))
822 return nullptr;
823
824 assert(!Op1C->uge(TypeBits) &&
825 "Shift over the type width should have been removed already");
826
827 // See if we can propagate this shift into the input, this covers the trivial
828 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
829 if (I.getOpcode() != Instruction::AShr &&
830 canEvaluateShifted(Op0, Op1C->getZExtValue(), IsLeftShift, *this, &I)) {
832 dbgs() << "ICE: GetShiftedValue propagating shift through expression"
833 " to eliminate shift:\n IN: "
834 << *Op0 << "\n SH: " << I << "\n");
835
836 return replaceInstUsesWith(
837 I, getShiftedValue(Op0, Op1C->getZExtValue(), IsLeftShift, *this, DL));
838 }
839
840 if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
841 return FoldedShift;
842
843 if (!Op0->hasOneUse())
844 return nullptr;
845
846 if (auto *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
847 // If the operand is a bitwise operator with a constant RHS, and the
848 // shift is the only use, we can pull it out of the shift.
849 const APInt *Op0C;
850 if (match(Op0BO->getOperand(1), m_APInt(Op0C))) {
851 if (canShiftBinOpWithConstantRHS(I, Op0BO)) {
852 Value *NewRHS =
853 Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(1), C1);
854
855 Value *NewShift =
856 Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), C1);
857 NewShift->takeName(Op0BO);
858
859 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift, NewRHS);
860 }
861 }
862 }
863
864 // If we have a select that conditionally executes some binary operator,
865 // see if we can pull it the select and operator through the shift.
866 //
867 // For example, turning:
868 // shl (select C, (add X, C1), X), C2
869 // Into:
870 // Y = shl X, C2
871 // select C, (add Y, C1 << C2), Y
872 Value *Cond;
873 BinaryOperator *TBO;
874 Value *FalseVal;
875 if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)),
876 m_Value(FalseVal)))) {
877 const APInt *C;
878 if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal &&
879 match(TBO->getOperand(1), m_APInt(C)) &&
881 Value *NewRHS =
882 Builder.CreateBinOp(I.getOpcode(), TBO->getOperand(1), C1);
883
884 Value *NewShift = Builder.CreateBinOp(I.getOpcode(), FalseVal, C1);
885 Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift, NewRHS);
886 return SelectInst::Create(Cond, NewOp, NewShift);
887 }
888 }
889
890 BinaryOperator *FBO;
891 Value *TrueVal;
892 if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal),
893 m_OneUse(m_BinOp(FBO))))) {
894 const APInt *C;
895 if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal &&
896 match(FBO->getOperand(1), m_APInt(C)) &&
898 Value *NewRHS =
899 Builder.CreateBinOp(I.getOpcode(), FBO->getOperand(1), C1);
900
901 Value *NewShift = Builder.CreateBinOp(I.getOpcode(), TrueVal, C1);
902 Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift, NewRHS);
903 return SelectInst::Create(Cond, NewShift, NewOp);
904 }
905 }
906
907 return nullptr;
908}
909
910// Tries to perform
911// (lshr (add (zext X), (zext Y)), K)
912// -> (icmp ult (add X, Y), X)
913// where
914// - The add's operands are zexts from a K-bits integer to a bigger type.
915// - The add is only used by the shr, or by iK (or narrower) truncates.
916// - The lshr type has more than 2 bits (other types are boolean math).
917// - K > 1
918// note that
919// - The resulting add cannot have nuw/nsw, else on overflow we get a
920// poison value and the transform isn't legal anymore.
921Instruction *InstCombinerImpl::foldLShrOverflowBit(BinaryOperator &I) {
922 assert(I.getOpcode() == Instruction::LShr);
923
924 Value *Add = I.getOperand(0);
925 Value *ShiftAmt = I.getOperand(1);
926 Type *Ty = I.getType();
927
928 if (Ty->getScalarSizeInBits() < 3)
929 return nullptr;
930
931 const APInt *ShAmtAPInt = nullptr;
932 Value *X = nullptr, *Y = nullptr;
933 if (!match(ShiftAmt, m_APInt(ShAmtAPInt)) ||
934 !match(Add,
936 return nullptr;
937
938 const unsigned ShAmt = ShAmtAPInt->getZExtValue();
939 if (ShAmt == 1)
940 return nullptr;
941
942 // X/Y are zexts from `ShAmt`-sized ints.
943 if (X->getType()->getScalarSizeInBits() != ShAmt ||
944 Y->getType()->getScalarSizeInBits() != ShAmt)
945 return nullptr;
946
947 // Make sure that `Add` is only used by `I` and `ShAmt`-truncates.
948 if (!Add->hasOneUse()) {
949 for (User *U : Add->users()) {
950 if (U == &I)
951 continue;
952
953 TruncInst *Trunc = dyn_cast<TruncInst>(U);
954 if (!Trunc || Trunc->getType()->getScalarSizeInBits() > ShAmt)
955 return nullptr;
956 }
957 }
958
959 // Insert at Add so that the newly created `NarrowAdd` will dominate it's
960 // users (i.e. `Add`'s users).
961 Instruction *AddInst = cast<Instruction>(Add);
962 Builder.SetInsertPoint(AddInst);
963
964 Value *NarrowAdd = Builder.CreateAdd(X, Y, "add.narrowed");
965 Value *Overflow =
966 Builder.CreateICmpULT(NarrowAdd, X, "add.narrowed.overflow");
967
968 // Replace the uses of the original add with a zext of the
969 // NarrowAdd's result. Note that all users at this stage are known to
970 // be ShAmt-sized truncs, or the lshr itself.
971 if (!Add->hasOneUse()) {
972 replaceInstUsesWith(*AddInst, Builder.CreateZExt(NarrowAdd, Ty));
973 eraseInstFromFunction(*AddInst);
974 }
975
976 // Replace the LShr with a zext of the overflow check.
977 return new ZExtInst(Overflow, Ty);
978}
979
980// Try to set nuw/nsw flags on shl or exact flag on lshr/ashr using knownbits.
982 assert(I.isShift() && "Expected a shift as input");
983 // We already have all the flags.
984 if (I.getOpcode() == Instruction::Shl) {
985 if (I.hasNoUnsignedWrap() && I.hasNoSignedWrap())
986 return false;
987 } else {
988 if (I.isExact())
989 return false;
990
991 // shr (shl X, Y), Y
992 if (match(I.getOperand(0), m_Shl(m_Value(), m_Specific(I.getOperand(1))))) {
993 I.setIsExact();
994 return true;
995 }
996 }
997
998 // Compute what we know about shift count.
999 KnownBits KnownCnt = computeKnownBits(I.getOperand(1), /* Depth */ 0, Q);
1000 unsigned BitWidth = KnownCnt.getBitWidth();
1001 // Since shift produces a poison value if RHS is equal to or larger than the
1002 // bit width, we can safely assume that RHS is less than the bit width.
1003 uint64_t MaxCnt = KnownCnt.getMaxValue().getLimitedValue(BitWidth - 1);
1004
1005 KnownBits KnownAmt = computeKnownBits(I.getOperand(0), /* Depth */ 0, Q);
1006 bool Changed = false;
1007
1008 if (I.getOpcode() == Instruction::Shl) {
1009 // If we have as many leading zeros than maximum shift cnt we have nuw.
1010 if (!I.hasNoUnsignedWrap() && MaxCnt <= KnownAmt.countMinLeadingZeros()) {
1011 I.setHasNoUnsignedWrap();
1012 Changed = true;
1013 }
1014 // If we have more sign bits than maximum shift cnt we have nsw.
1015 if (!I.hasNoSignedWrap()) {
1016 if (MaxCnt < KnownAmt.countMinSignBits() ||
1017 MaxCnt < ComputeNumSignBits(I.getOperand(0), Q.DL, /*Depth*/ 0, Q.AC,
1018 Q.CxtI, Q.DT)) {
1019 I.setHasNoSignedWrap();
1020 Changed = true;
1021 }
1022 }
1023 return Changed;
1024 }
1025
1026 // If we have at least as many trailing zeros as maximum count then we have
1027 // exact.
1028 Changed = MaxCnt <= KnownAmt.countMinTrailingZeros();
1029 I.setIsExact(Changed);
1030
1031 return Changed;
1032}
1033
1036
1037 if (Value *V = simplifyShlInst(I.getOperand(0), I.getOperand(1),
1038 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(), Q))
1039 return replaceInstUsesWith(I, V);
1040
1042 return X;
1043
1045 return V;
1046
1048 return V;
1049
1050 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1051 Type *Ty = I.getType();
1052 unsigned BitWidth = Ty->getScalarSizeInBits();
1053
1054 const APInt *C;
1055 if (match(Op1, m_APInt(C))) {
1056 unsigned ShAmtC = C->getZExtValue();
1057
1058 // shl (zext X), C --> zext (shl X, C)
1059 // This is only valid if X would have zeros shifted out.
1060 Value *X;
1061 if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
1062 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1063 if (ShAmtC < SrcWidth &&
1064 MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmtC), 0, &I))
1065 return new ZExtInst(Builder.CreateShl(X, ShAmtC), Ty);
1066 }
1067
1068 // (X >> C) << C --> X & (-1 << C)
1069 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) {
1071 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
1072 }
1073
1074 const APInt *C1;
1075 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(C1)))) &&
1076 C1->ult(BitWidth)) {
1077 unsigned ShrAmt = C1->getZExtValue();
1078 if (ShrAmt < ShAmtC) {
1079 // If C1 < C: (X >>?,exact C1) << C --> X << (C - C1)
1080 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShrAmt);
1081 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
1082 NewShl->setHasNoUnsignedWrap(
1083 I.hasNoUnsignedWrap() ||
1084 (ShrAmt &&
1085 cast<Instruction>(Op0)->getOpcode() == Instruction::LShr &&
1086 I.hasNoSignedWrap()));
1087 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
1088 return NewShl;
1089 }
1090 if (ShrAmt > ShAmtC) {
1091 // If C1 > C: (X >>?exact C1) << C --> X >>?exact (C1 - C)
1092 Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmtC);
1093 auto *NewShr = BinaryOperator::Create(
1094 cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff);
1095 NewShr->setIsExact(true);
1096 return NewShr;
1097 }
1098 }
1099
1100 if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_APInt(C1)))) &&
1101 C1->ult(BitWidth)) {
1102 unsigned ShrAmt = C1->getZExtValue();
1103 if (ShrAmt < ShAmtC) {
1104 // If C1 < C: (X >>? C1) << C --> (X << (C - C1)) & (-1 << C)
1105 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShrAmt);
1106 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
1107 NewShl->setHasNoUnsignedWrap(
1108 I.hasNoUnsignedWrap() ||
1109 (ShrAmt &&
1110 cast<Instruction>(Op0)->getOpcode() == Instruction::LShr &&
1111 I.hasNoSignedWrap()));
1112 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
1113 Builder.Insert(NewShl);
1115 return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
1116 }
1117 if (ShrAmt > ShAmtC) {
1118 // If C1 > C: (X >>? C1) << C --> (X >>? (C1 - C)) & (-1 << C)
1119 Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmtC);
1120 auto *OldShr = cast<BinaryOperator>(Op0);
1121 auto *NewShr =
1122 BinaryOperator::Create(OldShr->getOpcode(), X, ShiftDiff);
1123 NewShr->setIsExact(OldShr->isExact());
1124 Builder.Insert(NewShr);
1126 return BinaryOperator::CreateAnd(NewShr, ConstantInt::get(Ty, Mask));
1127 }
1128 }
1129
1130 // Similar to above, but look through an intermediate trunc instruction.
1131 BinaryOperator *Shr;
1132 if (match(Op0, m_OneUse(m_Trunc(m_OneUse(m_BinOp(Shr))))) &&
1133 match(Shr, m_Shr(m_Value(X), m_APInt(C1)))) {
1134 // The larger shift direction survives through the transform.
1135 unsigned ShrAmtC = C1->getZExtValue();
1136 unsigned ShDiff = ShrAmtC > ShAmtC ? ShrAmtC - ShAmtC : ShAmtC - ShrAmtC;
1137 Constant *ShiftDiffC = ConstantInt::get(X->getType(), ShDiff);
1138 auto ShiftOpc = ShrAmtC > ShAmtC ? Shr->getOpcode() : Instruction::Shl;
1139
1140 // If C1 > C:
1141 // (trunc (X >> C1)) << C --> (trunc (X >> (C1 - C))) && (-1 << C)
1142 // If C > C1:
1143 // (trunc (X >> C1)) << C --> (trunc (X << (C - C1))) && (-1 << C)
1144 Value *NewShift = Builder.CreateBinOp(ShiftOpc, X, ShiftDiffC, "sh.diff");
1145 Value *Trunc = Builder.CreateTrunc(NewShift, Ty, "tr.sh.diff");
1147 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Ty, Mask));
1148 }
1149
1150 // If we have an opposite shift by the same amount, we may be able to
1151 // reorder binops and shifts to eliminate math/logic.
1152 auto isSuitableBinOpcode = [](Instruction::BinaryOps BinOpcode) {
1153 switch (BinOpcode) {
1154 default:
1155 return false;
1156 case Instruction::Add:
1157 case Instruction::And:
1158 case Instruction::Or:
1159 case Instruction::Xor:
1160 case Instruction::Sub:
1161 // NOTE: Sub is not commutable and the tranforms below may not be valid
1162 // when the shift-right is operand 1 (RHS) of the sub.
1163 return true;
1164 }
1165 };
1166 BinaryOperator *Op0BO;
1167 if (match(Op0, m_OneUse(m_BinOp(Op0BO))) &&
1168 isSuitableBinOpcode(Op0BO->getOpcode())) {
1169 // Commute so shift-right is on LHS of the binop.
1170 // (Y bop (X >> C)) << C -> ((X >> C) bop Y) << C
1171 // (Y bop ((X >> C) & CC)) << C -> (((X >> C) & CC) bop Y) << C
1172 Value *Shr = Op0BO->getOperand(0);
1173 Value *Y = Op0BO->getOperand(1);
1174 Value *X;
1175 const APInt *CC;
1176 if (Op0BO->isCommutative() && Y->hasOneUse() &&
1177 (match(Y, m_Shr(m_Value(), m_Specific(Op1))) ||
1179 m_APInt(CC)))))
1180 std::swap(Shr, Y);
1181
1182 // ((X >> C) bop Y) << C -> (X bop (Y << C)) & (~0 << C)
1183 if (match(Shr, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
1184 // Y << C
1185 Value *YS = Builder.CreateShl(Y, Op1, Op0BO->getName());
1186 // (X bop (Y << C))
1187 Value *B =
1188 Builder.CreateBinOp(Op0BO->getOpcode(), X, YS, Shr->getName());
1189 unsigned Op1Val = C->getLimitedValue(BitWidth);
1190 APInt Bits = APInt::getHighBitsSet(BitWidth, BitWidth - Op1Val);
1191 Constant *Mask = ConstantInt::get(Ty, Bits);
1192 return BinaryOperator::CreateAnd(B, Mask);
1193 }
1194
1195 // (((X >> C) & CC) bop Y) << C -> (X & (CC << C)) bop (Y << C)
1196 if (match(Shr,
1198 m_APInt(CC))))) {
1199 // Y << C
1200 Value *YS = Builder.CreateShl(Y, Op1, Op0BO->getName());
1201 // X & (CC << C)
1202 Value *M = Builder.CreateAnd(X, ConstantInt::get(Ty, CC->shl(*C)),
1203 X->getName() + ".mask");
1204 auto *NewOp = BinaryOperator::Create(Op0BO->getOpcode(), M, YS);
1205 if (auto *Disjoint = dyn_cast<PossiblyDisjointInst>(Op0BO);
1206 Disjoint && Disjoint->isDisjoint())
1207 cast<PossiblyDisjointInst>(NewOp)->setIsDisjoint(true);
1208 return NewOp;
1209 }
1210 }
1211
1212 // (C1 - X) << C --> (C1 << C) - (X << C)
1213 if (match(Op0, m_OneUse(m_Sub(m_APInt(C1), m_Value(X))))) {
1214 Constant *NewLHS = ConstantInt::get(Ty, C1->shl(*C));
1215 Value *NewShift = Builder.CreateShl(X, Op1);
1216 return BinaryOperator::CreateSub(NewLHS, NewShift);
1217 }
1218 }
1219
1220 if (setShiftFlags(I, Q))
1221 return &I;
1222
1223 // Transform (x >> y) << y to x & (-1 << y)
1224 // Valid for any type of right-shift.
1225 Value *X;
1226 if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
1228 Value *Mask = Builder.CreateShl(AllOnes, Op1);
1229 return BinaryOperator::CreateAnd(Mask, X);
1230 }
1231
1232 // Transform (-1 >> y) << y to -1 << y
1233 if (match(Op0, m_LShr(m_AllOnes(), m_Specific(Op1)))) {
1235 return BinaryOperator::CreateShl(AllOnes, Op1);
1236 }
1237
1238 Constant *C1;
1239 if (match(Op1, m_ImmConstant(C1))) {
1240 Constant *C2;
1241 Value *X;
1242 // (X * C2) << C1 --> X * (C2 << C1)
1243 if (match(Op0, m_Mul(m_Value(X), m_ImmConstant(C2))))
1244 return BinaryOperator::CreateMul(X, Builder.CreateShl(C2, C1));
1245
1246 // shl (zext i1 X), C1 --> select (X, 1 << C1, 0)
1247 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1248 auto *NewC = Builder.CreateShl(ConstantInt::get(Ty, 1), C1);
1250 }
1251 }
1252
1253 if (match(Op0, m_One())) {
1254 // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
1255 if (match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X))))
1256 return BinaryOperator::CreateLShr(
1257 ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X);
1258
1259 // Canonicalize "extract lowest set bit" using cttz to and-with-negate:
1260 // 1 << (cttz X) --> -X & X
1261 if (match(Op1,
1262 m_OneUse(m_Intrinsic<Intrinsic::cttz>(m_Value(X), m_Value())))) {
1263 Value *NegX = Builder.CreateNeg(X, "neg");
1264 return BinaryOperator::CreateAnd(NegX, X);
1265 }
1266 }
1267
1268 return nullptr;
1269}
1270
1272 if (Value *V = simplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1274 return replaceInstUsesWith(I, V);
1275
1277 return X;
1278
1280 return R;
1281
1282 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1283 Type *Ty = I.getType();
1284 Value *X;
1285 const APInt *C;
1286 unsigned BitWidth = Ty->getScalarSizeInBits();
1287
1288 // (iN (~X) u>> (N - 1)) --> zext (X > -1)
1289 if (match(Op0, m_OneUse(m_Not(m_Value(X)))) &&
1291 return new ZExtInst(Builder.CreateIsNotNeg(X, "isnotneg"), Ty);
1292
1293 // ((X << nuw Z) sub nuw Y) >>u exact Z --> X sub nuw (Y >>u exact Z)
1294 Value *Y;
1295 if (I.isExact() &&
1297 m_Value(Y))))) {
1298 Value *NewLshr = Builder.CreateLShr(Y, Op1, "", /*isExact=*/true);
1299 auto *NewSub = BinaryOperator::CreateNUWSub(X, NewLshr);
1300 NewSub->setHasNoSignedWrap(
1301 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap());
1302 return NewSub;
1303 }
1304
1305 // Fold (X + Y) / 2 --> (X & Y) iff (X u<= 1) && (Y u<= 1)
1306 if (match(Op0, m_Add(m_Value(X), m_Value(Y))) && match(Op1, m_One()) &&
1307 computeKnownBits(X, /*Depth=*/0, &I).countMaxActiveBits() <= 1 &&
1308 computeKnownBits(Y, /*Depth=*/0, &I).countMaxActiveBits() <= 1)
1309 return BinaryOperator::CreateAnd(X, Y);
1310
1311 // (sub nuw X, (Y << nuw Z)) >>u exact Z --> (X >>u exact Z) sub nuw Y
1312 if (I.isExact() &&
1314 m_NUWShl(m_Value(Y), m_Specific(Op1)))))) {
1315 Value *NewLshr = Builder.CreateLShr(X, Op1, "", /*isExact=*/true);
1316 auto *NewSub = BinaryOperator::CreateNUWSub(NewLshr, Y);
1317 NewSub->setHasNoSignedWrap(
1318 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap());
1319 return NewSub;
1320 }
1321
1322 auto isSuitableBinOpcode = [](Instruction::BinaryOps BinOpcode) {
1323 switch (BinOpcode) {
1324 default:
1325 return false;
1326 case Instruction::Add:
1327 case Instruction::And:
1328 case Instruction::Or:
1329 case Instruction::Xor:
1330 // Sub is handled separately.
1331 return true;
1332 }
1333 };
1334
1335 // If both the binop and the shift are nuw, then:
1336 // ((X << nuw Z) binop nuw Y) >>u Z --> X binop nuw (Y >>u Z)
1338 m_Value(Y))))) {
1339 BinaryOperator *Op0OB = cast<BinaryOperator>(Op0);
1340 if (isSuitableBinOpcode(Op0OB->getOpcode())) {
1341 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op0);
1342 !OBO || OBO->hasNoUnsignedWrap()) {
1343 Value *NewLshr = Builder.CreateLShr(
1344 Y, Op1, "", I.isExact() && Op0OB->getOpcode() != Instruction::And);
1345 auto *NewBinOp = BinaryOperator::Create(Op0OB->getOpcode(), NewLshr, X);
1346 if (OBO) {
1347 NewBinOp->setHasNoUnsignedWrap(true);
1348 NewBinOp->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1349 } else if (auto *Disjoint = dyn_cast<PossiblyDisjointInst>(Op0)) {
1350 cast<PossiblyDisjointInst>(NewBinOp)->setIsDisjoint(
1351 Disjoint->isDisjoint());
1352 }
1353 return NewBinOp;
1354 }
1355 }
1356 }
1357
1358 if (match(Op1, m_APInt(C))) {
1359 unsigned ShAmtC = C->getZExtValue();
1360 auto *II = dyn_cast<IntrinsicInst>(Op0);
1361 if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmtC &&
1362 (II->getIntrinsicID() == Intrinsic::ctlz ||
1363 II->getIntrinsicID() == Intrinsic::cttz ||
1364 II->getIntrinsicID() == Intrinsic::ctpop)) {
1365 // ctlz.i32(x)>>5 --> zext(x == 0)
1366 // cttz.i32(x)>>5 --> zext(x == 0)
1367 // ctpop.i32(x)>>5 --> zext(x == -1)
1368 bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
1369 Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
1370 Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS);
1371 return new ZExtInst(Cmp, Ty);
1372 }
1373
1374 const APInt *C1;
1375 if (match(Op0, m_Shl(m_Value(X), m_APInt(C1))) && C1->ult(BitWidth)) {
1376 if (C1->ult(ShAmtC)) {
1377 unsigned ShlAmtC = C1->getZExtValue();
1378 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShlAmtC);
1379 if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1380 // (X <<nuw C1) >>u C --> X >>u (C - C1)
1381 auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
1382 NewLShr->setIsExact(I.isExact());
1383 return NewLShr;
1384 }
1385 if (Op0->hasOneUse()) {
1386 // (X << C1) >>u C --> (X >>u (C - C1)) & (-1 >> C)
1387 Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact());
1389 return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
1390 }
1391 } else if (C1->ugt(ShAmtC)) {
1392 unsigned ShlAmtC = C1->getZExtValue();
1393 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmtC - ShAmtC);
1394 if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1395 // (X <<nuw C1) >>u C --> X <<nuw/nsw (C1 - C)
1396 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
1397 NewShl->setHasNoUnsignedWrap(true);
1398 NewShl->setHasNoSignedWrap(ShAmtC > 0);
1399 return NewShl;
1400 }
1401 if (Op0->hasOneUse()) {
1402 // (X << C1) >>u C --> X << (C1 - C) & (-1 >> C)
1403 Value *NewShl = Builder.CreateShl(X, ShiftDiff);
1405 return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
1406 }
1407 } else {
1408 assert(*C1 == ShAmtC);
1409 // (X << C) >>u C --> X & (-1 >>u C)
1411 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
1412 }
1413 }
1414
1415 // ((X << C) + Y) >>u C --> (X + (Y >>u C)) & (-1 >>u C)
1416 // TODO: Consolidate with the more general transform that starts from shl
1417 // (the shifts are in the opposite order).
1418 if (match(Op0,
1420 m_Value(Y))))) {
1421 Value *NewLshr = Builder.CreateLShr(Y, Op1);
1422 Value *NewAdd = Builder.CreateAdd(NewLshr, X);
1423 unsigned Op1Val = C->getLimitedValue(BitWidth);
1424 APInt Bits = APInt::getLowBitsSet(BitWidth, BitWidth - Op1Val);
1425 Constant *Mask = ConstantInt::get(Ty, Bits);
1426 return BinaryOperator::CreateAnd(NewAdd, Mask);
1427 }
1428
1429 if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) &&
1430 (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
1431 assert(ShAmtC < X->getType()->getScalarSizeInBits() &&
1432 "Big shift not simplified to zero?");
1433 // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
1434 Value *NewLShr = Builder.CreateLShr(X, ShAmtC);
1435 return new ZExtInst(NewLShr, Ty);
1436 }
1437
1438 if (match(Op0, m_SExt(m_Value(X)))) {
1439 unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
1440 // lshr (sext i1 X to iN), C --> select (X, -1 >> C, 0)
1441 if (SrcTyBitWidth == 1) {
1442 auto *NewC = ConstantInt::get(
1443 Ty, APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
1445 }
1446
1447 if ((!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType())) &&
1448 Op0->hasOneUse()) {
1449 // Are we moving the sign bit to the low bit and widening with high
1450 // zeros? lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
1451 if (ShAmtC == BitWidth - 1) {
1452 Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1);
1453 return new ZExtInst(NewLShr, Ty);
1454 }
1455
1456 // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
1457 if (ShAmtC == BitWidth - SrcTyBitWidth) {
1458 // The new shift amount can't be more than the narrow source type.
1459 unsigned NewShAmt = std::min(ShAmtC, SrcTyBitWidth - 1);
1460 Value *AShr = Builder.CreateAShr(X, NewShAmt);
1461 return new ZExtInst(AShr, Ty);
1462 }
1463 }
1464 }
1465
1466 if (ShAmtC == BitWidth - 1) {
1467 // lshr i32 or(X,-X), 31 --> zext (X != 0)
1468 if (match(Op0, m_OneUse(m_c_Or(m_Neg(m_Value(X)), m_Deferred(X)))))
1469 return new ZExtInst(Builder.CreateIsNotNull(X), Ty);
1470
1471 // lshr i32 (X -nsw Y), 31 --> zext (X < Y)
1472 if (match(Op0, m_OneUse(m_NSWSub(m_Value(X), m_Value(Y)))))
1473 return new ZExtInst(Builder.CreateICmpSLT(X, Y), Ty);
1474
1475 // Check if a number is negative and odd:
1476 // lshr i32 (srem X, 2), 31 --> and (X >> 31), X
1477 if (match(Op0, m_OneUse(m_SRem(m_Value(X), m_SpecificInt(2))))) {
1478 Value *Signbit = Builder.CreateLShr(X, ShAmtC);
1479 return BinaryOperator::CreateAnd(Signbit, X);
1480 }
1481 }
1482
1483 Instruction *TruncSrc;
1484 if (match(Op0, m_OneUse(m_Trunc(m_Instruction(TruncSrc)))) &&
1485 match(TruncSrc, m_LShr(m_Value(X), m_APInt(C1)))) {
1486 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1487 unsigned AmtSum = ShAmtC + C1->getZExtValue();
1488
1489 // If the combined shift fits in the source width:
1490 // (trunc (X >>u C1)) >>u C --> and (trunc (X >>u (C1 + C)), MaskC
1491 //
1492 // If the first shift covers the number of bits truncated, then the
1493 // mask instruction is eliminated (and so the use check is relaxed).
1494 if (AmtSum < SrcWidth &&
1495 (TruncSrc->hasOneUse() || C1->uge(SrcWidth - BitWidth))) {
1496 Value *SumShift = Builder.CreateLShr(X, AmtSum, "sum.shift");
1497 Value *Trunc = Builder.CreateTrunc(SumShift, Ty, I.getName());
1498
1499 // If the first shift does not cover the number of bits truncated, then
1500 // we require a mask to get rid of high bits in the result.
1501 APInt MaskC = APInt::getAllOnes(BitWidth).lshr(ShAmtC);
1502 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Ty, MaskC));
1503 }
1504 }
1505
1506 const APInt *MulC;
1507 if (match(Op0, m_NUWMul(m_Value(X), m_APInt(MulC)))) {
1508 if (BitWidth > 2 && (*MulC - 1).isPowerOf2() &&
1509 MulC->logBase2() == ShAmtC) {
1510 // Look for a "splat" mul pattern - it replicates bits across each half
1511 // of a value, so a right shift simplifies back to just X:
1512 // lshr i[2N] (mul nuw X, (2^N)+1), N --> X
1513 if (ShAmtC * 2 == BitWidth)
1514 return replaceInstUsesWith(I, X);
1515
1516 // lshr (mul nuw (X, 2^N + 1)), N -> add nuw (X, lshr(X, N))
1517 if (Op0->hasOneUse()) {
1518 auto *NewAdd = BinaryOperator::CreateNUWAdd(
1519 X, Builder.CreateLShr(X, ConstantInt::get(Ty, ShAmtC), "",
1520 I.isExact()));
1521 NewAdd->setHasNoSignedWrap(
1522 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap());
1523 return NewAdd;
1524 }
1525 }
1526
1527 // The one-use check is not strictly necessary, but codegen may not be
1528 // able to invert the transform and perf may suffer with an extra mul
1529 // instruction.
1530 if (Op0->hasOneUse()) {
1531 APInt NewMulC = MulC->lshr(ShAmtC);
1532 // if c is divisible by (1 << ShAmtC):
1533 // lshr (mul nuw x, MulC), ShAmtC -> mul nuw nsw x, (MulC >> ShAmtC)
1534 if (MulC->eq(NewMulC.shl(ShAmtC))) {
1535 auto *NewMul =
1536 BinaryOperator::CreateNUWMul(X, ConstantInt::get(Ty, NewMulC));
1537 assert(ShAmtC != 0 &&
1538 "lshr X, 0 should be handled by simplifyLShrInst.");
1539 NewMul->setHasNoSignedWrap(true);
1540 return NewMul;
1541 }
1542 }
1543 }
1544
1545 // lshr (mul nsw (X, 2^N + 1)), N -> add nsw (X, lshr(X, N))
1546 if (match(Op0, m_OneUse(m_NSWMul(m_Value(X), m_APInt(MulC))))) {
1547 if (BitWidth > 2 && (*MulC - 1).isPowerOf2() &&
1548 MulC->logBase2() == ShAmtC) {
1549 return BinaryOperator::CreateNSWAdd(
1550 X, Builder.CreateLShr(X, ConstantInt::get(Ty, ShAmtC), "",
1551 I.isExact()));
1552 }
1553 }
1554
1555 // Try to narrow bswap.
1556 // In the case where the shift amount equals the bitwidth difference, the
1557 // shift is eliminated.
1558 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::bswap>(
1559 m_OneUse(m_ZExt(m_Value(X))))))) {
1560 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1561 unsigned WidthDiff = BitWidth - SrcWidth;
1562 if (SrcWidth % 16 == 0) {
1563 Value *NarrowSwap = Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X);
1564 if (ShAmtC >= WidthDiff) {
1565 // (bswap (zext X)) >> C --> zext (bswap X >> C')
1566 Value *NewShift = Builder.CreateLShr(NarrowSwap, ShAmtC - WidthDiff);
1567 return new ZExtInst(NewShift, Ty);
1568 } else {
1569 // (bswap (zext X)) >> C --> (zext (bswap X)) << C'
1570 Value *NewZExt = Builder.CreateZExt(NarrowSwap, Ty);
1571 Constant *ShiftDiff = ConstantInt::get(Ty, WidthDiff - ShAmtC);
1572 return BinaryOperator::CreateShl(NewZExt, ShiftDiff);
1573 }
1574 }
1575 }
1576
1577 // Reduce add-carry of bools to logic:
1578 // ((zext BoolX) + (zext BoolY)) >> 1 --> zext (BoolX && BoolY)
1579 Value *BoolX, *BoolY;
1580 if (ShAmtC == 1 && match(Op0, m_Add(m_Value(X), m_Value(Y))) &&
1581 match(X, m_ZExt(m_Value(BoolX))) && match(Y, m_ZExt(m_Value(BoolY))) &&
1582 BoolX->getType()->isIntOrIntVectorTy(1) &&
1583 BoolY->getType()->isIntOrIntVectorTy(1) &&
1584 (X->hasOneUse() || Y->hasOneUse() || Op0->hasOneUse())) {
1585 Value *And = Builder.CreateAnd(BoolX, BoolY);
1586 return new ZExtInst(And, Ty);
1587 }
1588 }
1589
1591 if (setShiftFlags(I, Q))
1592 return &I;
1593
1594 // Transform (x << y) >> y to x & (-1 >> y)
1595 if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
1597 Value *Mask = Builder.CreateLShr(AllOnes, Op1);
1598 return BinaryOperator::CreateAnd(Mask, X);
1599 }
1600
1601 // Transform (-1 << y) >> y to -1 >> y
1602 if (match(Op0, m_Shl(m_AllOnes(), m_Specific(Op1)))) {
1604 return BinaryOperator::CreateLShr(AllOnes, Op1);
1605 }
1606
1607 if (Instruction *Overflow = foldLShrOverflowBit(I))
1608 return Overflow;
1609
1610 return nullptr;
1611}
1612
1615 BinaryOperator &OldAShr) {
1616 assert(OldAShr.getOpcode() == Instruction::AShr &&
1617 "Must be called with arithmetic right-shift instruction only.");
1618
1619 // Check that constant C is a splat of the element-wise bitwidth of V.
1620 auto BitWidthSplat = [](Constant *C, Value *V) {
1621 return match(
1623 APInt(C->getType()->getScalarSizeInBits(),
1624 V->getType()->getScalarSizeInBits())));
1625 };
1626
1627 // It should look like variable-length sign-extension on the outside:
1628 // (Val << (bitwidth(Val)-Nbits)) a>> (bitwidth(Val)-Nbits)
1629 Value *NBits;
1630 Instruction *MaybeTrunc;
1631 Constant *C1, *C2;
1632 if (!match(&OldAShr,
1633 m_AShr(m_Shl(m_Instruction(MaybeTrunc),
1635 m_ZExtOrSelf(m_Value(NBits))))),
1637 m_ZExtOrSelf(m_Deferred(NBits)))))) ||
1638 !BitWidthSplat(C1, &OldAShr) || !BitWidthSplat(C2, &OldAShr))
1639 return nullptr;
1640
1641 // There may or may not be a truncation after outer two shifts.
1642 Instruction *HighBitExtract;
1643 match(MaybeTrunc, m_TruncOrSelf(m_Instruction(HighBitExtract)));
1644 bool HadTrunc = MaybeTrunc != HighBitExtract;
1645
1646 // And finally, the innermost part of the pattern must be a right-shift.
1647 Value *X, *NumLowBitsToSkip;
1648 if (!match(HighBitExtract, m_Shr(m_Value(X), m_Value(NumLowBitsToSkip))))
1649 return nullptr;
1650
1651 // Said right-shift must extract high NBits bits - C0 must be it's bitwidth.
1652 Constant *C0;
1653 if (!match(NumLowBitsToSkip,
1655 m_Sub(m_Constant(C0), m_ZExtOrSelf(m_Specific(NBits))))) ||
1656 !BitWidthSplat(C0, HighBitExtract))
1657 return nullptr;
1658
1659 // Since the NBits is identical for all shifts, if the outermost and
1660 // innermost shifts are identical, then outermost shifts are redundant.
1661 // If we had truncation, do keep it though.
1662 if (HighBitExtract->getOpcode() == OldAShr.getOpcode())
1663 return replaceInstUsesWith(OldAShr, MaybeTrunc);
1664
1665 // Else, if there was a truncation, then we need to ensure that one
1666 // instruction will go away.
1667 if (HadTrunc && !match(&OldAShr, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1668 return nullptr;
1669
1670 // Finally, bypass two innermost shifts, and perform the outermost shift on
1671 // the operands of the innermost shift.
1672 Instruction *NewAShr =
1673 BinaryOperator::Create(OldAShr.getOpcode(), X, NumLowBitsToSkip);
1674 NewAShr->copyIRFlags(HighBitExtract); // We can preserve 'exact'-ness.
1675 if (!HadTrunc)
1676 return NewAShr;
1677
1678 Builder.Insert(NewAShr);
1679 return TruncInst::CreateTruncOrBitCast(NewAShr, OldAShr.getType());
1680}
1681
1683 if (Value *V = simplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1685 return replaceInstUsesWith(I, V);
1686
1688 return X;
1689
1691 return R;
1692
1693 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1694 Type *Ty = I.getType();
1695 unsigned BitWidth = Ty->getScalarSizeInBits();
1696 const APInt *ShAmtAPInt;
1697 if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) {
1698 unsigned ShAmt = ShAmtAPInt->getZExtValue();
1699
1700 // If the shift amount equals the difference in width of the destination
1701 // and source scalar types:
1702 // ashr (shl (zext X), C), C --> sext X
1703 Value *X;
1704 if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
1705 ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
1706 return new SExtInst(X, Ty);
1707
1708 // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
1709 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
1710 const APInt *ShOp1;
1711 if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) &&
1712 ShOp1->ult(BitWidth)) {
1713 unsigned ShlAmt = ShOp1->getZExtValue();
1714 if (ShlAmt < ShAmt) {
1715 // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
1716 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1717 auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff);
1718 NewAShr->setIsExact(I.isExact());
1719 return NewAShr;
1720 }
1721 if (ShlAmt > ShAmt) {
1722 // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
1723 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1724 auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff);
1725 NewShl->setHasNoSignedWrap(true);
1726 return NewShl;
1727 }
1728 }
1729
1730 if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) &&
1731 ShOp1->ult(BitWidth)) {
1732 unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1733 // Oversized arithmetic shifts replicate the sign bit.
1734 AmtSum = std::min(AmtSum, BitWidth - 1);
1735 // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
1736 return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
1737 }
1738
1739 if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) &&
1740 (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) {
1741 // ashr (sext X), C --> sext (ashr X, C')
1742 Type *SrcTy = X->getType();
1743 ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1);
1744 Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt));
1745 return new SExtInst(NewSh, Ty);
1746 }
1747
1748 if (ShAmt == BitWidth - 1) {
1749 // ashr i32 or(X,-X), 31 --> sext (X != 0)
1750 if (match(Op0, m_OneUse(m_c_Or(m_Neg(m_Value(X)), m_Deferred(X)))))
1751 return new SExtInst(Builder.CreateIsNotNull(X), Ty);
1752
1753 // ashr i32 (X -nsw Y), 31 --> sext (X < Y)
1754 Value *Y;
1755 if (match(Op0, m_OneUse(m_NSWSub(m_Value(X), m_Value(Y)))))
1756 return new SExtInst(Builder.CreateICmpSLT(X, Y), Ty);
1757 }
1758
1759 const APInt *MulC;
1760 if (match(Op0, m_OneUse(m_NSWMul(m_Value(X), m_APInt(MulC)))) &&
1761 (BitWidth > 2 && (*MulC - 1).isPowerOf2() &&
1762 MulC->logBase2() == ShAmt &&
1763 (ShAmt < BitWidth - 1))) /* Minus 1 for the sign bit */ {
1764
1765 // ashr (mul nsw (X, 2^N + 1)), N -> add nsw (X, ashr(X, N))
1766 auto *NewAdd = BinaryOperator::CreateNSWAdd(
1767 X,
1768 Builder.CreateAShr(X, ConstantInt::get(Ty, ShAmt), "", I.isExact()));
1769 NewAdd->setHasNoUnsignedWrap(
1770 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap());
1771 return NewAdd;
1772 }
1773 }
1774
1776 if (setShiftFlags(I, Q))
1777 return &I;
1778
1779 // Prefer `-(x & 1)` over `(x << (bitwidth(x)-1)) a>> (bitwidth(x)-1)`
1780 // as the pattern to splat the lowest bit.
1781 // FIXME: iff X is already masked, we don't need the one-use check.
1782 Value *X;
1783 if (match(Op1, m_SpecificIntAllowPoison(BitWidth - 1)) &&
1786 Constant *Mask = ConstantInt::get(Ty, 1);
1787 // Retain the knowledge about the ignored lanes.
1789 Constant::mergeUndefsWith(Mask, cast<Constant>(Op1)),
1790 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)));
1791 X = Builder.CreateAnd(X, Mask);
1793 }
1794
1796 return R;
1797
1798 // See if we can turn a signed shr into an unsigned shr.
1800 Instruction *Lshr = BinaryOperator::CreateLShr(Op0, Op1);
1801 Lshr->setIsExact(I.isExact());
1802 return Lshr;
1803 }
1804
1805 // ashr (xor %x, -1), %y --> xor (ashr %x, %y), -1
1806 if (match(Op0, m_OneUse(m_Not(m_Value(X))))) {
1807 // Note that we must drop 'exact'-ness of the shift!
1808 // Note that we can't keep undef's in -1 vector constant!
1809 auto *NewAShr = Builder.CreateAShr(X, Op1, Op0->getName() + ".not");
1810 return BinaryOperator::CreateNot(NewAShr);
1811 }
1812
1813 return nullptr;
1814}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Size
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This file provides internal interfaces used to implement the InstCombine.
static Value * foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt, bool IsOuterShl, InstCombiner::BuilderTy &Builder)
Fold OuterShift (InnerShift X, C1), C2.
static bool setShiftFlags(BinaryOperator &I, const SimplifyQuery &Q)
static Instruction * dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift, const SimplifyQuery &Q, InstCombiner::BuilderTy &Builder)
static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift, InstCombinerImpl &IC, Instruction *CxtI)
See if we can compute the specified value, but shifted logically to the left or right by some number ...
bool canTryToConstantAddTwoShiftAmounts(Value *Sh0, Value *ShAmt0, Value *Sh1, Value *ShAmt1)
static Instruction * foldShiftOfShiftedBinOp(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
If we have a shift-by-constant of a bin op (bitwise logic op or add/sub w/ shl) that itself has a shi...
static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl, Instruction *InnerShift, InstCombinerImpl &IC, Instruction *CxtI)
Return true if we can simplify two logical (either left or right) shifts that have constant shift amo...
static Value * getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift, InstCombinerImpl &IC, const DataLayout &DL)
When canEvaluateShifted() returns true for an expression, this function inserts the new computation t...
static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift, BinaryOperator *BO)
This file provides the interface for the instcombine pass implementation.
static bool hasNoSignedWrap(BinaryOperator &I)
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define I(x, y, z)
Definition: MD5.cpp:58
uint64_t IntrinsicInst * II
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const MCExpr * MaskShift(const MCExpr *Val, uint32_t Mask, uint32_t Shift, MCContext &Ctx)
static unsigned getScalarSizeInBits(Type *Ty)
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:40
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
Value * RHS
Class for arbitrary precision integers.
Definition: APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:212
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition: APInt.h:427
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:207
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition: APInt.h:401
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1498
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition: APInt.h:1160
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:358
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1089
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:307
bool eq(const APInt &RHS) const
Equality comparison.
Definition: APInt.h:1057
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition: APInt.h:1596
unsigned logBase2() const
Definition: APInt.h:1717
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition: APInt.h:453
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:851
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition: APInt.h:284
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition: APInt.h:274
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:829
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1199
static BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
BinaryOps getOpcode() const
Definition: InstrTypes.h:442
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static CastInst * CreateTruncOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a Trunc or BitCast cast instruction.
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:757
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:787
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:782
@ ICMP_EQ
equal
Definition: InstrTypes.h:778
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:785
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2618
static Constant * getNot(Constant *C)
Definition: Constants.cpp:2605
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2611
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2253
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition: Constants.h:124
This is an important base class in LLVM.
Definition: Constant.h:42
static Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
Definition: Constants.cpp:768
static Constant * mergeUndefsWith(Constant *C, Constant *Other)
Merges undefs of a Constant with another Constant, along with the undefs already present.
Definition: Constants.cpp:792
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:417
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
CallInst * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Definition: IRBuilder.cpp:914
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2277
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1454
Value * CreateIsNotNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg > -1.
Definition: IRBuilder.h:2579
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
Definition: IRBuilder.h:1738
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2261
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition: IRBuilder.h:142
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1433
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition: IRBuilder.h:2041
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1492
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1344
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition: IRBuilder.h:2569
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition: IRBuilder.h:2027
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1683
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2293
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:177
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1473
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2371
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * visitLShr(BinaryOperator &I)
Instruction * foldBinOpIntoSelectOrPhi(BinaryOperator &I)
This is a convenience wrapper function for the above two functions.
Value * reassociateShiftAmtsOfTwoSameDirectionShifts(BinaryOperator *Sh0, const SimplifyQuery &SQ, bool AnalyzeForSignBitExtraction=false)
Instruction * visitAShr(BinaryOperator &I)
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * visitShl(BinaryOperator &I)
Instruction * foldBinopWithPhiOperands(BinaryOperator &BO)
For a binary operator with 2 phi operands, try to hoist the binary operation before the phi.
Instruction * foldVariableSignZeroExtensionOfVariableHighBitExtract(BinaryOperator &OldAShr)
Instruction * commonShiftTransforms(BinaryOperator &I)
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
Instruction * foldVectorBinop(BinaryOperator &Inst)
Canonicalize the position of binops relative to shufflevector.
Instruction * FoldShiftByConstant(Value *Op0, Constant *Op1, BinaryOperator &I)
SimplifyQuery SQ
Definition: InstCombiner.h:76
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Definition: InstCombiner.h:386
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
Definition: InstCombiner.h:375
const DataLayout & DL
Definition: InstCombiner.h:75
AssumptionCache & AC
Definition: InstCombiner.h:72
void addToWorklist(Instruction *I)
Definition: InstCombiner.h:336
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
Definition: InstCombiner.h:410
void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, const Instruction *CxtI) const
Definition: InstCombiner.h:431
BuilderTy & Builder
Definition: InstCombiner.h:60
bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth=0, const Instruction *CxtI=nullptr) const
Definition: InstCombiner.h:447
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
bool isLogicalShift() const
Return true if this is a logical shift left or a logical shift right.
Definition: Instruction.h:313
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:274
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
op_range incoming_values()
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
This class represents a sign extension of integer types.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, Instruction *MDFrom=nullptr)
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:261
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:230
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Type * getExtendedType() const
Given scalar/vector integer type, returns a type with elements twice as wide as in the original type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:224
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
This class represents zero extension of integer types.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
Definition: PatternMatch.h:524
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:100
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
Definition: PatternMatch.h:619
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:165
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:972
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:816
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:875
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
Definition: PatternMatch.h:980
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:592
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
match_combine_and< LTy, RTy > m_CombineAnd(const LTy &L, const RTy &R)
Combine two pattern matchers matching L && R.
Definition: PatternMatch.h:245
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
deferredval_ty< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
Definition: PatternMatch.h:893
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
match_combine_and< class_match< Constant >, match_unless< constantexpr_match > > m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
Definition: PatternMatch.h:854
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:299
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
Exact_match< T > m_Exact(const T &SubPattern)
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
Definition: PatternMatch.h:239
cst_pred_ty< icmp_pred_with_threshold > m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold)
Match an integer or vector with every element comparing 'pred' (eg/ne/...) to Threshold.
Definition: PatternMatch.h:698
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Value * simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact, const SimplifyQuery &Q)
Given operands for a AShr, fold the result or return nulll.
Value * simplifySubInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Sub, fold the result or return null.
Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:340
Value * simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Shl, fold the result or return null.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:291
Value * simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact, const SimplifyQuery &Q)
Given operands for a LShr, fold the result or return null.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
@ And
Bitwise or logical AND of integers.
@ Add
Sum of integers.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition: KnownBits.h:244
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition: KnownBits.h:231
unsigned getBitWidth() const
Get the bit width of this value.
Definition: KnownBits.h:40
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition: KnownBits.h:237
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition: KnownBits.h:134
const DataLayout & DL
Definition: SimplifyQuery.h:71
const Instruction * CxtI
Definition: SimplifyQuery.h:75
const DominatorTree * DT
Definition: SimplifyQuery.h:73
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
Definition: SimplifyQuery.h:74