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