Skip to content

[InstCombine] Handle commuted pattern for ((X s/ C1) << C2) + X #121737

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 13 additions & 11 deletions llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1326,6 +1326,18 @@ Instruction *InstCombinerImpl::foldAddLikeCommutative(Value *LHS, Value *RHS,
R->setHasNoUnsignedWrap(NUWOut);
return R;
}

// ((X s/ C1) << C2) + X => X s% -C1 where -C1 is 1 << C2
const APInt *C1, *C2;
if (match(LHS, m_Shl(m_SDiv(m_Specific(RHS), m_APInt(C1)), m_APInt(C2)))) {
APInt One(C2->getBitWidth(), 1);
APInt MinusC1 = -(*C1);
if (MinusC1 == (One << *C2)) {
Constant *NewRHS = ConstantInt::get(RHS->getType(), MinusC1);
return BinaryOperator::CreateSRem(RHS, NewRHS);
}
}

return nullptr;
}

Expand Down Expand Up @@ -1623,17 +1635,7 @@ Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
// X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);

// ((X s/ C1) << C2) + X => X s% -C1 where -C1 is 1 << C2
const APInt *C1, *C2;
if (match(LHS, m_Shl(m_SDiv(m_Specific(RHS), m_APInt(C1)), m_APInt(C2)))) {
APInt one(C2->getBitWidth(), 1);
APInt minusC1 = -(*C1);
if (minusC1 == (one << *C2)) {
Constant *NewRHS = ConstantInt::get(RHS->getType(), minusC1);
return BinaryOperator::CreateSRem(RHS, NewRHS);
}
}

const APInt *C1;
// (A & 2^C1) + A => A & (2^C1 - 1) iff bit C1 in A is a sign bit
if (match(&I, m_c_Add(m_And(m_Value(A), m_APInt(C1)), m_Deferred(A))) &&
C1->isPowerOf2() && (ComputeNumSignBits(A) > C1->countl_zero())) {
Expand Down
11 changes: 11 additions & 0 deletions llvm/test/Transforms/InstCombine/add-shl-sdiv-to-srem.ll
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@ define i8 @add-shl-sdiv-scalar0(i8 %x) {
ret i8 %rz
}

define i8 @add-shl-sdiv-scalar0_commuted(i8 %x) {
; CHECK-LABEL: @add-shl-sdiv-scalar0_commuted(
; CHECK-NEXT: [[RZ:%.*]] = srem i8 [[X:%.*]], 4
; CHECK-NEXT: ret i8 [[RZ]]
;
%sd = sdiv i8 %x, -4
%sl = shl i8 %sd, 2
%rz = add i8 %x, %sl
ret i8 %rz
}

define i8 @add-shl-sdiv-scalar1(i8 %x) {
; CHECK-LABEL: @add-shl-sdiv-scalar1(
; CHECK-NEXT: [[RZ:%.*]] = srem i8 [[X:%.*]], 64
Expand Down
Loading