Search in sources :

Example 31 with BytecodeNode

use of com.facebook.presto.bytecode.BytecodeNode in project presto by prestodb.

the class FunctionCallCodeGenerator method generateCall.

public BytecodeNode generateCall(FunctionHandle functionHandle, BytecodeGeneratorContext context, Type returnType, List<RowExpression> arguments, Optional<Variable> outputBlockVariable) {
    FunctionAndTypeManager functionAndTypeManager = context.getFunctionManager();
    ScalarFunctionImplementation function = functionAndTypeManager.getScalarFunctionImplementation(functionHandle);
    checkArgument(function instanceof JavaScalarFunctionImplementation, format("FunctionCallCodeGenerator only handles JavaScalarFunctionImplementation, get %s", function.getClass().getName()));
    JavaScalarFunctionImplementation javaFunction = (JavaScalarFunctionImplementation) function;
    List<BytecodeNode> argumentsBytecode = new ArrayList<>();
    ScalarFunctionImplementationChoice choice = getAllScalarFunctionImplementationChoices(javaFunction).get(0);
    for (int i = 0; i < arguments.size(); i++) {
        RowExpression argument = arguments.get(i);
        ArgumentProperty argumentProperty = choice.getArgumentProperty(i);
        if (argumentProperty.getArgumentType() == VALUE_TYPE) {
            argumentsBytecode.add(context.generate(argument, Optional.empty()));
        } else {
            argumentsBytecode.add(context.generate(argument, Optional.empty(), Optional.of(argumentProperty.getLambdaInterface())));
        }
    }
    return context.generateCall(functionAndTypeManager.getFunctionMetadata(functionHandle).getName().getObjectName(), javaFunction, argumentsBytecode, outputBlockVariable.map(variable -> new OutputBlockVariableAndType(variable, returnType)));
}
Also used : JavaScalarFunctionImplementation(com.facebook.presto.spi.function.JavaScalarFunctionImplementation) ScalarFunctionImplementation(com.facebook.presto.spi.function.ScalarFunctionImplementation) FunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager) RowExpression(com.facebook.presto.spi.relation.RowExpression) VALUE_TYPE(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.ArgumentType.VALUE_TYPE) Variable(com.facebook.presto.bytecode.Variable) JavaScalarFunctionImplementation(com.facebook.presto.spi.function.JavaScalarFunctionImplementation) OutputBlockVariableAndType(com.facebook.presto.sql.gen.BytecodeUtils.OutputBlockVariableAndType) ScalarFunctionImplementationChoice(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice) String.format(java.lang.String.format) ArrayList(java.util.ArrayList) ArgumentProperty(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.ArgumentProperty) BytecodeUtils.getAllScalarFunctionImplementationChoices(com.facebook.presto.sql.gen.BytecodeUtils.getAllScalarFunctionImplementationChoices) BytecodeNode(com.facebook.presto.bytecode.BytecodeNode) List(java.util.List) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ScalarFunctionImplementation(com.facebook.presto.spi.function.ScalarFunctionImplementation) FunctionHandle(com.facebook.presto.spi.function.FunctionHandle) Optional(java.util.Optional) Type(com.facebook.presto.common.type.Type) JavaScalarFunctionImplementation(com.facebook.presto.spi.function.JavaScalarFunctionImplementation) ArgumentProperty(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.ArgumentProperty) ScalarFunctionImplementationChoice(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice) FunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager) ArrayList(java.util.ArrayList) RowExpression(com.facebook.presto.spi.relation.RowExpression) OutputBlockVariableAndType(com.facebook.presto.sql.gen.BytecodeUtils.OutputBlockVariableAndType) BytecodeNode(com.facebook.presto.bytecode.BytecodeNode)

Example 32 with BytecodeNode

use of com.facebook.presto.bytecode.BytecodeNode in project presto by prestodb.

the class BytecodeGeneratorContext method generateCall.

/**
 * Generates a function call with null handling, automatic binding of session parameter, etc.
 */
public BytecodeNode generateCall(String name, JavaScalarFunctionImplementation function, List<BytecodeNode> arguments, Optional<OutputBlockVariableAndType> outputBlockVariableAndType) {
    Optional<BytecodeNode> instance = Optional.empty();
    if (function instanceof BuiltInScalarFunctionImplementation && ((BuiltInScalarFunctionImplementation) function).getInstanceFactory().isPresent()) {
        FieldDefinition field = cachedInstanceBinder.getCachedInstance(((BuiltInScalarFunctionImplementation) function).getInstanceFactory().get());
        instance = Optional.of(scope.getThis().getField(field));
    }
    return generateInvocation(scope, name, function, instance, arguments, callSiteBinder, outputBlockVariableAndType);
}
Also used : BuiltInScalarFunctionImplementation(com.facebook.presto.operator.scalar.BuiltInScalarFunctionImplementation) FieldDefinition(com.facebook.presto.bytecode.FieldDefinition) BytecodeNode(com.facebook.presto.bytecode.BytecodeNode)

Example 33 with BytecodeNode

use of com.facebook.presto.bytecode.BytecodeNode in project presto by prestodb.

the class TestSetFieldBytecodeExpression method assertSetPoint.

public static void assertSetPoint(Function<BytecodeExpression, BytecodeExpression> setX) throws Exception {
    Function<Scope, BytecodeNode> nodeGenerator = scope -> {
        Variable point = scope.declareVariable(Point.class, "point");
        BytecodeExpression setExpression = setX.apply(point);
        assertEquals(setExpression.toString(), "point.x = 42;");
        return new BytecodeBlock().append(point.set(newInstance(Point.class, constantInt(3), constantInt(7)))).append(setExpression).append(point.ret());
    };
    assertBytecodeNode(nodeGenerator, type(Point.class), new Point(42, 7));
}
Also used : Variable(com.facebook.presto.bytecode.Variable) BytecodeExpressionAssertions.assertBytecodeNode(com.facebook.presto.bytecode.expression.BytecodeExpressionAssertions.assertBytecodeNode) BytecodeExpressions.constantInt(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantInt) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) Point(java.awt.Point) Field(java.lang.reflect.Field) BytecodeExpressions.newInstance(com.facebook.presto.bytecode.expression.BytecodeExpressions.newInstance) Function(java.util.function.Function) BytecodeExpressions.constantString(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantString) BytecodeNode(com.facebook.presto.bytecode.BytecodeNode) BytecodeExpressions.setStatic(com.facebook.presto.bytecode.expression.BytecodeExpressions.setStatic) Scope(com.facebook.presto.bytecode.Scope) ParameterizedType.type(com.facebook.presto.bytecode.ParameterizedType.type) BytecodeExpressionAssertions.assertBytecodeExpression(com.facebook.presto.bytecode.expression.BytecodeExpressionAssertions.assertBytecodeExpression) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) Variable(com.facebook.presto.bytecode.Variable) Scope(com.facebook.presto.bytecode.Scope) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) BytecodeExpressionAssertions.assertBytecodeNode(com.facebook.presto.bytecode.expression.BytecodeExpressionAssertions.assertBytecodeNode) BytecodeNode(com.facebook.presto.bytecode.BytecodeNode) Point(java.awt.Point) BytecodeExpressionAssertions.assertBytecodeExpression(com.facebook.presto.bytecode.expression.BytecodeExpressionAssertions.assertBytecodeExpression)

Example 34 with BytecodeNode

use of com.facebook.presto.bytecode.BytecodeNode in project presto by prestodb.

the class MapTransformValueFunction method generateTransform.

private static MethodHandle generateTransform(Type keyType, Type valueType, Type transformedValueType, Type resultMapType) {
    CallSiteBinder binder = new CallSiteBinder();
    Class<?> keyJavaType = Primitives.wrap(keyType.getJavaType());
    Class<?> valueJavaType = Primitives.wrap(valueType.getJavaType());
    Class<?> transformedValueJavaType = Primitives.wrap(transformedValueType.getJavaType());
    ClassDefinition definition = new ClassDefinition(a(PUBLIC, FINAL), makeClassName("MapTransformValue"), type(Object.class));
    definition.declareDefaultConstructor(a(PRIVATE));
    // define transform method
    Parameter state = arg("state", Object.class);
    Parameter block = arg("block", Block.class);
    Parameter function = arg("function", BinaryFunctionInterface.class);
    MethodDefinition method = definition.declareMethod(a(PUBLIC, STATIC), "transform", type(Block.class), ImmutableList.of(state, block, function));
    BytecodeBlock body = method.getBody();
    Scope scope = method.getScope();
    Variable positionCount = scope.declareVariable(int.class, "positionCount");
    Variable position = scope.declareVariable(int.class, "position");
    Variable pageBuilder = scope.declareVariable(PageBuilder.class, "pageBuilder");
    Variable mapBlockBuilder = scope.declareVariable(BlockBuilder.class, "mapBlockBuilder");
    Variable blockBuilder = scope.declareVariable(BlockBuilder.class, "blockBuilder");
    Variable keyElement = scope.declareVariable(keyJavaType, "keyElement");
    Variable valueElement = scope.declareVariable(valueJavaType, "valueElement");
    Variable transformedValueElement = scope.declareVariable(transformedValueJavaType, "transformedValueElement");
    // invoke block.getPositionCount()
    body.append(positionCount.set(block.invoke("getPositionCount", int.class)));
    // prepare the single map block builder
    body.append(pageBuilder.set(state.cast(PageBuilder.class)));
    body.append(new IfStatement().condition(pageBuilder.invoke("isFull", boolean.class)).ifTrue(pageBuilder.invoke("reset", void.class)));
    body.append(mapBlockBuilder.set(pageBuilder.invoke("getBlockBuilder", BlockBuilder.class, constantInt(0))));
    body.append(blockBuilder.set(mapBlockBuilder.invoke("beginBlockEntry", BlockBuilder.class)));
    // throw null key exception block
    BytecodeNode throwNullKeyException = new BytecodeBlock().append(newInstance(PrestoException.class, getStatic(INVALID_FUNCTION_ARGUMENT.getDeclaringClass(), "INVALID_FUNCTION_ARGUMENT").cast(ErrorCodeSupplier.class), constantString("map key cannot be null"))).throwObject();
    SqlTypeBytecodeExpression keySqlType = constantType(binder, keyType);
    BytecodeNode loadKeyElement;
    if (!keyType.equals(UNKNOWN)) {
        loadKeyElement = new BytecodeBlock().append(keyElement.set(keySqlType.getValue(block, position).cast(keyJavaType)));
    } else {
        // make sure invokeExact will not take uninitialized keys during compile time
        // but if we reach this point during runtime, it is an exception
        // also close the block builder before throwing as we may be in a TRY() call
        // so that subsequent calls do not find it in an inconsistent state
        loadKeyElement = new BytecodeBlock().append(mapBlockBuilder.invoke("closeEntry", BlockBuilder.class).pop()).append(keyElement.set(constantNull(keyJavaType))).append(throwNullKeyException);
    }
    SqlTypeBytecodeExpression valueSqlType = constantType(binder, valueType);
    BytecodeNode loadValueElement;
    if (!valueType.equals(UNKNOWN)) {
        loadValueElement = new IfStatement().condition(block.invoke("isNull", boolean.class, add(position, constantInt(1)))).ifTrue(valueElement.set(constantNull(valueJavaType))).ifFalse(valueElement.set(valueSqlType.getValue(block, add(position, constantInt(1))).cast(valueJavaType)));
    } else {
        loadValueElement = new BytecodeBlock().append(valueElement.set(constantNull(valueJavaType)));
    }
    BytecodeNode writeTransformedValueElement;
    if (!transformedValueType.equals(UNKNOWN)) {
        writeTransformedValueElement = new IfStatement().condition(equal(transformedValueElement, constantNull(transformedValueJavaType))).ifTrue(blockBuilder.invoke("appendNull", BlockBuilder.class).pop()).ifFalse(constantType(binder, transformedValueType).writeValue(blockBuilder, transformedValueElement.cast(transformedValueType.getJavaType())));
    } else {
        writeTransformedValueElement = new BytecodeBlock().append(blockBuilder.invoke("appendNull", BlockBuilder.class).pop());
    }
    Variable transformationException = scope.declareVariable(Throwable.class, "transformationException");
    body.append(new ForLoop().initialize(position.set(constantInt(0))).condition(lessThan(position, positionCount)).update(incrementVariable(position, (byte) 2)).body(new BytecodeBlock().append(loadKeyElement).append(loadValueElement).append(new TryCatch("Close builder before throwing to avoid subsequent calls finding it in an inconsistent state if we are in in a TRY() call.", transformedValueElement.set(function.invoke("apply", Object.class, keyElement.cast(Object.class), valueElement.cast(Object.class)).cast(transformedValueJavaType)), new BytecodeBlock().append(mapBlockBuilder.invoke("closeEntry", BlockBuilder.class).pop()).append(pageBuilder.invoke("declarePosition", void.class)).putVariable(transformationException).append(invokeStatic(Throwables.class, "throwIfUnchecked", void.class, transformationException)).append(newInstance(RuntimeException.class, transformationException)).throwObject(), type(Throwable.class))).append(keySqlType.invoke("appendTo", void.class, block, position, blockBuilder)).append(writeTransformedValueElement)));
    body.append(mapBlockBuilder.invoke("closeEntry", BlockBuilder.class).pop());
    body.append(pageBuilder.invoke("declarePosition", void.class));
    body.append(constantType(binder, resultMapType).invoke("getObject", Object.class, mapBlockBuilder.cast(Block.class), subtract(mapBlockBuilder.invoke("getPositionCount", int.class), constantInt(1))).ret());
    Class<?> generatedClass = defineClass(definition, Object.class, binder.getBindings(), MapTransformValueFunction.class.getClassLoader());
    return methodHandle(generatedClass, "transform", Object.class, Block.class, BinaryFunctionInterface.class);
}
Also used : TryCatch(com.facebook.presto.bytecode.control.TryCatch) Signature.typeVariable(com.facebook.presto.spi.function.Signature.typeVariable) Variable(com.facebook.presto.bytecode.Variable) VariableInstruction.incrementVariable(com.facebook.presto.bytecode.instruction.VariableInstruction.incrementVariable) ErrorCodeSupplier(com.facebook.presto.spi.ErrorCodeSupplier) ForLoop(com.facebook.presto.bytecode.control.ForLoop) Throwables(com.google.common.base.Throwables) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) IfStatement(com.facebook.presto.bytecode.control.IfStatement) Scope(com.facebook.presto.bytecode.Scope) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) CallSiteBinder(com.facebook.presto.bytecode.CallSiteBinder) Parameter(com.facebook.presto.bytecode.Parameter) TypeSignatureParameter(com.facebook.presto.common.type.TypeSignatureParameter) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) Block(com.facebook.presto.common.block.Block) BytecodeNode(com.facebook.presto.bytecode.BytecodeNode) SqlTypeBytecodeExpression(com.facebook.presto.sql.gen.SqlTypeBytecodeExpression) BlockBuilder(com.facebook.presto.common.block.BlockBuilder)

Example 35 with BytecodeNode

use of com.facebook.presto.bytecode.BytecodeNode in project presto by prestodb.

the class MapFilterFunction method mapFilter.

@CodegenScalarFunction(value = "map_filter", deterministic = false)
@Description("return map containing entries that match the given predicate")
@TypeParameter("K")
@TypeParameter("V")
@SqlType("map(K,V)")
public static MethodHandle mapFilter(@SqlType("map(K,V)") Type inputType, @SqlType("function(K,V,boolean)") Type filter) {
    MapType mapType = (MapType) inputType;
    CallSiteBinder binder = new CallSiteBinder();
    Type keyType = mapType.getKeyType();
    Type valueType = mapType.getValueType();
    Class<?> keyJavaType = Primitives.wrap(keyType.getJavaType());
    Class<?> valueJavaType = Primitives.wrap(valueType.getJavaType());
    ClassDefinition definition = new ClassDefinition(a(PUBLIC, FINAL), makeClassName("MapFilter"), type(Object.class));
    definition.declareDefaultConstructor(a(PRIVATE));
    Parameter block = arg("block", Block.class);
    Parameter function = arg("function", BinaryFunctionInterface.class);
    MethodDefinition method = definition.declareMethod(a(PUBLIC, STATIC), "filter", type(Block.class), ImmutableList.of(block, function));
    BytecodeBlock body = method.getBody();
    Scope scope = method.getScope();
    Variable positionCount = scope.declareVariable(int.class, "positionCount");
    Variable position = scope.declareVariable(int.class, "position");
    Variable mapBlockBuilder = scope.declareVariable(BlockBuilder.class, "mapBlockBuilder");
    Variable singleMapBlockWriter = scope.declareVariable(BlockBuilder.class, "singleMapBlockWriter");
    Variable keyElement = scope.declareVariable(keyJavaType, "keyElement");
    Variable valueElement = scope.declareVariable(valueJavaType, "valueElement");
    Variable keep = scope.declareVariable(Boolean.class, "keep");
    // invoke block.getPositionCount()
    body.append(positionCount.set(block.invoke("getPositionCount", int.class)));
    // prepare the single map block builder
    body.append(mapBlockBuilder.set(constantType(binder, mapType).invoke("createBlockBuilder", BlockBuilder.class, constantNull(BlockBuilderStatus.class), constantInt(0))));
    body.append(singleMapBlockWriter.set(mapBlockBuilder.invoke("beginBlockEntry", BlockBuilder.class)));
    SqlTypeBytecodeExpression keySqlType = constantType(binder, keyType);
    BytecodeNode loadKeyElement;
    if (!keyType.equals(UNKNOWN)) {
        // key element must be non-null
        loadKeyElement = new BytecodeBlock().append(keyElement.set(keySqlType.getValue(block, position).cast(keyJavaType)));
    } else {
        loadKeyElement = new BytecodeBlock().append(keyElement.set(constantNull(keyJavaType)));
    }
    SqlTypeBytecodeExpression valueSqlType = constantType(binder, valueType);
    BytecodeNode loadValueElement;
    if (!valueType.equals(UNKNOWN)) {
        loadValueElement = new IfStatement().condition(block.invoke("isNull", boolean.class, add(position, constantInt(1)))).ifTrue(valueElement.set(constantNull(valueJavaType))).ifFalse(valueElement.set(valueSqlType.getValue(block, add(position, constantInt(1))).cast(valueJavaType)));
    } else {
        loadValueElement = new BytecodeBlock().append(valueElement.set(constantNull(valueJavaType)));
    }
    body.append(new ForLoop().initialize(position.set(constantInt(0))).condition(lessThan(position, positionCount)).update(incrementVariable(position, (byte) 2)).body(new BytecodeBlock().append(loadKeyElement).append(loadValueElement).append(keep.set(function.invoke("apply", Object.class, keyElement.cast(Object.class), valueElement.cast(Object.class)).cast(Boolean.class))).append(new IfStatement("if (keep != null && keep) ...").condition(and(notEqual(keep, constantNull(Boolean.class)), keep.cast(boolean.class))).ifTrue(new BytecodeBlock().append(keySqlType.invoke("appendTo", void.class, block, position, singleMapBlockWriter)).append(valueSqlType.invoke("appendTo", void.class, block, add(position, constantInt(1)), singleMapBlockWriter))))));
    body.append(mapBlockBuilder.invoke("closeEntry", BlockBuilder.class).pop());
    body.append(constantType(binder, mapType).invoke("getObject", Object.class, mapBlockBuilder.cast(Block.class), subtract(mapBlockBuilder.invoke("getPositionCount", int.class), constantInt(1))).ret());
    Class<?> generatedClass = defineClass(definition, Object.class, binder.getBindings(), MapFilterFunction.class.getClassLoader());
    return methodHandle(generatedClass, "filter", Block.class, BinaryFunctionInterface.class);
}
Also used : Variable(com.facebook.presto.bytecode.Variable) VariableInstruction.incrementVariable(com.facebook.presto.bytecode.instruction.VariableInstruction.incrementVariable) ForLoop(com.facebook.presto.bytecode.control.ForLoop) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) MapType(com.facebook.presto.common.type.MapType) IfStatement(com.facebook.presto.bytecode.control.IfStatement) MapType(com.facebook.presto.common.type.MapType) Type(com.facebook.presto.common.type.Type) SqlTypeBytecodeExpression.constantType(com.facebook.presto.sql.gen.SqlTypeBytecodeExpression.constantType) SqlType(com.facebook.presto.spi.function.SqlType) Scope(com.facebook.presto.bytecode.Scope) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) CallSiteBinder(com.facebook.presto.bytecode.CallSiteBinder) TypeParameter(com.facebook.presto.spi.function.TypeParameter) Parameter(com.facebook.presto.bytecode.Parameter) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) Block(com.facebook.presto.common.block.Block) BytecodeNode(com.facebook.presto.bytecode.BytecodeNode) BlockBuilderStatus(com.facebook.presto.common.block.BlockBuilderStatus) SqlTypeBytecodeExpression(com.facebook.presto.sql.gen.SqlTypeBytecodeExpression) TypeParameter(com.facebook.presto.spi.function.TypeParameter) Description(com.facebook.presto.spi.function.Description) CodegenScalarFunction(com.facebook.presto.spi.function.CodegenScalarFunction) SqlType(com.facebook.presto.spi.function.SqlType)

Aggregations

BytecodeNode (com.facebook.presto.bytecode.BytecodeNode)42 Variable (com.facebook.presto.bytecode.Variable)33 BytecodeBlock (com.facebook.presto.bytecode.BytecodeBlock)29 IfStatement (com.facebook.presto.bytecode.control.IfStatement)23 Scope (com.facebook.presto.bytecode.Scope)21 MethodDefinition (com.facebook.presto.bytecode.MethodDefinition)19 Parameter (com.facebook.presto.bytecode.Parameter)16 LabelNode (com.facebook.presto.bytecode.instruction.LabelNode)12 ClassDefinition (com.facebook.presto.bytecode.ClassDefinition)7 ForLoop (com.facebook.presto.bytecode.control.ForLoop)7 RowExpression (com.facebook.presto.sql.relational.RowExpression)7 ArrayList (java.util.ArrayList)6 FieldDefinition (com.facebook.presto.bytecode.FieldDefinition)5 BytecodeExpression (com.facebook.presto.bytecode.expression.BytecodeExpression)5 Block (com.facebook.presto.common.block.Block)5 Type (com.facebook.presto.common.type.Type)5 FunctionHandle (com.facebook.presto.spi.function.FunctionHandle)5 RowExpression (com.facebook.presto.spi.relation.RowExpression)5 SqlTypeBytecodeExpression (com.facebook.presto.sql.gen.SqlTypeBytecodeExpression)5 ImmutableList (com.google.common.collect.ImmutableList)5