Search in sources :

Example 41 with VirtualFrame

use of com.oracle.truffle.api.frame.VirtualFrame in project graal by oracle.

the class ContextLookupTest method invalidLookup.

@Test
public void invalidLookup() throws Exception {
    LanguageLookupContext context = new LanguageLookupContext(null);
    PolyglotEngine vm = createBuilder().config(LanguageLookup.MIME_TYPE, "channel", context).build();
    vm.getLanguages().get(LanguageLookup.MIME_TYPE).getGlobalObject();
    try {
        LanguageLookup.getContext();
        fail();
    } catch (IllegalStateException e) {
    }
    try {
        LanguageLookup.getLanguage();
        fail();
    } catch (IllegalStateException e) {
    }
    RootNode root = new RootNode(context.language) {

        @Override
        public Object execute(VirtualFrame frame) {
            return null;
        }
    };
    try {
        root.getCurrentContext(LanguageLookup.class);
        fail();
    } catch (IllegalStateException e) {
    }
    try {
        // using an exposed context reference outside of PE does not work
        context.language.sharedChannelRef.get();
        fail();
    } catch (IllegalStateException e) {
    }
    try {
        // but you can create context references outside
        context.language.getContextReference();
    } catch (IllegalStateException e) {
    }
    try {
        // creating a context reference in the constructor does not work
        context.language.getContextReference().get();
        fail();
    } catch (IllegalStateException e) {
    // illegal state expected. context not yet initialized
    }
}
Also used : VirtualFrame(com.oracle.truffle.api.frame.VirtualFrame) RootNode(com.oracle.truffle.api.nodes.RootNode) Test(org.junit.Test)

Example 42 with VirtualFrame

use of com.oracle.truffle.api.frame.VirtualFrame in project graal by oracle.

the class InstrumentableProcessor method generateWrapper.

@SuppressWarnings("deprecation")
private CodeTypeElement generateWrapper(ProcessorContext context, Element e, boolean topLevelClass) {
    if (!e.getKind().isClass()) {
        return null;
    }
    if (e.getModifiers().contains(Modifier.PRIVATE)) {
        emitError(e, "Class must not be private to generate a wrapper.");
        return null;
    }
    if (e.getModifiers().contains(Modifier.FINAL)) {
        emitError(e, "Class must not be final to generate a wrapper.");
        return null;
    }
    if (e.getEnclosingElement().getKind() != ElementKind.PACKAGE && !e.getModifiers().contains(Modifier.STATIC)) {
        emitError(e, "Inner class must be static to generate a wrapper.");
        return null;
    }
    TypeElement sourceType = (TypeElement) e;
    ExecutableElement constructor = null;
    List<ExecutableElement> constructors = ElementFilter.constructorsIn(e.getEnclosedElements());
    if (constructors.isEmpty()) {
        // add default constructor
        constructors.add(new CodeExecutableElement(ElementUtils.modifiers(Modifier.PUBLIC), null, e.getSimpleName().toString()));
    }
    // try visible default constructor
    for (ListIterator<ExecutableElement> iterator = constructors.listIterator(); iterator.hasNext(); ) {
        ExecutableElement c = iterator.next();
        Modifier modifier = ElementUtils.getVisibility(c.getModifiers());
        if (modifier == Modifier.PRIVATE) {
            iterator.remove();
            continue;
        }
        if (c.getParameters().isEmpty()) {
            constructor = c;
            break;
        }
    }
    // try copy constructor
    if (constructor == null) {
        for (ExecutableElement c : constructors) {
            VariableElement firstParameter = c.getParameters().iterator().next();
            if (ElementUtils.typeEquals(firstParameter.asType(), sourceType.asType())) {
                constructor = c;
                break;
            }
        }
    }
    // try source section constructor
    if (constructor == null) {
        for (ExecutableElement c : constructors) {
            VariableElement firstParameter = c.getParameters().iterator().next();
            if (ElementUtils.typeEquals(firstParameter.asType(), context.getType(SourceSection.class))) {
                constructor = c;
                break;
            }
        }
    }
    if (constructor == null) {
        emitError(sourceType, "No suiteable constructor found for wrapper factory generation. At least one default or copy constructor must be visible.");
        return null;
    }
    PackageElement pack = context.getEnvironment().getElementUtils().getPackageOf(sourceType);
    Set<Modifier> typeModifiers;
    String wrapperClassName = createWrapperClassName(sourceType);
    if (topLevelClass) {
        typeModifiers = ElementUtils.modifiers(Modifier.FINAL);
    } else {
        typeModifiers = ElementUtils.modifiers(Modifier.PRIVATE, Modifier.FINAL);
        // add some suffix to avoid name clashes
        wrapperClassName += "0";
    }
    CodeTypeElement wrapperType = new CodeTypeElement(typeModifiers, ElementKind.CLASS, pack, wrapperClassName);
    TypeMirror resolvedSuperType = sourceType.asType();
    wrapperType.setSuperClass(resolvedSuperType);
    if (topLevelClass) {
        wrapperType.getImplements().add(context.getType(InstrumentableNode.WrapperNode.class));
    } else {
        wrapperType.getImplements().add(context.getType(com.oracle.truffle.api.instrumentation.InstrumentableFactory.WrapperNode.class));
    }
    addGeneratedBy(context, wrapperType, sourceType);
    wrapperType.add(createNodeChild(context, sourceType.asType(), FIELD_DELEGATE));
    wrapperType.add(createNodeChild(context, context.getType(ProbeNode.class), FIELD_PROBE));
    Set<Modifier> constructorModifiers;
    if (topLevelClass) {
        // package protected
        constructorModifiers = ElementUtils.modifiers();
    } else {
        constructorModifiers = ElementUtils.modifiers(Modifier.PRIVATE);
    }
    CodeExecutableElement wrappedConstructor = GeneratorUtils.createConstructorUsingFields(constructorModifiers, wrapperType, constructor);
    wrapperType.add(wrappedConstructor);
    // generate getters
    for (VariableElement field : wrapperType.getFields()) {
        CodeExecutableElement getter = new CodeExecutableElement(ElementUtils.modifiers(Modifier.PUBLIC), field.asType(), "get" + ElementUtils.firstLetterUpperCase(field.getSimpleName().toString()));
        getter.createBuilder().startReturn().string(field.getSimpleName().toString()).end();
        wrapperType.add(getter);
    }
    if (isOverrideableOrUndeclared(sourceType, METHOD_GET_NODE_COST)) {
        TypeMirror returnType = context.getType(NodeCost.class);
        CodeExecutableElement getInstrumentationTags = new CodeExecutableElement(ElementUtils.modifiers(Modifier.PUBLIC), returnType, METHOD_GET_NODE_COST);
        getInstrumentationTags.createBuilder().startReturn().staticReference(returnType, "NONE").end();
        wrapperType.add(getInstrumentationTags);
    }
    List<ExecutableElement> wrappedMethods = new ArrayList<>();
    List<ExecutableElement> wrappedExecuteMethods = new ArrayList<>();
    List<? extends Element> elementList = context.getEnvironment().getElementUtils().getAllMembers(sourceType);
    for (ExecutableElement method : ElementFilter.methodsIn(elementList)) {
        Set<Modifier> modifiers = method.getModifiers();
        if (modifiers.contains(Modifier.FINAL)) {
            continue;
        }
        Modifier visibility = ElementUtils.getVisibility(modifiers);
        if (visibility == Modifier.PRIVATE) {
            continue;
        }
        String methodName = method.getSimpleName().toString();
        if (methodName.startsWith(EXECUTE_METHOD_PREFIX)) {
            VariableElement firstParam = method.getParameters().isEmpty() ? null : method.getParameters().get(0);
            if (topLevelClass && (firstParam == null || !ElementUtils.isAssignable(firstParam.asType(), context.getType(VirtualFrame.class)))) {
                emitError(e, String.format("Wrapped execute method %s must have VirtualFrame as first parameter.", method.getSimpleName().toString()));
                return null;
            }
            wrappedExecuteMethods.add(method);
        } else {
            if (// 
            modifiers.contains(Modifier.ABSTRACT) && !methodName.equals("getSourceSection") && !methodName.equals(METHOD_GET_NODE_COST)) {
                wrappedMethods.add(method);
            }
        }
    }
    if (wrappedExecuteMethods.isEmpty()) {
        emitError(sourceType, String.format("No methods starting with name execute found to wrap."));
        return null;
    }
    Collections.sort(wrappedExecuteMethods, new Comparator<ExecutableElement>() {

        public int compare(ExecutableElement o1, ExecutableElement o2) {
            return ElementUtils.compareMethod(o1, o2);
        }
    });
    for (ExecutableElement executeMethod : wrappedExecuteMethods) {
        CodeExecutableElement wrappedExecute = CodeExecutableElement.clone(processingEnv, executeMethod);
        wrappedExecute.getModifiers().remove(Modifier.ABSTRACT);
        wrappedExecute.getAnnotationMirrors().clear();
        String frameParameterName = "null";
        for (VariableElement parameter : wrappedExecute.getParameters()) {
            if (ElementUtils.typeEquals(context.getType(VirtualFrame.class), parameter.asType())) {
                frameParameterName = parameter.getSimpleName().toString();
                break;
            }
        }
        CodeTreeBuilder builder = wrappedExecute.createBuilder();
        TypeMirror returnTypeMirror = executeMethod.getReturnType();
        boolean returnVoid = ElementUtils.isVoid(returnTypeMirror);
        String returnName;
        if (!returnVoid) {
            returnName = "returnValue";
            builder.declaration(returnTypeMirror, returnName, (CodeTree) null);
        } else {
            returnName = "null";
        }
        builder.startFor().startGroup().string(";;").end().end().startBlock();
        builder.declaration("boolean", VAR_RETURN_CALLED, "false");
        builder.startTryBlock();
        builder.startStatement().startCall(FIELD_PROBE, METHOD_ON_ENTER).string(frameParameterName).end().end();
        CodeTreeBuilder callDelegate = builder.create();
        callDelegate.startCall(FIELD_DELEGATE, executeMethod.getSimpleName().toString());
        for (VariableElement parameter : wrappedExecute.getParameters()) {
            callDelegate.string(parameter.getSimpleName().toString());
        }
        callDelegate.end();
        if (returnVoid) {
            builder.statement(callDelegate.build());
        } else {
            builder.startStatement().string(returnName).string(" = ").tree(callDelegate.build()).end();
        }
        builder.startStatement().string(VAR_RETURN_CALLED).string(" = true").end();
        builder.startStatement().startCall(FIELD_PROBE, METHOD_ON_RETURN_VALUE).string(frameParameterName).string(returnName).end().end();
        builder.statement("break");
        if (wrappedExecute.getThrownTypes().contains(context.getType(UnexpectedResultException.class))) {
            builder.end().startCatchBlock(context.getType(UnexpectedResultException.class), "e");
            builder.startStatement().string(VAR_RETURN_CALLED).string(" = true").end();
            builder.startStatement().startCall(FIELD_PROBE, METHOD_ON_RETURN_VALUE).string(frameParameterName).string("e.getResult()").end().end();
            builder.startThrow().string("e").end();
        }
        builder.end().startCatchBlock(context.getType(Throwable.class), "t");
        CodeTreeBuilder callExOrUnwind = builder.create();
        callExOrUnwind.startCall(FIELD_PROBE, METHOD_ON_RETURN_EXCEPTIONAL_OR_UNWIND).string(frameParameterName).string("t").string(VAR_RETURN_CALLED).end();
        builder.declaration("Object", "result", callExOrUnwind.build());
        builder.startIf().string("result == ").string(CONSTANT_REENTER).end();
        builder.startBlock();
        builder.statement("continue");
        builder.end().startElseIf();
        if (returnVoid) {
            builder.string("result != null").end();
            builder.startBlock();
            builder.statement("break");
        } else {
            boolean objectReturnType = "java.lang.Object".equals(ElementUtils.getQualifiedName(returnTypeMirror)) && returnTypeMirror.getKind() != TypeKind.ARRAY;
            boolean throwsUnexpectedResult = wrappedExecute.getThrownTypes().contains(context.getType(UnexpectedResultException.class));
            if (objectReturnType || !throwsUnexpectedResult) {
                builder.string("result != null").end();
                builder.startBlock();
                builder.startStatement().string(returnName).string(" = ");
                if (!objectReturnType) {
                    builder.string("(").string(ElementUtils.getSimpleName(returnTypeMirror)).string(") ");
                }
                builder.string("result").end();
                builder.statement("break");
            } else {
                // can throw UnexpectedResultException
                builder.string("result").instanceOf(boxed(returnTypeMirror, context.getEnvironment().getTypeUtils())).end();
                builder.startBlock();
                builder.startStatement().string(returnName).string(" = ");
                builder.string("(").string(ElementUtils.getSimpleName(returnTypeMirror)).string(") ");
                builder.string("result").end();
                builder.statement("break");
                builder.end();
                builder.startElseIf().string("result != null").end();
                builder.startBlock();
                builder.startThrow().string("new UnexpectedResultException(result)").end();
            }
        }
        builder.end();
        builder.startThrow().string("t").end();
        builder.end(2);
        if (!returnVoid) {
            builder.startReturn().string(returnName).end();
        }
        wrapperType.add(wrappedExecute);
    }
    for (ExecutableElement delegateMethod : wrappedMethods) {
        CodeExecutableElement generatedMethod = CodeExecutableElement.clone(processingEnv, delegateMethod);
        generatedMethod.getModifiers().remove(Modifier.ABSTRACT);
        CodeTreeBuilder callDelegate = generatedMethod.createBuilder();
        if (ElementUtils.isVoid(delegateMethod.getReturnType())) {
            callDelegate.startStatement();
        } else {
            callDelegate.startReturn();
        }
        callDelegate.startCall("this." + FIELD_DELEGATE, generatedMethod.getSimpleName().toString());
        for (VariableElement parameter : generatedMethod.getParameters()) {
            callDelegate.string(parameter.getSimpleName().toString());
        }
        callDelegate.end().end();
        wrapperType.add(generatedMethod);
    }
    return wrapperType;
}
Also used : CodeExecutableElement(com.oracle.truffle.dsl.processor.java.model.CodeExecutableElement) CodeExecutableElement(com.oracle.truffle.dsl.processor.java.model.CodeExecutableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ArrayList(java.util.ArrayList) VariableElement(javax.lang.model.element.VariableElement) CodeVariableElement(com.oracle.truffle.dsl.processor.java.model.CodeVariableElement) UnexpectedResultException(com.oracle.truffle.api.nodes.UnexpectedResultException) CodeTypeElement(com.oracle.truffle.dsl.processor.java.model.CodeTypeElement) CodeTypeMirror(com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror) TypeMirror(javax.lang.model.type.TypeMirror) SourceSection(com.oracle.truffle.api.source.SourceSection) Modifier(javax.lang.model.element.Modifier) TypeElement(javax.lang.model.element.TypeElement) CodeTypeElement(com.oracle.truffle.dsl.processor.java.model.CodeTypeElement) VirtualFrame(com.oracle.truffle.api.frame.VirtualFrame) PackageElement(javax.lang.model.element.PackageElement) CodeTreeBuilder(com.oracle.truffle.dsl.processor.java.model.CodeTreeBuilder)

Example 43 with VirtualFrame

use of com.oracle.truffle.api.frame.VirtualFrame in project graal by oracle.

the class ProxySPITestLanguage method parse.

@Override
protected CallTarget parse(ParsingRequest request) throws Exception {
    Object result = "null result";
    if (runinside != null) {
        try {
            result = runinside.apply(getContext().env);
        } finally {
            runinside = null;
        }
    }
    if (result == null) {
        result = "null result";
    }
    final Object finalResult = result;
    return Truffle.getRuntime().createCallTarget(new RootNode(this) {

        @Override
        public Object execute(VirtualFrame frame) {
            return finalResult;
        }
    });
}
Also used : VirtualFrame(com.oracle.truffle.api.frame.VirtualFrame) RootNode(com.oracle.truffle.api.nodes.RootNode)

Example 44 with VirtualFrame

use of com.oracle.truffle.api.frame.VirtualFrame in project graal by oracle.

the class ContextAPITestLanguage method parse.

@Override
protected CallTarget parse(ParsingRequest request) throws Exception {
    Object result = "null result";
    if (runinside != null) {
        try {
            result = runinside.apply(getContext().env);
        } finally {
            runinside = null;
        }
    }
    if (result == null) {
        result = "null result";
    }
    final Object finalResult = result;
    return Truffle.getRuntime().createCallTarget(new RootNode(this) {

        @Override
        public Object execute(VirtualFrame frame) {
            return finalResult;
        }
    });
}
Also used : VirtualFrame(com.oracle.truffle.api.frame.VirtualFrame) RootNode(com.oracle.truffle.api.nodes.RootNode)

Example 45 with VirtualFrame

use of com.oracle.truffle.api.frame.VirtualFrame in project graal by oracle.

the class ContextThreadLocalTest method testCompilation.

@Test
public void testCompilation() {
    ThreadLocal<Object> tl = createContextThreadLocal();
    Object context1 = createContext();
    CallTarget compiled = Truffle.getRuntime().createCallTarget(new RootNode(null) {

        @Override
        public Object execute(VirtualFrame frame) {
            Object result = tl.get();
            return result;
        }
    });
    tl.set(context1);
    for (int i = 0; i < 10000; i++) {
        compiled.call();
    }
}
Also used : VirtualFrame(com.oracle.truffle.api.frame.VirtualFrame) RootNode(com.oracle.truffle.api.nodes.RootNode) CallTarget(com.oracle.truffle.api.CallTarget) Test(org.junit.Test)

Aggregations

VirtualFrame (com.oracle.truffle.api.frame.VirtualFrame)48 Test (org.junit.Test)34 RootNode (com.oracle.truffle.api.nodes.RootNode)27 OptimizedCallTarget (org.graalvm.compiler.truffle.runtime.OptimizedCallTarget)14 CallTarget (com.oracle.truffle.api.CallTarget)11 FrameDescriptor (com.oracle.truffle.api.frame.FrameDescriptor)9 RootCallTarget (com.oracle.truffle.api.RootCallTarget)6 EventContext (com.oracle.truffle.api.instrumentation.EventContext)5 DirectCallNode (com.oracle.truffle.api.nodes.DirectCallNode)5 ExecutionEventListener (com.oracle.truffle.api.instrumentation.ExecutionEventListener)4 Node (com.oracle.truffle.api.nodes.Node)4 AbstractTestNode (org.graalvm.compiler.truffle.test.nodes.AbstractTestNode)4 RootTestNode (org.graalvm.compiler.truffle.test.nodes.RootTestNode)4 Ignore (org.junit.Ignore)4 TruffleContext (com.oracle.truffle.api.TruffleContext)3 TruffleException (com.oracle.truffle.api.TruffleException)3 FrameInstance (com.oracle.truffle.api.frame.FrameInstance)3 TruffleObject (com.oracle.truffle.api.interop.TruffleObject)3 UnknownIdentifierException (com.oracle.truffle.api.interop.UnknownIdentifierException)3 UnsupportedMessageException (com.oracle.truffle.api.interop.UnsupportedMessageException)3