Repository: prestodb/presto
Issue: Try/Lambda fails codegen when two identical instances appears in a single expression

These following queries fails:

```
SELECT
  try(1/x)+try(1/x)
FROM
  (VALUES 2) t(x)
```

Stack trace:

```
com.facebook.presto.spi.PrestoException: Compiler failed and interpreter is disabled
	at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitScanFilterAndProject(LocalExecutionPlanner.java:1056)
	at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitProject(LocalExecutionPlanner.java:950)
	at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitProject(LocalExecutionPlanner.java:538)
	at com.facebook.presto.sql.planner.plan.ProjectNode.accept(ProjectNode.java:91)
	at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitOutput(LocalExecutionPlanner.java:577)
	at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitOutput(LocalExecutionPlanner.java:538)
	at com.facebook.presto.sql.planner.plan.OutputNode.accept(OutputNode.java:81)
	at com.facebook.presto.sql.planner.LocalExecutionPlanner.plan(LocalExecutionPlanner.java:353)
	at com.facebook.presto.sql.planner.LocalExecutionPlanner.plan(LocalExecutionPlanner.java:292)
	at com.facebook.presto.execution.SqlTaskExecution.<init>(SqlTaskExecution.java:161)
	at com.facebook.presto.execution.SqlTaskExecution.createSqlTaskExecution(SqlTaskExecution.java:120)
	at com.facebook.presto.execution.SqlTaskExecutionFactory.create(SqlTaskExecutionFactory.java:70)
	at com.facebook.presto.execution.SqlTask.updateTask(SqlTask.java:315)
	at com.facebook.presto.execution.SqlTaskManager.updateTask(SqlTaskManager.java:324)
	at com.facebook.presto.server.TaskResource.createOrUpdateTask(TaskResource.java:125)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
	at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
	at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
	at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
	at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
	at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
	at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
	at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
	at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
	at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
	at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
	at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
	at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
	at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
	at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
	at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
	at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
	at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:845)
	at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1689)
	at io.airlift.http.server.TraceTokenFilter.doFilter(TraceTokenFilter.java:63)
	at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
	at io.airlift.http.server.TimingFilter.doFilter(TimingFilter.java:52)
	at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
	at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581)
	at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
	at org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:395)
	at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1182)
	at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
	at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
	at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
	at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119)
	at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:169)
	at org.eclipse.jetty.server.handler.HandlerList.handle(HandlerList.java:52)
	at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
	at org.eclipse.jetty.server.Server.handle(Server.java:523)
	at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)
	at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
	at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
	at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
	at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
	at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
	at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
	at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
	at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
	at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
	at java.lang.Thread.run(Thread.java:745)
Caused by: com.google.common.util.concurrent.UncheckedExecutionException: java.lang.IllegalArgumentException: Multiple entries with same key: $operator$DIVIDE(1, #0)=public java.lang.Long project_0_try_1(com.facebook.presto.spi.ConnectorSession session, com.facebook.presto.spi.block.Block block_0, int position) and $operator$DIVIDE(1, #0)=public java.lang.Long project_0_try_0(com.facebook.presto.spi.ConnectorSession session, com.facebook.presto.spi.block.Block block_0, int position)
	at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2203)
	at com.google.common.cache.LocalCache.get(LocalCache.java:3937)
	at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3941)
	at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4824)
	at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4830)
	at com.facebook.presto.sql.gen.ExpressionCompiler.compilePageProcessor(ExpressionCompiler.java:99)
	at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitScanFilterAndProject(LocalExecutionPlanner.java:1043)
	... 69 more
Caused by: java.lang.IllegalArgumentException: Multiple entries with same key: $operator$DIVIDE(1, #0)=public java.lang.Long project_0_try_1(com.facebook.presto.spi.ConnectorSession session, com.facebook.presto.spi.block.Block block_0, int position) and $operator$DIVIDE(1, #0)=public java.lang.Long project_0_try_0(com.facebook.presto.spi.ConnectorSession session, com.facebook.presto.spi.block.Block block_0, int position)
	at com.google.common.collect.ImmutableMap.checkNoConflict(ImmutableMap.java:150)
	at com.google.common.collect.RegularImmutableMap.checkNoConflictInBucket(RegularImmutableMap.java:104)
	at com.google.common.collect.RegularImmutableMap.<init>(RegularImmutableMap.java:70)
	at com.google.common.collect.ImmutableMap$Builder.build(ImmutableMap.java:254)
	at com.facebook.presto.sql.gen.PageProcessorCompiler.generateMethodsForLambdaAndTry(PageProcessorCompiler.java:798)
	at com.facebook.presto.sql.gen.PageProcessorCompiler.generateProjectMethod(PageProcessorCompiler.java:845)
	at com.facebook.presto.sql.gen.PageProcessorCompiler.generateMethods(PageProcessorCompiler.java:110)
	at com.facebook.presto.sql.gen.ExpressionCompiler.compileProcessor(ExpressionCompiler.java:134)
	at com.facebook.presto.sql.gen.ExpressionCompiler.compile(ExpressionCompiler.java:114)
	at com.facebook.presto.sql.gen.ExpressionCompiler.access$300(ExpressionCompiler.java:46)
	at com.facebook.presto.sql.gen.ExpressionCompiler$1.load(ExpressionCompiler.java:57)
	at com.facebook.presto.sql.gen.ExpressionCompiler$1.load(ExpressionCompiler.java:52)
	at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3527)
	at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2319)
	at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2282)
	at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2197)
	... 75 more
```

Changed files:
presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java
presto-main/src/main/java/com/facebook/presto/sql/gen/JoinFilterFunctionCompiler.java
presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java
presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java

diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java
index cdce084cef..0a2bf8d345 100644
--- a/presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java
+++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java
@@ -42,10 +42,12 @@ import com.facebook.presto.sql.relational.VariableReferenceExpression;
 import com.google.common.base.VerifyException;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
 import com.google.common.primitives.Primitives;
 import io.airlift.slice.Slice;
 
 import java.util.List;
+import java.util.Set;
 
 import static com.facebook.presto.bytecode.Access.PUBLIC;
 import static com.facebook.presto.bytecode.Access.a;
@@ -187,14 +189,13 @@ public class CursorProcessorCompiler
             RowExpression projection,
             String methodPrefix)
     {
-        List<RowExpression> lambdaAndTryExpressions = extractLambdaAndTryExpressions(projection);
+        Set<RowExpression> lambdaAndTryExpressions = ImmutableSet.copyOf(extractLambdaAndTryExpressions(projection));
 
         ImmutableMap.Builder<CallExpression, MethodDefinition> tryMethodMap = ImmutableMap.builder();
         ImmutableMap.Builder<LambdaDefinitionExpression, FieldDefinition> lambdaFieldMap = ImmutableMap.builder();
 
-        for (int i = 0; i < lambdaAndTryExpressions.size(); i++) {
-            RowExpression expression = lambdaAndTryExpressions.get(i);
-
+        int counter = 0;
+        for (RowExpression expression : lambdaAndTryExpressions) {
             if (expression instanceof CallExpression) {
                 CallExpression tryExpression = (CallExpression) expression;
                 verify(!Signatures.TRY.equals(tryExpression.getSignature().getName()));
@@ -217,7 +218,7 @@ public class CursorProcessorCompiler
                 MethodDefinition tryMethod = defineTryMethod(
                         innerExpressionVisitor,
                         containerClassDefinition,
-                        methodPrefix + "_try_" + i,
+                        methodPrefix + "_try_" + counter,
                         inputParameters,
                         Primitives.wrap(tryExpression.getType().getJavaType()),
                         tryExpression,
@@ -227,7 +228,7 @@ public class CursorProcessorCompiler
             }
             else if (expression instanceof LambdaDefinitionExpression) {
                 LambdaDefinitionExpression lambdaExpression = (LambdaDefinitionExpression) expression;
-                String fieldName = methodPrefix + "_lambda_" + i;
+                String fieldName = methodPrefix + "_lambda_" + counter;
                 PreGeneratedExpressions preGeneratedExpressions = new PreGeneratedExpressions(tryMethodMap.build(), lambdaFieldMap.build());
                 FieldDefinition methodHandleField = LambdaBytecodeGenerator.preGenerateLambdaExpression(
                         lambdaExpression,
@@ -242,6 +243,7 @@ public class CursorProcessorCompiler
             else {
                 throw new VerifyException(format("unexpected expression: %s", expression.toString()));
             }
+            counter++;
         }
 
         return new PreGeneratedExpressions(tryMethodMap.build(), lambdaFieldMap.build());
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/JoinFilterFunctionCompiler.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/JoinFilterFunctionCompiler.java
index e2674c36bf..779f34e164 100644
--- a/presto-main/src/main/java/com/facebook/presto/sql/gen/JoinFilterFunctionCompiler.java
+++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/JoinFilterFunctionCompiler.java
@@ -41,6 +41,7 @@ import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
 import com.google.common.primitives.Primitives;
 import it.unimi.dsi.fastutil.longs.LongArrayList;
 
@@ -49,6 +50,7 @@ import javax.inject.Inject;
 import java.lang.reflect.Constructor;
 import java.util.List;
 import java.util.Objects;
+import java.util.Set;
 
 import static com.facebook.presto.bytecode.Access.FINAL;
 import static com.facebook.presto.bytecode.Access.PRIVATE;
@@ -206,13 +208,12 @@ public class JoinFilterFunctionCompiler
             int leftBlocksSize,
             RowExpression filter)
     {
-        List<RowExpression> lambdaAndTryExpressions = extractLambdaAndTryExpressions(filter);
+        Set<RowExpression> lambdaAndTryExpressions = ImmutableSet.copyOf(extractLambdaAndTryExpressions(filter));
         ImmutableMap.Builder<CallExpression, MethodDefinition> tryMethodMap = ImmutableMap.builder();
         ImmutableMap.Builder<LambdaDefinitionExpression, FieldDefinition> lambdaFieldMap = ImmutableMap.builder();
 
-        for (int i = 0; i < lambdaAndTryExpressions.size(); i++) {
-            RowExpression expression = lambdaAndTryExpressions.get(i);
-
+        int counter = 0;
+        for (RowExpression expression : lambdaAndTryExpressions) {
             if (expression instanceof CallExpression) {
                 CallExpression tryExpression = (CallExpression) expression;
                 verify(!Signatures.TRY.equals(tryExpression.getSignature().getName()));
@@ -241,7 +242,7 @@ public class JoinFilterFunctionCompiler
                 MethodDefinition tryMethod = defineTryMethod(
                         innerExpressionVisitor,
                         containerClassDefinition,
-                        "try_" + i,
+                        "try_" + counter,
                         inputParameters,
                         Primitives.wrap(tryExpression.getType().getJavaType()),
                         tryExpression,
@@ -254,7 +255,7 @@ public class JoinFilterFunctionCompiler
                 PreGeneratedExpressions preGeneratedExpressions = new PreGeneratedExpressions(tryMethodMap.build(), lambdaFieldMap.build());
                 FieldDefinition methodHandleField = LambdaBytecodeGenerator.preGenerateLambdaExpression(
                         lambdaExpression,
-                        "lambda_" + i,
+                        "lambda_" + counter,
                         containerClassDefinition,
                         preGeneratedExpressions,
                         callSiteBinder,
@@ -265,6 +266,7 @@ public class JoinFilterFunctionCompiler
             else {
                 throw new VerifyException(format("unexpected expression: %s", expression.toString()));
             }
+            counter++;
         }
 
         return new PreGeneratedExpressions(tryMethodMap.build(), lambdaFieldMap.build());
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java
index dc3d308f1a..c88d29e35a 100644
--- a/presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java
+++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java
@@ -49,12 +49,14 @@ import com.facebook.presto.sql.relational.Signatures;
 import com.google.common.base.VerifyException;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
 import com.google.common.primitives.Primitives;
 
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.TreeSet;
 import java.util.stream.IntStream;
 
@@ -738,13 +740,12 @@ public class PageProcessorCompiler
             RowExpression projection,
             String methodPrefix)
     {
-        List<RowExpression> lambdaAndTryExpressions = extractLambdaAndTryExpressions(projection);
+        Set<RowExpression> lambdaAndTryExpressions = ImmutableSet.copyOf(extractLambdaAndTryExpressions(projection));
         ImmutableMap.Builder<CallExpression, MethodDefinition> tryMethodMap = ImmutableMap.builder();
         ImmutableMap.Builder<LambdaDefinitionExpression, FieldDefinition> lambdaFieldMap = ImmutableMap.builder();
 
-        for (int i = 0; i < lambdaAndTryExpressions.size(); i++) {
-            RowExpression expression = lambdaAndTryExpressions.get(i);
-
+        int counter = 0;
+        for (RowExpression expression : lambdaAndTryExpressions) {
             if (expression instanceof CallExpression) {
                 CallExpression tryExpression = (CallExpression) expression;
                 verify(!Signatures.TRY.equals(tryExpression.getSignature().getName()));
@@ -769,7 +770,7 @@ public class PageProcessorCompiler
                 MethodDefinition tryMethod = defineTryMethod(
                         innerExpressionVisitor,
                         containerClassDefinition,
-                        methodPrefix + "_try_" + i,
+                        methodPrefix + "_try_" + counter,
                         inputParameters,
                         Primitives.wrap(tryExpression.getType().getJavaType()),
                         tryExpression,
@@ -782,7 +783,7 @@ public class PageProcessorCompiler
                 PreGeneratedExpressions preGeneratedExpressions = new PreGeneratedExpressions(tryMethodMap.build(), lambdaFieldMap.build());
                 FieldDefinition methodHandleField = LambdaBytecodeGenerator.preGenerateLambdaExpression(
                         lambdaExpression,
-                        methodPrefix + "_lambda_" + i,
+                        methodPrefix + "_lambda_" + counter,
                         containerClassDefinition,
                         preGeneratedExpressions,
                         callSiteBinder,
@@ -793,6 +794,7 @@ public class PageProcessorCompiler
             else {
                 throw new VerifyException(format("unexpected expression: %s", expression.toString()));
             }
+            counter++;
         }
 
         return new PreGeneratedExpressions(tryMethodMap.build(), lambdaFieldMap.build());
diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java
index acf00efd70..2cbc0f0785 100644
--- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java
+++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java
@@ -216,6 +216,16 @@ public abstract class AbstractTestQueries
         assertQueryFails("SELECT transform(ARRAY[1], x -> max(x))", ".* Lambda expression cannot contain aggregations or window functions: .*");
     }
 
+    @Test
+    public void testTryLambdaRepeated()
+    {
+        assertQuery("SELECT x + x FROM (SELECT apply(a, i -> i * i) x FROM (VALUES 3) t(a))", "SELECT 18");
+        assertQuery("SELECT apply(a, i -> i * i) + apply(a, i -> i * i) FROM (VALUES 3) t(a)", "SELECT 18");
+        assertQuery("SELECT apply(a, i -> i * i), apply(a, i -> i * i) FROM (VALUES 3) t(a)", "SELECT 9, 9");
+        assertQuery("SELECT try(10 / a) + try(10 / a) FROM (VALUES 5) t(a)", "SELECT 4");
+        assertQuery("SELECT try(10 / a), try(10 / a) FROM (VALUES 5) t(a)", "SELECT 2, 2");
+    }
+
     @Test
     public void testNonDeterministicFilter()
     {