Search in sources :

Example 6 with SqlFunctionProperties

use of com.facebook.presto.common.function.SqlFunctionProperties in project presto by prestodb.

the class MapToMapCast method buildProcessor.

/**
 * The signature of the returned MethodHandle is (Block fromMap, int position, SqlFunctionProperties properties, BlockBuilder mapBlockBuilder)void.
 * The processor will get the value from fromMap, cast it and write to toBlock.
 */
private MethodHandle buildProcessor(FunctionAndTypeManager functionAndTypeManager, Type fromType, Type toType, boolean isKey) {
    MethodHandle getter = nativeValueGetter(fromType);
    // Adapt cast that takes ([SqlFunctionProperties,] ?) to one that takes (?, SqlFunctionProperties), where ? is the return type of getter.
    JavaScalarFunctionImplementation castImplementation = functionAndTypeManager.getJavaScalarFunctionImplementation(functionAndTypeManager.lookupCast(CastType.CAST, fromType.getTypeSignature(), toType.getTypeSignature()));
    MethodHandle cast = castImplementation.getMethodHandle();
    if (cast.type().parameterArray()[0] != SqlFunctionProperties.class) {
        cast = MethodHandles.dropArguments(cast, 0, SqlFunctionProperties.class);
    }
    cast = permuteArguments(cast, methodType(cast.type().returnType(), cast.type().parameterArray()[1], cast.type().parameterArray()[0]), 1, 0);
    MethodHandle target = compose(cast, getter);
    // If the key cast function is nullable, check the result is not null.
    if (isKey && castImplementation.isNullable()) {
        target = compose(nullChecker(target.type().returnType()), target);
    }
    MethodHandle writer = nativeValueWriter(toType);
    writer = permuteArguments(writer, methodType(void.class, writer.type().parameterArray()[1], writer.type().parameterArray()[0]), 1, 0);
    return compose(writer, target.asType(methodType(unwrap(target.type().returnType()), target.type().parameterArray())));
}
Also used : JavaScalarFunctionImplementation(com.facebook.presto.spi.function.JavaScalarFunctionImplementation) SqlFunctionProperties(com.facebook.presto.common.function.SqlFunctionProperties) MethodHandle(java.lang.invoke.MethodHandle)

Example 7 with SqlFunctionProperties

use of com.facebook.presto.common.function.SqlFunctionProperties in project presto by prestodb.

the class ArrayJoin method specializeArrayJoin.

private static BuiltInScalarFunctionImplementation specializeArrayJoin(Map<String, Type> types, FunctionAndTypeManager functionAndTypeManager, List<Boolean> nullableArguments, MethodHandle methodHandleStack, MethodHandle methodHandleProvidedBlock) {
    Type type = types.get("T");
    List<ArgumentProperty> argumentProperties = nullableArguments.stream().map(nullable -> nullable ? valueTypeArgumentProperty(USE_BOXED_TYPE) : valueTypeArgumentProperty(RETURN_NULL_ON_NULL)).collect(toImmutableList());
    if (type instanceof UnknownType) {
        return new BuiltInScalarFunctionImplementation(false, argumentProperties, methodHandleStack.bindTo(null), Optional.empty());
    } else {
        try {
            MethodHandle cast = functionAndTypeManager.getJavaScalarFunctionImplementation(functionAndTypeManager.lookupCast(CAST, type.getTypeSignature(), VARCHAR_TYPE_SIGNATURE)).getMethodHandle();
            MethodHandle getter;
            Class<?> elementType = type.getJavaType();
            if (elementType == boolean.class) {
                getter = GET_BOOLEAN;
            } else if (elementType == double.class) {
                getter = GET_DOUBLE;
            } else if (elementType == long.class) {
                getter = GET_LONG;
            } else if (elementType == Slice.class) {
                getter = GET_SLICE;
            } else {
                throw new UnsupportedOperationException("Unsupported type: " + elementType.getName());
            }
            // if the cast doesn't take a SqlFunctionProperties, create an adapter that drops the provided session
            if (cast.type().parameterArray()[0] != SqlFunctionProperties.class) {
                cast = MethodHandles.dropArguments(cast, 0, SqlFunctionProperties.class);
            }
            // Adapt a target cast that takes (SqlFunctionProperties, ?) to one that takes (Block, int, SqlFunctionProperties), which will be invoked by the implementation
            // The first two arguments (Block, int) are filtered through the element type's getXXX method to produce the underlying value that needs to be passed to
            // the cast.
            cast = MethodHandles.permuteArguments(cast, MethodType.methodType(Slice.class, cast.type().parameterArray()[1], cast.type().parameterArray()[0]), 1, 0);
            cast = MethodHandles.dropArguments(cast, 1, int.class);
            cast = MethodHandles.dropArguments(cast, 1, Block.class);
            cast = MethodHandles.foldArguments(cast, getter.bindTo(type));
            MethodHandle targetStack = MethodHandles.insertArguments(methodHandleStack, 0, cast);
            MethodHandle targetProvidedBlock = MethodHandles.insertArguments(methodHandleProvidedBlock, 0, cast);
            return new BuiltInScalarFunctionImplementation(ImmutableList.of(new ScalarFunctionImplementationChoice(false, argumentProperties, STACK, targetStack, Optional.empty()), new ScalarFunctionImplementationChoice(false, argumentProperties, PROVIDED_BLOCKBUILDER, targetProvidedBlock, Optional.empty())));
        } catch (PrestoException e) {
            throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Input type %s not supported", type), e);
        }
    }
}
Also used : FunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager) STACK(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.ReturnPlaceConvention.STACK) MethodHandle(java.lang.invoke.MethodHandle) StandardTypes(com.facebook.presto.common.type.StandardTypes) FunctionKind(com.facebook.presto.spi.function.FunctionKind) Slice(io.airlift.slice.Slice) VARCHAR(com.facebook.presto.common.type.VarcharType.VARCHAR) GENERIC_INTERNAL_ERROR(com.facebook.presto.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR) PrestoException(com.facebook.presto.spi.PrestoException) TypeSignature(com.facebook.presto.common.type.TypeSignature) ArgumentProperty(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.ArgumentProperty) DEFAULT_NAMESPACE(com.facebook.presto.metadata.BuiltInTypeAndFunctionNamespaceManager.DEFAULT_NAMESPACE) Signature.typeVariable(com.facebook.presto.spi.function.Signature.typeVariable) ImmutableList(com.google.common.collect.ImmutableList) Reflection.methodHandle(com.facebook.presto.util.Reflection.methodHandle) Map(java.util.Map) QualifiedObjectName(com.facebook.presto.common.QualifiedObjectName) INVALID_FUNCTION_ARGUMENT(com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT) UnknownType(com.facebook.presto.common.type.UnknownType) RETURN_NULL_ON_NULL(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.NullConvention.RETURN_NULL_ON_NULL) UsedByGeneratedCode(com.facebook.presto.annotation.UsedByGeneratedCode) Type(com.facebook.presto.common.type.Type) BlockBuilder(com.facebook.presto.common.block.BlockBuilder) BoundVariables(com.facebook.presto.metadata.BoundVariables) SqlScalarFunction(com.facebook.presto.metadata.SqlScalarFunction) PROVIDED_BLOCKBUILDER(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.ReturnPlaceConvention.PROVIDED_BLOCKBUILDER) SqlFunctionProperties(com.facebook.presto.common.function.SqlFunctionProperties) MethodHandles(java.lang.invoke.MethodHandles) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) USE_BOXED_TYPE(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.NullConvention.USE_BOXED_TYPE) String.format(java.lang.String.format) SqlFunctionVisibility(com.facebook.presto.spi.function.SqlFunctionVisibility) ArgumentProperty.valueTypeArgumentProperty(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.ArgumentProperty.valueTypeArgumentProperty) PUBLIC(com.facebook.presto.spi.function.SqlFunctionVisibility.PUBLIC) List(java.util.List) MethodType(java.lang.invoke.MethodType) TypeSignature.parseTypeSignature(com.facebook.presto.common.type.TypeSignature.parseTypeSignature) Signature(com.facebook.presto.spi.function.Signature) Optional(java.util.Optional) Block(com.facebook.presto.common.block.Block) CAST(com.facebook.presto.metadata.CastType.CAST) ArgumentProperty(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.ArgumentProperty) ArgumentProperty.valueTypeArgumentProperty(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.ArgumentProperty.valueTypeArgumentProperty) SqlFunctionProperties(com.facebook.presto.common.function.SqlFunctionProperties) PrestoException(com.facebook.presto.spi.PrestoException) UnknownType(com.facebook.presto.common.type.UnknownType) UnknownType(com.facebook.presto.common.type.UnknownType) Type(com.facebook.presto.common.type.Type) MethodType(java.lang.invoke.MethodType) Slice(io.airlift.slice.Slice) Block(com.facebook.presto.common.block.Block) MethodHandle(java.lang.invoke.MethodHandle)

Example 8 with SqlFunctionProperties

use of com.facebook.presto.common.function.SqlFunctionProperties in project presto by prestodb.

the class PageFunctionCompiler method compileProjectionInternal.

private Supplier<PageProjection> compileProjectionInternal(SqlFunctionProperties sqlFunctionProperties, Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions, List<RowExpression> projections, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix) {
    requireNonNull(projections, "projections is null");
    checkArgument(!projections.isEmpty() && projections.stream().allMatch(projection -> projection instanceof CallExpression || projection instanceof SpecialFormExpression));
    PageFieldsToInputParametersRewriter.Result result = rewritePageFieldsToInputParameters(projections);
    List<RowExpression> rewrittenExpression = result.getRewrittenExpressions();
    CallSiteBinder callSiteBinder = new CallSiteBinder();
    // generate Work
    ClassDefinition pageProjectionWorkDefinition = definePageProjectWorkClass(sqlFunctionProperties, sessionFunctions, rewrittenExpression, callSiteBinder, isOptimizeCommonSubExpression, classNameSuffix);
    Class<? extends Work> pageProjectionWorkClass;
    try {
        pageProjectionWorkClass = defineClass(pageProjectionWorkDefinition, Work.class, callSiteBinder.getBindings(), getClass().getClassLoader());
    } catch (PrestoException prestoException) {
        throw prestoException;
    } catch (Exception e) {
        throw new PrestoException(COMPILER_ERROR, e);
    }
    return () -> new GeneratedPageProjection(rewrittenExpression, rewrittenExpression.stream().allMatch(determinismEvaluator::isDeterministic), result.getInputChannels(), constructorMethodHandle(pageProjectionWorkClass, List.class, SqlFunctionProperties.class, Page.class, SelectedPositions.class));
}
Also used : SqlFunctionProperties(com.facebook.presto.common.function.SqlFunctionProperties) RowExpression(com.facebook.presto.spi.relation.RowExpression) PrestoException(com.facebook.presto.spi.PrestoException) GeneratedPageProjection(com.facebook.presto.operator.project.GeneratedPageProjection) Page(com.facebook.presto.common.Page) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) PrestoException(com.facebook.presto.spi.PrestoException) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) PageFieldsToInputParametersRewriter(com.facebook.presto.operator.project.PageFieldsToInputParametersRewriter) CallSiteBinder(com.facebook.presto.bytecode.CallSiteBinder) SelectedPositions(com.facebook.presto.operator.project.SelectedPositions) Work(com.facebook.presto.operator.Work) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) CallExpression(com.facebook.presto.spi.relation.CallExpression) SpecialFormExpression(com.facebook.presto.spi.relation.SpecialFormExpression)

Example 9 with SqlFunctionProperties

use of com.facebook.presto.common.function.SqlFunctionProperties in project presto by prestodb.

the class PageFunctionCompiler method defineFilterClass.

private ClassDefinition defineFilterClass(SqlFunctionProperties sqlFunctionProperties, Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions, RowExpression filter, InputChannels inputChannels, CallSiteBinder callSiteBinder, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix) {
    ClassDefinition classDefinition = new ClassDefinition(a(PUBLIC, FINAL), generateFilterClassName(classNameSuffix), type(Object.class), type(PageFilter.class));
    CachedInstanceBinder cachedInstanceBinder = new CachedInstanceBinder(classDefinition, callSiteBinder);
    Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap = generateMethodsForLambda(classDefinition, callSiteBinder, cachedInstanceBinder, filter, metadata, sqlFunctionProperties, sessionFunctions);
    // cse
    Map<VariableReferenceExpression, CommonSubExpressionFields> cseFields = ImmutableMap.of();
    RowExpressionCompiler compiler = new RowExpressionCompiler(classDefinition, callSiteBinder, cachedInstanceBinder, new FieldAndVariableReferenceCompiler(callSiteBinder, cseFields), metadata, sqlFunctionProperties, sessionFunctions, compiledLambdaMap);
    if (isOptimizeCommonSubExpression) {
        Map<Integer, Map<RowExpression, VariableReferenceExpression>> commonSubExpressionsByLevel = collectCSEByLevel(filter);
        if (!commonSubExpressionsByLevel.isEmpty()) {
            cseFields = declareCommonSubExpressionFields(classDefinition, commonSubExpressionsByLevel);
            compiler = new RowExpressionCompiler(classDefinition, callSiteBinder, cachedInstanceBinder, new FieldAndVariableReferenceCompiler(callSiteBinder, cseFields), metadata, sqlFunctionProperties, sessionFunctions, compiledLambdaMap);
            generateCommonSubExpressionMethods(classDefinition, compiler, commonSubExpressionsByLevel, cseFields);
            Map<RowExpression, VariableReferenceExpression> commonSubExpressions = commonSubExpressionsByLevel.values().stream().flatMap(m -> m.entrySet().stream()).collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
            filter = rewriteExpressionWithCSE(filter, commonSubExpressions);
            if (log.isDebugEnabled()) {
                log.debug("Extracted %d common sub-expressions", commonSubExpressions.size());
                commonSubExpressions.entrySet().forEach(entry -> log.debug("\t%s = %s", entry.getValue(), entry.getKey()));
                log.debug("Rewrote filter: %s", filter);
            }
        }
    }
    generateFilterMethod(classDefinition, compiler, filter, cseFields);
    FieldDefinition selectedPositions = classDefinition.declareField(a(PRIVATE), "selectedPositions", boolean[].class);
    generatePageFilterMethod(classDefinition, selectedPositions);
    // isDeterministic
    classDefinition.declareMethod(a(PUBLIC), "isDeterministic", type(boolean.class)).getBody().append(constantBoolean(determinismEvaluator.isDeterministic(filter))).retBoolean();
    // getInputChannels
    classDefinition.declareMethod(a(PUBLIC), "getInputChannels", type(InputChannels.class)).getBody().append(invoke(callSiteBinder.bind(inputChannels, InputChannels.class), "getInputChannels")).retObject();
    // toString
    String toStringResult = toStringHelper(classDefinition.getType().getJavaClassName()).add("filter", filter).toString();
    classDefinition.declareMethod(a(PUBLIC), "toString", type(String.class)).getBody().append(invoke(callSiteBinder.bind(toStringResult, String.class), "toString")).retObject();
    // constructor
    MethodDefinition constructorDefinition = classDefinition.declareConstructor(a(PUBLIC));
    BytecodeBlock body = constructorDefinition.getBody();
    Variable thisVariable = constructorDefinition.getThis();
    body.comment("super();").append(thisVariable).invokeConstructor(Object.class).append(thisVariable.setField(selectedPositions, newArray(type(boolean[].class), 0)));
    initializeCommonSubExpressionFields(cseFields.values(), thisVariable, body);
    cachedInstanceBinder.generateInitializations(thisVariable, body);
    body.ret();
    return classDefinition;
}
Also used : Page(com.facebook.presto.common.Page) LoadingCache(com.google.common.cache.LoadingCache) PageFieldsToInputParametersRewriter(com.facebook.presto.operator.project.PageFieldsToInputParametersRewriter) PageFilter(com.facebook.presto.operator.project.PageFilter) Expressions.subExpressions(com.facebook.presto.sql.relational.Expressions.subExpressions) SqlInvokedFunction(com.facebook.presto.spi.function.SqlInvokedFunction) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) InputPageProjection(com.facebook.presto.operator.project.InputPageProjection) CallSiteBinder(com.facebook.presto.bytecode.CallSiteBinder) ForLoop(com.facebook.presto.bytecode.control.ForLoop) BytecodeUtils.boxPrimitiveIfNecessary(com.facebook.presto.sql.gen.BytecodeUtils.boxPrimitiveIfNecessary) CommonSubExpressionRewriter.collectCSEByLevel(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.collectCSEByLevel) Map(java.util.Map) CompilerUtils.makeClassName(com.facebook.presto.util.CompilerUtils.makeClassName) IfStatement(com.facebook.presto.bytecode.control.IfStatement) BytecodeExpressions.add(com.facebook.presto.bytecode.expression.BytecodeExpressions.add) Variable(com.facebook.presto.bytecode.Variable) CommonSubExpressionRewriter.rewriteExpressionWithCSE(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.rewriteExpressionWithCSE) BlockBuilder(com.facebook.presto.common.block.BlockBuilder) Parameter(com.facebook.presto.bytecode.Parameter) SqlFunctionProperties(com.facebook.presto.common.function.SqlFunctionProperties) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) PageProjectionWithOutputs(com.facebook.presto.operator.project.PageProjectionWithOutputs) BytecodeExpressions.constantBoolean(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantBoolean) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) FINAL(com.facebook.presto.bytecode.Access.FINAL) Scope(com.facebook.presto.bytecode.Scope) BytecodeExpressions.invokeStatic(com.facebook.presto.bytecode.expression.BytecodeExpressions.invokeStatic) Joiner(com.google.common.base.Joiner) MoreObjects.toStringHelper(com.google.common.base.MoreObjects.toStringHelper) PageProjection(com.facebook.presto.operator.project.PageProjection) ConstantExpression(com.facebook.presto.spi.relation.ConstantExpression) BytecodeExpressions.constantFalse(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantFalse) Supplier(java.util.function.Supplier) CommonSubExpressionFields.initializeCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.initializeCommonSubExpressionFields) TreeSet(java.util.TreeSet) Managed(org.weakref.jmx.Managed) LambdaBytecodeGenerator.generateMethodsForLambda(com.facebook.presto.sql.gen.LambdaBytecodeGenerator.generateMethodsForLambda) GeneratedPageProjection(com.facebook.presto.operator.project.GeneratedPageProjection) CommonSubExpressionFields.declareCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.declareCommonSubExpressionFields) BytecodeExpressions.constantNull(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantNull) Nullable(javax.annotation.Nullable) Throwables.throwIfInstanceOf(com.google.common.base.Throwables.throwIfInstanceOf) SqlFunctionId(com.facebook.presto.spi.function.SqlFunctionId) Work(com.facebook.presto.operator.Work) CommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields) ParameterizedType(com.facebook.presto.bytecode.ParameterizedType) Metadata(com.facebook.presto.metadata.Metadata) BytecodeExpressions.newArray(com.facebook.presto.bytecode.expression.BytecodeExpressions.newArray) RowExpressionVisitor(com.facebook.presto.spi.relation.RowExpressionVisitor) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) BytecodeUtils.invoke(com.facebook.presto.sql.gen.BytecodeUtils.invoke) Access.a(com.facebook.presto.bytecode.Access.a) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) CommonSubExpressionRewriter.getExpressionsPartitionedByCSE(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.getExpressionsPartitionedByCSE) ParameterizedType.type(com.facebook.presto.bytecode.ParameterizedType.type) CallExpression(com.facebook.presto.spi.relation.CallExpression) SpecialFormExpression(com.facebook.presto.spi.relation.SpecialFormExpression) ImmutableMap(com.google.common.collect.ImmutableMap) BytecodeExpressions.lessThan(com.facebook.presto.bytecode.expression.BytecodeExpressions.lessThan) Collection(java.util.Collection) SelectedPositions(com.facebook.presto.operator.project.SelectedPositions) LambdaDefinitionExpression(com.facebook.presto.spi.relation.LambdaDefinitionExpression) CacheLoader(com.google.common.cache.CacheLoader) Objects(java.util.Objects) CompiledLambda(com.facebook.presto.sql.gen.LambdaBytecodeGenerator.CompiledLambda) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) List(java.util.List) ConstantPageProjection(com.facebook.presto.operator.project.ConstantPageProjection) Optional(java.util.Optional) CacheBuilder(com.google.common.cache.CacheBuilder) InputReferenceExpression(com.facebook.presto.spi.relation.InputReferenceExpression) Parameter.arg(com.facebook.presto.bytecode.Parameter.arg) IntStream(java.util.stream.IntStream) BytecodeExpressions.and(com.facebook.presto.bytecode.expression.BytecodeExpressions.and) DeterminismEvaluator(com.facebook.presto.spi.relation.DeterminismEvaluator) Nested(org.weakref.jmx.Nested) Logger(com.facebook.airlift.log.Logger) InputChannels(com.facebook.presto.operator.project.InputChannels) BytecodeExpressions.constantInt(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantInt) PRIVATE(com.facebook.presto.bytecode.Access.PRIVATE) RowExpressionDeterminismEvaluator(com.facebook.presto.sql.relational.RowExpressionDeterminismEvaluator) PrestoException(com.facebook.presto.spi.PrestoException) BytecodeExpressions.not(com.facebook.presto.bytecode.expression.BytecodeExpressions.not) Inject(javax.inject.Inject) ImmutableList(com.google.common.collect.ImmutableList) PageFieldsToInputParametersRewriter.rewritePageFieldsToInputParameters(com.facebook.presto.operator.project.PageFieldsToInputParametersRewriter.rewritePageFieldsToInputParameters) Verify.verify(com.google.common.base.Verify.verify) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) Objects.requireNonNull(java.util.Objects.requireNonNull) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) RowExpression(com.facebook.presto.spi.relation.RowExpression) PUBLIC(com.facebook.presto.bytecode.Access.PUBLIC) Collections.emptyMap(java.util.Collections.emptyMap) CompilerUtils.defineClass(com.facebook.presto.util.CompilerUtils.defineClass) Reflection.constructorMethodHandle(com.facebook.presto.util.Reflection.constructorMethodHandle) Primitives(com.google.common.primitives.Primitives) CompilerConfig(com.facebook.presto.sql.planner.CompilerConfig) BytecodeNode(com.facebook.presto.bytecode.BytecodeNode) FieldDefinition(com.facebook.presto.bytecode.FieldDefinition) BytecodeUtils.unboxPrimitiveIfNecessary(com.facebook.presto.sql.gen.BytecodeUtils.unboxPrimitiveIfNecessary) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Block(com.facebook.presto.common.block.Block) COMPILER_ERROR(com.facebook.presto.spi.StandardErrorCode.COMPILER_ERROR) Variable(com.facebook.presto.bytecode.Variable) FieldDefinition(com.facebook.presto.bytecode.FieldDefinition) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) RowExpression(com.facebook.presto.spi.relation.RowExpression) InputChannels(com.facebook.presto.operator.project.InputChannels) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) CompiledLambda(com.facebook.presto.sql.gen.LambdaBytecodeGenerator.CompiledLambda) CommonSubExpressionFields.initializeCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.initializeCommonSubExpressionFields) CommonSubExpressionFields.declareCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.declareCommonSubExpressionFields) CommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) PageFilter(com.facebook.presto.operator.project.PageFilter) Map(java.util.Map) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) ImmutableMap(com.google.common.collect.ImmutableMap) Collections.emptyMap(java.util.Collections.emptyMap) LambdaDefinitionExpression(com.facebook.presto.spi.relation.LambdaDefinitionExpression)

Example 10 with SqlFunctionProperties

use of com.facebook.presto.common.function.SqlFunctionProperties in project presto by prestodb.

the class PageFunctionCompiler method compileProjections.

public List<Supplier<PageProjectionWithOutputs>> compileProjections(SqlFunctionProperties sqlFunctionProperties, Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions, List<? extends RowExpression> projections, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix) {
    if (isOptimizeCommonSubExpression) {
        ImmutableList.Builder<Supplier<PageProjectionWithOutputs>> pageProjections = ImmutableList.builder();
        ImmutableMap.Builder<RowExpression, Integer> expressionsWithPositionBuilder = ImmutableMap.builder();
        for (int i = 0; i < projections.size(); i++) {
            RowExpression projection = projections.get(i);
            if (projection instanceof ConstantExpression || projection instanceof InputReferenceExpression) {
                pageProjections.add(toPageProjectionWithOutputs(compileProjection(sqlFunctionProperties, sessionFunctions, projection, classNameSuffix), new int[] { i }));
            } else {
                expressionsWithPositionBuilder.put(projection, i);
            }
        }
        Map<RowExpression, Integer> expressionsWithPosition = expressionsWithPositionBuilder.build();
        Map<List<RowExpression>, Boolean> projectionsPartitionedByCSE = getExpressionsPartitionedByCSE(expressionsWithPosition.keySet(), MAX_PROJECTION_GROUP_SIZE);
        for (Map.Entry<List<RowExpression>, Boolean> entry : projectionsPartitionedByCSE.entrySet()) {
            if (entry.getValue()) {
                pageProjections.add(toPageProjectionWithOutputs(compileProjectionCached(sqlFunctionProperties, sessionFunctions, entry.getKey(), true, classNameSuffix), toIntArray(entry.getKey().stream().map(expressionsWithPosition::get).collect(toImmutableList()))));
            } else {
                verify(entry.getKey().size() == 1, "Expect non-cse expression list to only have one element");
                RowExpression projection = entry.getKey().get(0);
                pageProjections.add(toPageProjectionWithOutputs(compileProjection(sqlFunctionProperties, sessionFunctions, projection, classNameSuffix), new int[] { expressionsWithPosition.get(projection) }));
            }
        }
        return pageProjections.build();
    }
    return IntStream.range(0, projections.size()).mapToObj(outputChannel -> toPageProjectionWithOutputs(compileProjection(sqlFunctionProperties, sessionFunctions, projections.get(outputChannel), classNameSuffix), new int[] { outputChannel })).collect(toImmutableList());
}
Also used : Page(com.facebook.presto.common.Page) LoadingCache(com.google.common.cache.LoadingCache) PageFieldsToInputParametersRewriter(com.facebook.presto.operator.project.PageFieldsToInputParametersRewriter) PageFilter(com.facebook.presto.operator.project.PageFilter) Expressions.subExpressions(com.facebook.presto.sql.relational.Expressions.subExpressions) SqlInvokedFunction(com.facebook.presto.spi.function.SqlInvokedFunction) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) InputPageProjection(com.facebook.presto.operator.project.InputPageProjection) CallSiteBinder(com.facebook.presto.bytecode.CallSiteBinder) ForLoop(com.facebook.presto.bytecode.control.ForLoop) BytecodeUtils.boxPrimitiveIfNecessary(com.facebook.presto.sql.gen.BytecodeUtils.boxPrimitiveIfNecessary) CommonSubExpressionRewriter.collectCSEByLevel(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.collectCSEByLevel) Map(java.util.Map) CompilerUtils.makeClassName(com.facebook.presto.util.CompilerUtils.makeClassName) IfStatement(com.facebook.presto.bytecode.control.IfStatement) BytecodeExpressions.add(com.facebook.presto.bytecode.expression.BytecodeExpressions.add) Variable(com.facebook.presto.bytecode.Variable) CommonSubExpressionRewriter.rewriteExpressionWithCSE(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.rewriteExpressionWithCSE) BlockBuilder(com.facebook.presto.common.block.BlockBuilder) Parameter(com.facebook.presto.bytecode.Parameter) SqlFunctionProperties(com.facebook.presto.common.function.SqlFunctionProperties) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) PageProjectionWithOutputs(com.facebook.presto.operator.project.PageProjectionWithOutputs) BytecodeExpressions.constantBoolean(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantBoolean) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) FINAL(com.facebook.presto.bytecode.Access.FINAL) Scope(com.facebook.presto.bytecode.Scope) BytecodeExpressions.invokeStatic(com.facebook.presto.bytecode.expression.BytecodeExpressions.invokeStatic) Joiner(com.google.common.base.Joiner) MoreObjects.toStringHelper(com.google.common.base.MoreObjects.toStringHelper) PageProjection(com.facebook.presto.operator.project.PageProjection) ConstantExpression(com.facebook.presto.spi.relation.ConstantExpression) BytecodeExpressions.constantFalse(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantFalse) Supplier(java.util.function.Supplier) CommonSubExpressionFields.initializeCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.initializeCommonSubExpressionFields) TreeSet(java.util.TreeSet) Managed(org.weakref.jmx.Managed) LambdaBytecodeGenerator.generateMethodsForLambda(com.facebook.presto.sql.gen.LambdaBytecodeGenerator.generateMethodsForLambda) GeneratedPageProjection(com.facebook.presto.operator.project.GeneratedPageProjection) CommonSubExpressionFields.declareCommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields.declareCommonSubExpressionFields) BytecodeExpressions.constantNull(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantNull) Nullable(javax.annotation.Nullable) Throwables.throwIfInstanceOf(com.google.common.base.Throwables.throwIfInstanceOf) SqlFunctionId(com.facebook.presto.spi.function.SqlFunctionId) Work(com.facebook.presto.operator.Work) CommonSubExpressionFields(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.CommonSubExpressionFields) ParameterizedType(com.facebook.presto.bytecode.ParameterizedType) Metadata(com.facebook.presto.metadata.Metadata) BytecodeExpressions.newArray(com.facebook.presto.bytecode.expression.BytecodeExpressions.newArray) RowExpressionVisitor(com.facebook.presto.spi.relation.RowExpressionVisitor) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) BytecodeUtils.invoke(com.facebook.presto.sql.gen.BytecodeUtils.invoke) Access.a(com.facebook.presto.bytecode.Access.a) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) CommonSubExpressionRewriter.getExpressionsPartitionedByCSE(com.facebook.presto.sql.gen.CommonSubExpressionRewriter.getExpressionsPartitionedByCSE) ParameterizedType.type(com.facebook.presto.bytecode.ParameterizedType.type) CallExpression(com.facebook.presto.spi.relation.CallExpression) SpecialFormExpression(com.facebook.presto.spi.relation.SpecialFormExpression) ImmutableMap(com.google.common.collect.ImmutableMap) BytecodeExpressions.lessThan(com.facebook.presto.bytecode.expression.BytecodeExpressions.lessThan) Collection(java.util.Collection) SelectedPositions(com.facebook.presto.operator.project.SelectedPositions) LambdaDefinitionExpression(com.facebook.presto.spi.relation.LambdaDefinitionExpression) CacheLoader(com.google.common.cache.CacheLoader) Objects(java.util.Objects) CompiledLambda(com.facebook.presto.sql.gen.LambdaBytecodeGenerator.CompiledLambda) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) List(java.util.List) ConstantPageProjection(com.facebook.presto.operator.project.ConstantPageProjection) Optional(java.util.Optional) CacheBuilder(com.google.common.cache.CacheBuilder) InputReferenceExpression(com.facebook.presto.spi.relation.InputReferenceExpression) Parameter.arg(com.facebook.presto.bytecode.Parameter.arg) IntStream(java.util.stream.IntStream) BytecodeExpressions.and(com.facebook.presto.bytecode.expression.BytecodeExpressions.and) DeterminismEvaluator(com.facebook.presto.spi.relation.DeterminismEvaluator) Nested(org.weakref.jmx.Nested) Logger(com.facebook.airlift.log.Logger) InputChannels(com.facebook.presto.operator.project.InputChannels) BytecodeExpressions.constantInt(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantInt) PRIVATE(com.facebook.presto.bytecode.Access.PRIVATE) RowExpressionDeterminismEvaluator(com.facebook.presto.sql.relational.RowExpressionDeterminismEvaluator) PrestoException(com.facebook.presto.spi.PrestoException) BytecodeExpressions.not(com.facebook.presto.bytecode.expression.BytecodeExpressions.not) Inject(javax.inject.Inject) ImmutableList(com.google.common.collect.ImmutableList) PageFieldsToInputParametersRewriter.rewritePageFieldsToInputParameters(com.facebook.presto.operator.project.PageFieldsToInputParametersRewriter.rewritePageFieldsToInputParameters) Verify.verify(com.google.common.base.Verify.verify) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) Objects.requireNonNull(java.util.Objects.requireNonNull) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) RowExpression(com.facebook.presto.spi.relation.RowExpression) PUBLIC(com.facebook.presto.bytecode.Access.PUBLIC) Collections.emptyMap(java.util.Collections.emptyMap) CompilerUtils.defineClass(com.facebook.presto.util.CompilerUtils.defineClass) Reflection.constructorMethodHandle(com.facebook.presto.util.Reflection.constructorMethodHandle) Primitives(com.google.common.primitives.Primitives) CompilerConfig(com.facebook.presto.sql.planner.CompilerConfig) BytecodeNode(com.facebook.presto.bytecode.BytecodeNode) FieldDefinition(com.facebook.presto.bytecode.FieldDefinition) BytecodeUtils.unboxPrimitiveIfNecessary(com.facebook.presto.sql.gen.BytecodeUtils.unboxPrimitiveIfNecessary) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Block(com.facebook.presto.common.block.Block) COMPILER_ERROR(com.facebook.presto.spi.StandardErrorCode.COMPILER_ERROR) InputReferenceExpression(com.facebook.presto.spi.relation.InputReferenceExpression) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) ConstantExpression(com.facebook.presto.spi.relation.ConstantExpression) RowExpression(com.facebook.presto.spi.relation.RowExpression) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) ImmutableMap(com.google.common.collect.ImmutableMap) Supplier(java.util.function.Supplier) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) BytecodeExpressions.constantBoolean(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantBoolean) Map(java.util.Map) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) ImmutableMap(com.google.common.collect.ImmutableMap) Collections.emptyMap(java.util.Collections.emptyMap)

Aggregations

SqlFunctionProperties (com.facebook.presto.common.function.SqlFunctionProperties)12 CallSiteBinder (com.facebook.presto.bytecode.CallSiteBinder)6 ClassDefinition (com.facebook.presto.bytecode.ClassDefinition)6 Parameter (com.facebook.presto.bytecode.Parameter)6 PrestoException (com.facebook.presto.spi.PrestoException)6 CallExpression (com.facebook.presto.spi.relation.CallExpression)6 RowExpression (com.facebook.presto.spi.relation.RowExpression)6 SpecialFormExpression (com.facebook.presto.spi.relation.SpecialFormExpression)6 ImmutableList (com.google.common.collect.ImmutableList)6 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)6 PRIVATE (com.facebook.presto.bytecode.Access.PRIVATE)5 PUBLIC (com.facebook.presto.bytecode.Access.PUBLIC)5 Access.a (com.facebook.presto.bytecode.Access.a)5 BytecodeBlock (com.facebook.presto.bytecode.BytecodeBlock)5 BytecodeNode (com.facebook.presto.bytecode.BytecodeNode)5 MethodDefinition (com.facebook.presto.bytecode.MethodDefinition)5 Parameter.arg (com.facebook.presto.bytecode.Parameter.arg)5 ParameterizedType.type (com.facebook.presto.bytecode.ParameterizedType.type)5 Scope (com.facebook.presto.bytecode.Scope)5 Variable (com.facebook.presto.bytecode.Variable)5