Skip to content

Commit 9f099ce

Browse files
committed
[InstCombine] Fold (sub nuw X, (Y << nuw Z)) >>u exact Z --> (X >>u exact Z) sub nuw Y
This is the same fold as ((X << nuw Z) sub nuw Y) >>u exact Z --> X sub nuw (Y >>u exact Z), but with the sub operands swapped. Proof: https://alive2.llvm.org/ce/z/2cRcdx
1 parent 2ec30cd commit 9f099ce

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1275,6 +1275,17 @@ Instruction *InstCombinerImpl::visitLShr(BinaryOperator &I) {
12751275
return NewSub;
12761276
}
12771277

1278+
// (sub nuw X, (Y << nuw Z)) >>u exact Z --> (X >>u exact Z) sub nuw Y
1279+
if (I.isExact() &&
1280+
match(Op0, m_OneUse(m_NUWSub(m_Value(X),
1281+
m_NUWShl(m_Value(Y), m_Specific(Op1)))))) {
1282+
Value *NewLshr = Builder.CreateLShr(X, Op1, "", /*isExact=*/true);
1283+
auto *NewSub = BinaryOperator::CreateNUWSub(NewLshr, Y);
1284+
NewSub->setHasNoSignedWrap(
1285+
cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap());
1286+
return NewSub;
1287+
}
1288+
12781289
auto isSuitableBinOpcode = [](Instruction::BinaryOps BinOpcode) {
12791290
switch (BinOpcode) {
12801291
default:

llvm/test/Transforms/InstCombine/lshr.ll

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -468,9 +468,8 @@ define i32 @shl_sub_lshr(i32 %x, i32 %c, i32 %y) {
468468

469469
define i32 @shl_sub_lshr_reverse(i32 %x, i32 %c, i32 %y) {
470470
; CHECK-LABEL: @shl_sub_lshr_reverse(
471-
; CHECK-NEXT: [[SHL:%.*]] = shl nuw i32 [[X:%.*]], [[C:%.*]]
472-
; CHECK-NEXT: [[SUB:%.*]] = sub nuw nsw i32 [[Y:%.*]], [[SHL]]
473-
; CHECK-NEXT: [[LSHR:%.*]] = lshr exact i32 [[SUB]], [[C]]
471+
; CHECK-NEXT: [[TMP1:%.*]] = lshr exact i32 [[Y:%.*]], [[C:%.*]]
472+
; CHECK-NEXT: [[LSHR:%.*]] = sub nuw nsw i32 [[TMP1]], [[X:%.*]]
474473
; CHECK-NEXT: ret i32 [[LSHR]]
475474
;
476475
%shl = shl nuw i32 %x, %c

0 commit comments

Comments
 (0)