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