# HG changeset patch # User Thomas Wuerthinger # Date 1429562538 -7200 # Node ID eae62344f72c0973e339ef5d7d3ed1815d199610 # Parent 41f99f9a8f6394cf6dd1bf880e07368575b8b1db# Parent db8f1141631f8f89c93e19a6162129138e98b61f Merge. diff -r 41f99f9a8f63 -r eae62344f72c CHANGELOG.md --- a/CHANGELOG.md Mon Apr 20 22:42:05 2015 +0200 +++ b/CHANGELOG.md Mon Apr 20 22:42:18 2015 +0200 @@ -5,9 +5,11 @@ ## `tip` ### Graal +* Merged with jdk8u40-b25. * Add utilities ModifiersProvider#isConcrete, ResolvedJavaMethod#hasBytecodes, ResolvedJavaMethod#hasReceiver to Graal API. * Add `GraalDirectives` API, containing methods to influence compiler behavior for unittests and microbenchmarks. * Introduce `LIRSuites`, an extensible configuration for the low-level compiler pipeline. +* The Graal class loader now loads all lib/graal/graal*.jar jars. * ... ### Truffle diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.graal.api.code/src/com/oracle/graal/api/code/BytecodeFrame.java --- a/graal/com.oracle.graal.api.code/src/com/oracle/graal/api/code/BytecodeFrame.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.graal.api.code/src/com/oracle/graal/api/code/BytecodeFrame.java Mon Apr 20 22:42:18 2015 +0200 @@ -132,6 +132,13 @@ public static final int INVALID_FRAMESTATE_BCI = -6; /** + * Determines if a given BCI matches one of the synthetic BCI contants defined in this class. + */ + public static boolean isSyntheticBci(int bci) { + return bci < 0; + } + + /** * Creates a new frame object. * * @param caller the caller frame (which may be {@code null}) diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.graal.compiler.test/src/com/oracle/graal/compiler/test/CheckGraalInvariants.java --- a/graal/com.oracle.graal.compiler.test/src/com/oracle/graal/compiler/test/CheckGraalInvariants.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.graal.compiler.test/src/com/oracle/graal/compiler/test/CheckGraalInvariants.java Mon Apr 20 22:42:18 2015 +0200 @@ -42,7 +42,7 @@ import com.oracle.graal.debug.*; import com.oracle.graal.graph.*; import com.oracle.graal.graphbuilderconf.*; -import com.oracle.graal.graphbuilderconf.GraphBuilderConfiguration.*; +import com.oracle.graal.graphbuilderconf.GraphBuilderConfiguration.Plugins; import com.oracle.graal.java.*; import com.oracle.graal.nodeinfo.*; import com.oracle.graal.nodes.*; @@ -57,9 +57,8 @@ import com.oracle.graal.test.*; /** - * Checks that all classes in graal.jar (which must be on the class path) comply with global - * invariants such as using {@link Object#equals(Object)} to compare certain types instead of - * identity comparisons. + * Checks that all classes in graal*.jar from the boot classpath comply with global invariants such + * as using {@link Object#equals(Object)} to compare certain types instead of identity comparisons. */ public class CheckGraalInvariants extends GraalTest { @@ -82,31 +81,26 @@ bootclasspath.split(File.pathSeparator); final List classNames = new ArrayList<>(); - for (String jarName : new String[]{"graal.jar", "graal-truffle.jar"}) { - - String jar = null; - for (String e : bootclasspath.split(File.pathSeparator)) { - if (e.endsWith(jarName)) { - jar = e; - break; + for (String path : bootclasspath.split(File.pathSeparator)) { + File file = new File(path); + String fileName = file.getName(); + if (fileName.startsWith("graal") && fileName.endsWith(".jar")) { + try { + final ZipFile zipFile = new ZipFile(file); + for (final Enumeration entry = zipFile.entries(); entry.hasMoreElements();) { + final ZipEntry zipEntry = entry.nextElement(); + String name = zipEntry.getName(); + if (name.endsWith(".class")) { + String className = name.substring(0, name.length() - ".class".length()).replace('/', '.'); + classNames.add(className); + } + } + } catch (IOException ex) { + Assert.fail(ex.toString()); } } - Assert.assertNotNull("Could not find graal.jar on boot class path: " + bootclasspath, jar); - - try { - final ZipFile zipFile = new ZipFile(new File(jar)); - for (final Enumeration e = zipFile.entries(); e.hasMoreElements();) { - final ZipEntry zipEntry = e.nextElement(); - String name = zipEntry.getName(); - if (name.endsWith(".class")) { - String className = name.substring(0, name.length() - ".class".length()).replace('/', '.'); - classNames.add(className); - } - } - } catch (IOException e) { - Assert.fail(e.toString()); - } } + Assert.assertFalse("Could not find graal jars on boot class path: " + bootclasspath, classNames.isEmpty()); // Allows a subset of methods to be checked through use of a system property String property = System.getProperty(CheckGraalInvariants.class.getName() + ".filters"); diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.graal.graph/src/com/oracle/graal/graph/Graph.java --- a/graal/com.oracle.graal.graph/src/com/oracle/graal/graph/Graph.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.graal.graph/src/com/oracle/graal/graph/Graph.java Mon Apr 20 22:42:18 2015 +0200 @@ -725,11 +725,68 @@ return getNodes(type).iterator().hasNext(); } - Node getStartNode(int iterableId) { - Node start = iterableNodesFirst.size() <= iterableId ? null : iterableNodesFirst.get(iterableId); + /** + * @param iterableId + * @return the first live Node with a matching iterableId + */ + Node getIterableNodeStart(int iterableId) { + if (iterableNodesFirst.size() <= iterableId) { + return null; + } + Node start = iterableNodesFirst.get(iterableId); + if (start == null || !start.isDeleted()) { + return start; + } + return findFirstLiveIterable(iterableId, start); + } + + private Node findFirstLiveIterable(int iterableId, Node node) { + assert iterableNodesFirst.get(iterableId) == node; + Node start = node; + while (start != null && start.isDeleted()) { + start = start.typeCacheNext; + } + iterableNodesFirst.set(iterableId, start); + if (start == null) { + iterableNodesLast.set(iterableId, start); + } return start; } + /** + * @param node + * @return return the first live Node with a matching iterableId starting from {@code node} + */ + Node getIterableNodeNext(Node node) { + if (node == null) { + return null; + } + Node n = node; + if (n == null || !n.isDeleted()) { + return n; + } + + return findNextLiveiterable(node); + } + + private Node findNextLiveiterable(Node start) { + Node n = start; + while (n != null && n.isDeleted()) { + n = n.typeCacheNext; + } + if (n == null) { + // Only dead nodes after this one + start.typeCacheNext = null; + int nodeClassId = start.getNodeClass().iterableId(); + assert nodeClassId != Node.NOT_ITERABLE; + iterableNodesLast.set(nodeClassId, start); + } else { + // Everything in between is dead + start.typeCacheNext = n; + } + return n; + } + public NodeBitMap createNodeBitMap() { return new NodeBitMap(this); } diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.graal.graph/src/com/oracle/graal/graph/TypedGraphNodeIterator.java --- a/graal/com.oracle.graal.graph/src/com/oracle/graal/graph/TypedGraphNodeIterator.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.graal.graph/src/com/oracle/graal/graph/TypedGraphNodeIterator.java Mon Apr 20 22:42:18 2015 +0200 @@ -47,7 +47,7 @@ forward(); } else { Node c = current(); - Node afterDeleted = skipDeleted(c); + Node afterDeleted = graph.getIterableNodeNext(c); if (afterDeleted == null) { needsForward = true; } else if (c != afterDeleted) { @@ -60,25 +60,16 @@ return current(); } - private static Node skipDeleted(Node node) { - Node n = node; - while (n != null && n.isDeleted()) { - n = n.typeCacheNext; - } - return n; - } - private void forward() { needsForward = false; int startIdx = currentIdIndex; while (true) { Node next; if (current() == Graph.PLACE_HOLDER) { - next = graph.getStartNode(ids[currentIdIndex]); + next = graph.getIterableNodeStart(ids[currentIdIndex]); } else { - next = current().typeCacheNext; + next = graph.getIterableNodeNext(current().typeCacheNext); } - next = skipDeleted(next); if (next == null) { currentIdIndex++; if (currentIdIndex >= ids.length) { diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.graal.hotspot.loader/src/com/oracle/graal/hotspot/loader/Factory.java --- a/graal/com.oracle.graal.hotspot.loader/src/com/oracle/graal/hotspot/loader/Factory.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.graal.hotspot.loader/src/com/oracle/graal/hotspot/loader/Factory.java Mon Apr 20 22:42:18 2015 +0200 @@ -24,10 +24,11 @@ import java.io.*; import java.net.*; +import java.util.*; /** * Utility to create and register a separate class loader for loading Graal classes (i.e., those in - * {@code graal.jar} and {@code graal-truffle.jar}). + * found in lib/graal/graal*.jar). */ public class Factory { @@ -47,32 +48,40 @@ } /** - * Creates a new class loader for loading classes in {@code graal.jar} and - * {@code graal-truffle.jar}. + * Creates a new class loader for loading graal classes. */ private static ClassLoader newClassLoader() { - URL[] urls = {getGraalJarUrl("graal"), getGraalJarUrl("graal-truffle")}; + URL[] urls = getGraalJarsUrls(); ClassLoader parent = null; return URLClassLoader.newInstance(urls, parent); } /** - * Gets the URL for {@code base.jar}. + * Gets the URLs for lib/graal/graal*.jar. */ - private static URL getGraalJarUrl(String base) { - File file = new File(System.getProperty("java.home")); - for (String name : new String[]{"lib", base + ".jar"}) { - file = new File(file, name); + private static URL[] getGraalJarsUrls() { + File javaHome = new File(System.getProperty("java.home")); + File lib = new File(javaHome, "lib"); + File graal = new File(lib, "graal"); + if (!graal.exists()) { + throw new InternalError(graal + " does not exist"); } - if (!file.exists()) { - throw new InternalError(file + " does not exist"); + List urls = new ArrayList<>(); + for (String fileName : graal.list()) { + if (fileName.startsWith("graal") && fileName.endsWith(".jar")) { + File file = new File(graal, fileName); + if (file.isDirectory()) { + continue; + } + try { + urls.add(file.toURI().toURL()); + } catch (MalformedURLException e) { + throw new InternalError(e); + } + } } - try { - return file.toURI().toURL(); - } catch (MalformedURLException e) { - throw new InternalError(e); - } + return urls.toArray(new URL[urls.size()]); } } diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.graal.hotspot.sourcegen/src/com/oracle/graal/hotspot/sourcegen/GenGraalRuntimeInlineHpp.java --- a/graal/com.oracle.graal.hotspot.sourcegen/src/com/oracle/graal/hotspot/sourcegen/GenGraalRuntimeInlineHpp.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.graal.hotspot.sourcegen/src/com/oracle/graal/hotspot/sourcegen/GenGraalRuntimeInlineHpp.java Mon Apr 20 22:42:18 2015 +0200 @@ -30,7 +30,6 @@ import com.oracle.graal.api.runtime.*; import com.oracle.graal.compiler.common.*; -import com.oracle.graal.hotspot.*; import com.oracle.graal.options.*; /** @@ -38,7 +37,6 @@ * generated code is comprised of: *
    *
  • {@code -G} command line option parsing {@linkplain #genSetOption(PrintStream) helper}
  • - *
  • {@link Service} loading {@linkplain #genGetServiceImpls(PrintStream) helper}
  • *
* * The purpose of the generated code is to avoid executing Graal related Java code as much as @@ -93,7 +91,6 @@ public static void main(String[] args) { PrintStream out = System.out; try { - genGetServiceImpls(out); genSetOption(out); } catch (Throwable t) { t.printStackTrace(out); @@ -102,65 +99,6 @@ } /** - * Generates code for {@code GraalRuntime::get_service_impls()}. - */ - private static void genGetServiceImpls(PrintStream out) throws Exception { - final List> services = new ArrayList<>(); - for (ZipEntry zipEntry : graalJars) { - String name = zipEntry.getName(); - if (name.startsWith("META-INF/services/")) { - String serviceName = name.substring("META-INF/services/".length()); - Class c = Class.forName(serviceName); - if (Service.class.isAssignableFrom(c)) { - @SuppressWarnings("unchecked") - Class sc = (Class) c; - - services.add(sc); - } - } - } - - Set lengths = new TreeSet<>(); - for (Class service : services) { - lengths.add(toInternalName(service).length()); - } - - out.println("Handle GraalRuntime::get_service_impls(KlassHandle serviceKlass, TRAPS) {"); - out.println(" switch (serviceKlass->name()->utf8_length()) {"); - for (int len : lengths) { - boolean printedCase = false; - for (Class service : services) { - String serviceName = toInternalName(service); - if (len == serviceName.length()) { - if (!printedCase) { - printedCase = true; - out.println(" case " + len + ":"); - } - out.printf(" if (serviceKlass->name()->equals(\"%s\", %d)) {%n", serviceName, serviceName.length()); - List> impls = new ArrayList<>(); - for (Object impl : ServiceLoader.load(service)) { - impls.add(impl.getClass()); - } - - out.printf(" objArrayOop servicesOop = oopFactory::new_objArray(serviceKlass(), %d, CHECK_NH);%n", impls.size()); - out.println(" objArrayHandle services(THREAD, servicesOop);"); - for (int i = 0; i < impls.size(); i++) { - String name = toInternalName(impls.get(i)); - out.printf(" %sservice = create_Service(\"%s\", CHECK_NH);%n", (i == 0 ? "Handle " : ""), name); - out.printf(" services->obj_at_put(%d, service());%n", i); - } - out.println(" return services;"); - out.println(" }"); - } - } - - } - out.println(" }"); - out.println(" return Handle();"); - out.println("}"); - } - - /** * Generates code for {@code GraalRuntime::set_option()} and * {@code GraalRuntime::set_option_bool()}. */ diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.graal.hotspot.test/src/com/oracle/graal/hotspot/test/ArrayCopyIntrinsificationTest.java --- a/graal/com.oracle.graal.hotspot.test/src/com/oracle/graal/hotspot/test/ArrayCopyIntrinsificationTest.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.graal.hotspot.test/src/com/oracle/graal/hotspot/test/ArrayCopyIntrinsificationTest.java Mon Apr 20 22:42:18 2015 +0200 @@ -251,4 +251,25 @@ return dst; } + /** + * Test case derived from assertion while compiling com.google.common.collect.ArrayTable(ArrayTable other). + */ + @Ignore + @Test + public void testCopyRows() { + mustIntrinsify = false; + Object[][] rows = {{"a1", "a2", "a3", "a4"}, {"b1", "b2", "b3", "b4"}, {"c1", "c2", "c3", "c4"}}; + test("copyRows", rows, 4, new Integer(rows.length)); + mustIntrinsify = true; + } + + public static Object[][] copyRows(Object[][] rows, int rowSize, Integer rowCount) { + Object[][] copy = new Object[rows.length][rowSize]; + for (int i = 0; i < rowCount.intValue(); i++) { + System.arraycopy(rows[i], 0, copy[i], 0, rows[i].length); + } + return copy; + } } diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/FrameState.java --- a/graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/FrameState.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/FrameState.java Mon Apr 20 22:42:18 2015 +0200 @@ -293,6 +293,9 @@ * is that a stateAfter is being transformed into a stateDuring, so the stack depth may change. */ private boolean checkStackDepth(int oldBci, int oldStackSize, boolean oldDuringCall, boolean oldRethrowException, int newBci, int newStackSize, boolean newDuringCall, boolean newRethrowException) { + if (BytecodeFrame.isSyntheticBci(oldBci)) { + return true; + } /* * It would be nice to have a complete check of the shape of the FrameState based on a * dataflow of the bytecodes but for now just check for obvious expression stack depth diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/GuardProxyNode.java --- a/graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/GuardProxyNode.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/GuardProxyNode.java Mon Apr 20 22:42:18 2015 +0200 @@ -24,12 +24,13 @@ import com.oracle.graal.compiler.common.type.*; import com.oracle.graal.graph.*; +import com.oracle.graal.graph.spi.*; import com.oracle.graal.nodeinfo.*; import com.oracle.graal.nodes.extended.*; import com.oracle.graal.nodes.spi.*; @NodeInfo(allowedUsageTypes = {InputType.Guard}, nameTemplate = "Proxy({i#value})") -public final class GuardProxyNode extends ProxyNode implements GuardingNode, Proxy, LIRLowerable { +public final class GuardProxyNode extends ProxyNode implements GuardingNode, Proxy, LIRLowerable, Canonicalizable { public static final NodeClass TYPE = NodeClass.create(GuardProxyNode.class); @OptionalInput(InputType.Guard) GuardingNode value; @@ -56,4 +57,11 @@ public Node getOriginalNode() { return (value == null ? null : value.asNode()); } + + public Node canonical(CanonicalizerTool tool) { + if (value == null) { + return null; + } + return this; + } } diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/ProxyNode.java --- a/graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/ProxyNode.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/ProxyNode.java Mon Apr 20 22:42:18 2015 +0200 @@ -53,8 +53,6 @@ @Override public boolean verify() { - assert value() != null; - assert proxyPoint != null; assert !(value() instanceof ProxyNode) || ((ProxyNode) value()).proxyPoint != proxyPoint; return super.verify(); } diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.graal.phases.common/src/com/oracle/graal/phases/common/DominatorConditionalEliminationPhase.java --- a/graal/com.oracle.graal.phases.common/src/com/oracle/graal/phases/common/DominatorConditionalEliminationPhase.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.graal.phases.common/src/com/oracle/graal/phases/common/DominatorConditionalEliminationPhase.java Mon Apr 20 22:42:18 2015 +0200 @@ -208,18 +208,26 @@ } private void processCheckCast(CheckCastNode node) { - tryProofCondition(node, (guard, result) -> { - if (result) { - PiNode piNode = node.graph().unique(new PiNode(node.object(), node.stamp(), guard)); - node.replaceAtUsages(piNode); - GraphUtil.unlinkFixedNode(node); - node.safeDelete(); - } else { - DeoptimizeNode deopt = node.graph().add(new DeoptimizeNode(InvalidateReprofile, UnreachedCode)); - node.replaceAtPredecessor(deopt); - GraphUtil.killCFG(node); + for (InfoElement infoElement : getInfoElements(node.object())) { + TriState result = node.tryFold(infoElement.getStamp()); + if (result.isKnown()) { + if (rewireGuards(infoElement.getGuard(), result.toBoolean(), (guard, checkCastResult) -> { + if (checkCastResult) { + PiNode piNode = node.graph().unique(new PiNode(node.object(), node.stamp(), guard)); + node.replaceAtUsages(piNode); + GraphUtil.unlinkFixedNode(node); + node.safeDelete(); + } else { + DeoptimizeNode deopt = node.graph().add(new DeoptimizeNode(InvalidateReprofile, UnreachedCode)); + node.replaceAtPredecessor(deopt); + GraphUtil.killCFG(node); + } + return true; + })) { + return; + } } - }); + } } private void processIf(IfNode node, List undoOperations) { @@ -232,6 +240,7 @@ if (survivingSuccessor instanceof BeginNode) { undoOperations.add(() -> ((BeginNode) survivingSuccessor).trySimplify()); } + return true; }); } @@ -253,8 +262,8 @@ Stamp newStampY = binaryOpLogicNode.getSucceedingStampForY(negated); registerNewStamp(y, newStampY, guard, undoOperations); } - registerCondition(condition, negated, guard, undoOperations); } + registerCondition(condition, negated, guard, undoOperations); } private void registerCondition(LogicNode condition, boolean negated, ValueNode guard, List undoOperations) { @@ -271,12 +280,11 @@ } } - private boolean rewireGuards(ValueNode guard, boolean result, BiConsumer rewireGuardFunction) { + private boolean rewireGuards(ValueNode guard, boolean result, GuardRewirer rewireGuardFunction) { assert guard instanceof GuardingNode; metricStampsFound.increment(); ValueNode proxiedGuard = proxyGuard(guard); - rewireGuardFunction.accept(proxiedGuard, result); - return true; + return rewireGuardFunction.rewire(proxiedGuard, result); } private ValueNode proxyGuard(ValueNode guard) { @@ -301,7 +309,25 @@ return proxiedGuard; } - private boolean tryProofCondition(Node node, BiConsumer rewireGuardFunction) { + @FunctionalInterface + private interface GuardRewirer { + /** + * Called if the condition could be proven to have a constant value ({@code result}) + * under {@code guard}. + * + * Return whether a transformation could be applied. + */ + boolean rewire(ValueNode guard, boolean result); + } + + private boolean tryProofCondition(LogicNode node, GuardRewirer rewireGuardFunction) { + for (InfoElement infoElement : getInfoElements(node)) { + Stamp stamp = infoElement.getStamp(); + JavaConstant constant = (JavaConstant) stamp.asConstant(); + if (constant != null) { + return rewireGuards(infoElement.getGuard(), constant.asBoolean(), rewireGuardFunction); + } + } if (node instanceof UnaryOpLogicNode) { UnaryOpLogicNode unaryLogicNode = (UnaryOpLogicNode) node; ValueNode value = unaryLogicNode.getValue(); @@ -337,25 +363,18 @@ return rewireGuards(infoElement.getGuard(), result.toBoolean(), rewireGuardFunction); } } - } else if (node instanceof CheckCastNode) { - CheckCastNode checkCastNode = (CheckCastNode) node; - for (InfoElement infoElement : getInfoElements(checkCastNode.object())) { - TriState result = checkCastNode.tryFold(infoElement.getStamp()); - if (result.isKnown()) { - return rewireGuards(infoElement.getGuard(), result.toBoolean(), rewireGuardFunction); - } - } } else if (node instanceof ShortCircuitOrNode) { final ShortCircuitOrNode shortCircuitOrNode = (ShortCircuitOrNode) node; if (this.loopExits.isEmpty()) { - tryProofCondition(shortCircuitOrNode.getX(), (guard, result) -> { + return tryProofCondition(shortCircuitOrNode.getX(), (guard, result) -> { if (result == !shortCircuitOrNode.isXNegated()) { - rewireGuards(guard, result, rewireGuardFunction); + return rewireGuards(guard, result, rewireGuardFunction); } else { - tryProofCondition(shortCircuitOrNode.getY(), (innerGuard, innerResult) -> { + return tryProofCondition(shortCircuitOrNode.getY(), (innerGuard, innerResult) -> { if (innerGuard == guard) { - rewireGuards(guard, shortCircuitOrNode.isYNegated() ? !innerResult : innerResult, rewireGuardFunction); + return rewireGuards(guard, shortCircuitOrNode.isYNegated() ? !innerResult : innerResult, rewireGuardFunction); } + return false; }); } }); @@ -391,6 +410,7 @@ node.replaceAtUsages(valueAnchor); node.graph().replaceFixedWithFixed(node, valueAnchor); } + return true; }); } @@ -405,6 +425,7 @@ beginNode.setNext(deopt); GraphUtil.killCFG(next); } + return true; })) { registerNewCondition(node.condition(), node.isNegated(), node, undoOperations); } @@ -422,6 +443,7 @@ node.replaceAtPredecessor(deopt); GraphUtil.killCFG(node); } + return true; })) { registerNewCondition(node.condition(), node.isNegated(), node, undoOperations); } diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.graal.replacements/src/com/oracle/graal/replacements/CollapseFrameForSingleSideEffectPhase.java --- a/graal/com.oracle.graal.replacements/src/com/oracle/graal/replacements/CollapseFrameForSingleSideEffectPhase.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.graal.replacements/src/com/oracle/graal/replacements/CollapseFrameForSingleSideEffectPhase.java Mon Apr 20 22:42:18 2015 +0200 @@ -135,6 +135,8 @@ state = state.addSideEffect(stateSplit); } else if (currentState.invalid) { setStateAfter(node.graph(), stateSplit, INVALID_FRAMESTATE_BCI, false); + } else if (stateSplit instanceof StartNode) { + setStateAfter(node.graph(), stateSplit, BEFORE_BCI, false); } else { stateSplit.setStateAfter(null); if (frameState.hasNoUsages()) { @@ -219,13 +221,13 @@ * * @param graph the graph context * @param node the node whose frame state is updated - * @param bci {@link BytecodeFrame#AFTER_BCI}, {@link BytecodeFrame#AFTER_EXCEPTION_BCI} or + * @param bci {@link BytecodeFrame#BEFORE_BCI}, {@link BytecodeFrame#AFTER_EXCEPTION_BCI} or * {@link BytecodeFrame#INVALID_FRAMESTATE_BCI} * @param replaceOnly only perform the update if the node currently has a non-null frame * state */ private static void setStateAfter(StructuredGraph graph, StateSplit node, int bci, boolean replaceOnly) { - assert bci == AFTER_BCI || bci == AFTER_EXCEPTION_BCI || bci == INVALID_FRAMESTATE_BCI; + assert (bci == BEFORE_BCI && node instanceof StartNode) || bci == AFTER_BCI || bci == AFTER_EXCEPTION_BCI || bci == INVALID_FRAMESTATE_BCI; FrameState currentStateAfter = node.stateAfter(); if (currentStateAfter != null || !replaceOnly) { node.setStateAfter(graph.add(new FrameState(bci))); diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.graal.truffle/src/com/oracle/graal/truffle/PartialEvaluator.java --- a/graal/com.oracle.graal.truffle/src/com/oracle/graal/truffle/PartialEvaluator.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.graal.truffle/src/com/oracle/graal/truffle/PartialEvaluator.java Mon Apr 20 22:42:18 2015 +0200 @@ -69,7 +69,7 @@ public class PartialEvaluator { @Option(help = "New partial evaluation on Graal graphs", type = OptionType.Expert)// - public static final StableOptionValue GraphPE = new StableOptionValue<>(false); + public static final StableOptionValue GraphPE = new StableOptionValue<>(true); private final Providers providers; private final Architecture architecture; diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.truffle.api.object/src/com/oracle/truffle/api/object/Property.java --- a/graal/com.oracle.truffle.api.object/src/com/oracle/truffle/api/object/Property.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.truffle.api.object/src/com/oracle/truffle/api/object/Property.java Mon Apr 20 22:42:18 2015 +0200 @@ -25,10 +25,8 @@ package com.oracle.truffle.api.object; /** - * Property objects represent the mapping between low-level stores and high-level data. The simplest - * Property could be nothing more than a map of one index to one property's value, but abstracting - * the interface allows for getter/setter methods, type-checked properties, and other such - * specialized and language-specific behavior. ECMAScript[8.6.1] + * Property objects represent the mapping between property identifiers (keys) and storage locations. + * Optionally, properties may have metadata attached to them. */ public abstract class Property { protected Property() { diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.truffle.object/src/com/oracle/truffle/object/PropertyImpl.java --- a/graal/com.oracle.truffle.object/src/com/oracle/truffle/object/PropertyImpl.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.truffle.object/src/com/oracle/truffle/object/PropertyImpl.java Mon Apr 20 22:42:18 2015 +0200 @@ -28,10 +28,8 @@ import com.oracle.truffle.object.Locations.*; /** - * Property objects represent the mapping between low-level stores and high-level data. The simplest - * Property could be nothing more than a map of one index to one property's value, but abstracting - * the interface allows for getter/setter methods, type-checked properties, and other such - * specialized and language-specific behavior. ECMAScript[8.6.1] + * Property objects represent the mapping between property identifiers (keys) and storage locations. + * Optionally, properties may have metadata attached to them. */ public class PropertyImpl extends Property { private final Object key; diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.truffle.object/src/com/oracle/truffle/object/PropertyMap.java --- a/graal/com.oracle.truffle.object/src/com/oracle/truffle/object/PropertyMap.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.truffle.object/src/com/oracle/truffle/object/PropertyMap.java Mon Apr 20 22:42:18 2015 +0200 @@ -296,7 +296,7 @@ } public PropertyMap removeCopy(Property value) { - LinkedList shelve = new LinkedList<>(); + Deque shelve = new ArrayDeque<>(); PropertyMap current = this; while (!current.isEmpty()) { if (current.getLastProperty().equals(value)) { @@ -314,7 +314,7 @@ } public PropertyMap replaceCopy(Property oldValue, Property newValue) { - LinkedList shelve = new LinkedList<>(); + Deque shelve = new ArrayDeque<>(); PropertyMap current = this; while (!current.isEmpty()) { if (current.getLastProperty().equals(oldValue)) { diff -r 41f99f9a8f63 -r eae62344f72c graal/com.oracle.truffle.object/src/com/oracle/truffle/object/ShapeImpl.java --- a/graal/com.oracle.truffle.object/src/com/oracle/truffle/object/ShapeImpl.java Mon Apr 20 22:42:05 2015 +0200 +++ b/graal/com.oracle.truffle.object/src/com/oracle/truffle/object/ShapeImpl.java Mon Apr 20 22:42:18 2015 +0200 @@ -276,14 +276,7 @@ @Override @TruffleBoundary public Property getProperty(Object key) { - PropertyMap current = this.propertyMap; - while (current.getLastProperty() != null) { - if (current.getLastProperty().getKey().equals(key)) { - return current.getLastProperty(); - } - current = current.getParentMap(); - } - return null; + return propertyMap.get(key); } protected final void addDirectTransition(Transition transition, ShapeImpl next) { diff -r 41f99f9a8f63 -r eae62344f72c make/defs.make --- a/make/defs.make Mon Apr 20 22:42:05 2015 +0200 +++ b/make/defs.make Mon Apr 20 22:42:18 2015 +0200 @@ -341,6 +341,7 @@ EXPORT_JRE_BIN_DIR = $(EXPORT_JRE_DIR)/bin EXPORT_JRE_LIB_DIR = $(EXPORT_JRE_DIR)/lib EXPORT_JRE_LIB_EXT_DIR = $(EXPORT_JRE_LIB_DIR)/ext +EXPORT_JRE_LIB_GRAAL_DIR = $(EXPORT_JRE_LIB_DIR)/graal EXPORT_JRE_LIB_ARCH_DIR = $(EXPORT_JRE_LIB_DIR)/$(LIBARCH) # non-universal macosx builds need to appear universal @@ -356,8 +357,8 @@ EXPORT_LIST += $(EXPORT_INCLUDE_DIR)/jni.h EXPORT_LIST += $(EXPORT_INCLUDE_DIR)/$(JDK_INCLUDE_SUBDIR)/jni_md.h EXPORT_LIST += $(EXPORT_INCLUDE_DIR)/jmm.h -EXPORT_LIST += $(EXPORT_JRE_LIB_DIR)/graal.jar -EXPORT_LIST += $(EXPORT_JRE_LIB_DIR)/graal-truffle.jar +EXPORT_LIST += $(EXPORT_JRE_LIB_GRAAL_DIR)/graal.jar +EXPORT_LIST += $(EXPORT_JRE_LIB_GRAAL_DIR)/graal-truffle.jar EXPORT_LIST += $(EXPORT_JRE_LIB_DIR)/graal-loader.jar EXPORT_LIST += $(EXPORT_JRE_LIB_DIR)/truffle.jar diff -r 41f99f9a8f63 -r eae62344f72c mx/mx_graal.py --- a/mx/mx_graal.py Mon Apr 20 22:42:05 2015 +0200 +++ b/mx/mx_graal.py Mon Apr 20 22:42:18 2015 +0200 @@ -87,15 +87,16 @@ _untilVersion = None class JDKDeployedDist: - def __init__(self, name, isExtension): + def __init__(self, name, isExtension=False, isGraalClassLoader=False): self.name = name self.isExtension = isExtension + self.isGraalClassLoader = isGraalClassLoader _jdkDeployedDists = [ - JDKDeployedDist('TRUFFLE', isExtension=False), - JDKDeployedDist('GRAAL_LOADER', isExtension=False), - JDKDeployedDist('GRAAL', isExtension=False), - JDKDeployedDist('GRAAL_TRUFFLE', isExtension=False) + JDKDeployedDist('TRUFFLE'), + JDKDeployedDist('GRAAL_LOADER'), + JDKDeployedDist('GRAAL', isGraalClassLoader=True), + JDKDeployedDist('GRAAL_TRUFFLE', isGraalClassLoader=True) ] JDK_UNIX_PERMISSIONS_DIR = 0755 @@ -483,7 +484,7 @@ for jdkDist in _jdkDeployedDists: dist = mx.distribution(jdkDist.name) if exists(dist.path): - _installDistInJdks(dist, jdkDist.isExtension) + _installDistInJdks(jdkDist) if vmToCheck is not None: jvmCfg = _vmCfgInJdk(jdk) @@ -593,14 +594,13 @@ shutil.move(tmp, dstLib) os.chmod(dstLib, permissions) -def _installDistInJdksExt(dist): - _installDistInJdks(dist, True) - -def _installDistInJdks(dist, ext=False): +def _installDistInJdks(deployableDist): """ Installs the jar(s) for a given Distribution into all existing Graal JDKs """ + dist = mx.distribution(deployableDist.name) + if dist.name == 'GRAAL_TRUFFLE': # The content in graalRuntime.inline.hpp is generated from Graal # classes that implement com.oracle.graal.api.runtime.Service @@ -614,12 +614,34 @@ if exists(jdks): for e in os.listdir(jdks): jreLibDir = join(jdks, e, 'jre', 'lib') - if ext: - jreLibDir = join(jreLibDir, 'ext') if exists(jreLibDir): - _copyToJdk(dist.path, jreLibDir) + if deployableDist.isExtension: + targetDir = join(jreLibDir, 'ext') + elif deployableDist.isGraalClassLoader: + targetDir = join(jreLibDir, 'graal') + else: + targetDir = jreLibDir + if not exists(targetDir): + os.makedirs(targetDir) + _copyToJdk(dist.path, targetDir) if dist.sourcesPath: _copyToJdk(dist.sourcesPath, join(jdks, e)) + # deploy service files + if deployableDist.isGraalClassLoader: + # deploy services files + jreGraalServicesDir = join(jreLibDir, 'graal', 'services') + if not exists(jreGraalServicesDir): + os.makedirs(jreGraalServicesDir) + with zipfile.ZipFile(dist.path) as zf: + for member in zf.namelist(): + if not member.startswith('META-INF/services'): + continue + serviceName = basename(member) + # we don't handle directories + assert serviceName + target = join(jreGraalServicesDir, serviceName) + with zf.open(member) as serviceFile, open(target, "w+") as targetFile: + shutil.copyfileobj(serviceFile, targetFile) # run a command in the windows SDK Debug Shell def _runInDebugShell(cmd, workingDir, logFile=None, findInOutput=None, respondTo=None): @@ -785,6 +807,8 @@ defLine = 'EXPORT_LIST += $(EXPORT_JRE_LIB_DIR)/' + basename(dist.path) if jdkDist.isExtension: defLine = 'EXPORT_LIST += $(EXPORT_JRE_LIB_EXT_DIR)/' + basename(dist.path) + elif jdkDist.isGraalClassLoader: + defLine = 'EXPORT_LIST += $(EXPORT_JRE_LIB_GRAAL_DIR)/' + basename(dist.path) else: defLine = 'EXPORT_LIST += $(EXPORT_JRE_LIB_DIR)/' + basename(dist.path) if defLine not in defs: @@ -1388,6 +1412,7 @@ parser = ArgumentParser(prog='mx buildvms') parser.add_argument('--vms', help='a comma separated list of VMs to build (default: ' + vmsDefault + ')', metavar='', default=vmsDefault) parser.add_argument('--builds', help='a comma separated list of build types (default: ' + vmbuildsDefault + ')', metavar='', default=vmbuildsDefault) + parser.add_argument('--check-distributions', action='store_true', dest='check_distributions', help='check built distributions for overlap') parser.add_argument('-n', '--no-check', action='store_true', help='omit running "java -version" after each build') parser.add_argument('-c', '--console', action='store_true', help='send build output to console instead of log file') @@ -1396,6 +1421,7 @@ builds = args.builds.split(',') allStart = time.time() + check_dists_args = ['--check-distributions'] if args.check_distributions else [] for v in vms: if not isVMSupported(v): mx.log('The ' + v + ' VM is not supported on this platform - skipping') @@ -1411,14 +1437,14 @@ mx.log('BEGIN: ' + v + '-' + vmbuild + '\t(see: ' + logFile + ')') verbose = ['-v'] if mx._opts.verbose else [] # Run as subprocess so that output can be directed to a file - cmd = [sys.executable, '-u', join('mxtool', 'mx.py')] + verbose + ['--vm', v, '--vmbuild', vmbuild, 'build'] + cmd = [sys.executable, '-u', join('mxtool', 'mx.py')] + verbose + ['--vm', v, '--vmbuild', vmbuild, 'build'] + check_dists_args mx.logv("executing command: " + str(cmd)) subprocess.check_call(cmd, cwd=_graal_home, stdout=log, stderr=subprocess.STDOUT) duration = datetime.timedelta(seconds=time.time() - start) mx.log('END: ' + v + '-' + vmbuild + '\t[' + str(duration) + ']') else: with VM(v, vmbuild): - build([]) + build(check_dists_args) if not args.no_check: vmargs = ['-version'] if v == 'graal': @@ -1501,7 +1527,7 @@ def _basic_gate_body(args, tasks): # Build server-hosted-graal now so we can run the unit tests with Task('BuildHotSpotGraalHosted: product', tasks) as t: - if t: buildvms(['--vms', 'server', '--builds', 'product']) + if t: buildvms(['--vms', 'server', '--builds', 'product', '--check-distributions']) # Run unit tests on server-hosted-graal with VM('server', 'product'): @@ -1515,7 +1541,7 @@ # Build the other VM flavors with Task('BuildHotSpotGraalOthers: fastdebug,product', tasks) as t: - if t: buildvms(['--vms', 'graal,server', '--builds', 'fastdebug,product']) + if t: buildvms(['--vms', 'graal,server', '--builds', 'fastdebug,product', '--check-distributions']) with VM('graal', 'fastdebug'): with Task('BootstrapWithSystemAssertions:fastdebug', tasks) as t: @@ -2556,7 +2582,9 @@ _vm_prefix = opts.vm_prefix for jdkDist in _jdkDeployedDists: - if jdkDist.isExtension: - mx.distribution(jdkDist.name).add_update_listener(_installDistInJdksExt) - else: - mx.distribution(jdkDist.name).add_update_listener(_installDistInJdks) + def _close(jdkDeployable): + def _install(dist): + assert dist.name == jdkDeployable.name, dist.name + "!=" + jdkDeployable.name + _installDistInJdks(jdkDeployable) + return _install + mx.distribution(jdkDist.name).add_update_listener(_close(jdkDist)) diff -r 41f99f9a8f63 -r eae62344f72c mxtool/mx.py --- a/mxtool/mx.py Mon Apr 20 22:42:05 2015 +0200 +++ b/mxtool/mx.py Mon Apr 20 22:42:18 2015 +0200 @@ -101,7 +101,7 @@ A distribution is a jar or zip file containing the output from one or more Java projects. """ class Distribution: - def __init__(self, suite, name, path, sourcesPath, deps, mainClass, excludedDependencies, distDependencies, javaCompliance): + def __init__(self, suite, name, path, sourcesPath, deps, mainClass, excludedDependencies, distDependencies, javaCompliance, isProcessorDistribution=False): self.suite = suite self.name = name self.path = path.replace('/', os.sep) @@ -113,6 +113,7 @@ self.excludedDependencies = excludedDependencies self.distDependencies = distDependencies self.javaCompliance = JavaCompliance(javaCompliance) if javaCompliance else None + self.isProcessorDistribution = isProcessorDistribution def sorted_deps(self, includeLibs=False, transitive=False): deps = [] @@ -1090,7 +1091,7 @@ exclDeps = [] distDeps = [] javaCompliance = None - d = Distribution(self, dname, path, sourcesPath, deps, mainClass, exclDeps, distDeps, javaCompliance) + d = Distribution(self, dname, path, sourcesPath, deps, mainClass, exclDeps, distDeps, javaCompliance, True) d.subDir = os.path.relpath(os.path.dirname(p.dir), self.dir) self.dists.append(d) p.definedAnnotationProcessors = annotationProcessors @@ -2563,6 +2564,7 @@ parser.add_argument('-p', action='store_true', dest='parallelize', help='parallelizes Java compilation if possible') parser.add_argument('--source', dest='compliance', help='Java compliance level for projects without an explicit one') parser.add_argument('--Wapi', action='store_true', dest='warnAPI', help='show warnings about using internal APIs') + parser.add_argument('--check-distributions', action='store_true', dest='check_distributions', help='check built distributions for overlap') parser.add_argument('--projects', action='store', help='comma separated projects to build (omit to build all projects)') parser.add_argument('--only', action='store', help='comma separated projects to build, without checking their dependencies (omit to build all projects)') parser.add_argument('--no-java', action='store_false', dest='java', help='do not build Java projects') @@ -2790,9 +2792,16 @@ abort('{0} Java compilation tasks failed'.format(len(failed))) if args.java: + files = [] for dist in sorted_dists(): if dist not in updatedAnnotationProcessorDists: archive(['@' + dist.name]) + if args.check_distributions and not dist.isProcessorDistribution: + with zipfile.ZipFile(dist.path, 'r') as zf: + files.extend([member for member in zf.namelist() if not member.startswith('META-INF/services')]) + dups = set([x for x in files if files.count(x) > 1]) + if len(dups) > 0: + abort('Distributions overlap! duplicates: ' + str(dups)) if suppliedParser: return args diff -r 41f99f9a8f63 -r eae62344f72c src/share/tools/IdealGraphVisualizer/View/src/com/sun/hotspot/igv/view/widgets/FigureWidget.java --- a/src/share/tools/IdealGraphVisualizer/View/src/com/sun/hotspot/igv/view/widgets/FigureWidget.java Mon Apr 20 22:42:05 2015 +0200 +++ b/src/share/tools/IdealGraphVisualizer/View/src/com/sun/hotspot/igv/view/widgets/FigureWidget.java Mon Apr 20 22:42:18 2015 +0200 @@ -32,10 +32,8 @@ import com.sun.hotspot.igv.util.PropertiesSheet; import com.sun.hotspot.igv.view.DiagramScene; import java.awt.*; -import java.awt.color.ColorSpace; import java.awt.event.ActionEvent; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashSet; import java.util.Set; import javax.swing.AbstractAction; @@ -93,7 +91,6 @@ } public FigureWidget(final Figure f, WidgetAction hoverAction, WidgetAction selectAction, DiagramScene scene, Widget parent) { - super(scene); assert this.getScene() != null; @@ -115,32 +112,20 @@ middleWidget.getActions().addAction(new DoubleClickAction(this)); middleWidget.setCheckClipping(true); - labelWidgets = new ArrayList<>(); - - String[] strings = figure.getLines(); - dummyTop = new Widget(scene); dummyTop.setMinimumSize(new Dimension(Figure.INSET / 2, 1)); middleWidget.addChild(dummyTop); - for (String cur : strings) { + String[] strings = figure.getLines(); + labelWidgets = new ArrayList<>(strings.length); - String displayString = cur; - + for (String displayString : strings) { LabelWidget lw = new LabelWidget(scene); labelWidgets.add(lw); middleWidget.addChild(lw); lw.setLabel(displayString); lw.setFont(figure.getDiagram().getFont()); - - Color bg = f.getColor(); - double brightness = bg.getRed() * 0.21 + bg.getGreen() * 0.72 + bg.getBlue() * 0.07; - if (brightness < 150) { - lw.setForeground(Color.WHITE); - } else { - lw.setForeground(Color.BLACK); - } - + lw.setForeground(getTextColor()); lw.setAlignment(LabelWidget.Alignment.CENTER); lw.setVerticalAlignment(LabelWidget.VerticalAlignment.CENTER); lw.setBorder(BorderFactory.createEmptyBorder()); @@ -209,6 +194,16 @@ return figure; } + private Color getTextColor() { + Color bg = figure.getColor(); + double brightness = bg.getRed() * 0.21 + bg.getGreen() * 0.72 + bg.getBlue() * 0.07; + if (brightness < 150) { + return Color.WHITE; + } else { + return Color.BLACK; + } + } + @Override protected void paintChildren() { Composite oldComposite = null; @@ -226,9 +221,20 @@ for (LabelWidget labelWidget : labelWidgets) { labelWidget.setVisible(true); } - } else { + Color oldColor = null; + if (boundary) { + for (LabelWidget labelWidget : labelWidgets) { + oldColor = labelWidget.getForeground(); + labelWidget.setForeground(Color.BLACK); + } + } super.paintChildren(); + if (boundary) { + for (LabelWidget labelWidget : labelWidgets) { + labelWidget.setForeground(oldColor); + } + } } if (boundary) { diff -r 41f99f9a8f63 -r eae62344f72c src/share/vm/graal/graalCodeInstaller.cpp --- a/src/share/vm/graal/graalCodeInstaller.cpp Mon Apr 20 22:42:05 2015 +0200 +++ b/src/share/vm/graal/graalCodeInstaller.cpp Mon Apr 20 22:42:18 2015 +0200 @@ -689,12 +689,6 @@ } void CodeInstaller::process_exception_handlers() { - // allocate some arrays for use by the collection code. - const int num_handlers = 5; - GrowableArray* bcis = new GrowableArray (num_handlers); - GrowableArray* scope_depths = new GrowableArray (num_handlers); - GrowableArray* pcos = new GrowableArray (num_handlers); - if (exception_handlers() != NULL) { objArrayOop handlers = exception_handlers(); for (int i = 0; i < handlers->length(); i++) { diff -r 41f99f9a8f63 -r eae62344f72c src/share/vm/graal/graalRuntime.cpp --- a/src/share/vm/graal/graalRuntime.cpp Mon Apr 20 22:42:05 2015 +0200 +++ b/src/share/vm/graal/graalRuntime.cpp Mon Apr 20 22:42:18 2015 +0200 @@ -1,1077 +1,1139 @@ -/* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -#include "precompiled.hpp" -#include "asm/codeBuffer.hpp" -#include "compiler/compileBroker.hpp" -#include "compiler/disassembler.hpp" -#include "graal/graalRuntime.hpp" -#include "graal/graalCompilerToVM.hpp" -#include "graal/graalCompiler.hpp" -#include "graal/graalJavaAccess.hpp" -#include "graal/graalEnv.hpp" -#include "memory/oopFactory.hpp" -#include "prims/jvm.h" -#include "runtime/biasedLocking.hpp" -#include "runtime/interfaceSupport.hpp" -#include "runtime/arguments.hpp" -#include "runtime/reflection.hpp" -#include "utilities/debug.hpp" - -jobject GraalRuntime::_HotSpotGraalRuntime_instance = NULL; -bool GraalRuntime::_HotSpotGraalRuntime_initialized = false; -bool GraalRuntime::_shutdown_called = false; - -void GraalRuntime::initialize_natives(JNIEnv *env, jclass c2vmClass) { - uintptr_t heap_end = (uintptr_t) Universe::heap()->reserved_region().end(); - uintptr_t allocation_end = heap_end + ((uintptr_t)16) * 1024 * 1024 * 1024; - AMD64_ONLY(guarantee(heap_end < allocation_end, "heap end too close to end of address space (might lead to erroneous TLAB allocations)")); - NOT_LP64(error("check TLAB allocation code for address space conflicts")); - - ensure_graal_class_loader_is_initialized(); - - JavaThread* THREAD = JavaThread::current(); - { - ThreadToNativeFromVM trans(THREAD); - - ResourceMark rm; - HandleMark hm; - - graal_compute_offsets(); - - // Ensure _non_oop_bits is initialized - Universe::non_oop_word(); - - env->RegisterNatives(c2vmClass, CompilerToVM_methods, CompilerToVM_methods_count()); - } - if (HAS_PENDING_EXCEPTION) { - abort_on_pending_exception(PENDING_EXCEPTION, "Could not register natives"); - } -} - -BufferBlob* GraalRuntime::initialize_buffer_blob() { - JavaThread* THREAD = JavaThread::current(); - BufferBlob* buffer_blob = THREAD->get_buffer_blob(); - if (buffer_blob == NULL) { - buffer_blob = BufferBlob::create("Graal thread-local CodeBuffer", GraalNMethodSizeLimit); - if (buffer_blob != NULL) { - THREAD->set_buffer_blob(buffer_blob); - } - } - return buffer_blob; -} - -BasicType GraalRuntime::kindToBasicType(jchar ch) { - switch(ch) { - case 'z': return T_BOOLEAN; - case 'b': return T_BYTE; - case 's': return T_SHORT; - case 'c': return T_CHAR; - case 'i': return T_INT; - case 'f': return T_FLOAT; - case 'j': return T_LONG; - case 'd': return T_DOUBLE; - case 'a': return T_OBJECT; - case '-': return T_ILLEGAL; - default: - fatal(err_msg("unexpected Kind: %c", ch)); - break; - } - return T_ILLEGAL; -} - -// Simple helper to see if the caller of a runtime stub which -// entered the VM has been deoptimized - -static bool caller_is_deopted() { - JavaThread* thread = JavaThread::current(); - RegisterMap reg_map(thread, false); - frame runtime_frame = thread->last_frame(); - frame caller_frame = runtime_frame.sender(®_map); - assert(caller_frame.is_compiled_frame(), "must be compiled"); - return caller_frame.is_deoptimized_frame(); -} - -// Stress deoptimization -static void deopt_caller() { - if ( !caller_is_deopted()) { - JavaThread* thread = JavaThread::current(); - RegisterMap reg_map(thread, false); - frame runtime_frame = thread->last_frame(); - frame caller_frame = runtime_frame.sender(®_map); - Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint); - assert(caller_is_deopted(), "Must be deoptimized"); - } -} - -JRT_BLOCK_ENTRY(void, GraalRuntime::new_instance(JavaThread* thread, Klass* klass)) - JRT_BLOCK; - assert(klass->is_klass(), "not a class"); - instanceKlassHandle h(thread, klass); - h->check_valid_for_instantiation(true, CHECK); - // make sure klass is initialized - h->initialize(CHECK); - // allocate instance and return via TLS - oop obj = h->allocate_instance(CHECK); - thread->set_vm_result(obj); - JRT_BLOCK_END; - - if (GraalDeferredInitBarriers) { - new_store_pre_barrier(thread); - } -JRT_END - -JRT_BLOCK_ENTRY(void, GraalRuntime::new_array(JavaThread* thread, Klass* array_klass, jint length)) - JRT_BLOCK; - // Note: no handle for klass needed since they are not used - // anymore after new_objArray() and no GC can happen before. - // (This may have to change if this code changes!) - assert(array_klass->is_klass(), "not a class"); - oop obj; - if (array_klass->oop_is_typeArray()) { - BasicType elt_type = TypeArrayKlass::cast(array_klass)->element_type(); - obj = oopFactory::new_typeArray(elt_type, length, CHECK); - } else { - Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass(); - obj = oopFactory::new_objArray(elem_klass, length, CHECK); - } - thread->set_vm_result(obj); - // This is pretty rare but this runtime patch is stressful to deoptimization - // if we deoptimize here so force a deopt to stress the path. - if (DeoptimizeALot) { - static int deopts = 0; - // Alternate between deoptimizing and raising an error (which will also cause a deopt) - if (deopts++ % 2 == 0) { - ResourceMark rm(THREAD); - THROW(vmSymbols::java_lang_OutOfMemoryError()); - } else { - deopt_caller(); - } - } - JRT_BLOCK_END; - - if (GraalDeferredInitBarriers) { - new_store_pre_barrier(thread); - } -JRT_END - -void GraalRuntime::new_store_pre_barrier(JavaThread* thread) { - // After any safepoint, just before going back to compiled code, - // we inform the GC that we will be doing initializing writes to - // this object in the future without emitting card-marks, so - // GC may take any compensating steps. - // NOTE: Keep this code consistent with GraphKit::store_barrier. - - oop new_obj = thread->vm_result(); - if (new_obj == NULL) return; - - assert(Universe::heap()->can_elide_tlab_store_barriers(), - "compiler must check this first"); - // GC may decide to give back a safer copy of new_obj. - new_obj = Universe::heap()->new_store_pre_barrier(thread, new_obj); - thread->set_vm_result(new_obj); -} - -JRT_ENTRY(void, GraalRuntime::new_multi_array(JavaThread* thread, Klass* klass, int rank, jint* dims)) - assert(klass->is_klass(), "not a class"); - assert(rank >= 1, "rank must be nonzero"); - oop obj = ArrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK); - thread->set_vm_result(obj); -JRT_END - -JRT_ENTRY(void, GraalRuntime::dynamic_new_array(JavaThread* thread, oopDesc* element_mirror, jint length)) - oop obj = Reflection::reflect_new_array(element_mirror, length, CHECK); - thread->set_vm_result(obj); -JRT_END - -JRT_ENTRY(void, GraalRuntime::dynamic_new_instance(JavaThread* thread, oopDesc* type_mirror)) - instanceKlassHandle klass(THREAD, java_lang_Class::as_Klass(type_mirror)); - - if (klass == NULL) { - ResourceMark rm(THREAD); - THROW(vmSymbols::java_lang_InstantiationException()); - } - - // Create new instance (the receiver) - klass->check_valid_for_instantiation(false, CHECK); - - // Make sure klass gets initialized - klass->initialize(CHECK); - - oop obj = klass->allocate_instance(CHECK); - thread->set_vm_result(obj); -JRT_END - -extern void vm_exit(int code); - -// Enter this method from compiled code handler below. This is where we transition -// to VM mode. This is done as a helper routine so that the method called directly -// from compiled code does not have to transition to VM. This allows the entry -// method to see if the nmethod that we have just looked up a handler for has -// been deoptimized while we were in the vm. This simplifies the assembly code -// cpu directories. -// -// We are entering here from exception stub (via the entry method below) -// If there is a compiled exception handler in this method, we will continue there; -// otherwise we will unwind the stack and continue at the caller of top frame method -// Note: we enter in Java using a special JRT wrapper. This wrapper allows us to -// control the area where we can allow a safepoint. After we exit the safepoint area we can -// check to see if the handler we are going to return is now in a nmethod that has -// been deoptimized. If that is the case we return the deopt blob -// unpack_with_exception entry instead. This makes life for the exception blob easier -// because making that same check and diverting is painful from assembly language. -JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* thread, oopDesc* ex, address pc, nmethod*& nm)) - // Reset method handle flag. - thread->set_is_method_handle_return(false); - - Handle exception(thread, ex); - nm = CodeCache::find_nmethod(pc); - assert(nm != NULL, "this is not an nmethod"); - // Adjust the pc as needed/ - if (nm->is_deopt_pc(pc)) { - RegisterMap map(thread, false); - frame exception_frame = thread->last_frame().sender(&map); - // if the frame isn't deopted then pc must not correspond to the caller of last_frame - assert(exception_frame.is_deoptimized_frame(), "must be deopted"); - pc = exception_frame.pc(); - } -#ifdef ASSERT - assert(exception.not_null(), "NULL exceptions should be handled by throw_exception"); - assert(exception->is_oop(), "just checking"); - // Check that exception is a subclass of Throwable, otherwise we have a VerifyError - if (!(exception->is_a(SystemDictionary::Throwable_klass()))) { - if (ExitVMOnVerifyError) vm_exit(-1); - ShouldNotReachHere(); - } -#endif - - // Check the stack guard pages and reenable them if necessary and there is - // enough space on the stack to do so. Use fast exceptions only if the guard - // pages are enabled. - bool guard_pages_enabled = thread->stack_yellow_zone_enabled(); - if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack(); - - if (JvmtiExport::can_post_on_exceptions()) { - // To ensure correct notification of exception catches and throws - // we have to deoptimize here. If we attempted to notify the - // catches and throws during this exception lookup it's possible - // we could deoptimize on the way out of the VM and end back in - // the interpreter at the throw site. This would result in double - // notifications since the interpreter would also notify about - // these same catches and throws as it unwound the frame. - - RegisterMap reg_map(thread); - frame stub_frame = thread->last_frame(); - frame caller_frame = stub_frame.sender(®_map); - - // We don't really want to deoptimize the nmethod itself since we - // can actually continue in the exception handler ourselves but I - // don't see an easy way to have the desired effect. - Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint); - assert(caller_is_deopted(), "Must be deoptimized"); - - return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls(); - } - - // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions - if (guard_pages_enabled) { - address fast_continuation = nm->handler_for_exception_and_pc(exception, pc); - if (fast_continuation != NULL) { - // Set flag if return address is a method handle call site. - thread->set_is_method_handle_return(nm->is_method_handle_return(pc)); - return fast_continuation; - } - } - - // If the stack guard pages are enabled, check whether there is a handler in - // the current method. Otherwise (guard pages disabled), force an unwind and - // skip the exception cache update (i.e., just leave continuation==NULL). - address continuation = NULL; - if (guard_pages_enabled) { - - // New exception handling mechanism can support inlined methods - // with exception handlers since the mappings are from PC to PC - - // debugging support - // tracing - if (TraceExceptions) { - ttyLocker ttyl; - ResourceMark rm; - tty->print_cr("Exception <%s> (" INTPTR_FORMAT ") thrown in compiled method <%s> at PC " INTPTR_FORMAT " for thread " INTPTR_FORMAT "", - exception->print_value_string(), p2i((address)exception()), nm->method()->print_value_string(), p2i(pc), p2i(thread)); - } - // for AbortVMOnException flag - NOT_PRODUCT(Exceptions::debug_check_abort(exception)); - - // Clear out the exception oop and pc since looking up an - // exception handler can cause class loading, which might throw an - // exception and those fields are expected to be clear during - // normal bytecode execution. - thread->clear_exception_oop_and_pc(); - - continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false); - // If an exception was thrown during exception dispatch, the exception oop may have changed - thread->set_exception_oop(exception()); - thread->set_exception_pc(pc); - - // the exception cache is used only by non-implicit exceptions - if (continuation != NULL && !SharedRuntime::deopt_blob()->contains(continuation)) { - nm->add_handler_for_exception_and_pc(exception, pc, continuation); - } - } - - // Set flag if return address is a method handle call site. - thread->set_is_method_handle_return(nm->is_method_handle_return(pc)); - - if (TraceExceptions) { - ttyLocker ttyl; - ResourceMark rm; - tty->print_cr("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT " for exception thrown at PC " PTR_FORMAT, - p2i(thread), p2i(continuation), p2i(pc)); - } - - return continuation; -JRT_END - -// Enter this method from compiled code only if there is a Java exception handler -// in the method handling the exception. -// We are entering here from exception stub. We don't do a normal VM transition here. -// We do it in a helper. This is so we can check to see if the nmethod we have just -// searched for an exception handler has been deoptimized in the meantime. -address GraalRuntime::exception_handler_for_pc(JavaThread* thread) { - oop exception = thread->exception_oop(); - address pc = thread->exception_pc(); - // Still in Java mode - DEBUG_ONLY(ResetNoHandleMark rnhm); - nmethod* nm = NULL; - address continuation = NULL; - { - // Enter VM mode by calling the helper - ResetNoHandleMark rnhm; - continuation = exception_handler_for_pc_helper(thread, exception, pc, nm); - } - // Back in JAVA, use no oops DON'T safepoint - - // Now check to see if the nmethod we were called from is now deoptimized. - // If so we must return to the deopt blob and deoptimize the nmethod - if (nm != NULL && caller_is_deopted()) { - continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls(); - } - - assert(continuation != NULL, "no handler found"); - return continuation; -} - -JRT_ENTRY(void, GraalRuntime::create_null_exception(JavaThread* thread)) - SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_NullPointerException()); - thread->set_vm_result(PENDING_EXCEPTION); - CLEAR_PENDING_EXCEPTION; -JRT_END - -JRT_ENTRY(void, GraalRuntime::create_out_of_bounds_exception(JavaThread* thread, jint index)) - char message[jintAsStringSize]; - sprintf(message, "%d", index); - SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), message); - thread->set_vm_result(PENDING_EXCEPTION); - CLEAR_PENDING_EXCEPTION; -JRT_END - -JRT_ENTRY_NO_ASYNC(void, GraalRuntime::monitorenter(JavaThread* thread, oopDesc* obj, BasicLock* lock)) - if (TraceGraal >= 3) { - char type[O_BUFLEN]; - obj->klass()->name()->as_C_string(type, O_BUFLEN); - markOop mark = obj->mark(); - tty->print_cr("%s: entered locking slow case with obj=" INTPTR_FORMAT ", type=%s, mark=" INTPTR_FORMAT ", lock=" INTPTR_FORMAT, thread->name(), p2i(obj), type, p2i(mark), p2i(lock)); - tty->flush(); - } -#ifdef ASSERT - if (PrintBiasedLockingStatistics) { - Atomic::inc(BiasedLocking::slow_path_entry_count_addr()); - } -#endif - Handle h_obj(thread, obj); - assert(h_obj()->is_oop(), "must be NULL or an object"); - if (UseBiasedLocking) { - // Retry fast entry if bias is revoked to avoid unnecessary inflation - ObjectSynchronizer::fast_enter(h_obj, lock, true, CHECK); - } else { - if (GraalUseFastLocking) { - // When using fast locking, the compiled code has already tried the fast case - ObjectSynchronizer::slow_enter(h_obj, lock, THREAD); - } else { - ObjectSynchronizer::fast_enter(h_obj, lock, false, THREAD); - } - } - if (TraceGraal >= 3) { - tty->print_cr("%s: exiting locking slow with obj=" INTPTR_FORMAT, thread->name(), p2i(obj)); - } -JRT_END - -JRT_LEAF(void, GraalRuntime::monitorexit(JavaThread* thread, oopDesc* obj, BasicLock* lock)) - assert(thread == JavaThread::current(), "threads must correspond"); - assert(thread->last_Java_sp(), "last_Java_sp must be set"); - // monitorexit is non-blocking (leaf routine) => no exceptions can be thrown - EXCEPTION_MARK; - -#ifdef DEBUG - if (!obj->is_oop()) { - ResetNoHandleMark rhm; - nmethod* method = thread->last_frame().cb()->as_nmethod_or_null(); - if (method != NULL) { - tty->print_cr("ERROR in monitorexit in method %s wrong obj " INTPTR_FORMAT, method->name(), p2i(obj)); - } - thread->print_stack_on(tty); - assert(false, "invalid lock object pointer dected"); - } -#endif - - if (GraalUseFastLocking) { - // When using fast locking, the compiled code has already tried the fast case - ObjectSynchronizer::slow_exit(obj, lock, THREAD); - } else { - ObjectSynchronizer::fast_exit(obj, lock, THREAD); - } - if (TraceGraal >= 3) { - char type[O_BUFLEN]; - obj->klass()->name()->as_C_string(type, O_BUFLEN); - tty->print_cr("%s: exited locking slow case with obj=" INTPTR_FORMAT ", type=%s, mark=" INTPTR_FORMAT ", lock=" INTPTR_FORMAT, thread->name(), p2i(obj), type, p2i(obj->mark()), p2i(lock)); - tty->flush(); - } -JRT_END - -JRT_LEAF(void, GraalRuntime::log_object(JavaThread* thread, oopDesc* obj, jint flags)) - bool string = mask_bits_are_true(flags, LOG_OBJECT_STRING); - bool addr = mask_bits_are_true(flags, LOG_OBJECT_ADDRESS); - bool newline = mask_bits_are_true(flags, LOG_OBJECT_NEWLINE); - if (!string) { - if (!addr && obj->is_oop_or_null(true)) { - char buf[O_BUFLEN]; - tty->print("%s@" INTPTR_FORMAT, obj->klass()->name()->as_C_string(buf, O_BUFLEN), p2i(obj)); - } else { - tty->print(INTPTR_FORMAT, p2i(obj)); - } - } else { - ResourceMark rm; - assert(obj != NULL && java_lang_String::is_instance(obj), "must be"); - char *buf = java_lang_String::as_utf8_string(obj); - tty->print_raw(buf); - } - if (newline) { - tty->cr(); - } -JRT_END - -JRT_LEAF(void, GraalRuntime::write_barrier_pre(JavaThread* thread, oopDesc* obj)) - thread->satb_mark_queue().enqueue(obj); -JRT_END - -JRT_LEAF(void, GraalRuntime::write_barrier_post(JavaThread* thread, void* card_addr)) - thread->dirty_card_queue().enqueue(card_addr); -JRT_END - -JRT_LEAF(jboolean, GraalRuntime::validate_object(JavaThread* thread, oopDesc* parent, oopDesc* child)) - bool ret = true; - if(!Universe::heap()->is_in_closed_subset(parent)) { - tty->print_cr("Parent Object "INTPTR_FORMAT" not in heap", p2i(parent)); - parent->print(); - ret=false; - } - if(!Universe::heap()->is_in_closed_subset(child)) { - tty->print_cr("Child Object "INTPTR_FORMAT" not in heap", p2i(child)); - child->print(); - ret=false; - } - return (jint)ret; -JRT_END - -JRT_ENTRY(void, GraalRuntime::vm_error(JavaThread* thread, jlong where, jlong format, jlong value)) - ResourceMark rm; - const char *error_msg = where == 0L ? "" : (char*) (address) where; - char *detail_msg = NULL; - if (format != 0L) { - const char* buf = (char*) (address) format; - size_t detail_msg_length = strlen(buf) * 2; - detail_msg = (char *) NEW_RESOURCE_ARRAY(u_char, detail_msg_length); - jio_snprintf(detail_msg, detail_msg_length, buf, value); - } - report_vm_error(__FILE__, __LINE__, error_msg, detail_msg); -JRT_END - -JRT_LEAF(oopDesc*, GraalRuntime::load_and_clear_exception(JavaThread* thread)) - oop exception = thread->exception_oop(); - assert(exception != NULL, "npe"); - thread->set_exception_oop(NULL); - thread->set_exception_pc(0); - return exception; -JRT_END - -JRT_LEAF(void, GraalRuntime::log_printf(JavaThread* thread, oopDesc* format, jlong v1, jlong v2, jlong v3)) - ResourceMark rm; - assert(format != NULL && java_lang_String::is_instance(format), "must be"); - char *buf = java_lang_String::as_utf8_string(format); - tty->print(buf, v1, v2, v3); -JRT_END - -static void decipher(jlong v, bool ignoreZero) { - if (v != 0 || !ignoreZero) { - void* p = (void *)(address) v; - CodeBlob* cb = CodeCache::find_blob(p); - if (cb) { - if (cb->is_nmethod()) { - char buf[O_BUFLEN]; - tty->print("%s [" INTPTR_FORMAT "+" JLONG_FORMAT "]", cb->as_nmethod_or_null()->method()->name_and_sig_as_C_string(buf, O_BUFLEN), p2i(cb->code_begin()), (jlong)((address)v - cb->code_begin())); - return; - } - cb->print_value_on(tty); - return; - } - if (Universe::heap()->is_in(p)) { - oop obj = oop(p); - obj->print_value_on(tty); - return; - } - tty->print(INTPTR_FORMAT " [long: " JLONG_FORMAT ", double %lf, char %c]",p2i((void *)v), (jlong)v, (jdouble)v, (char)v); - } -} - -JRT_LEAF(void, GraalRuntime::vm_message(jboolean vmError, jlong format, jlong v1, jlong v2, jlong v3)) - ResourceMark rm; - char *buf = (char*) (address) format; - if (vmError) { - if (buf != NULL) { - fatal(err_msg(buf, v1, v2, v3)); - } else { - fatal(""); - } - } else if (buf != NULL) { - tty->print(buf, v1, v2, v3); - } else { - assert(v2 == 0, "v2 != 0"); - assert(v3 == 0, "v3 != 0"); - decipher(v1, false); - } -JRT_END - -JRT_LEAF(void, GraalRuntime::log_primitive(JavaThread* thread, jchar typeChar, jlong value, jboolean newline)) - union { - jlong l; - jdouble d; - jfloat f; - } uu; - uu.l = value; - switch (typeChar) { - case 'z': tty->print(value == 0 ? "false" : "true"); break; - case 'b': tty->print("%d", (jbyte) value); break; - case 'c': tty->print("%c", (jchar) value); break; - case 's': tty->print("%d", (jshort) value); break; - case 'i': tty->print("%d", (jint) value); break; - case 'f': tty->print("%f", uu.f); break; - case 'j': tty->print(JLONG_FORMAT, value); break; - case 'd': tty->print("%lf", uu.d); break; - default: assert(false, "unknown typeChar"); break; - } - if (newline) { - tty->cr(); - } -JRT_END - -JRT_ENTRY(jint, GraalRuntime::identity_hash_code(JavaThread* thread, oopDesc* obj)) - return (jint) obj->identity_hash(); -JRT_END - -JRT_ENTRY(jboolean, GraalRuntime::thread_is_interrupted(JavaThread* thread, oopDesc* receiver, jboolean clear_interrupted)) - // Ensure that the C++ Thread and OSThread structures aren't freed before we operate - Handle receiverHandle(thread, receiver); - MutexLockerEx ml(thread->threadObj() == (void*)receiver ? NULL : Threads_lock); - JavaThread* receiverThread = java_lang_Thread::thread(receiverHandle()); - if (receiverThread == NULL) { - // The other thread may exit during this process, which is ok so return false. - return JNI_FALSE; - } else { - return (jint) Thread::is_interrupted(receiverThread, clear_interrupted != 0); - } -JRT_END - -JRT_ENTRY(jint, GraalRuntime::test_deoptimize_call_int(JavaThread* thread, int value)) - deopt_caller(); - return value; -JRT_END - -// private static void Factory.init() -JVM_ENTRY(void, JVM_InitGraalClassLoader(JNIEnv *env, jclass c, jobject loader_handle)) - SystemDictionary::init_graal_loader(JNIHandles::resolve(loader_handle)); - SystemDictionary::WKID scan = SystemDictionary::FIRST_GRAAL_WKID; - SystemDictionary::initialize_wk_klasses_through(SystemDictionary::LAST_GRAAL_WKID, scan, CHECK); -JVM_END - -// private static GraalRuntime Graal.initializeRuntime() -JVM_ENTRY(jobject, JVM_GetGraalRuntime(JNIEnv *env, jclass c)) - GraalRuntime::initialize_HotSpotGraalRuntime(); - return GraalRuntime::get_HotSpotGraalRuntime_jobject(); -JVM_END - -// private static String[] Graal.getServiceImpls(Class service) -JVM_ENTRY(jobject, JVM_GetGraalServiceImpls(JNIEnv *env, jclass c, jclass serviceClass)) - HandleMark hm; - KlassHandle serviceKlass(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(serviceClass))); - return JNIHandles::make_local(THREAD, GraalRuntime::get_service_impls(serviceKlass, THREAD)()); -JVM_END - -// private static TruffleRuntime Truffle.createRuntime() -JVM_ENTRY(jobject, JVM_CreateTruffleRuntime(JNIEnv *env, jclass c)) - GraalRuntime::ensure_graal_class_loader_is_initialized(); - TempNewSymbol name = SymbolTable::new_symbol("com/oracle/graal/truffle/hotspot/HotSpotTruffleRuntime", CHECK_NULL); - KlassHandle klass = GraalRuntime::resolve_or_fail(name, CHECK_NULL); - - TempNewSymbol makeInstance = SymbolTable::new_symbol("makeInstance", CHECK_NULL); - TempNewSymbol sig = SymbolTable::new_symbol("()Lcom/oracle/truffle/api/TruffleRuntime;", CHECK_NULL); - JavaValue result(T_OBJECT); - JavaCalls::call_static(&result, klass, makeInstance, sig, CHECK_NULL); - return JNIHandles::make_local(THREAD, (oop) result.get_jobject()); -JVM_END - -// private static NativeFunctionInterfaceRuntime.createInterface() -JVM_ENTRY(jobject, JVM_CreateNativeFunctionInterface(JNIEnv *env, jclass c)) - GraalRuntime::ensure_graal_class_loader_is_initialized(); - TempNewSymbol name = SymbolTable::new_symbol("com/oracle/graal/truffle/hotspot/HotSpotTruffleRuntime", CHECK_NULL); - KlassHandle klass = GraalRuntime::resolve_or_fail(name, CHECK_NULL); - - TempNewSymbol makeInstance = SymbolTable::new_symbol("createNativeFunctionInterface", CHECK_NULL); - TempNewSymbol sig = SymbolTable::new_symbol("()Lcom/oracle/nfi/api/NativeFunctionInterface;", CHECK_NULL); - JavaValue result(T_OBJECT); - JavaCalls::call_static(&result, klass, makeInstance, sig, CHECK_NULL); - return JNIHandles::make_local(THREAD, (oop) result.get_jobject()); -JVM_END - -void GraalRuntime::check_generated_sources_sha1(TRAPS) { - TempNewSymbol name = SymbolTable::new_symbol("com/oracle/graal/hotspot/sourcegen/GeneratedSourcesSha1", CHECK_ABORT); - KlassHandle klass = load_required_class(name); - fieldDescriptor fd; - if (!InstanceKlass::cast(klass())->find_field(vmSymbols::value_name(), vmSymbols::string_signature(), true, &fd)) { - THROW_MSG(vmSymbols::java_lang_NoSuchFieldError(), "GeneratedSourcesSha1.value"); - } - - Symbol* value = java_lang_String::as_symbol(klass->java_mirror()->obj_field(fd.offset()), CHECK); - if (!value->equals(_generated_sources_sha1)) { - char buf[200]; - jio_snprintf(buf, sizeof(buf), "Generated sources SHA1 check failed (%s != %s) - need to rebuild the VM", value->as_C_string(), _generated_sources_sha1); - THROW_MSG(vmSymbols::java_lang_InternalError(), buf); - } -} - -Handle GraalRuntime::callInitializer(const char* className, const char* methodName, const char* returnType) { - guarantee(!_HotSpotGraalRuntime_initialized, "cannot reinitialize HotSpotGraalRuntime"); - Thread* THREAD = Thread::current(); - check_generated_sources_sha1(CHECK_ABORT_(Handle())); - - TempNewSymbol name = SymbolTable::new_symbol(className, CHECK_ABORT_(Handle())); - KlassHandle klass = load_required_class(name); - TempNewSymbol runtime = SymbolTable::new_symbol(methodName, CHECK_ABORT_(Handle())); - TempNewSymbol sig = SymbolTable::new_symbol(returnType, CHECK_ABORT_(Handle())); - JavaValue result(T_OBJECT); - JavaCalls::call_static(&result, klass, runtime, sig, CHECK_ABORT_(Handle())); - return Handle((oop)result.get_jobject()); -} - -void GraalRuntime::initialize_HotSpotGraalRuntime() { - if (JNIHandles::resolve(_HotSpotGraalRuntime_instance) == NULL) { -#ifdef ASSERT - // This should only be called in the context of the Graal class being initialized - Thread* THREAD = Thread::current(); - TempNewSymbol name = SymbolTable::new_symbol("com/oracle/graal/api/runtime/Graal", CHECK_ABORT); - instanceKlassHandle klass = InstanceKlass::cast(load_required_class(name)); - assert(klass->is_being_initialized() && klass->is_reentrant_initialization(THREAD), - "HotSpotGraalRuntime initialization should only be triggered through Graal initialization"); -#endif - - Handle result = callInitializer("com/oracle/graal/hotspot/HotSpotGraalRuntime", "runtime", - "()Lcom/oracle/graal/hotspot/HotSpotGraalRuntime;"); - _HotSpotGraalRuntime_initialized = true; - _HotSpotGraalRuntime_instance = JNIHandles::make_global(result()); - } -} - -void GraalRuntime::initialize_Graal() { - if (JNIHandles::resolve(_HotSpotGraalRuntime_instance) == NULL) { - callInitializer("com/oracle/graal/api/runtime/Graal", "getRuntime", "()Lcom/oracle/graal/api/runtime/GraalRuntime;"); - } - assert(_HotSpotGraalRuntime_initialized == true, "what?"); -} - -// private static void CompilerToVMImpl.init() -JVM_ENTRY(void, JVM_InitializeGraalNatives(JNIEnv *env, jclass c2vmClass)) - GraalRuntime::initialize_natives(env, c2vmClass); -JVM_END - -// private static boolean HotSpotOptions.parseVMOptions() -JVM_ENTRY(jboolean, JVM_ParseGraalOptions(JNIEnv *env, jclass c)) - HandleMark hm; - KlassHandle hotSpotOptionsClass(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(c))); - bool result = GraalRuntime::parse_arguments(hotSpotOptionsClass, CHECK_false); - return result; -JVM_END - - -void GraalRuntime::ensure_graal_class_loader_is_initialized() { - // This initialization code is guarded by a static pointer to the Factory class. - // Once it is non-null, the Graal class loader and well known Graal classes are - // guaranteed to have been initialized. By going through the static - // initializer of Factory, we can rely on class initialization semantics to - // synchronize threads racing to do the initialization. - static Klass* _FactoryKlass = NULL; - if (_FactoryKlass == NULL) { - Thread* THREAD = Thread::current(); - TempNewSymbol name = SymbolTable::new_symbol("com/oracle/graal/hotspot/loader/Factory", CHECK_ABORT); - KlassHandle klass = SystemDictionary::resolve_or_fail(name, true, THREAD); - if (HAS_PENDING_EXCEPTION) { - static volatile int seen_error = 0; - if (!seen_error && Atomic::cmpxchg(1, &seen_error, 0) == 0) { - // Only report the failure on the first thread that hits it - abort_on_pending_exception(PENDING_EXCEPTION, "Graal classes are not available"); - } else { - CLEAR_PENDING_EXCEPTION; - // Give first thread time to report the error. - os::sleep(THREAD, 100, false); - vm_abort(false); - } - } - - // We cannot use graalJavaAccess for this because we are currently in the - // process of initializing that mechanism. - TempNewSymbol field_name = SymbolTable::new_symbol("useGraalClassLoader", CHECK_ABORT); - fieldDescriptor field_desc; - if (klass->find_field(field_name, vmSymbols::bool_signature(), &field_desc) == NULL) { - ResourceMark rm; - fatal(err_msg("Invalid layout of %s at %s", field_name->as_C_string(), klass->external_name())); - } - - InstanceKlass* ik = InstanceKlass::cast(klass()); - address addr = ik->static_field_addr(field_desc.offset() - InstanceMirrorKlass::offset_of_static_fields()); - *((jboolean *) addr) = (jboolean) UseGraalClassLoader; - klass->initialize(CHECK_ABORT); - _FactoryKlass = klass(); - } -} - -jint GraalRuntime::check_arguments(TRAPS) { - KlassHandle nullHandle; - parse_arguments(nullHandle, THREAD); - if (HAS_PENDING_EXCEPTION) { - // Errors in parsing Graal arguments cause exceptions. - // We now load and initialize HotSpotOptions which in turn - // causes argument parsing to be redone with better error messages. - CLEAR_PENDING_EXCEPTION; - TempNewSymbol name = SymbolTable::new_symbol("Lcom/oracle/graal/hotspot/HotSpotOptions;", CHECK_ABORT_(JNI_ERR)); - instanceKlassHandle hotSpotOptionsClass = resolve_or_fail(name, CHECK_ABORT_(JNI_ERR)); - - parse_arguments(hotSpotOptionsClass, THREAD); - assert(HAS_PENDING_EXCEPTION, "must be"); - - ResourceMark rm; - Handle exception = PENDING_EXCEPTION; - CLEAR_PENDING_EXCEPTION; - oop message = java_lang_Throwable::message(exception); - if (message != NULL) { - tty->print_cr("Error parsing Graal options: %s", java_lang_String::as_utf8_string(message)); - } else { - call_printStackTrace(exception, THREAD); - } - return JNI_ERR; - } - return JNI_OK; -} - -bool GraalRuntime::parse_arguments(KlassHandle hotSpotOptionsClass, TRAPS) { - ResourceMark rm(THREAD); - - // Process option overrides from graal.options first - parse_graal_options_file(hotSpotOptionsClass, CHECK_false); - - // Now process options on the command line - int numOptions = Arguments::num_graal_args(); - for (int i = 0; i < numOptions; i++) { - char* arg = Arguments::graal_args_array()[i]; - parse_argument(hotSpotOptionsClass, arg, CHECK_false); - } - return CITime || CITimeEach; -} - -void GraalRuntime::check_required_value(const char* name, size_t name_len, const char* value, TRAPS) { - if (value == NULL) { - char buf[200]; - jio_snprintf(buf, sizeof(buf), "Must use '-G:%.*s=' format for %.*s option", name_len, name, name_len, name); - THROW_MSG(vmSymbols::java_lang_InternalError(), buf); - } -} - -void GraalRuntime::parse_argument(KlassHandle hotSpotOptionsClass, char* arg, TRAPS) { - ensure_graal_class_loader_is_initialized(); - char first = arg[0]; - char* name; - size_t name_len; - bool recognized = true; - if (first == '+' || first == '-') { - name = arg + 1; - name_len = strlen(name); - recognized = set_option_bool(hotSpotOptionsClass, name, name_len, first, CHECK); - } else { - char* sep = strchr(arg, '='); - name = arg; - char* value = NULL; - if (sep != NULL) { - name_len = sep - name; - value = sep + 1; - } else { - name_len = strlen(name); - } - recognized = set_option(hotSpotOptionsClass, name, name_len, value, CHECK); - } - - if (!recognized) { - bool throw_err = hotSpotOptionsClass.is_null(); - if (!hotSpotOptionsClass.is_null()) { - set_option_helper(hotSpotOptionsClass, name, name_len, Handle(), ' ', Handle(), 0L); - if (!HAS_PENDING_EXCEPTION) { - throw_err = true; - } - } - - if (throw_err) { - char buf[200]; - jio_snprintf(buf, sizeof(buf), "Unrecognized Graal option %.*s", name_len, name); - THROW_MSG(vmSymbols::java_lang_InternalError(), buf); - } - } -} - -void GraalRuntime::parse_graal_options_file(KlassHandle hotSpotOptionsClass, TRAPS) { - const char* home = Arguments::get_java_home(); - size_t path_len = strlen(home) + strlen("/lib/graal.options") + 1; - char* path = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, path_len); - char sep = os::file_separator()[0]; - sprintf(path, "%s%clib%cgraal.options", home, sep, sep); - - struct stat st; - if (os::stat(path, &st) == 0) { - int file_handle = os::open(path, 0, 0); - if (file_handle != -1) { - char* buffer = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, st.st_size); - int num_read = (int) os::read(file_handle, (char*) buffer, st.st_size); - if (num_read == -1) { - warning("Error reading file %s due to %s", path, strerror(errno)); - } else if (num_read != st.st_size) { - warning("Only read %d of " SIZE_FORMAT " bytes from %s", num_read, (size_t) st.st_size, path); - } - os::close(file_handle); - if (num_read == st.st_size) { - char* line = buffer; - int lineNo = 1; - while (line - buffer < num_read) { - char* nl = strchr(line, '\n'); - if (nl != NULL) { - *nl = '\0'; - } - parse_argument(hotSpotOptionsClass, line, THREAD); - if (HAS_PENDING_EXCEPTION) { - warning("Error in %s:%d", path, lineNo); - return; - } - if (nl != NULL) { - line = nl + 1; - lineNo++; - } else { - // File without newline at the end - break; - } - } - } - } else { - warning("Error opening file %s due to %s", path, strerror(errno)); - } - } -} - -jlong GraalRuntime::parse_primitive_option_value(char spec, const char* name, size_t name_len, const char* value, TRAPS) { - check_required_value(name, name_len, value, CHECK_(0L)); - union { - jint i; - jlong l; - double d; - } uu; - uu.l = 0L; - char dummy; - switch (spec) { - case 'd': - case 'f': { - if (sscanf(value, "%lf%c", &uu.d, &dummy) == 1) { - return uu.l; - } - break; - } - case 'i': { - if (sscanf(value, "%d%c", &uu.i, &dummy) == 1) { - return (jlong)uu.i; - } - break; - } - default: - ShouldNotReachHere(); - } - ResourceMark rm(THREAD); - char buf[200]; - bool missing = strlen(value) == 0; - if (missing) { - jio_snprintf(buf, sizeof(buf), "Missing %s value for Graal option %.*s", (spec == 'i' ? "numeric" : "float/double"), name_len, name); - } else { - jio_snprintf(buf, sizeof(buf), "Invalid %s value for Graal option %.*s: %s", (spec == 'i' ? "numeric" : "float/double"), name_len, name, value); - } - THROW_MSG_(vmSymbols::java_lang_InternalError(), buf, 0L); -} - -void GraalRuntime::set_option_helper(KlassHandle hotSpotOptionsClass, char* name, size_t name_len, Handle option, jchar spec, Handle stringValue, jlong primitiveValue) { - Thread* THREAD = Thread::current(); - Handle name_handle; - if (name != NULL) { - if (strlen(name) > name_len) { - // Temporarily replace '=' with NULL to create the Java string for the option name - char save = name[name_len]; - name[name_len] = '\0'; - name_handle = java_lang_String::create_from_str(name, THREAD); - name[name_len] = '='; - if (HAS_PENDING_EXCEPTION) { - return; - } - } else { - assert(strlen(name) == name_len, "must be"); - name_handle = java_lang_String::create_from_str(name, CHECK); - } - } - - TempNewSymbol setOption = SymbolTable::new_symbol("setOption", CHECK); - TempNewSymbol sig = SymbolTable::new_symbol("(Ljava/lang/String;Lcom/oracle/graal/options/OptionValue;CLjava/lang/String;J)V", CHECK); - JavaValue result(T_VOID); - JavaCallArguments args; - args.push_oop(name_handle()); - args.push_oop(option()); - args.push_int(spec); - args.push_oop(stringValue()); - args.push_long(primitiveValue); - JavaCalls::call_static(&result, hotSpotOptionsClass, setOption, sig, &args, CHECK); -} - -Handle GraalRuntime::get_OptionValue(const char* declaringClass, const char* fieldName, const char* fieldSig, TRAPS) { - TempNewSymbol name = SymbolTable::new_symbol(declaringClass, CHECK_NH); - Klass* klass = resolve_or_fail(name, CHECK_NH); - - // The class has been loaded so the field and signature should already be in the symbol - // table. If they're not there, the field doesn't exist. - TempNewSymbol fieldname = SymbolTable::probe(fieldName, (int)strlen(fieldName)); - TempNewSymbol signame = SymbolTable::probe(fieldSig, (int)strlen(fieldSig)); - if (fieldname == NULL || signame == NULL) { - THROW_MSG_(vmSymbols::java_lang_NoSuchFieldError(), (char*) fieldName, Handle()); - } - // Make sure class is initialized before handing id's out to fields - klass->initialize(CHECK_NH); - - fieldDescriptor fd; - if (!InstanceKlass::cast(klass)->find_field(fieldname, signame, true, &fd)) { - THROW_MSG_(vmSymbols::java_lang_NoSuchFieldError(), (char*) fieldName, Handle()); - } - - Handle ret = klass->java_mirror()->obj_field(fd.offset()); - return ret; -} - -Handle GraalRuntime::create_Service(const char* name, TRAPS) { - TempNewSymbol kname = SymbolTable::new_symbol(name, CHECK_NH); - Klass* k = resolve_or_fail(kname, CHECK_NH); - instanceKlassHandle klass(THREAD, k); - klass->initialize(CHECK_NH); - klass->check_valid_for_instantiation(true, CHECK_NH); - JavaValue result(T_VOID); - instanceHandle service = klass->allocate_instance_handle(CHECK_NH); - JavaCalls::call_special(&result, service, klass, vmSymbols::object_initializer_name(), vmSymbols::void_method_signature(), THREAD); - return service; -} - -void GraalRuntime::shutdown() { - if (_HotSpotGraalRuntime_instance != NULL) { - _shutdown_called = true; - JavaThread* THREAD = JavaThread::current(); - HandleMark hm(THREAD); - TempNewSymbol name = SymbolTable::new_symbol("com/oracle/graal/hotspot/HotSpotGraalRuntime", CHECK_ABORT); - KlassHandle klass = load_required_class(name); - JavaValue result(T_VOID); - JavaCallArguments args; - args.push_oop(get_HotSpotGraalRuntime()); - JavaCalls::call_special(&result, klass, vmSymbols::shutdown_method_name(), vmSymbols::void_method_signature(), &args, CHECK_ABORT); - - JNIHandles::destroy_global(_HotSpotGraalRuntime_instance); - _HotSpotGraalRuntime_instance = NULL; - } -} - -void GraalRuntime::call_printStackTrace(Handle exception, Thread* thread) { - assert(exception->is_a(SystemDictionary::Throwable_klass()), "Throwable instance expected"); - JavaValue result(T_VOID); - JavaCalls::call_virtual(&result, - exception, - KlassHandle(thread, - SystemDictionary::Throwable_klass()), - vmSymbols::printStackTrace_name(), - vmSymbols::void_method_signature(), - thread); -} - -void GraalRuntime::abort_on_pending_exception(Handle exception, const char* message, bool dump_core) { - Thread* THREAD = Thread::current(); - CLEAR_PENDING_EXCEPTION; - tty->print_raw_cr(message); - call_printStackTrace(exception, THREAD); - - // Give other aborting threads to also print their stack traces. - // This can be very useful when debugging class initialization - // failures. - os::sleep(THREAD, 200, false); - - vm_abort(dump_core); -} - -Klass* GraalRuntime::resolve_or_null(Symbol* name, TRAPS) { - return SystemDictionary::resolve_or_null(name, SystemDictionary::graal_loader(), Handle(), CHECK_NULL); -} - -Klass* GraalRuntime::resolve_or_fail(Symbol* name, TRAPS) { - return SystemDictionary::resolve_or_fail(name, SystemDictionary::graal_loader(), Handle(), true, CHECK_NULL); -} - -Klass* GraalRuntime::load_required_class(Symbol* name) { - Klass* klass = resolve_or_null(name, Thread::current()); - if (klass == NULL) { - tty->print_cr("Could not load class %s", name->as_C_string()); - vm_abort(false); - } - return klass; -} - -#include "graalRuntime.inline.hpp" +/* + * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#include "precompiled.hpp" +#include "asm/codeBuffer.hpp" +#include "compiler/compileBroker.hpp" +#include "compiler/disassembler.hpp" +#include "graal/graalRuntime.hpp" +#include "graal/graalCompilerToVM.hpp" +#include "graal/graalCompiler.hpp" +#include "graal/graalJavaAccess.hpp" +#include "graal/graalEnv.hpp" +#include "memory/oopFactory.hpp" +#include "prims/jvm.h" +#include "runtime/biasedLocking.hpp" +#include "runtime/interfaceSupport.hpp" +#include "runtime/arguments.hpp" +#include "runtime/reflection.hpp" +#include "utilities/debug.hpp" + +jobject GraalRuntime::_HotSpotGraalRuntime_instance = NULL; +bool GraalRuntime::_HotSpotGraalRuntime_initialized = false; +bool GraalRuntime::_shutdown_called = false; + +void GraalRuntime::initialize_natives(JNIEnv *env, jclass c2vmClass) { + uintptr_t heap_end = (uintptr_t) Universe::heap()->reserved_region().end(); + uintptr_t allocation_end = heap_end + ((uintptr_t)16) * 1024 * 1024 * 1024; + AMD64_ONLY(guarantee(heap_end < allocation_end, "heap end too close to end of address space (might lead to erroneous TLAB allocations)")); + NOT_LP64(error("check TLAB allocation code for address space conflicts")); + + ensure_graal_class_loader_is_initialized(); + + JavaThread* THREAD = JavaThread::current(); + { + ThreadToNativeFromVM trans(THREAD); + + ResourceMark rm; + HandleMark hm; + + graal_compute_offsets(); + + // Ensure _non_oop_bits is initialized + Universe::non_oop_word(); + + env->RegisterNatives(c2vmClass, CompilerToVM_methods, CompilerToVM_methods_count()); + } + if (HAS_PENDING_EXCEPTION) { + abort_on_pending_exception(PENDING_EXCEPTION, "Could not register natives"); + } +} + +BufferBlob* GraalRuntime::initialize_buffer_blob() { + JavaThread* THREAD = JavaThread::current(); + BufferBlob* buffer_blob = THREAD->get_buffer_blob(); + if (buffer_blob == NULL) { + buffer_blob = BufferBlob::create("Graal thread-local CodeBuffer", GraalNMethodSizeLimit); + if (buffer_blob != NULL) { + THREAD->set_buffer_blob(buffer_blob); + } + } + return buffer_blob; +} + +BasicType GraalRuntime::kindToBasicType(jchar ch) { + switch(ch) { + case 'z': return T_BOOLEAN; + case 'b': return T_BYTE; + case 's': return T_SHORT; + case 'c': return T_CHAR; + case 'i': return T_INT; + case 'f': return T_FLOAT; + case 'j': return T_LONG; + case 'd': return T_DOUBLE; + case 'a': return T_OBJECT; + case '-': return T_ILLEGAL; + default: + fatal(err_msg("unexpected Kind: %c", ch)); + break; + } + return T_ILLEGAL; +} + +// Simple helper to see if the caller of a runtime stub which +// entered the VM has been deoptimized + +static bool caller_is_deopted() { + JavaThread* thread = JavaThread::current(); + RegisterMap reg_map(thread, false); + frame runtime_frame = thread->last_frame(); + frame caller_frame = runtime_frame.sender(®_map); + assert(caller_frame.is_compiled_frame(), "must be compiled"); + return caller_frame.is_deoptimized_frame(); +} + +// Stress deoptimization +static void deopt_caller() { + if ( !caller_is_deopted()) { + JavaThread* thread = JavaThread::current(); + RegisterMap reg_map(thread, false); + frame runtime_frame = thread->last_frame(); + frame caller_frame = runtime_frame.sender(®_map); + Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint); + assert(caller_is_deopted(), "Must be deoptimized"); + } +} + +JRT_BLOCK_ENTRY(void, GraalRuntime::new_instance(JavaThread* thread, Klass* klass)) + JRT_BLOCK; + assert(klass->is_klass(), "not a class"); + instanceKlassHandle h(thread, klass); + h->check_valid_for_instantiation(true, CHECK); + // make sure klass is initialized + h->initialize(CHECK); + // allocate instance and return via TLS + oop obj = h->allocate_instance(CHECK); + thread->set_vm_result(obj); + JRT_BLOCK_END; + + if (GraalDeferredInitBarriers) { + new_store_pre_barrier(thread); + } +JRT_END + +JRT_BLOCK_ENTRY(void, GraalRuntime::new_array(JavaThread* thread, Klass* array_klass, jint length)) + JRT_BLOCK; + // Note: no handle for klass needed since they are not used + // anymore after new_objArray() and no GC can happen before. + // (This may have to change if this code changes!) + assert(array_klass->is_klass(), "not a class"); + oop obj; + if (array_klass->oop_is_typeArray()) { + BasicType elt_type = TypeArrayKlass::cast(array_klass)->element_type(); + obj = oopFactory::new_typeArray(elt_type, length, CHECK); + } else { + Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass(); + obj = oopFactory::new_objArray(elem_klass, length, CHECK); + } + thread->set_vm_result(obj); + // This is pretty rare but this runtime patch is stressful to deoptimization + // if we deoptimize here so force a deopt to stress the path. + if (DeoptimizeALot) { + static int deopts = 0; + // Alternate between deoptimizing and raising an error (which will also cause a deopt) + if (deopts++ % 2 == 0) { + ResourceMark rm(THREAD); + THROW(vmSymbols::java_lang_OutOfMemoryError()); + } else { + deopt_caller(); + } + } + JRT_BLOCK_END; + + if (GraalDeferredInitBarriers) { + new_store_pre_barrier(thread); + } +JRT_END + +void GraalRuntime::new_store_pre_barrier(JavaThread* thread) { + // After any safepoint, just before going back to compiled code, + // we inform the GC that we will be doing initializing writes to + // this object in the future without emitting card-marks, so + // GC may take any compensating steps. + // NOTE: Keep this code consistent with GraphKit::store_barrier. + + oop new_obj = thread->vm_result(); + if (new_obj == NULL) return; + + assert(Universe::heap()->can_elide_tlab_store_barriers(), + "compiler must check this first"); + // GC may decide to give back a safer copy of new_obj. + new_obj = Universe::heap()->new_store_pre_barrier(thread, new_obj); + thread->set_vm_result(new_obj); +} + +JRT_ENTRY(void, GraalRuntime::new_multi_array(JavaThread* thread, Klass* klass, int rank, jint* dims)) + assert(klass->is_klass(), "not a class"); + assert(rank >= 1, "rank must be nonzero"); + oop obj = ArrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK); + thread->set_vm_result(obj); +JRT_END + +JRT_ENTRY(void, GraalRuntime::dynamic_new_array(JavaThread* thread, oopDesc* element_mirror, jint length)) + oop obj = Reflection::reflect_new_array(element_mirror, length, CHECK); + thread->set_vm_result(obj); +JRT_END + +JRT_ENTRY(void, GraalRuntime::dynamic_new_instance(JavaThread* thread, oopDesc* type_mirror)) + instanceKlassHandle klass(THREAD, java_lang_Class::as_Klass(type_mirror)); + + if (klass == NULL) { + ResourceMark rm(THREAD); + THROW(vmSymbols::java_lang_InstantiationException()); + } + + // Create new instance (the receiver) + klass->check_valid_for_instantiation(false, CHECK); + + // Make sure klass gets initialized + klass->initialize(CHECK); + + oop obj = klass->allocate_instance(CHECK); + thread->set_vm_result(obj); +JRT_END + +extern void vm_exit(int code); + +// Enter this method from compiled code handler below. This is where we transition +// to VM mode. This is done as a helper routine so that the method called directly +// from compiled code does not have to transition to VM. This allows the entry +// method to see if the nmethod that we have just looked up a handler for has +// been deoptimized while we were in the vm. This simplifies the assembly code +// cpu directories. +// +// We are entering here from exception stub (via the entry method below) +// If there is a compiled exception handler in this method, we will continue there; +// otherwise we will unwind the stack and continue at the caller of top frame method +// Note: we enter in Java using a special JRT wrapper. This wrapper allows us to +// control the area where we can allow a safepoint. After we exit the safepoint area we can +// check to see if the handler we are going to return is now in a nmethod that has +// been deoptimized. If that is the case we return the deopt blob +// unpack_with_exception entry instead. This makes life for the exception blob easier +// because making that same check and diverting is painful from assembly language. +JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* thread, oopDesc* ex, address pc, nmethod*& nm)) + // Reset method handle flag. + thread->set_is_method_handle_return(false); + + Handle exception(thread, ex); + nm = CodeCache::find_nmethod(pc); + assert(nm != NULL, "this is not an nmethod"); + // Adjust the pc as needed/ + if (nm->is_deopt_pc(pc)) { + RegisterMap map(thread, false); + frame exception_frame = thread->last_frame().sender(&map); + // if the frame isn't deopted then pc must not correspond to the caller of last_frame + assert(exception_frame.is_deoptimized_frame(), "must be deopted"); + pc = exception_frame.pc(); + } +#ifdef ASSERT + assert(exception.not_null(), "NULL exceptions should be handled by throw_exception"); + assert(exception->is_oop(), "just checking"); + // Check that exception is a subclass of Throwable, otherwise we have a VerifyError + if (!(exception->is_a(SystemDictionary::Throwable_klass()))) { + if (ExitVMOnVerifyError) vm_exit(-1); + ShouldNotReachHere(); + } +#endif + + // Check the stack guard pages and reenable them if necessary and there is + // enough space on the stack to do so. Use fast exceptions only if the guard + // pages are enabled. + bool guard_pages_enabled = thread->stack_yellow_zone_enabled(); + if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack(); + + if (JvmtiExport::can_post_on_exceptions()) { + // To ensure correct notification of exception catches and throws + // we have to deoptimize here. If we attempted to notify the + // catches and throws during this exception lookup it's possible + // we could deoptimize on the way out of the VM and end back in + // the interpreter at the throw site. This would result in double + // notifications since the interpreter would also notify about + // these same catches and throws as it unwound the frame. + + RegisterMap reg_map(thread); + frame stub_frame = thread->last_frame(); + frame caller_frame = stub_frame.sender(®_map); + + // We don't really want to deoptimize the nmethod itself since we + // can actually continue in the exception handler ourselves but I + // don't see an easy way to have the desired effect. + Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint); + assert(caller_is_deopted(), "Must be deoptimized"); + + return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls(); + } + + // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions + if (guard_pages_enabled) { + address fast_continuation = nm->handler_for_exception_and_pc(exception, pc); + if (fast_continuation != NULL) { + // Set flag if return address is a method handle call site. + thread->set_is_method_handle_return(nm->is_method_handle_return(pc)); + return fast_continuation; + } + } + + // If the stack guard pages are enabled, check whether there is a handler in + // the current method. Otherwise (guard pages disabled), force an unwind and + // skip the exception cache update (i.e., just leave continuation==NULL). + address continuation = NULL; + if (guard_pages_enabled) { + + // New exception handling mechanism can support inlined methods + // with exception handlers since the mappings are from PC to PC + + // debugging support + // tracing + if (TraceExceptions) { + ttyLocker ttyl; + ResourceMark rm; + tty->print_cr("Exception <%s> (" INTPTR_FORMAT ") thrown in compiled method <%s> at PC " INTPTR_FORMAT " for thread " INTPTR_FORMAT "", + exception->print_value_string(), p2i((address)exception()), nm->method()->print_value_string(), p2i(pc), p2i(thread)); + } + // for AbortVMOnException flag + NOT_PRODUCT(Exceptions::debug_check_abort(exception)); + + // Clear out the exception oop and pc since looking up an + // exception handler can cause class loading, which might throw an + // exception and those fields are expected to be clear during + // normal bytecode execution. + thread->clear_exception_oop_and_pc(); + + continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false); + // If an exception was thrown during exception dispatch, the exception oop may have changed + thread->set_exception_oop(exception()); + thread->set_exception_pc(pc); + + // the exception cache is used only by non-implicit exceptions + if (continuation != NULL && !SharedRuntime::deopt_blob()->contains(continuation)) { + nm->add_handler_for_exception_and_pc(exception, pc, continuation); + } + } + + // Set flag if return address is a method handle call site. + thread->set_is_method_handle_return(nm->is_method_handle_return(pc)); + + if (TraceExceptions) { + ttyLocker ttyl; + ResourceMark rm; + tty->print_cr("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT " for exception thrown at PC " PTR_FORMAT, + p2i(thread), p2i(continuation), p2i(pc)); + } + + return continuation; +JRT_END + +// Enter this method from compiled code only if there is a Java exception handler +// in the method handling the exception. +// We are entering here from exception stub. We don't do a normal VM transition here. +// We do it in a helper. This is so we can check to see if the nmethod we have just +// searched for an exception handler has been deoptimized in the meantime. +address GraalRuntime::exception_handler_for_pc(JavaThread* thread) { + oop exception = thread->exception_oop(); + address pc = thread->exception_pc(); + // Still in Java mode + DEBUG_ONLY(ResetNoHandleMark rnhm); + nmethod* nm = NULL; + address continuation = NULL; + { + // Enter VM mode by calling the helper + ResetNoHandleMark rnhm; + continuation = exception_handler_for_pc_helper(thread, exception, pc, nm); + } + // Back in JAVA, use no oops DON'T safepoint + + // Now check to see if the nmethod we were called from is now deoptimized. + // If so we must return to the deopt blob and deoptimize the nmethod + if (nm != NULL && caller_is_deopted()) { + continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls(); + } + + assert(continuation != NULL, "no handler found"); + return continuation; +} + +JRT_ENTRY(void, GraalRuntime::create_null_exception(JavaThread* thread)) + SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_NullPointerException()); + thread->set_vm_result(PENDING_EXCEPTION); + CLEAR_PENDING_EXCEPTION; +JRT_END + +JRT_ENTRY(void, GraalRuntime::create_out_of_bounds_exception(JavaThread* thread, jint index)) + char message[jintAsStringSize]; + sprintf(message, "%d", index); + SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), message); + thread->set_vm_result(PENDING_EXCEPTION); + CLEAR_PENDING_EXCEPTION; +JRT_END + +JRT_ENTRY_NO_ASYNC(void, GraalRuntime::monitorenter(JavaThread* thread, oopDesc* obj, BasicLock* lock)) + if (TraceGraal >= 3) { + char type[O_BUFLEN]; + obj->klass()->name()->as_C_string(type, O_BUFLEN); + markOop mark = obj->mark(); + tty->print_cr("%s: entered locking slow case with obj=" INTPTR_FORMAT ", type=%s, mark=" INTPTR_FORMAT ", lock=" INTPTR_FORMAT, thread->name(), p2i(obj), type, p2i(mark), p2i(lock)); + tty->flush(); + } +#ifdef ASSERT + if (PrintBiasedLockingStatistics) { + Atomic::inc(BiasedLocking::slow_path_entry_count_addr()); + } +#endif + Handle h_obj(thread, obj); + assert(h_obj()->is_oop(), "must be NULL or an object"); + if (UseBiasedLocking) { + // Retry fast entry if bias is revoked to avoid unnecessary inflation + ObjectSynchronizer::fast_enter(h_obj, lock, true, CHECK); + } else { + if (GraalUseFastLocking) { + // When using fast locking, the compiled code has already tried the fast case + ObjectSynchronizer::slow_enter(h_obj, lock, THREAD); + } else { + ObjectSynchronizer::fast_enter(h_obj, lock, false, THREAD); + } + } + if (TraceGraal >= 3) { + tty->print_cr("%s: exiting locking slow with obj=" INTPTR_FORMAT, thread->name(), p2i(obj)); + } +JRT_END + +JRT_LEAF(void, GraalRuntime::monitorexit(JavaThread* thread, oopDesc* obj, BasicLock* lock)) + assert(thread == JavaThread::current(), "threads must correspond"); + assert(thread->last_Java_sp(), "last_Java_sp must be set"); + // monitorexit is non-blocking (leaf routine) => no exceptions can be thrown + EXCEPTION_MARK; + +#ifdef DEBUG + if (!obj->is_oop()) { + ResetNoHandleMark rhm; + nmethod* method = thread->last_frame().cb()->as_nmethod_or_null(); + if (method != NULL) { + tty->print_cr("ERROR in monitorexit in method %s wrong obj " INTPTR_FORMAT, method->name(), p2i(obj)); + } + thread->print_stack_on(tty); + assert(false, "invalid lock object pointer dected"); + } +#endif + + if (GraalUseFastLocking) { + // When using fast locking, the compiled code has already tried the fast case + ObjectSynchronizer::slow_exit(obj, lock, THREAD); + } else { + ObjectSynchronizer::fast_exit(obj, lock, THREAD); + } + if (TraceGraal >= 3) { + char type[O_BUFLEN]; + obj->klass()->name()->as_C_string(type, O_BUFLEN); + tty->print_cr("%s: exited locking slow case with obj=" INTPTR_FORMAT ", type=%s, mark=" INTPTR_FORMAT ", lock=" INTPTR_FORMAT, thread->name(), p2i(obj), type, p2i(obj->mark()), p2i(lock)); + tty->flush(); + } +JRT_END + +JRT_LEAF(void, GraalRuntime::log_object(JavaThread* thread, oopDesc* obj, jint flags)) + bool string = mask_bits_are_true(flags, LOG_OBJECT_STRING); + bool addr = mask_bits_are_true(flags, LOG_OBJECT_ADDRESS); + bool newline = mask_bits_are_true(flags, LOG_OBJECT_NEWLINE); + if (!string) { + if (!addr && obj->is_oop_or_null(true)) { + char buf[O_BUFLEN]; + tty->print("%s@" INTPTR_FORMAT, obj->klass()->name()->as_C_string(buf, O_BUFLEN), p2i(obj)); + } else { + tty->print(INTPTR_FORMAT, p2i(obj)); + } + } else { + ResourceMark rm; + assert(obj != NULL && java_lang_String::is_instance(obj), "must be"); + char *buf = java_lang_String::as_utf8_string(obj); + tty->print_raw(buf); + } + if (newline) { + tty->cr(); + } +JRT_END + +JRT_LEAF(void, GraalRuntime::write_barrier_pre(JavaThread* thread, oopDesc* obj)) + thread->satb_mark_queue().enqueue(obj); +JRT_END + +JRT_LEAF(void, GraalRuntime::write_barrier_post(JavaThread* thread, void* card_addr)) + thread->dirty_card_queue().enqueue(card_addr); +JRT_END + +JRT_LEAF(jboolean, GraalRuntime::validate_object(JavaThread* thread, oopDesc* parent, oopDesc* child)) + bool ret = true; + if(!Universe::heap()->is_in_closed_subset(parent)) { + tty->print_cr("Parent Object "INTPTR_FORMAT" not in heap", p2i(parent)); + parent->print(); + ret=false; + } + if(!Universe::heap()->is_in_closed_subset(child)) { + tty->print_cr("Child Object "INTPTR_FORMAT" not in heap", p2i(child)); + child->print(); + ret=false; + } + return (jint)ret; +JRT_END + +JRT_ENTRY(void, GraalRuntime::vm_error(JavaThread* thread, jlong where, jlong format, jlong value)) + ResourceMark rm; + const char *error_msg = where == 0L ? "" : (char*) (address) where; + char *detail_msg = NULL; + if (format != 0L) { + const char* buf = (char*) (address) format; + size_t detail_msg_length = strlen(buf) * 2; + detail_msg = (char *) NEW_RESOURCE_ARRAY(u_char, detail_msg_length); + jio_snprintf(detail_msg, detail_msg_length, buf, value); + } + report_vm_error(__FILE__, __LINE__, error_msg, detail_msg); +JRT_END + +JRT_LEAF(oopDesc*, GraalRuntime::load_and_clear_exception(JavaThread* thread)) + oop exception = thread->exception_oop(); + assert(exception != NULL, "npe"); + thread->set_exception_oop(NULL); + thread->set_exception_pc(0); + return exception; +JRT_END + +JRT_LEAF(void, GraalRuntime::log_printf(JavaThread* thread, oopDesc* format, jlong v1, jlong v2, jlong v3)) + ResourceMark rm; + assert(format != NULL && java_lang_String::is_instance(format), "must be"); + char *buf = java_lang_String::as_utf8_string(format); + tty->print(buf, v1, v2, v3); +JRT_END + +static void decipher(jlong v, bool ignoreZero) { + if (v != 0 || !ignoreZero) { + void* p = (void *)(address) v; + CodeBlob* cb = CodeCache::find_blob(p); + if (cb) { + if (cb->is_nmethod()) { + char buf[O_BUFLEN]; + tty->print("%s [" INTPTR_FORMAT "+" JLONG_FORMAT "]", cb->as_nmethod_or_null()->method()->name_and_sig_as_C_string(buf, O_BUFLEN), p2i(cb->code_begin()), (jlong)((address)v - cb->code_begin())); + return; + } + cb->print_value_on(tty); + return; + } + if (Universe::heap()->is_in(p)) { + oop obj = oop(p); + obj->print_value_on(tty); + return; + } + tty->print(INTPTR_FORMAT " [long: " JLONG_FORMAT ", double %lf, char %c]",p2i((void *)v), (jlong)v, (jdouble)v, (char)v); + } +} + +JRT_LEAF(void, GraalRuntime::vm_message(jboolean vmError, jlong format, jlong v1, jlong v2, jlong v3)) + ResourceMark rm; + char *buf = (char*) (address) format; + if (vmError) { + if (buf != NULL) { + fatal(err_msg(buf, v1, v2, v3)); + } else { + fatal(""); + } + } else if (buf != NULL) { + tty->print(buf, v1, v2, v3); + } else { + assert(v2 == 0, "v2 != 0"); + assert(v3 == 0, "v3 != 0"); + decipher(v1, false); + } +JRT_END + +JRT_LEAF(void, GraalRuntime::log_primitive(JavaThread* thread, jchar typeChar, jlong value, jboolean newline)) + union { + jlong l; + jdouble d; + jfloat f; + } uu; + uu.l = value; + switch (typeChar) { + case 'z': tty->print(value == 0 ? "false" : "true"); break; + case 'b': tty->print("%d", (jbyte) value); break; + case 'c': tty->print("%c", (jchar) value); break; + case 's': tty->print("%d", (jshort) value); break; + case 'i': tty->print("%d", (jint) value); break; + case 'f': tty->print("%f", uu.f); break; + case 'j': tty->print(JLONG_FORMAT, value); break; + case 'd': tty->print("%lf", uu.d); break; + default: assert(false, "unknown typeChar"); break; + } + if (newline) { + tty->cr(); + } +JRT_END + +JRT_ENTRY(jint, GraalRuntime::identity_hash_code(JavaThread* thread, oopDesc* obj)) + return (jint) obj->identity_hash(); +JRT_END + +JRT_ENTRY(jboolean, GraalRuntime::thread_is_interrupted(JavaThread* thread, oopDesc* receiver, jboolean clear_interrupted)) + // Ensure that the C++ Thread and OSThread structures aren't freed before we operate + Handle receiverHandle(thread, receiver); + MutexLockerEx ml(thread->threadObj() == (void*)receiver ? NULL : Threads_lock); + JavaThread* receiverThread = java_lang_Thread::thread(receiverHandle()); + if (receiverThread == NULL) { + // The other thread may exit during this process, which is ok so return false. + return JNI_FALSE; + } else { + return (jint) Thread::is_interrupted(receiverThread, clear_interrupted != 0); + } +JRT_END + +JRT_ENTRY(jint, GraalRuntime::test_deoptimize_call_int(JavaThread* thread, int value)) + deopt_caller(); + return value; +JRT_END + +// private static void Factory.init() +JVM_ENTRY(void, JVM_InitGraalClassLoader(JNIEnv *env, jclass c, jobject loader_handle)) + SystemDictionary::init_graal_loader(JNIHandles::resolve(loader_handle)); + SystemDictionary::WKID scan = SystemDictionary::FIRST_GRAAL_WKID; + SystemDictionary::initialize_wk_klasses_through(SystemDictionary::LAST_GRAAL_WKID, scan, CHECK); +JVM_END + +// private static GraalRuntime Graal.initializeRuntime() +JVM_ENTRY(jobject, JVM_GetGraalRuntime(JNIEnv *env, jclass c)) + GraalRuntime::initialize_HotSpotGraalRuntime(); + return GraalRuntime::get_HotSpotGraalRuntime_jobject(); +JVM_END + +// private static String[] Services.getServiceImpls(Class service) +JVM_ENTRY(jobject, JVM_GetGraalServiceImpls(JNIEnv *env, jclass c, jclass serviceClass)) + HandleMark hm; + ResourceMark rm; + KlassHandle serviceKlass(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(serviceClass))); + return JNIHandles::make_local(THREAD, GraalRuntime::get_service_impls(serviceKlass, THREAD)()); +JVM_END + +// private static TruffleRuntime Truffle.createRuntime() +JVM_ENTRY(jobject, JVM_CreateTruffleRuntime(JNIEnv *env, jclass c)) + GraalRuntime::ensure_graal_class_loader_is_initialized(); + TempNewSymbol name = SymbolTable::new_symbol("com/oracle/graal/truffle/hotspot/HotSpotTruffleRuntime", CHECK_NULL); + KlassHandle klass = GraalRuntime::resolve_or_fail(name, CHECK_NULL); + + TempNewSymbol makeInstance = SymbolTable::new_symbol("makeInstance", CHECK_NULL); + TempNewSymbol sig = SymbolTable::new_symbol("()Lcom/oracle/truffle/api/TruffleRuntime;", CHECK_NULL); + JavaValue result(T_OBJECT); + JavaCalls::call_static(&result, klass, makeInstance, sig, CHECK_NULL); + return JNIHandles::make_local(THREAD, (oop) result.get_jobject()); +JVM_END + +// private static NativeFunctionInterfaceRuntime.createInterface() +JVM_ENTRY(jobject, JVM_CreateNativeFunctionInterface(JNIEnv *env, jclass c)) + GraalRuntime::ensure_graal_class_loader_is_initialized(); + TempNewSymbol name = SymbolTable::new_symbol("com/oracle/graal/truffle/hotspot/HotSpotTruffleRuntime", CHECK_NULL); + KlassHandle klass = GraalRuntime::resolve_or_fail(name, CHECK_NULL); + + TempNewSymbol makeInstance = SymbolTable::new_symbol("createNativeFunctionInterface", CHECK_NULL); + TempNewSymbol sig = SymbolTable::new_symbol("()Lcom/oracle/nfi/api/NativeFunctionInterface;", CHECK_NULL); + JavaValue result(T_OBJECT); + JavaCalls::call_static(&result, klass, makeInstance, sig, CHECK_NULL); + return JNIHandles::make_local(THREAD, (oop) result.get_jobject()); +JVM_END + +void GraalRuntime::check_generated_sources_sha1(TRAPS) { + TempNewSymbol name = SymbolTable::new_symbol("com/oracle/graal/hotspot/sourcegen/GeneratedSourcesSha1", CHECK_ABORT); + KlassHandle klass = load_required_class(name); + fieldDescriptor fd; + if (!InstanceKlass::cast(klass())->find_field(vmSymbols::value_name(), vmSymbols::string_signature(), true, &fd)) { + THROW_MSG(vmSymbols::java_lang_NoSuchFieldError(), "GeneratedSourcesSha1.value"); + } + + Symbol* value = java_lang_String::as_symbol(klass->java_mirror()->obj_field(fd.offset()), CHECK); + if (!value->equals(_generated_sources_sha1)) { + char buf[200]; + jio_snprintf(buf, sizeof(buf), "Generated sources SHA1 check failed (%s != %s) - need to rebuild the VM", value->as_C_string(), _generated_sources_sha1); + THROW_MSG(vmSymbols::java_lang_InternalError(), buf); + } +} + +Handle GraalRuntime::callInitializer(const char* className, const char* methodName, const char* returnType) { + guarantee(!_HotSpotGraalRuntime_initialized, "cannot reinitialize HotSpotGraalRuntime"); + Thread* THREAD = Thread::current(); + check_generated_sources_sha1(CHECK_ABORT_(Handle())); + + TempNewSymbol name = SymbolTable::new_symbol(className, CHECK_ABORT_(Handle())); + KlassHandle klass = load_required_class(name); + TempNewSymbol runtime = SymbolTable::new_symbol(methodName, CHECK_ABORT_(Handle())); + TempNewSymbol sig = SymbolTable::new_symbol(returnType, CHECK_ABORT_(Handle())); + JavaValue result(T_OBJECT); + JavaCalls::call_static(&result, klass, runtime, sig, CHECK_ABORT_(Handle())); + return Handle((oop)result.get_jobject()); +} + +void GraalRuntime::initialize_HotSpotGraalRuntime() { + if (JNIHandles::resolve(_HotSpotGraalRuntime_instance) == NULL) { +#ifdef ASSERT + // This should only be called in the context of the Graal class being initialized + Thread* THREAD = Thread::current(); + TempNewSymbol name = SymbolTable::new_symbol("com/oracle/graal/api/runtime/Graal", CHECK_ABORT); + instanceKlassHandle klass = InstanceKlass::cast(load_required_class(name)); + assert(klass->is_being_initialized() && klass->is_reentrant_initialization(THREAD), + "HotSpotGraalRuntime initialization should only be triggered through Graal initialization"); +#endif + + Handle result = callInitializer("com/oracle/graal/hotspot/HotSpotGraalRuntime", "runtime", + "()Lcom/oracle/graal/hotspot/HotSpotGraalRuntime;"); + _HotSpotGraalRuntime_initialized = true; + _HotSpotGraalRuntime_instance = JNIHandles::make_global(result()); + } +} + +void GraalRuntime::initialize_Graal() { + if (JNIHandles::resolve(_HotSpotGraalRuntime_instance) == NULL) { + callInitializer("com/oracle/graal/api/runtime/Graal", "getRuntime", "()Lcom/oracle/graal/api/runtime/GraalRuntime;"); + } + assert(_HotSpotGraalRuntime_initialized == true, "what?"); +} + +// private static void CompilerToVMImpl.init() +JVM_ENTRY(void, JVM_InitializeGraalNatives(JNIEnv *env, jclass c2vmClass)) + GraalRuntime::initialize_natives(env, c2vmClass); +JVM_END + +// private static boolean HotSpotOptions.parseVMOptions() +JVM_ENTRY(jboolean, JVM_ParseGraalOptions(JNIEnv *env, jclass c)) + HandleMark hm; + KlassHandle hotSpotOptionsClass(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(c))); + bool result = GraalRuntime::parse_arguments(hotSpotOptionsClass, CHECK_false); + return result; +JVM_END + + +void GraalRuntime::ensure_graal_class_loader_is_initialized() { + // This initialization code is guarded by a static pointer to the Factory class. + // Once it is non-null, the Graal class loader and well known Graal classes are + // guaranteed to have been initialized. By going through the static + // initializer of Factory, we can rely on class initialization semantics to + // synchronize threads racing to do the initialization. + static Klass* _FactoryKlass = NULL; + if (_FactoryKlass == NULL) { + Thread* THREAD = Thread::current(); + TempNewSymbol name = SymbolTable::new_symbol("com/oracle/graal/hotspot/loader/Factory", CHECK_ABORT); + KlassHandle klass = SystemDictionary::resolve_or_fail(name, true, THREAD); + if (HAS_PENDING_EXCEPTION) { + static volatile int seen_error = 0; + if (!seen_error && Atomic::cmpxchg(1, &seen_error, 0) == 0) { + // Only report the failure on the first thread that hits it + abort_on_pending_exception(PENDING_EXCEPTION, "Graal classes are not available"); + } else { + CLEAR_PENDING_EXCEPTION; + // Give first thread time to report the error. + os::sleep(THREAD, 100, false); + vm_abort(false); + } + } + + // We cannot use graalJavaAccess for this because we are currently in the + // process of initializing that mechanism. + TempNewSymbol field_name = SymbolTable::new_symbol("useGraalClassLoader", CHECK_ABORT); + fieldDescriptor field_desc; + if (klass->find_field(field_name, vmSymbols::bool_signature(), &field_desc) == NULL) { + ResourceMark rm; + fatal(err_msg("Invalid layout of %s at %s", field_name->as_C_string(), klass->external_name())); + } + + InstanceKlass* ik = InstanceKlass::cast(klass()); + address addr = ik->static_field_addr(field_desc.offset() - InstanceMirrorKlass::offset_of_static_fields()); + *((jboolean *) addr) = (jboolean) UseGraalClassLoader; + klass->initialize(CHECK_ABORT); + _FactoryKlass = klass(); + } +} + +jint GraalRuntime::check_arguments(TRAPS) { + KlassHandle nullHandle; + parse_arguments(nullHandle, THREAD); + if (HAS_PENDING_EXCEPTION) { + // Errors in parsing Graal arguments cause exceptions. + // We now load and initialize HotSpotOptions which in turn + // causes argument parsing to be redone with better error messages. + CLEAR_PENDING_EXCEPTION; + TempNewSymbol name = SymbolTable::new_symbol("Lcom/oracle/graal/hotspot/HotSpotOptions;", CHECK_ABORT_(JNI_ERR)); + instanceKlassHandle hotSpotOptionsClass = resolve_or_fail(name, CHECK_ABORT_(JNI_ERR)); + + parse_arguments(hotSpotOptionsClass, THREAD); + assert(HAS_PENDING_EXCEPTION, "must be"); + + ResourceMark rm; + Handle exception = PENDING_EXCEPTION; + CLEAR_PENDING_EXCEPTION; + oop message = java_lang_Throwable::message(exception); + if (message != NULL) { + tty->print_cr("Error parsing Graal options: %s", java_lang_String::as_utf8_string(message)); + } else { + call_printStackTrace(exception, THREAD); + } + return JNI_ERR; + } + return JNI_OK; +} + +bool GraalRuntime::parse_arguments(KlassHandle hotSpotOptionsClass, TRAPS) { + ResourceMark rm(THREAD); + + // Process option overrides from graal.options first + parse_graal_options_file(hotSpotOptionsClass, CHECK_false); + + // Now process options on the command line + int numOptions = Arguments::num_graal_args(); + for (int i = 0; i < numOptions; i++) { + char* arg = Arguments::graal_args_array()[i]; + parse_argument(hotSpotOptionsClass, arg, CHECK_false); + } + return CITime || CITimeEach; +} + +void GraalRuntime::check_required_value(const char* name, size_t name_len, const char* value, TRAPS) { + if (value == NULL) { + char buf[200]; + jio_snprintf(buf, sizeof(buf), "Must use '-G:%.*s=' format for %.*s option", name_len, name, name_len, name); + THROW_MSG(vmSymbols::java_lang_InternalError(), buf); + } +} + +void GraalRuntime::parse_argument(KlassHandle hotSpotOptionsClass, char* arg, TRAPS) { + ensure_graal_class_loader_is_initialized(); + char first = arg[0]; + char* name; + size_t name_len; + bool recognized = true; + if (first == '+' || first == '-') { + name = arg + 1; + name_len = strlen(name); + recognized = set_option_bool(hotSpotOptionsClass, name, name_len, first, CHECK); + } else { + char* sep = strchr(arg, '='); + name = arg; + char* value = NULL; + if (sep != NULL) { + name_len = sep - name; + value = sep + 1; + } else { + name_len = strlen(name); + } + recognized = set_option(hotSpotOptionsClass, name, name_len, value, CHECK); + } + + if (!recognized) { + bool throw_err = hotSpotOptionsClass.is_null(); + if (!hotSpotOptionsClass.is_null()) { + set_option_helper(hotSpotOptionsClass, name, name_len, Handle(), ' ', Handle(), 0L); + if (!HAS_PENDING_EXCEPTION) { + throw_err = true; + } + } + + if (throw_err) { + char buf[200]; + jio_snprintf(buf, sizeof(buf), "Unrecognized Graal option %.*s", name_len, name); + THROW_MSG(vmSymbols::java_lang_InternalError(), buf); + } + } +} + +void GraalRuntime::parse_graal_options_file(KlassHandle hotSpotOptionsClass, TRAPS) { + const char* home = Arguments::get_java_home(); + size_t path_len = strlen(home) + strlen("/lib/graal.options") + 1; + char* path = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, path_len); + char sep = os::file_separator()[0]; + sprintf(path, "%s%clib%cgraal.options", home, sep, sep); + + struct stat st; + if (os::stat(path, &st) == 0) { + int file_handle = os::open(path, 0, 0); + if (file_handle != -1) { + char* buffer = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, st.st_size); + int num_read = (int) os::read(file_handle, (char*) buffer, st.st_size); + if (num_read == -1) { + warning("Error reading file %s due to %s", path, strerror(errno)); + } else if (num_read != st.st_size) { + warning("Only read %d of " SIZE_FORMAT " bytes from %s", num_read, (size_t) st.st_size, path); + } + os::close(file_handle); + if (num_read == st.st_size) { + char* line = buffer; + int lineNo = 1; + while (line - buffer < num_read) { + char* nl = strchr(line, '\n'); + if (nl != NULL) { + *nl = '\0'; + } + parse_argument(hotSpotOptionsClass, line, THREAD); + if (HAS_PENDING_EXCEPTION) { + warning("Error in %s:%d", path, lineNo); + return; + } + if (nl != NULL) { + line = nl + 1; + lineNo++; + } else { + // File without newline at the end + break; + } + } + } + } else { + warning("Error opening file %s due to %s", path, strerror(errno)); + } + } +} + +jlong GraalRuntime::parse_primitive_option_value(char spec, const char* name, size_t name_len, const char* value, TRAPS) { + check_required_value(name, name_len, value, CHECK_(0L)); + union { + jint i; + jlong l; + double d; + } uu; + uu.l = 0L; + char dummy; + switch (spec) { + case 'd': + case 'f': { + if (sscanf(value, "%lf%c", &uu.d, &dummy) == 1) { + return uu.l; + } + break; + } + case 'i': { + if (sscanf(value, "%d%c", &uu.i, &dummy) == 1) { + return (jlong)uu.i; + } + break; + } + default: + ShouldNotReachHere(); + } + ResourceMark rm(THREAD); + char buf[200]; + bool missing = strlen(value) == 0; + if (missing) { + jio_snprintf(buf, sizeof(buf), "Missing %s value for Graal option %.*s", (spec == 'i' ? "numeric" : "float/double"), name_len, name); + } else { + jio_snprintf(buf, sizeof(buf), "Invalid %s value for Graal option %.*s: %s", (spec == 'i' ? "numeric" : "float/double"), name_len, name, value); + } + THROW_MSG_(vmSymbols::java_lang_InternalError(), buf, 0L); +} + +void GraalRuntime::set_option_helper(KlassHandle hotSpotOptionsClass, char* name, size_t name_len, Handle option, jchar spec, Handle stringValue, jlong primitiveValue) { + Thread* THREAD = Thread::current(); + Handle name_handle; + if (name != NULL) { + if (strlen(name) > name_len) { + // Temporarily replace '=' with NULL to create the Java string for the option name + char save = name[name_len]; + name[name_len] = '\0'; + name_handle = java_lang_String::create_from_str(name, THREAD); + name[name_len] = '='; + if (HAS_PENDING_EXCEPTION) { + return; + } + } else { + assert(strlen(name) == name_len, "must be"); + name_handle = java_lang_String::create_from_str(name, CHECK); + } + } + + TempNewSymbol setOption = SymbolTable::new_symbol("setOption", CHECK); + TempNewSymbol sig = SymbolTable::new_symbol("(Ljava/lang/String;Lcom/oracle/graal/options/OptionValue;CLjava/lang/String;J)V", CHECK); + JavaValue result(T_VOID); + JavaCallArguments args; + args.push_oop(name_handle()); + args.push_oop(option()); + args.push_int(spec); + args.push_oop(stringValue()); + args.push_long(primitiveValue); + JavaCalls::call_static(&result, hotSpotOptionsClass, setOption, sig, &args, CHECK); +} + +Handle GraalRuntime::get_OptionValue(const char* declaringClass, const char* fieldName, const char* fieldSig, TRAPS) { + TempNewSymbol name = SymbolTable::new_symbol(declaringClass, CHECK_NH); + Klass* klass = resolve_or_fail(name, CHECK_NH); + + // The class has been loaded so the field and signature should already be in the symbol + // table. If they're not there, the field doesn't exist. + TempNewSymbol fieldname = SymbolTable::probe(fieldName, (int)strlen(fieldName)); + TempNewSymbol signame = SymbolTable::probe(fieldSig, (int)strlen(fieldSig)); + if (fieldname == NULL || signame == NULL) { + THROW_MSG_(vmSymbols::java_lang_NoSuchFieldError(), (char*) fieldName, Handle()); + } + // Make sure class is initialized before handing id's out to fields + klass->initialize(CHECK_NH); + + fieldDescriptor fd; + if (!InstanceKlass::cast(klass)->find_field(fieldname, signame, true, &fd)) { + THROW_MSG_(vmSymbols::java_lang_NoSuchFieldError(), (char*) fieldName, Handle()); + } + + Handle ret = klass->java_mirror()->obj_field(fd.offset()); + return ret; +} + +Handle GraalRuntime::create_Service(const char* name, TRAPS) { + TempNewSymbol kname = SymbolTable::new_symbol(name, CHECK_NH); + Klass* k = resolve_or_fail(kname, CHECK_NH); + instanceKlassHandle klass(THREAD, k); + klass->initialize(CHECK_NH); + klass->check_valid_for_instantiation(true, CHECK_NH); + JavaValue result(T_VOID); + instanceHandle service = klass->allocate_instance_handle(CHECK_NH); + JavaCalls::call_special(&result, service, klass, vmSymbols::object_initializer_name(), vmSymbols::void_method_signature(), THREAD); + return service; +} + +void GraalRuntime::shutdown() { + if (_HotSpotGraalRuntime_instance != NULL) { + _shutdown_called = true; + JavaThread* THREAD = JavaThread::current(); + HandleMark hm(THREAD); + TempNewSymbol name = SymbolTable::new_symbol("com/oracle/graal/hotspot/HotSpotGraalRuntime", CHECK_ABORT); + KlassHandle klass = load_required_class(name); + JavaValue result(T_VOID); + JavaCallArguments args; + args.push_oop(get_HotSpotGraalRuntime()); + JavaCalls::call_special(&result, klass, vmSymbols::shutdown_method_name(), vmSymbols::void_method_signature(), &args, CHECK_ABORT); + + JNIHandles::destroy_global(_HotSpotGraalRuntime_instance); + _HotSpotGraalRuntime_instance = NULL; + } +} + +void GraalRuntime::call_printStackTrace(Handle exception, Thread* thread) { + assert(exception->is_a(SystemDictionary::Throwable_klass()), "Throwable instance expected"); + JavaValue result(T_VOID); + JavaCalls::call_virtual(&result, + exception, + KlassHandle(thread, + SystemDictionary::Throwable_klass()), + vmSymbols::printStackTrace_name(), + vmSymbols::void_method_signature(), + thread); +} + +void GraalRuntime::abort_on_pending_exception(Handle exception, const char* message, bool dump_core) { + Thread* THREAD = Thread::current(); + CLEAR_PENDING_EXCEPTION; + tty->print_raw_cr(message); + call_printStackTrace(exception, THREAD); + + // Give other aborting threads to also print their stack traces. + // This can be very useful when debugging class initialization + // failures. + os::sleep(THREAD, 200, false); + + vm_abort(dump_core); +} + +Klass* GraalRuntime::resolve_or_null(Symbol* name, TRAPS) { + return SystemDictionary::resolve_or_null(name, SystemDictionary::graal_loader(), Handle(), CHECK_NULL); +} + +Klass* GraalRuntime::resolve_or_fail(Symbol* name, TRAPS) { + return SystemDictionary::resolve_or_fail(name, SystemDictionary::graal_loader(), Handle(), true, CHECK_NULL); +} + +Klass* GraalRuntime::load_required_class(Symbol* name) { + Klass* klass = resolve_or_null(name, Thread::current()); + if (klass == NULL) { + tty->print_cr("Could not load class %s", name->as_C_string()); + vm_abort(false); + } + return klass; +} + +Handle GraalRuntime::get_service_impls(KlassHandle serviceKlass, TRAPS) { + const char* home = Arguments::get_java_home(); + const char* serviceName = serviceKlass->external_name(); + size_t path_len = strlen(home) + strlen("/lib/graal/services/") + strlen(serviceName) + 1; + char* path = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, path_len); + char sep = os::file_separator()[0]; + sprintf(path, "%s%clib%cgraal%cservices%c%s", home, sep, sep, sep, sep, serviceName); + struct stat st; + if (os::stat(path, &st) == 0) { + int file_handle = os::open(path, 0, 0); + if (file_handle != -1) { + char* buffer = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, st.st_size + 1); + int num_read = (int) os::read(file_handle, (char*) buffer, st.st_size); + if (num_read == -1) { + warning("Error reading file %s due to %s", path, strerror(errno)); + } else if (num_read != st.st_size) { + warning("Only read %d of " SIZE_FORMAT " bytes from %s", num_read, (size_t) st.st_size, path); + } + os::close(file_handle); + if (num_read == st.st_size) { + buffer[num_read] = '\0'; + GrowableArray* implNames = new GrowableArray(); + char* line = buffer; + while (line - buffer < num_read) { + char* nl = strchr(line, '\n'); + if (nl != NULL) { + *nl = '\0'; + } + // Turn all '.'s into '/'s + for (size_t index = 0; line[index] != '\0'; index++) { + if (line[index] == '.') { + line[index] = '/'; + } + } + implNames->append(line); + if (nl != NULL) { + line = nl + 1; + } else { + // File without newline at the end + break; + } + } + + objArrayOop servicesOop = oopFactory::new_objArray(serviceKlass(), implNames->length(), CHECK_NH); + objArrayHandle services(THREAD, servicesOop); + for (int i = 0; i < implNames->length(); ++i) { + char* implName = implNames->at(i); + Handle service = create_Service(implName, CHECK_NH); + services->obj_at_put(i, service()); + } + return services; + } + } else { + warning("Error opening file %s due to %s", path, strerror(errno)); + } + } else { + warning("Error opening file %s due to %s", path, strerror(errno)); + } + return Handle(); +} + +#include "graalRuntime.inline.hpp" diff -r 41f99f9a8f63 -r eae62344f72c src/share/vm/memory/threadLocalAllocBuffer.cpp --- a/src/share/vm/memory/threadLocalAllocBuffer.cpp Mon Apr 20 22:42:05 2015 +0200 +++ b/src/share/vm/memory/threadLocalAllocBuffer.cpp Mon Apr 20 22:42:18 2015 +0200 @@ -44,7 +44,7 @@ _slow_refill_waste += (unsigned)remaining(); // In debug mode we expect the storage above top to be uninitialized // or filled with a padding object. - assert(top() == NULL || *(intptr_t*)top() != 0, "overzeroing detected"); + assert(!ZapUnusedHeapArea || top() == NULL || *(intptr_t*)top() != 0, "overzeroing detected"); make_parsable(true); // also retire the TLAB } diff -r 41f99f9a8f63 -r eae62344f72c src/share/vm/runtime/arguments.cpp --- a/src/share/vm/runtime/arguments.cpp Mon Apr 20 22:42:05 2015 +0200 +++ b/src/share/vm/runtime/arguments.cpp Mon Apr 20 22:42:18 2015 +0200 @@ -3621,10 +3621,28 @@ #ifdef GRAAL if (!UseGraalClassLoader) { - // Append graal.jar to boot class path - const char* home = Arguments::get_java_home(); - scp_p->add_suffix(os::format_boot_path("%/lib/graal.jar:%/lib/graal-truffle.jar", home, (int)strlen(home), os::file_separator()[0], os::path_separator()[0])); - scp_assembly_required = true; + // Append lib/graal/graal*.jar to boot class path + char graalDir[JVM_MAXPATHLEN]; + const char* fileSep = os::file_separator(); + jio_snprintf(graalDir, sizeof(graalDir), "%s%slib%sgraal", Arguments::get_java_home(), fileSep, fileSep); + DIR* dir = os::opendir(graalDir); + if (dir != NULL) { + struct dirent *entry; + char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(graalDir), mtInternal); + while ((entry = os::readdir(dir, (dirent *) dbuf)) != NULL) { + const char* name = entry->d_name; + const char* ext = name + strlen(name) - 4; + if (ext > name && strcmp(ext, ".jar") == 0 + && strlen(name) > strlen("graal") + && strncmp(name, "graal", strlen("graal")) == 0) { + char fileName[JVM_MAXPATHLEN]; + jio_snprintf(fileName, sizeof(fileName), "%s%s%s", graalDir, fileSep, name); + scp_p->add_suffix(fileName); + scp_assembly_required = true; + } + } + } + } #endif @@ -3654,7 +3672,7 @@ FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold); } -#ifndef COMPILER2 +#if !defined(COMPILER2) && !defined(COMPILERGRAAL) // Don't degrade server performance for footprint if (FLAG_IS_DEFAULT(UseLargePages) && MaxHeapSize < LargePageHeapSizeThreshold) { @@ -3664,7 +3682,7 @@ FLAG_SET_DEFAULT(UseLargePages, false); } -#else +#elif defined(COMPILER2) if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) { FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1); }