com.oracle.truffle.api.Truffle Java Examples

The following examples show how to use com.oracle.truffle.api.Truffle. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ObjectGraphUtils.java    From trufflesqueak with MIT License 6 votes vote down vote up
private void addObjectsFromTruffleFrames() {
    CompilerAsserts.neverPartOfCompilation();
    Truffle.getRuntime().iterateFrames(frameInstance -> {
        final Frame current = frameInstance.getFrame(FrameInstance.FrameAccess.READ_ONLY);
        if (!FrameAccess.isTruffleSqueakFrame(current)) {
            return null;
        }
        for (final Object argument : current.getArguments()) {
            addIfUnmarked(argument);
        }
        final CompiledCodeObject blockOrMethod = FrameAccess.getBlockOrMethod(current);
        addIfUnmarked(FrameAccess.getContext(current, blockOrMethod));
        for (final FrameSlot slot : blockOrMethod.getStackSlotsUnsafe()) {
            if (slot == null) {
                return null; // Stop here, slot has not (yet) been created.
            }
            if (current.isObject(slot)) {
                addIfUnmarked(FrameUtil.getObjectSafe(current, slot));
            }
        }
        return null;
    });
}
 
Example #2
Source File: FrameAccess.java    From trufflesqueak with MIT License 6 votes vote down vote up
@TruffleBoundary
public static MaterializedFrame findFrameForMarker(final FrameMarker frameMarker) {
    CompilerDirectives.bailout("Finding materializable frames should never be part of compiled code as it triggers deopts");
    LogUtils.ITERATE_FRAMES.fine("Iterating frames to find a marker...");
    final Frame frame = Truffle.getRuntime().iterateFrames(frameInstance -> {
        final Frame current = frameInstance.getFrame(FrameInstance.FrameAccess.READ_ONLY);
        if (!isTruffleSqueakFrame(current)) {
            return null;
        }
        LogUtils.ITERATE_FRAMES.fine(() -> "..." + FrameAccess.getMethod(current).toString());
        if (frameMarker == getMarker(current)) {
            return frameInstance.getFrame(FrameInstance.FrameAccess.MATERIALIZE);
        }
        return null;
    });
    if (frame == null) {
        throw SqueakException.create("Could not find frame for:", frameMarker);
    } else {
        return frame.materialize();
    }
}
 
Example #3
Source File: HashemParseInContextTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@Override
protected CallTarget parse(ParsingRequest request) throws Exception {
    return Truffle.getRuntime().createCallTarget(new RootNode(this) {

        @CompilationFinal private ContextReference<Env> reference;

        @Override
        public Object execute(VirtualFrame frame) {
            return parseAndEval();
        }

        @TruffleBoundary
        private Object parseAndEval() {
            if (reference == null) {
                CompilerDirectives.transferToInterpreterAndInvalidate();
                this.reference = lookupContextReference(EvalLang.class);
            }
            Source aPlusB = Source.newBuilder("hashemi", "a + b", "plus.hashem").build();
            return reference.get().parsePublic(aPlusB, "a", "b").call(30, 12);
        }
    });
}
 
Example #4
Source File: ContextObject.java    From trufflesqueak with MIT License 6 votes vote down vote up
private ContextObject(final ContextObject original) {
    super(original);
    final CompiledCodeObject code = FrameAccess.getBlockOrMethod(original.truffleFrame);
    hasModifiedSender = original.hasModifiedSender();
    escaped = original.escaped;
    size = original.size;
    // Create shallow copy of Truffle frame
    truffleFrame = Truffle.getRuntime().createMaterializedFrame(original.truffleFrame.getArguments().clone(), code.getFrameDescriptor());
    // Copy frame slot values
    FrameAccess.initializeMarker(truffleFrame, code);
    FrameAccess.setContext(truffleFrame, code, this);
    FrameAccess.setInstructionPointer(truffleFrame, code, FrameAccess.getInstructionPointer(original.truffleFrame, code));
    FrameAccess.setStackPointer(truffleFrame, code, FrameAccess.getStackPointer(original.truffleFrame, code));
    // Copy stack
    final int numStackSlots = code.getNumStackSlots();
    for (int i = 0; i < numStackSlots; i++) {
        final FrameSlot slot = code.getStackSlot(i);
        final Object value = original.truffleFrame.getValue(slot);
        if (value != null) {
            FrameAccess.setStackSlot(truffleFrame, slot, value);
        } else {
            break; // This and all following slots are not in use.
        }
    }
}
 
Example #5
Source File: CompiledCodeObject.java    From trufflesqueak with MIT License 6 votes vote down vote up
@TruffleBoundary
public final RootCallTarget getResumptionCallTarget(final ContextObject context) {
    if (resumptionCallTarget == null) {
        CompilerDirectives.transferToInterpreterAndInvalidate();
        resumptionCallTarget = Truffle.getRuntime().createCallTarget(ResumeContextRootNode.create(SqueakLanguage.getContext().getLanguage(), context));
    } else {
        final ResumeContextRootNode resumeNode = (ResumeContextRootNode) resumptionCallTarget.getRootNode();
        if (resumeNode.getActiveContext() != context) {
            /**
             * This is a trick: we set the activeContext of the {@link ResumeContextRootNode} to
             * the given context to be able to reuse the call target.
             */
            resumeNode.setActiveContext(context);
        }
    }
    return resumptionCallTarget;
}
 
Example #6
Source File: SqueakLanguage.java    From trufflesqueak with MIT License 5 votes vote down vote up
@Override
protected CallTarget parse(final ParsingRequest request) throws Exception {
    final SqueakImageContext image = getContext();
    final Source source = request.getSource();
    if (source.hasBytes()) {
        image.setImagePath(source.getPath());
        return image.getSqueakImage().asCallTarget();
    } else {
        image.ensureLoaded();
        if (source.isInternal()) {
            image.printToStdOut(MiscUtils.format("Evaluating '%s'...", source.getCharacters().toString()));
        }
        return Truffle.getRuntime().createCallTarget(image.getDoItContextNode(source));
    }
}
 
Example #7
Source File: DebugUtils.java    From trufflesqueak with MIT License 5 votes vote down vote up
public static void printSqStackTrace() {
    CompilerAsserts.neverPartOfCompilation("For debugging purposes only");
    final boolean isCIBuild = System.getenv().containsKey("GITHUB_ACTIONS");
    final int[] depth = new int[1];
    final Object[] lastSender = new Object[]{null};
    final PrintWriter err = SqueakLanguage.getContext().getError();
    err.println("== Truffle stack trace ===========================================================");
    Truffle.getRuntime().iterateFrames(frameInstance -> {
        if (depth[0]++ > 50 && isCIBuild) {
            return null;
        }
        final Frame current = frameInstance.getFrame(FrameInstance.FrameAccess.READ_ONLY);
        if (!FrameAccess.isTruffleSqueakFrame(current)) {
            return null;
        }
        final CompiledMethodObject method = FrameAccess.getMethod(current);
        lastSender[0] = FrameAccess.getSender(current);
        final Object marker = FrameAccess.getMarker(current, method);
        final Object context = FrameAccess.getContext(current, method);
        final String prefix = FrameAccess.getClosure(current) == null ? "" : "[] in ";
        final String argumentsString = ArrayUtils.toJoinedString(", ", FrameAccess.getReceiverAndArguments(current));
        err.println(MiscUtils.format("%s%s #(%s) [marker: %s, context: %s, sender: %s]", prefix, method, argumentsString, marker, context, lastSender[0]));
        return null;
    });
    if (lastSender[0] instanceof ContextObject) {
        err.println("== Squeak frames ================================================================");
        printSqStackTrace((ContextObject) lastSender[0]);
    }
}
 
Example #8
Source File: AbstractSqueakTestCaseWithImage.java    From trufflesqueak with MIT License 5 votes vote down vote up
protected static Object evaluate(final String expression) {
    context.enter();
    try {
        final ExecuteTopLevelContextNode doItContextNode = image.getDoItContextNode(expression);
        return Truffle.getRuntime().createCallTarget(doItContextNode).call();
    } finally {
        context.leave();
    }
}
 
Example #9
Source File: ContextObject.java    From trufflesqueak with MIT License 5 votes vote down vote up
public MaterializedFrame getOrCreateTruffleFrame() {
    if (truffleFrame == null) {
        CompilerDirectives.transferToInterpreterAndInvalidate();
        // Method is unknown, use dummy frame instead
        final Object[] dummyArguments = FrameAccess.newDummyWith(null, NilObject.SINGLETON, null, new Object[2]);
        final CompiledMethodObject dummyMethod = SqueakLanguage.getContext().dummyMethod;
        truffleFrame = Truffle.getRuntime().createMaterializedFrame(dummyArguments, dummyMethod.getFrameDescriptor());
        FrameAccess.setInstructionPointer(truffleFrame, dummyMethod, 0);
        FrameAccess.setStackPointer(truffleFrame, dummyMethod, 1);
    }
    return truffleFrame;
}
 
Example #10
Source File: MumblerException.java    From mumbler with GNU General Public License v3.0 5 votes vote down vote up
public static Throwable fillInMumblerStackTrace(Throwable t) {
    final List<StackTraceElement> stackTrace = new ArrayList<>();
    Truffle.getRuntime().iterateFrames((FrameInstanceVisitor<Void>) frame -> {
        Node callNode = frame.getCallNode();
        if (callNode == null) {
            return null;
        }
        RootNode root = callNode.getRootNode();

        /*
         * There should be no RootNodes other than SLRootNodes on the stack. Just for the
         * case if this would change.
         */
        String methodName = "$unknownFunction";
        if (root instanceof MumblerRootNode) {
            methodName = ((MumblerRootNode) root).name;
        }

        SourceSection sourceSection = callNode.getEncapsulatingSourceSection();
        Source source = sourceSection != null ? sourceSection.getSource() : null;
        String sourceName = source != null ? source.getName() : null;
        int lineNumber;
        try {
            lineNumber = sourceSection != null ? sourceSection.getStartLine() : -1;
        } catch (UnsupportedOperationException e) {
            /*
             * SourceSection#getLineLocation() may throw an UnsupportedOperationException.
             */
            lineNumber = -1;
        }
        stackTrace.add(new StackTraceElement("mumbler", methodName, sourceName, lineNumber));
        return null;
    });
    t.setStackTrace(stackTrace.toArray(new StackTraceElement[stackTrace.size()]));
    return t;
}
 
Example #11
Source File: MapDeviceArrayFunction.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected CallTarget createUncachedLoop(Object source, GrCUDAContext context) {
    ConcurrentHashMap<Class<?>, CallTarget> uncachedCallTargets = context.getMapCallTargets();
    DynamicDispatchLibrary dispatch = DynamicDispatchLibrary.getFactory().getUncached(source);
    Class<?> clazz = dispatch.dispatch(source);
    if (clazz == null) {
        clazz = source.getClass();
    }
    return uncachedCallTargets.computeIfAbsent(clazz, c -> Truffle.getRuntime().createCallTarget(new LoopRootNode(source, c)));
}
 
Example #12
Source File: BuiltinNode.java    From mumbler with GNU General Public License v3.0 5 votes vote down vote up
public static MumblerFunction createBuiltinFunction(
        MumblerLanguage lang,
        NodeFactory<? extends BuiltinNode> factory,
        VirtualFrame outerFrame) {
    int argumentCount = factory.getExecutionSignature().size();
    MumblerNode[] argumentNodes = new MumblerNode[argumentCount];
    for (int i=0; i<argumentCount; i++) {
        argumentNodes[i] = new ReadArgumentNode(i);
    }
    BuiltinNode node = factory.createNode((Object) argumentNodes);
    return new MumblerFunction(Truffle.getRuntime().createCallTarget(
            new MumblerRootNode(lang, new MumblerNode[] {node},
                    new FrameDescriptor())));
}
 
Example #13
Source File: HashemSeparatedClassLoadersTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Test
public void sdkAndTruffleLanguageAPIAndSLInSeparateClassLoaders() throws Exception {
    final ProtectionDomain sdkDomain = Engine.class.getProtectionDomain();
    Assume.assumeNotNull(sdkDomain);
    Assume.assumeNotNull(sdkDomain.getCodeSource());
    URL sdkURL = sdkDomain.getCodeSource().getLocation();
    Assume.assumeNotNull(sdkURL);

    URL truffleURL = Truffle.class.getProtectionDomain().getCodeSource().getLocation();
    Assume.assumeNotNull(truffleURL);

    URL slURL = HashemLanguage.class.getProtectionDomain().getCodeSource().getLocation();
    Assume.assumeNotNull(slURL);

    ClassLoader parent = Engine.class.getClassLoader().getParent();

    URLClassLoader sdkLoader = new URLClassLoader(new URL[]{sdkURL}, parent);
    boolean sdkLoaderLoadsTruffleLanguage;
    try {
        Class.forName("com.oracle.truffle.api.TruffleLanguage", false, sdkLoader);
        sdkLoaderLoadsTruffleLanguage = true;
    } catch (ClassNotFoundException cnf) {
        sdkLoaderLoadsTruffleLanguage = false;
    }
    Assume.assumeFalse(sdkLoaderLoadsTruffleLanguage);
    URLClassLoader truffleLoader = new URLClassLoader(new URL[]{truffleURL}, sdkLoader);
    URLClassLoader slLoader = new URLClassLoader(new URL[]{slURL}, truffleLoader);
    Thread.currentThread().setContextClassLoader(slLoader);

    Class<?> engineClass = sdkLoader.loadClass(Engine.class.getName());
    Object engine = engineClass.getMethod("create").invoke(null);
    assertNotNull("Engine has been created", engine);

    Map<?, ?> languages = (Map<?, ?>) engineClass.getMethod("getLanguages").invoke(engine);
    Object lang = languages.get("hashemi");
    assertNotNull("SL language found: " + languages, lang);
}
 
Example #14
Source File: HashemStackTraceBuiltin.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@TruffleBoundary
private static String createStackTrace() {
    final StringBuilder str = new StringBuilder();

    Truffle.getRuntime().iterateFrames(new FrameInstanceVisitor<Integer>() {
        private int skip = 1; // skip stack trace builtin

        @Override
        public Integer visitFrame(FrameInstance frameInstance) {
            if (skip > 0) {
                skip--;
                return null;
            }
            CallTarget callTarget = frameInstance.getCallTarget();
            Frame frame = frameInstance.getFrame(FrameAccess.READ_ONLY);
            RootNode rn = ((RootCallTarget) callTarget).getRootNode();
            // ignore internal or interop stack frames
            if (rn.isInternal() || rn.getLanguageInfo() == null) {
                return 1;
            }
            if (str.length() > 0) {
                str.append(System.getProperty("line.separator"));
            }
            str.append("Frame: ").append(rn.toString());
            FrameDescriptor frameDescriptor = frame.getFrameDescriptor();
            for (FrameSlot s : frameDescriptor.getSlots()) {
                str.append(", ").append(s.getIdentifier()).append("=").append(frame.getValue(s));
            }
            return null;
        }
    });
    return str.toString();
}
 
Example #15
Source File: SqueakProfiles.java    From trufflesqueak with MIT License 4 votes vote down vote up
private static boolean isProfilingEnabled() {
    return Truffle.getRuntime().isProfilingEnabled();
}
 
Example #16
Source File: MumblerContext.java    From mumbler with GNU General Public License v3.0 4 votes vote down vote up
private MaterializedFrame initGlobalFrame(MumblerLanguage lang) {
    VirtualFrame frame = Truffle.getRuntime().createVirtualFrame(null,
            this.globalFrameDescriptor);
    addGlobalFunctions(lang, frame);
    return frame.materialize();
}
 
Example #17
Source File: LoopNode.java    From mumbler with GNU General Public License v3.0 4 votes vote down vote up
public LoopNode(InvokeNode callNode) {
    this.callString = callNode.toString();
    this.loopNode = Truffle.getRuntime().createLoopNode(
            new LoopReapeatingNode(callNode));
}
 
Example #18
Source File: AbstractSqueakTestCase.java    From trufflesqueak with MIT License 4 votes vote down vote up
protected static VirtualFrame createTestFrame(final CompiledMethodObject code) {
    final Object[] arguments = FrameAccess.newWith(code, NilObject.SINGLETON, null, new Object[]{NilObject.SINGLETON});
    return Truffle.getRuntime().createVirtualFrame(arguments, code.getFrameDescriptor());
}
 
Example #19
Source File: SqueakImage.java    From trufflesqueak with MIT License 4 votes vote down vote up
public RootCallTarget asCallTarget() {
    return Truffle.getRuntime().createCallTarget(new SqueakImageNode(this));
}
 
Example #20
Source File: DirectDispatchNode.java    From mumbler with GNU General Public License v3.0 4 votes vote down vote up
public DirectDispatchNode(DispatchNode next, CallTarget callTarget) {
    this.cachedCallTarget = callTarget;
    this.callCachedTargetNode = Truffle.getRuntime().createDirectCallNode(
            this.cachedCallTarget);
    this.nextNode = next;
}
 
Example #21
Source File: MumblerFunction.java    From mumbler with GNU General Public License v3.0 4 votes vote down vote up
public static MumblerFunction create(MumblerLanguage lang, FrameSlot[] arguments,
                                     MumblerNode[] bodyNodes, FrameDescriptor frameDescriptor) {
    return new MumblerFunction(
            Truffle.getRuntime().createCallTarget(
                    MumblerRootNode.create(lang, arguments, bodyNodes, frameDescriptor)));
}
 
Example #22
Source File: SqueakImageContext.java    From trufflesqueak with MIT License 4 votes vote down vote up
@TruffleBoundary
public Object evaluate(final String sourceCode) {
    final Source source = Source.newBuilder(SqueakLanguageConfig.NAME, sourceCode, "<image#evaluate>").build();
    return Truffle.getRuntime().createCallTarget(getDoItContextNode(source)).call();
}
 
Example #23
Source File: TruffleSqueakPlugin.java    From trufflesqueak with MIT License 4 votes vote down vote up
@Specialization
protected static final Object doGet(@SuppressWarnings("unused") final Object receiver) {
    return JavaObjectWrapper.wrap(Truffle.getRuntime());
}
 
Example #24
Source File: ContextPrimitives.java    From trufflesqueak with MIT License 4 votes vote down vote up
@TruffleBoundary
@Specialization(guards = {"!receiver.hasMaterializedSender()"})
protected final AbstractSqueakObject findNextAvoidingMaterialization(final ContextObject receiver) {
    final boolean[] foundMyself = new boolean[1];
    final Object[] lastSender = new Object[1];
    final ContextObject result = Truffle.getRuntime().iterateFrames(frameInstance -> {
        final Frame current = frameInstance.getFrame(FrameInstance.FrameAccess.READ_ONLY);
        if (!FrameAccess.isTruffleSqueakFrame(current)) {
            final RootNode rootNode = ((RootCallTarget) frameInstance.getCallTarget()).getRootNode();
            if (rootNode.isInternal() || rootNode.getLanguageInfo().getId().equals(SqueakLanguageConfig.ID)) {
                /* Skip internal and all other nodes that belong to TruffleSqueak. */
                return null;
            } else {
                /*
                 * Found a frame of another language. Stop here by returning the receiver
                 * context. This special case will be handled later on.
                 */
                return receiver;
            }
        }
        final ContextObject context = FrameAccess.getContext(current);
        if (!foundMyself[0]) {
            if (context == receiver) {
                foundMyself[0] = true;
            }
        } else {
            if (FrameAccess.getMethod(current).isExceptionHandlerMarked()) {
                if (context != null) {
                    return context;
                } else {
                    return ContextObject.create(frameInstance);
                }
            } else {
                lastSender[0] = FrameAccess.getSender(current);
            }
        }
        return null;
    });
    if (result == receiver) {
        /*
         * Foreign frame found during frame iteration. Inject a fake context which will
         * throw the Smalltalk exception as polyglot exception.
         */
        return getInteropExceptionThrowingContext();
    } else if (result == null) {
        if (!foundMyself[0]) {
            return findNext(receiver); // Fallback to other version.
        }
        if (lastSender[0] instanceof ContextObject) {
            return findNext((ContextObject) lastSender[0]);
        } else {
            return NilObject.SINGLETON;
        }
    } else {
        return result;
    }
}
 
Example #25
Source File: HashemLanguage.java    From mr-hashemi with Universal Permissive License v1.0 4 votes vote down vote up
@Override
protected CallTarget parse(ParsingRequest request) throws Exception {
    Source source = request.getSource();
    Map<String, RootCallTarget> functions;
    /*
     * Parse the provided source. At this point, we do not have a SLContext yet. Registration of
     * the functions with the SLContext happens lazily in SLEvalRootNode.
     */
    if (request.getArgumentNames().isEmpty()) {
        functions = HashemLanguageParser.parseHashemiLang(this, source);
    } else {
        Source requestedSource = request.getSource();
        StringBuilder sb = new StringBuilder();
        sb.append("bebin azinja(");
        String sep = "";
        for (String argumentName : request.getArgumentNames()) {
            sb.append(sep);
            sb.append(argumentName);
            sep = ",";
        }
        sb.append(") { return ");
        sb.append(request.getSource().getCharacters());
        sb.append(";}");
        String language = requestedSource.getLanguage() == null ? ID : requestedSource.getLanguage();
        Source decoratedSource = Source.newBuilder(language, sb.toString(), request.getSource().getName()).build();
        functions = HashemLanguageParser.parseHashemiLang(this, decoratedSource);
    }

    RootCallTarget main = functions.get("azinja");
    RootNode evalMain;
    if (main != null) {
        /*
         * We have a main function, so "evaluating" the parsed source means invoking that main
         * function. However, we need to lazily register functions into the SLContext first, so
         * we cannot use the original SLRootNode for the main function. Instead, we create a new
         * SLEvalRootNode that does everything we need.
         */
        evalMain = new HashemEvalRootNode(this, main, functions);
    } else {
        /*
         * Even without a main function, "evaluating" the parsed source needs to register the
         * functions into the SLContext.
         */
        evalMain = new HashemEvalRootNode(this, null, functions);
    }
    return Truffle.getRuntime().createCallTarget(evalMain);
}
 
Example #26
Source File: CompiledCodeObject.java    From trufflesqueak with MIT License 4 votes vote down vote up
protected final void initializeCallTargetUnsafe() {
    callTarget = Truffle.getRuntime().createCallTarget(EnterCodeNode.create(SqueakLanguage.getContext().getLanguage(), this));
}
 
Example #27
Source File: MapDeviceArrayFunction.java    From grcuda with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected CallTarget createLoop(Object source) {
    return Truffle.getRuntime().createCallTarget(new LoopRootNode(source, null));
}
 
Example #28
Source File: MapDeviceArrayFunction.java    From grcuda with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected LoopRootNode(Object source, Class<?> clazz) {
    super(GrCUDALanguage.getCurrentLanguage(), DESCRIPTOR);
    this.clazz = clazz;
    this.loop = Truffle.getRuntime().createLoopNode(new RepeatingLoopNode(InteropLibrary.getFactory().create(source)));
}
 
Example #29
Source File: GrCUDALanguage.java    From grcuda with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected CallTarget parse(ParsingRequest request) {
    ExpressionNode expression = new ParserAntlr().parse(request.getSource());
    GrCUDARootNode newParserRoot = new GrCUDARootNode(this, expression);
    return Truffle.getRuntime().createCallTarget(newParserRoot);
}
 
Example #30
Source File: HashemBebin.java    From mr-hashemi with Universal Permissive License v1.0 4 votes vote down vote up
protected HashemBebin(HashemLanguage language, String name) {
    this.name = name;
    this.callTarget = Truffle.getRuntime().createCallTarget(new HashemUndefinedBebinRootNode(language, name));
    this.callTargetStable = new CyclicAssumption(name);
}