Some code size optimizations

1. Eliminate empty switch statements
2. Eliminate unnecessary == 0 and != 0 conditions in 'if'
This commit is contained in:
Alexey Andreev 2018-10-03 11:57:51 +03:00
parent 168bf1fa9c
commit 6b063bc567
2 changed files with 28 additions and 3 deletions

View File

@ -246,7 +246,7 @@ class OptimizingVisitor implements StatementVisitor, ExprVisitor {
pushLocation(expr.getLocation());
try {
expr.getCondition().acceptVisitor(this);
Expr cond = resultExpr;
Expr cond = optimizeCondition(resultExpr);
Statement barrier = addBarrier();
expr.getConsequent().acceptVisitor(this);
@ -786,7 +786,7 @@ class OptimizingVisitor implements StatementVisitor, ExprVisitor {
@Override
public void visit(ConditionalStatement statement) {
statement.getCondition().acceptVisitor(this);
statement.setCondition(resultExpr);
statement.setCondition(optimizeCondition(resultExpr));
List<Statement> consequent = processSequence(statement.getConsequent());
List<Statement> alternative = processSequence(statement.getAlternative());
if (consequent.isEmpty()) {
@ -871,7 +871,14 @@ class OptimizingVisitor implements StatementVisitor, ExprVisitor {
List<Statement> newDefault = processSequence(statement.getDefaultClause());
statement.getDefaultClause().clear();
statement.getDefaultClause().addAll(newDefault);
resultStmt = statement;
if (statement.getClauses().isEmpty()) {
SequentialStatement seq = new SequentialStatement();
seq.getSequence().addAll(statement.getDefaultClause());
resultStmt = seq;
} else {
resultStmt = statement;
}
}
@Override
@ -1074,4 +1081,19 @@ class OptimizingVisitor implements StatementVisitor, ExprVisitor {
return false;
}
private Expr optimizeCondition(Expr expr) {
if (expr instanceof BinaryExpr) {
BinaryExpr binary = (BinaryExpr) expr;
if (isZero(((BinaryExpr) expr).getSecondOperand())) {
switch (binary.getOperation()) {
case EQUALS:
return ExprOptimizer.invert(binary.getFirstOperand());
case NOT_EQUALS:
return binary.getFirstOperand();
}
}
}
return expr;
}
}

View File

@ -1354,6 +1354,9 @@ public class StatementRenderer implements ExprVisitor, StatementVisitor {
precedence = Precedence.CONDITIONAL.next();
expr.getExpr().acceptVisitor(this);
writer.append(" instanceof ").appendClass(clsName);
if (needsParentheses) {
writer.append(')');
}
if (expr.getLocation() != null) {
popLocation();
}