Skip to content

Optimize binary operators with equal children even if side effect #7460

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

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Prev Previous commit
Next Next commit
opt for 7440
  • Loading branch information
xuruiyang2002 committed Apr 7, 2025
commit 4362844a225f4ddb31b129e99e8876fcc6cb56cb
27 changes: 14 additions & 13 deletions src/passes/OptimizeInstructions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -856,13 +856,11 @@ struct OptimizeInstructions
if (auto* ret = replaceZeroBitsWithZero(curr)) {
return replaceCurrent(ret);
}
// finally, try more expensive operations on the curr in
// the case that they have no side effects
if (!effects(curr->left).hasSideEffects()) {
if (ExpressionAnalyzer::equal(curr->left, curr->right)) {
if (auto* ret = optimizeBinaryWithEqualEffectlessChildren(curr)) {
return replaceCurrent(ret);
}
// finally, try more expensive operations on the curr
// regardless of whether they have side effects or not.
if (areConsecutiveInputsEqual(curr->left, curr->right)) {
if (auto* ret = optimizeBinaryWithEqualChildren(curr)) {
return replaceCurrent(ret);
}
}

Expand Down Expand Up @@ -5177,16 +5175,17 @@ struct OptimizeInstructions
return nullptr;
}

// given a binary expression with equal children and no side effects in
// either, we can fold various things
Expression* optimizeBinaryWithEqualEffectlessChildren(Binary* binary) {
// given a binary expression with equal children, we can fold various things
// regardless of side effects.
Expression* optimizeBinaryWithEqualChildren(Binary* binary) {
// TODO add: perhaps worth doing 2*x if x is quite large?
switch (binary->op) {
case SubInt32:
case XorInt32:
case SubInt64:
case XorInt64:
return LiteralUtils::makeZero(binary->left->type, *getModule());
return getDroppedChildrenAndAppend(binary->left,
LiteralUtils::makeZero(binary->left->type, *getModule()));
case NeInt32:
case LtSInt32:
case LtUInt32:
Expand All @@ -5197,7 +5196,8 @@ struct OptimizeInstructions
case LtUInt64:
case GtSInt64:
case GtUInt64:
return LiteralUtils::makeZero(Type::i32, *getModule());
return getDroppedChildrenAndAppend(binary->left,
LiteralUtils::makeZero(Type::i32, *getModule()));
case AndInt32:
case OrInt32:
case AndInt64:
Expand All @@ -5213,7 +5213,8 @@ struct OptimizeInstructions
case LeUInt64:
case GeSInt64:
case GeUInt64:
return LiteralUtils::makeFromInt32(1, Type::i32, *getModule());
return getDroppedChildrenAndAppend(binary->left,
LiteralUtils::makeFromInt32(1, Type::i32, *getModule()));
default:
return nullptr;
}
Expand Down
Loading