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