From c38555ae41d3d80d94babd67439a7df03dc769ae Mon Sep 17 00:00:00 2001 From: Washi Date: Tue, 21 May 2024 21:04:19 +0200 Subject: [PATCH] Reduce redundant local variable reassignments. --- src/Core/Echo.Ast/AstFormatter.cs | 4 ++-- src/Core/Echo.Ast/Construction/ControlFlowGraphLifter.cs | 6 +++++- src/Core/Echo.Ast/IAstNodeVisitor.cs | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Core/Echo.Ast/AstFormatter.cs b/src/Core/Echo.Ast/AstFormatter.cs index 67ba43bd..e739a3ef 100644 --- a/src/Core/Echo.Ast/AstFormatter.cs +++ b/src/Core/Echo.Ast/AstFormatter.cs @@ -86,9 +86,9 @@ public void Visit(AssignmentStatement statement, IndentedTextWrite } /// - public void Visit(ExpressionStatement expression, IndentedTextWriter state) + public void Visit(ExpressionStatement statement, IndentedTextWriter state) { - expression.Expression.Accept(this, state); + statement.Expression.Accept(this, state); state.Write(';'); } diff --git a/src/Core/Echo.Ast/Construction/ControlFlowGraphLifter.cs b/src/Core/Echo.Ast/Construction/ControlFlowGraphLifter.cs index 006d67aa..fd0e585c 100644 --- a/src/Core/Echo.Ast/Construction/ControlFlowGraphLifter.cs +++ b/src/Core/Echo.Ast/Construction/ControlFlowGraphLifter.cs @@ -208,6 +208,10 @@ private static void FlushStackAndPush(LiftedNode node, Stack { + // Optimization: If we are simply reassigning variables, we can skip introducing a new variable (inlining). + if (value is VariableExpression variableExpression) + return variableExpression.Variable; + var intermediate = n.DeclareStackIntermediate(); n.Transformed.Contents.Instructions.Add(Statement.Assignment(intermediate, value)); return intermediate; @@ -245,7 +249,7 @@ private void FlushStackIfImpure( private static IList FlushStackInternal( LiftedNode node, Stack> stack, - Func, Expression, SyntheticVariable> flush) + Func, Expression, IVariable> flush) { // Collect all values from the stack. var values = new Expression[stack.Count]; diff --git a/src/Core/Echo.Ast/IAstNodeVisitor.cs b/src/Core/Echo.Ast/IAstNodeVisitor.cs index b250dfbe..4c0619f4 100644 --- a/src/Core/Echo.Ast/IAstNodeVisitor.cs +++ b/src/Core/Echo.Ast/IAstNodeVisitor.cs @@ -73,7 +73,7 @@ public interface IAstNodeVisitor /// /// Visits a given /// - void Visit(ExpressionStatement expression, TState state); + void Visit(ExpressionStatement statement, TState state); /// /// Visits a given