Skip to content

[InstCombine] Fold (op x, ({z,s}ext (icmp eq x, C))) to select #89020

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

Closed
wants to merge 2 commits into from
Closed
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
6 changes: 6 additions & 0 deletions llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1487,6 +1487,9 @@ Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
if (Instruction *Phi = foldBinopWithPhiOperands(I))
return Phi;

if (Value *R = foldOpOfXWithXEqC(&I, SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, R);

// (A*B)+(A*C) -> A*(B+C) etc
if (Value *V = foldUsingDistributiveLaws(I))
return replaceInstUsesWith(I, V);
Expand Down Expand Up @@ -2092,6 +2095,9 @@ Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
if (Instruction *Phi = foldBinopWithPhiOperands(I))
return Phi;

if (Value *R = foldOpOfXWithXEqC(&I, SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, R);

Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);

// If this is a 'B = x-(-A)', change to B = x+A.
Expand Down
9 changes: 9 additions & 0 deletions llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2275,6 +2275,9 @@ Instruction *InstCombinerImpl::visitAnd(BinaryOperator &I) {
if (Instruction *Phi = foldBinopWithPhiOperands(I))
return Phi;

if (Value *R = foldOpOfXWithXEqC(&I, SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, R);

// See if we can simplify any instructions used by the instruction whose sole
// purpose is to compute bits we don't care about.
if (SimplifyDemandedInstructionBits(I))
Expand Down Expand Up @@ -3438,6 +3441,9 @@ Instruction *InstCombinerImpl::visitOr(BinaryOperator &I) {
if (Instruction *Phi = foldBinopWithPhiOperands(I))
return Phi;

if (Value *R = foldOpOfXWithXEqC(&I, SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, R);

// See if we can simplify any instructions used by the instruction whose sole
// purpose is to compute bits we don't care about.
if (SimplifyDemandedInstructionBits(I))
Expand Down Expand Up @@ -4571,6 +4577,9 @@ Instruction *InstCombinerImpl::visitXor(BinaryOperator &I) {
if (Instruction *NewXor = foldXorToXor(I, Builder))
return NewXor;

if (Value *R = foldOpOfXWithXEqC(&I, SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, R);

// (A&B)^(A&C) -> A&(B^C) etc
if (Value *V = foldUsingDistributiveLaws(I))
return replaceInstUsesWith(I, V);
Expand Down
3 changes: 3 additions & 0 deletions llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1491,6 +1491,9 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
if (!II) return visitCallBase(CI);

if (Value *R = foldOpOfXWithXEqC(II, SQ.getWithInstruction(&CI)))
return replaceInstUsesWith(CI, R);

// For atomic unordered mem intrinsics if len is not a positive or
// not a multiple of element size then behavior is undefined.
if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(II))
Expand Down
1 change: 1 addition & 0 deletions llvm/lib/Transforms/InstCombine/InstCombineInternal.h
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,7 @@ class LLVM_LIBRARY_VISIBILITY InstCombinerImpl final

Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);

Value *foldOpOfXWithXEqC(Value *Op, const SimplifyQuery &SQ);
bool tryToSinkInstruction(Instruction *I, BasicBlock *DestBlock);
void tryToSinkInstructionDbgValues(
Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,
Expand Down
3 changes: 3 additions & 0 deletions llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,9 @@ Instruction *InstCombinerImpl::visitMul(BinaryOperator &I) {
if (Instruction *Phi = foldBinopWithPhiOperands(I))
return Phi;

if (Value *R = foldOpOfXWithXEqC(&I, SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, R);

if (Value *V = foldUsingDistributiveLaws(I))
return replaceInstUsesWith(I, V);

Expand Down
9 changes: 9 additions & 0 deletions llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1020,6 +1020,9 @@ Instruction *InstCombinerImpl::visitShl(BinaryOperator &I) {
if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(&I, Q, Builder))
return V;

if (Value *R = foldOpOfXWithXEqC(&I, Q))
return replaceInstUsesWith(I, R);

Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Type *Ty = I.getType();
unsigned BitWidth = Ty->getScalarSizeInBits();
Expand Down Expand Up @@ -1252,6 +1255,9 @@ Instruction *InstCombinerImpl::visitLShr(BinaryOperator &I) {
if (Instruction *R = commonShiftTransforms(I))
return R;

if (Value *R = foldOpOfXWithXEqC(&I, SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, R);

Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Type *Ty = I.getType();
Value *X;
Expand Down Expand Up @@ -1625,6 +1631,9 @@ Instruction *InstCombinerImpl::visitAShr(BinaryOperator &I) {
if (Instruction *R = commonShiftTransforms(I))
return R;

if (Value *R = foldOpOfXWithXEqC(&I, SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, R);

Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Type *Ty = I.getType();
unsigned BitWidth = Ty->getScalarSizeInBits();
Expand Down
83 changes: 83 additions & 0 deletions llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4829,6 +4829,89 @@ void InstCombinerImpl::tryToSinkInstructionDbgValues(
}
}

// If we have:
// `(op X, (zext/sext (icmp eq X, C)))`
// We can transform it to:
// `(select (icmp eq X, C), (op C, (zext/sext 1)), (op X, 0))`
// We do so if the `zext/sext` is one use and `(op X, 0)` simplifies.
Value *InstCombinerImpl::foldOpOfXWithXEqC(Value *Op, const SimplifyQuery &SQ) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to handle add X, (zext/sext (icmp eq/ne X, C)) first. The current version looks like an over-generalization.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I remember correctly, similar patterns like X * (X != 0) -> X exist already. Can they be folded here too?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The X != C case isn't the same. We can handle if if (op x, 1) simplifies which is a lot rarer than (op x, 0).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to handle add X, (zext/sext (icmp eq/ne X, C)) first. The current version looks like an over-generalization.

I can see the argument that the intrinsics complicate the situation a bit and can drop those if you feel strongly, but imo the rest of the code is basically the same if its just add vs any op.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, I think the additional complexity is actually quite significant. Doing this for just add is something like:

  if (match(I, m_c_Add(m_Value(X),
                       m_ZExt(m_CombineAnd(
                           m_Value(Cond),
                           m_ICmp(Pred, m_Deferred(X), m_ImmConstant(C)))))) &&
      Pred == ICmpInst::ICMP_EQ) 
    return Builder.CreateSelect(
        Cond, Builder.CreateAdd(C, ConstantInt::get(C->getType(), 1)), X);

Generalizing it to other operations is a hundred lines of code here, plus a dozen call sites elsewhere.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, let me test which operators get hit. If its just add ill drop all this, otherwise think its worth the generlization.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, created #93840

Value *Cond;
Constant *C, *ExtC;

// match `(op X, (zext/sext (icmp eq X, C)))` and see if `(op X, 0)`
// simplifies.
// If we match and simplify, store the `icmp` in `Cond`, `(zext/sext C)` in
// `ExtC`.
auto MatchXWithXEqC = [&](Value *Op0, Value *Op1) -> Value * {
if (match(Op0, m_OneUse(m_ZExtOrSExt(m_Value(Cond))))) {
ICmpInst::Predicate Pred;
if (!match(Cond, m_ICmp(Pred, m_Specific(Op1), m_ImmConstant(C))) ||
Pred != ICmpInst::ICMP_EQ)
return nullptr;

ExtC = isa<SExtInst>(Op0) ? ConstantInt::getAllOnesValue(C->getType())
: ConstantInt::get(C->getType(), 1);
return simplifyWithOpReplaced(Op, Op0,
Constant::getNullValue(Op1->getType()), SQ,
/*AllowRefinement=*/true);
}
return nullptr;
};

Value *SimpleOp = nullptr, *ConstOp = nullptr;
if (auto *BO = dyn_cast<BinaryOperator>(Op)) {
switch (BO->getOpcode()) {
// Potential TODO: For all of these, if Op1 is the compare, the compare
// must be true and we could replace Op0 with C (otherwise immediate UB).
case Instruction::UDiv:
case Instruction::SDiv:
case Instruction::URem:
case Instruction::SRem:
return nullptr;
default:
break;
}

// Try X is Op0
if ((SimpleOp = MatchXWithXEqC(BO->getOperand(0), BO->getOperand(1))))
ConstOp = Builder.CreateBinOp(BO->getOpcode(), ExtC, C);
// Try X is Op1
else if ((SimpleOp = MatchXWithXEqC(BO->getOperand(1), BO->getOperand(0))))
ConstOp = Builder.CreateBinOp(BO->getOpcode(), C, ExtC);
} else if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
switch (II->getIntrinsicID()) {
default:
return nullptr;
case Intrinsic::sshl_sat:
case Intrinsic::ushl_sat:
case Intrinsic::umax:
case Intrinsic::umin:
case Intrinsic::smax:
case Intrinsic::smin:
case Intrinsic::uadd_sat:
case Intrinsic::usub_sat:
case Intrinsic::sadd_sat:
case Intrinsic::ssub_sat:
// Try X is Op0
if ((SimpleOp =
MatchXWithXEqC(II->getArgOperand(0), II->getArgOperand(1))))
ConstOp = Builder.CreateBinaryIntrinsic(II->getIntrinsicID(), ExtC, C);
// Try X is Op1
else if ((SimpleOp =
MatchXWithXEqC(II->getArgOperand(1), II->getArgOperand(0))))
ConstOp = Builder.CreateBinaryIntrinsic(II->getIntrinsicID(), C, ExtC);
break;
}
}

assert((SimpleOp == nullptr) == (ConstOp == nullptr) &&
"Simplfied Op and Constant Op are de-synced!");
if (SimpleOp == nullptr)
return nullptr;

return Builder.CreateSelect(Cond, ConstOp, SimpleOp);
}

void InstCombinerImpl::tryToSinkInstructionDbgVariableRecords(
Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,
BasicBlock *DestBlock,
Expand Down
9 changes: 1 addition & 8 deletions llvm/test/Transforms/InstCombine/apint-shift.ll
Original file line number Diff line number Diff line change
Expand Up @@ -564,14 +564,7 @@ define i40 @test26(i40 %A) {
; https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9880
define i177 @ossfuzz_9880(i177 %X) {
; CHECK-LABEL: @ossfuzz_9880(
; CHECK-NEXT: [[A:%.*]] = alloca i177, align 8
; CHECK-NEXT: [[L1:%.*]] = load i177, ptr [[A]], align 4
; CHECK-NEXT: [[TMP1:%.*]] = icmp eq i177 [[L1]], -1
; CHECK-NEXT: [[B5_NEG:%.*]] = sext i1 [[TMP1]] to i177
; CHECK-NEXT: [[B14:%.*]] = add i177 [[L1]], [[B5_NEG]]
; CHECK-NEXT: [[TMP2:%.*]] = icmp eq i177 [[B14]], -1
; CHECK-NEXT: [[B1:%.*]] = zext i1 [[TMP2]] to i177
; CHECK-NEXT: ret i177 [[B1]]
; CHECK-NEXT: ret i177 0
;
%A = alloca i177
%L1 = load i177, ptr %A
Expand Down
Loading
Loading