[InstCombine] refactor sdiv by (negative) power-of-2 folds; NFCI

It's probably better to try harder on this kind of
pattern by using ValueTracking.
This commit is contained in:
Sanjay Patel 2022-10-07 11:21:28 -04:00
parent 68f267d2df
commit bdfefac9a4
3 changed files with 18 additions and 14 deletions

View File

@ -1192,20 +1192,20 @@ Instruction *InstCombinerImpl::visitSDiv(BinaryOperator &I) {
if (match(Op1, m_SignMask()))
return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty);
// sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative
// sdiv exact X, -1<<C --> -(ashr exact X, C)
if (I.isExact() && ((match(Op1, m_Power2()) && match(Op1, m_NonNegative())) ||
match(Op1, m_NegatedPower2()))) {
bool DivisorWasNegative = match(Op1, m_NegatedPower2());
if (DivisorWasNegative)
Op1 = ConstantExpr::getNeg(cast<Constant>(Op1));
auto *AShr = BinaryOperator::CreateExactAShr(
Op0, ConstantExpr::getExactLogBase2(cast<Constant>(Op1)), I.getName());
if (!DivisorWasNegative)
return AShr;
Builder.Insert(AShr);
AShr->setName(I.getName() + ".neg");
return BinaryOperator::CreateNeg(AShr, I.getName());
if (I.isExact()) {
// sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative
if (match(Op1, m_Power2()) && match(Op1, m_NonNegative())) {
Constant *C = ConstantExpr::getExactLogBase2(cast<Constant>(Op1));
return BinaryOperator::CreateExactAShr(Op0, C);
}
// sdiv exact X, -1<<C --> -(ashr exact X, C)
if (match(Op1, m_NegatedPower2())) {
Constant *NegPow2C = ConstantExpr::getNeg(cast<Constant>(Op1));
Constant *C = ConstantExpr::getExactLogBase2(NegPow2C);
Value *Ashr = Builder.CreateAShr(Op0, C, I.getName() + ".neg", true);
return BinaryOperator::CreateNeg(Ashr);
}
}
const APInt *Op1C;

View File

@ -15,6 +15,7 @@ define i8 @t0(i8 %x) {
%div = sdiv exact i8 %x, -32
ret i8 %div
}
define i8 @n1(i8 %x) {
; CHECK-LABEL: @n1(
; CHECK-NEXT: [[DIV:%.*]] = sdiv i8 [[X:%.*]], -32

View File

@ -15,6 +15,7 @@ define i8 @t0(i8 %x) {
%div = sdiv exact i8 %x, 32
ret i8 %div
}
define i8 @n1(i8 %x) {
; CHECK-LABEL: @n1(
; CHECK-NEXT: [[DIV:%.*]] = sdiv i8 [[X:%.*]], 32
@ -23,6 +24,7 @@ define i8 @n1(i8 %x) {
%div = sdiv i8 %x, 32 ; not exact
ret i8 %div
}
define i8 @n2(i8 %x) {
; CHECK-LABEL: @n2(
; CHECK-NEXT: [[TMP1:%.*]] = icmp eq i8 [[X:%.*]], -128
@ -58,6 +60,7 @@ define <2 x i8> @n5_vec_undef(<2 x i8> %x) {
%div = sdiv exact <2 x i8> %x, <i8 32, i8 undef>
ret <2 x i8> %div
}
define <2 x i8> @n6_vec_negative(<2 x i8> %x) {
; CHECK-LABEL: @n6_vec_negative(
; CHECK-NEXT: [[DIV:%.*]] = sdiv exact <2 x i8> [[X:%.*]], <i8 32, i8 -128>