@@ -1411,13 +1411,24 @@ Instruction *InstCombinerImpl::visitLShr(BinaryOperator &I) {
1411
1411
1412
1412
const APInt *MulC;
1413
1413
if (match (Op0, m_NUWMul (m_Value (X), m_APInt (MulC)))) {
1414
- // Look for a "splat" mul pattern - it replicates bits across each half of
1415
- // a value, so a right shift is just a mask of the low bits:
1416
- // lshr i[2N] (mul nuw X, (2^N)+1), N --> and iN X, (2^N)-1
1417
- // TODO: Generalize to allow more than just half-width shifts?
1418
- if (BitWidth > 2 && ShAmtC * 2 == BitWidth && (*MulC - 1 ).isPowerOf2 () &&
1419
- MulC->logBase2 () == ShAmtC)
1420
- return BinaryOperator::CreateAnd (X, ConstantInt::get (Ty, *MulC - 2 ));
1414
+ if (BitWidth > 2 && (*MulC - 1 ).isPowerOf2 () &&
1415
+ MulC->logBase2 () == ShAmtC) {
1416
+ // Look for a "splat" mul pattern - it replicates bits across each half
1417
+ // of a value, so a right shift is just a mask of the low bits:
1418
+ // lshr i[2N] (mul nuw X, (2^N)+1), N --> and iN X, (2^N)-1
1419
+ if (ShAmtC * 2 == BitWidth)
1420
+ return BinaryOperator::CreateAnd (X, ConstantInt::get (Ty, *MulC - 2 ));
1421
+
1422
+ // lshr (mul nuw (X, 2^N + 1)), N -> add nuw (X, lshr(X, N))
1423
+ if (Op0->hasOneUse ()) {
1424
+ auto *NewAdd = BinaryOperator::CreateNUWAdd (
1425
+ X, Builder.CreateLShr (X, ConstantInt::get (Ty, ShAmtC), " " ,
1426
+ I.isExact ()));
1427
+ NewAdd->setHasNoSignedWrap (
1428
+ cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap ());
1429
+ return NewAdd;
1430
+ }
1431
+ }
1421
1432
1422
1433
// The one-use check is not strictly necessary, but codegen may not be
1423
1434
// able to invert the transform and perf may suffer with an extra mul
@@ -1437,6 +1448,16 @@ Instruction *InstCombinerImpl::visitLShr(BinaryOperator &I) {
1437
1448
}
1438
1449
}
1439
1450
1451
+ // lshr (mul nsw (X, 2^N + 1)), N -> add nsw (X, lshr(X, N))
1452
+ if (match (Op0, m_OneUse (m_NSWMul (m_Value (X), m_APInt (MulC))))) {
1453
+ if (BitWidth > 2 && (*MulC - 1 ).isPowerOf2 () &&
1454
+ MulC->logBase2 () == ShAmtC) {
1455
+ return BinaryOperator::CreateNSWAdd (
1456
+ X, Builder.CreateLShr (X, ConstantInt::get (Ty, ShAmtC), " " ,
1457
+ I.isExact ()));
1458
+ }
1459
+ }
1460
+
1440
1461
// Try to narrow bswap.
1441
1462
// In the case where the shift amount equals the bitwidth difference, the
1442
1463
// shift is eliminated.
@@ -1681,4 +1702,4 @@ Instruction *InstCombinerImpl::visitAShr(BinaryOperator &I) {
1681
1702
}
1682
1703
1683
1704
return nullptr ;
1684
- }
1705
+ }
0 commit comments