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