Search in sources :

Example 1 with PRIVATE

use of com.facebook.presto.bytecode.Access.PRIVATE in project presto by prestodb.

the class ConcatFunction method generateConcat.

private static Class<?> generateConcat(int arity) {
    ClassDefinition definition = new ClassDefinition(a(PUBLIC, FINAL), CompilerUtils.makeClassName("Concat" + arity + "ScalarFunction"), type(Object.class));
    // Generate constructor
    definition.declareDefaultConstructor(a(PRIVATE));
    // Generate concat()
    List<Parameter> parameters = IntStream.range(0, arity).mapToObj(i -> arg("arg" + i, Slice.class)).collect(toImmutableList());
    MethodDefinition method = definition.declareMethod(a(PUBLIC, STATIC), "concat", type(Slice.class), parameters);
    Scope scope = method.getScope();
    BytecodeBlock body = method.getBody();
    Variable length = scope.declareVariable(int.class, "length");
    body.append(length.set(constantInt(0)));
    for (int i = 0; i < arity; ++i) {
        body.append(length.set(generateCheckedAdd(length, parameters.get(i).invoke("length", int.class))));
    }
    Variable result = scope.declareVariable(Slice.class, "result");
    body.append(result.set(invokeStatic(Slices.class, "allocate", Slice.class, length)));
    Variable position = scope.declareVariable(int.class, "position");
    body.append(position.set(constantInt(0)));
    for (int i = 0; i < arity; ++i) {
        body.append(result.invoke("setBytes", void.class, position, parameters.get(i)));
        body.append(position.set(add(position, parameters.get(i).invoke("length", int.class))));
    }
    body.getVariable(result).retObject();
    return defineClass(definition, Object.class, ImmutableMap.of(), new DynamicClassLoader(ConcatFunction.class.getClassLoader()));
}
Also used : IntStream(java.util.stream.IntStream) BytecodeExpression(com.facebook.presto.bytecode.expression.BytecodeExpression) MethodHandle(java.lang.invoke.MethodHandle) TypeManager(com.facebook.presto.spi.type.TypeManager) Slice(io.airlift.slice.Slice) BytecodeExpressions.constantInt(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantInt) PRIVATE(com.facebook.presto.bytecode.Access.PRIVATE) PrestoException(com.facebook.presto.spi.PrestoException) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) FunctionKind(com.facebook.presto.metadata.FunctionKind) Access.a(com.facebook.presto.bytecode.Access.a) ImmutableList(com.google.common.collect.ImmutableList) ParameterizedType.type(com.facebook.presto.bytecode.ParameterizedType.type) Reflection.methodHandle(com.facebook.presto.util.Reflection.methodHandle) Slices(io.airlift.slice.Slices) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) INVALID_FUNCTION_ARGUMENT(com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT) ImmutableCollectors.toImmutableList(com.facebook.presto.util.ImmutableCollectors.toImmutableList) UsedByGeneratedCode(com.facebook.presto.annotation.UsedByGeneratedCode) BytecodeExpressions.add(com.facebook.presto.bytecode.expression.BytecodeExpressions.add) PUBLIC(com.facebook.presto.bytecode.Access.PUBLIC) Variable(com.facebook.presto.bytecode.Variable) BoundVariables(com.facebook.presto.metadata.BoundVariables) Parameter(com.facebook.presto.bytecode.Parameter) ImmutableMap(com.google.common.collect.ImmutableMap) SqlScalarFunction(com.facebook.presto.metadata.SqlScalarFunction) FunctionRegistry(com.facebook.presto.metadata.FunctionRegistry) Signature(com.facebook.presto.metadata.Signature) DynamicClassLoader(com.facebook.presto.bytecode.DynamicClassLoader) VarcharType.createUnboundedVarcharType(com.facebook.presto.spi.type.VarcharType.createUnboundedVarcharType) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) List(java.util.List) CompilerUtils(com.facebook.presto.bytecode.CompilerUtils) FINAL(com.facebook.presto.bytecode.Access.FINAL) STATIC(com.facebook.presto.bytecode.Access.STATIC) Math.addExact(java.lang.Math.addExact) Scope(com.facebook.presto.bytecode.Scope) CompilerUtils.defineClass(com.facebook.presto.bytecode.CompilerUtils.defineClass) BytecodeExpressions.invokeStatic(com.facebook.presto.bytecode.expression.BytecodeExpressions.invokeStatic) Collections(java.util.Collections) Parameter.arg(com.facebook.presto.bytecode.Parameter.arg) DynamicClassLoader(com.facebook.presto.bytecode.DynamicClassLoader) Variable(com.facebook.presto.bytecode.Variable) Scope(com.facebook.presto.bytecode.Scope) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) Slice(io.airlift.slice.Slice) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) Parameter(com.facebook.presto.bytecode.Parameter) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition)

Example 2 with PRIVATE

use of com.facebook.presto.bytecode.Access.PRIVATE in project presto by prestodb.

the class CommonSubExpressionRewriter method removeRedundantCSE.

private static Map<Integer, Map<RowExpression, Integer>> removeRedundantCSE(Map<Integer, Set<RowExpression>> cseByLevel, Map<RowExpression, Integer> expressionCount) {
    Map<Integer, Map<RowExpression, Integer>> results = new HashMap<>();
    int startCSELevel = cseByLevel.keySet().stream().reduce(Math::max).get();
    int stopCSELevel = cseByLevel.keySet().stream().reduce(Math::min).get();
    for (int i = startCSELevel; i > stopCSELevel; i--) {
        if (!cseByLevel.containsKey(i)) {
            continue;
        }
        Map<RowExpression, Integer> expressions = cseByLevel.get(i).stream().filter(expression -> expressionCount.get(expression) > 0).collect(toImmutableMap(identity(), expressionCount::get));
        if (!expressions.isEmpty()) {
            results.put(i, expressions);
        }
        for (RowExpression expression : expressions.keySet()) {
            int expressionOccurrence = expressionCount.get(expression);
            subExpressions(expression).stream().filter(subExpression -> !subExpression.equals(expression)).forEach(subExpression -> {
                if (expressionCount.containsKey(subExpression)) {
                    expressionCount.put(subExpression, expressionCount.get(subExpression) - expressionOccurrence);
                }
            });
        }
    }
    Map<RowExpression, Integer> expressions = cseByLevel.get(stopCSELevel).stream().filter(expression -> expressionCount.get(expression) > 0).collect(toImmutableMap(identity(), expression -> expressionCount.get(expression) + 1));
    if (!expressions.isEmpty()) {
        results.put(stopCSELevel, expressions);
    }
    return results;
}
Also used : WHEN(com.facebook.presto.spi.relation.SpecialFormExpression.Form.WHEN) Expressions.subExpressions(com.facebook.presto.sql.relational.Expressions.subExpressions) RowExpressionVisitor(com.facebook.presto.spi.relation.RowExpressionVisitor) PRIVATE(com.facebook.presto.bytecode.Access.PRIVATE) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) HashMap(java.util.HashMap) ConstantExpression(com.facebook.presto.spi.relation.ConstantExpression) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Access.a(com.facebook.presto.bytecode.Access.a) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) CallExpression(com.facebook.presto.spi.relation.CallExpression) BytecodeExpressions.constantNull(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantNull) SpecialFormExpression(com.facebook.presto.spi.relation.SpecialFormExpression) RowExpression(com.facebook.presto.spi.relation.RowExpression) Variable(com.facebook.presto.bytecode.Variable) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) LambdaDefinitionExpression(com.facebook.presto.spi.relation.LambdaDefinitionExpression) BytecodeExpressions.constantBoolean(com.facebook.presto.bytecode.expression.BytecodeExpressions.constantBoolean) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Primitives(com.google.common.primitives.Primitives) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) List(java.util.List) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) PlanVariableAllocator(com.facebook.presto.sql.planner.PlanVariableAllocator) FieldDefinition(com.facebook.presto.bytecode.FieldDefinition) Function.identity(java.util.function.Function.identity) BIND(com.facebook.presto.spi.relation.SpecialFormExpression.Form.BIND) InputReferenceExpression(com.facebook.presto.spi.relation.InputReferenceExpression) HashMap(java.util.HashMap) RowExpression(com.facebook.presto.spi.relation.RowExpression) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap)

Example 3 with PRIVATE

use of com.facebook.presto.bytecode.Access.PRIVATE in project presto by prestodb.

the class PageFunctionCompiler method definePageProjectWorkClass.

private ClassDefinition definePageProjectWorkClass(SqlFunctionProperties sqlFunctionProperties, Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions, List<RowExpression> projections, CallSiteBinder callSiteBinder, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix) {
    ClassDefinition classDefinition = new ClassDefinition(a(PUBLIC, FINAL), generateProjectionWorkClassName(classNameSuffix), type(Object.class), type(Work.class));
    FieldDefinition blockBuilderFields = classDefinition.declareField(a(PRIVATE), "blockBuilders", type(List.class, BlockBuilder.class));
    FieldDefinition propertiesField = classDefinition.declareField(a(PRIVATE), "properties", SqlFunctionProperties.class);
    FieldDefinition pageField = classDefinition.declareField(a(PRIVATE), "page", Page.class);
    FieldDefinition selectedPositionsField = classDefinition.declareField(a(PRIVATE), "selectedPositions", SelectedPositions.class);
    FieldDefinition nextIndexOrPositionField = classDefinition.declareField(a(PRIVATE), "nextIndexOrPosition", int.class);
    FieldDefinition resultField = classDefinition.declareField(a(PRIVATE), "result", List.class);
    CachedInstanceBinder cachedInstanceBinder = new CachedInstanceBinder(classDefinition, callSiteBinder);
    // process
    generateProcessMethod(classDefinition, blockBuilderFields, projections.size(), propertiesField, pageField, selectedPositionsField, nextIndexOrPositionField, resultField);
    // getResult
    MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "getResult", type(Object.class), ImmutableList.of());
    method.getBody().append(method.getThis().getField(resultField)).ret(Object.class);
    Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap = generateMethodsForLambda(classDefinition, callSiteBinder, cachedInstanceBinder, projections, 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(projections);
        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));
            projections = projections.stream().map(projection -> rewriteExpressionWithCSE(projection, commonSubExpressions)).collect(toImmutableList());
            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 %d projections: %s", projections.size(), Joiner.on(", ").join(projections));
            }
        }
    }
    // evaluate
    generateEvaluateMethod(classDefinition, compiler, projections, blockBuilderFields, cseFields);
    // constructor
    Parameter blockBuilders = arg("blockBuilders", type(List.class, BlockBuilder.class));
    Parameter properties = arg("properties", SqlFunctionProperties.class);
    Parameter page = arg("page", Page.class);
    Parameter selectedPositions = arg("selectedPositions", SelectedPositions.class);
    MethodDefinition constructorDefinition = classDefinition.declareConstructor(a(PUBLIC), blockBuilders, properties, page, selectedPositions);
    BytecodeBlock body = constructorDefinition.getBody();
    Variable thisVariable = constructorDefinition.getThis();
    body.comment("super();").append(thisVariable).invokeConstructor(Object.class).append(thisVariable.setField(blockBuilderFields, invokeStatic(ImmutableList.class, "copyOf", ImmutableList.class, blockBuilders.cast(Collection.class)))).append(thisVariable.setField(propertiesField, properties)).append(thisVariable.setField(pageField, page)).append(thisVariable.setField(selectedPositionsField, selectedPositions)).append(thisVariable.setField(nextIndexOrPositionField, selectedPositions.invoke("getOffset", int.class))).append(thisVariable.setField(resultField, constantNull(Block.class)));
    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) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) FieldDefinition(com.facebook.presto.bytecode.FieldDefinition) 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) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) Work(com.facebook.presto.operator.Work) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) BlockBuilder(com.facebook.presto.common.block.BlockBuilder) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) RowExpression(com.facebook.presto.spi.relation.RowExpression) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) Parameter(com.facebook.presto.bytecode.Parameter) 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 4 with PRIVATE

use of com.facebook.presto.bytecode.Access.PRIVATE in project presto by prestodb.

the class AbstractGreatestLeast method generate.

private Class<?> generate(List<Class<?>> javaTypes, Type type, MethodHandle compareMethod) {
    checkCondition(javaTypes.size() <= 127, NOT_SUPPORTED, "Too many arguments for function call %s()", getSignature().getNameSuffix());
    String javaTypeName = javaTypes.stream().map(Class::getSimpleName).collect(joining());
    ClassDefinition definition = new ClassDefinition(a(PUBLIC, FINAL), makeClassName(javaTypeName + "$" + getSignature().getNameSuffix()), type(Object.class));
    definition.declareDefaultConstructor(a(PRIVATE));
    List<Parameter> parameters = IntStream.range(0, javaTypes.size()).mapToObj(i -> arg("arg" + i, javaTypes.get(i))).collect(toImmutableList());
    MethodDefinition method = definition.declareMethod(a(PUBLIC, STATIC), getSignature().getNameSuffix(), type(javaTypes.get(0)), parameters);
    Scope scope = method.getScope();
    BytecodeBlock body = method.getBody();
    CallSiteBinder binder = new CallSiteBinder();
    if (type.getTypeSignature().getBase().equals(StandardTypes.DOUBLE)) {
        for (Parameter parameter : parameters) {
            body.append(parameter);
            body.append(invoke(binder.bind(CHECK_NOT_NAN.bindTo(getSignature().getNameSuffix())), "checkNotNaN"));
        }
    }
    Variable value = scope.declareVariable(javaTypes.get(0), "value");
    body.append(value.set(parameters.get(0)));
    for (int i = 1; i < javaTypes.size(); i++) {
        body.append(new IfStatement().condition(new BytecodeBlock().append(parameters.get(i)).append(value).append(invoke(binder.bind(compareMethod), "compare"))).ifTrue(value.set(parameters.get(i))));
    }
    body.append(value.ret());
    return defineClass(definition, Object.class, binder.getBindings(), new DynamicClassLoader(getClass().getClassLoader()));
}
Also used : FunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) 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) CallSiteBinder(com.facebook.presto.bytecode.CallSiteBinder) ParameterizedType.type(com.facebook.presto.bytecode.ParameterizedType.type) Reflection.methodHandle(com.facebook.presto.util.Reflection.methodHandle) QualifiedObjectName(com.facebook.presto.common.QualifiedObjectName) INVALID_FUNCTION_ARGUMENT(com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT) CompilerUtils.makeClassName(com.facebook.presto.util.CompilerUtils.makeClassName) Signature.orderableTypeParameter(com.facebook.presto.spi.function.Signature.orderableTypeParameter) UsedByGeneratedCode(com.facebook.presto.annotation.UsedByGeneratedCode) IfStatement(com.facebook.presto.bytecode.control.IfStatement) Variable(com.facebook.presto.bytecode.Variable) BoundVariables(com.facebook.presto.metadata.BoundVariables) Parameter(com.facebook.presto.bytecode.Parameter) Collections.nCopies(java.util.Collections.nCopies) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) DynamicClassLoader(com.facebook.presto.bytecode.DynamicClassLoader) String.format(java.lang.String.format) Collectors.joining(java.util.stream.Collectors.joining) SqlFunctionVisibility(com.facebook.presto.spi.function.SqlFunctionVisibility) ArgumentProperty.valueTypeArgumentProperty(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.ArgumentProperty.valueTypeArgumentProperty) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) List(java.util.List) FINAL(com.facebook.presto.bytecode.Access.FINAL) Scope(com.facebook.presto.bytecode.Scope) NOT_SUPPORTED(com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED) Parameter.arg(com.facebook.presto.bytecode.Parameter.arg) IntStream(java.util.stream.IntStream) MethodHandle(java.lang.invoke.MethodHandle) StandardTypes(com.facebook.presto.common.type.StandardTypes) FunctionKind(com.facebook.presto.spi.function.FunctionKind) PRIVATE(com.facebook.presto.bytecode.Access.PRIVATE) PrestoException(com.facebook.presto.spi.PrestoException) TypeSignatureProvider.fromTypes(com.facebook.presto.sql.analyzer.TypeSignatureProvider.fromTypes) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) RETURN_NULL_ON_NULL(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.NullConvention.RETURN_NULL_ON_NULL) Type(com.facebook.presto.common.type.Type) Failures.checkCondition(com.facebook.presto.util.Failures.checkCondition) PUBLIC(com.facebook.presto.bytecode.Access.PUBLIC) CompilerUtils.defineClass(com.facebook.presto.util.CompilerUtils.defineClass) SqlScalarFunction(com.facebook.presto.metadata.SqlScalarFunction) OperatorType(com.facebook.presto.common.function.OperatorType) STATIC(com.facebook.presto.bytecode.Access.STATIC) TypeSignature.parseTypeSignature(com.facebook.presto.common.type.TypeSignature.parseTypeSignature) Signature(com.facebook.presto.spi.function.Signature) DynamicClassLoader(com.facebook.presto.bytecode.DynamicClassLoader) Variable(com.facebook.presto.bytecode.Variable) 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) Signature.orderableTypeParameter(com.facebook.presto.spi.function.Signature.orderableTypeParameter) Parameter(com.facebook.presto.bytecode.Parameter)

Example 5 with PRIVATE

use of com.facebook.presto.bytecode.Access.PRIVATE in project presto by prestodb.

the class ConcatFunction method generateConcat.

private static Class<?> generateConcat(TypeSignature type, int arity) {
    checkCondition(arity <= 254, NOT_SUPPORTED, "Too many arguments for string concatenation");
    ClassDefinition definition = new ClassDefinition(a(PUBLIC, FINAL), makeClassName(type.getBase() + "_concat" + arity + "ScalarFunction"), type(Object.class));
    // Generate constructor
    definition.declareDefaultConstructor(a(PRIVATE));
    // Generate concat()
    List<Parameter> parameters = IntStream.range(0, arity).mapToObj(i -> arg("arg" + i, Slice.class)).collect(toImmutableList());
    MethodDefinition method = definition.declareMethod(a(PUBLIC, STATIC), "concat", type(Slice.class), parameters);
    Scope scope = method.getScope();
    BytecodeBlock body = method.getBody();
    Variable result = scope.declareVariable(Slice.class, "result");
    body.append(invokeStatic(ConcatFunction.class, "concat", Slice.class, BytecodeExpressions.newArray(ParameterizedType.type(Slice[].class), parameters))).retObject();
    return defineClass(definition, Object.class, ImmutableMap.of(), new DynamicClassLoader(ConcatFunction.class.getClassLoader()));
}
Also used : FunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager) IntStream(java.util.stream.IntStream) MethodHandle(java.lang.invoke.MethodHandle) FunctionKind(com.facebook.presto.spi.function.FunctionKind) Slice(io.airlift.slice.Slice) VarcharType.createUnboundedVarcharType(com.facebook.presto.common.type.VarcharType.createUnboundedVarcharType) BytecodeExpressions(com.facebook.presto.bytecode.expression.BytecodeExpressions) PRIVATE(com.facebook.presto.bytecode.Access.PRIVATE) PrestoException(com.facebook.presto.spi.PrestoException) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) TypeSignature(com.facebook.presto.common.type.TypeSignature) Access.a(com.facebook.presto.bytecode.Access.a) DEFAULT_NAMESPACE(com.facebook.presto.metadata.BuiltInTypeAndFunctionNamespaceManager.DEFAULT_NAMESPACE) ImmutableList(com.google.common.collect.ImmutableList) ParameterizedType.type(com.facebook.presto.bytecode.ParameterizedType.type) Reflection.methodHandle(com.facebook.presto.util.Reflection.methodHandle) Slices(io.airlift.slice.Slices) QualifiedObjectName(com.facebook.presto.common.QualifiedObjectName) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) INVALID_FUNCTION_ARGUMENT(com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT) CompilerUtils.makeClassName(com.facebook.presto.util.CompilerUtils.makeClassName) RETURN_NULL_ON_NULL(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.NullConvention.RETURN_NULL_ON_NULL) UsedByGeneratedCode(com.facebook.presto.annotation.UsedByGeneratedCode) Failures.checkCondition(com.facebook.presto.util.Failures.checkCondition) PUBLIC(com.facebook.presto.bytecode.Access.PUBLIC) Variable(com.facebook.presto.bytecode.Variable) CompilerUtils.defineClass(com.facebook.presto.util.CompilerUtils.defineClass) BoundVariables(com.facebook.presto.metadata.BoundVariables) Parameter(com.facebook.presto.bytecode.Parameter) ImmutableMap(com.google.common.collect.ImmutableMap) SqlScalarFunction(com.facebook.presto.metadata.SqlScalarFunction) Collections.nCopies(java.util.Collections.nCopies) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) VARBINARY(com.facebook.presto.common.type.VarbinaryType.VARBINARY) DynamicClassLoader(com.facebook.presto.bytecode.DynamicClassLoader) SqlFunctionVisibility(com.facebook.presto.spi.function.SqlFunctionVisibility) ArgumentProperty.valueTypeArgumentProperty(com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.ArgumentProperty.valueTypeArgumentProperty) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) List(java.util.List) FINAL(com.facebook.presto.bytecode.Access.FINAL) STATIC(com.facebook.presto.bytecode.Access.STATIC) Scope(com.facebook.presto.bytecode.Scope) NOT_SUPPORTED(com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED) Signature(com.facebook.presto.spi.function.Signature) BytecodeExpressions.invokeStatic(com.facebook.presto.bytecode.expression.BytecodeExpressions.invokeStatic) Parameter.arg(com.facebook.presto.bytecode.Parameter.arg) ParameterizedType(com.facebook.presto.bytecode.ParameterizedType) DynamicClassLoader(com.facebook.presto.bytecode.DynamicClassLoader) Variable(com.facebook.presto.bytecode.Variable) Scope(com.facebook.presto.bytecode.Scope) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) Slice(io.airlift.slice.Slice) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) Parameter(com.facebook.presto.bytecode.Parameter) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition)

Aggregations

PRIVATE (com.facebook.presto.bytecode.Access.PRIVATE)7 Access.a (com.facebook.presto.bytecode.Access.a)7 BytecodeBlock (com.facebook.presto.bytecode.BytecodeBlock)7 ClassDefinition (com.facebook.presto.bytecode.ClassDefinition)7 Variable (com.facebook.presto.bytecode.Variable)7 ImmutableList (com.google.common.collect.ImmutableList)7 List (java.util.List)7 PUBLIC (com.facebook.presto.bytecode.Access.PUBLIC)6 MethodDefinition (com.facebook.presto.bytecode.MethodDefinition)6 Parameter (com.facebook.presto.bytecode.Parameter)6 Parameter.arg (com.facebook.presto.bytecode.Parameter.arg)6 ParameterizedType.type (com.facebook.presto.bytecode.ParameterizedType.type)6 Scope (com.facebook.presto.bytecode.Scope)6 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)6 ImmutableMap (com.google.common.collect.ImmutableMap)6 FINAL (com.facebook.presto.bytecode.Access.FINAL)5 PrestoException (com.facebook.presto.spi.PrestoException)5 CallSiteBinder (com.facebook.presto.bytecode.CallSiteBinder)4 FieldDefinition (com.facebook.presto.bytecode.FieldDefinition)4 BytecodeExpressions.invokeStatic (com.facebook.presto.bytecode.expression.BytecodeExpressions.invokeStatic)4