diff --git a/codeOptimizers/src/prog8/optimizer/ExpressionSimplifier.kt b/codeOptimizers/src/prog8/optimizer/ExpressionSimplifier.kt index b759e2115..9577a4b7d 100644 --- a/codeOptimizers/src/prog8/optimizer/ExpressionSimplifier.kt +++ b/codeOptimizers/src/prog8/optimizer/ExpressionSimplifier.kt @@ -19,13 +19,7 @@ import kotlin.math.pow Investigate what optimizations binaryen has, also see https://egorbo.com/peephole-optimizations.html -some of these may already be present: - -X ^ -1 => ~x -X >= 1 => X > 0 -X < 1 => X <= 0 - -and some const foldings (that may already be done as well): +Add some const foldings (that may already be done as well): X + ะก1 == C2 => X == C2 - C1 ((X + C1) + C2) => (X + (C1 + C2)) ((X + C1) + (Y + C2)) => ((X + Y) + (C1 + C2)) @@ -191,6 +185,12 @@ class ExpressionSimplifier(private val program: Program) : AstWalker() { } } + if(leftDt!=DataType.FLOAT && expr.operator == ">=" && rightVal?.number == 1.0) { + // for integers: x >= 1 --> x > 0 + expr.operator = ">" + return listOf(IAstModification.ReplaceNode(expr.right, NumericLiteralValue.optimalInteger(0, expr.right.position), expr)) + } + if(expr.operator == ">=" && rightVal?.number == 0.0) { if (leftDt == DataType.UBYTE || leftDt == DataType.UWORD) { // unsigned >= 0 --> true @@ -198,6 +198,12 @@ class ExpressionSimplifier(private val program: Program) : AstWalker() { } } + if(leftDt!=DataType.FLOAT && expr.operator == "<" && rightVal?.number == 1.0) { + // for integers: x < 1 --> x <= 0 + expr.operator = "<=" + return listOf(IAstModification.ReplaceNode(expr.right, NumericLiteralValue.optimalInteger(0, expr.right.position), expr)) + } + if(expr.operator == "<" && rightVal?.number == 0.0) { if (leftDt == DataType.UBYTE || leftDt == DataType.UWORD) { // unsigned < 0 --> false diff --git a/examples/test.p8 b/examples/test.p8 index ad290db0a..3590901c9 100644 --- a/examples/test.p8 +++ b/examples/test.p8 @@ -1,4 +1,5 @@ %import textio +%import floats main { @@ -7,20 +8,24 @@ main { ubyte xx = 1.234 ubyte yy = 2.234 uword aw + byte bb + float fl ; TODO: bitwise operations with a negative constant number -> replace the number by its positive 2 complement - aw = xx ^ 65535 - aw = ~xx - yy = xx ^ 255 - yy = ~xx + if aw<1 + yy++ + if aw<=0 + yy++ -; *(&X) => X -; X % 1 => 0 -; X / 1 => X -; X ^ -1 => ~x -; X >= 1 => X > 0 -; X < 1 => X <= 0 + if yy<1 + yy++ + if yy<=0 + yy++ + if bb<1 + yy++ + if bb<=0 + yy++ txt.print_ub(yy) txt.print_uw(aw)