HotSpotGraalCompiler.java revision 12968:4d8a004e5c6d
1/*
2 * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23package org.graalvm.compiler.hotspot;
24
25import static org.graalvm.compiler.core.common.GraalOptions.OptAssumptions;
26import static org.graalvm.compiler.nodes.graphbuilderconf.IntrinsicContext.CompilationContext.ROOT_COMPILATION;
27import java.io.ByteArrayOutputStream;
28import java.io.PrintStream;
29import java.util.Formattable;
30import java.util.Formatter;
31
32import org.graalvm.compiler.api.runtime.GraalJVMCICompiler;
33import org.graalvm.compiler.code.CompilationResult;
34import org.graalvm.compiler.core.GraalCompiler;
35import org.graalvm.compiler.core.common.CompilationIdentifier;
36import org.graalvm.compiler.core.common.util.CompilationAlarm;
37import org.graalvm.compiler.debug.Debug;
38import org.graalvm.compiler.debug.DebugConfigScope;
39import org.graalvm.compiler.debug.DebugEnvironment;
40import org.graalvm.compiler.debug.GraalDebugConfig;
41import org.graalvm.compiler.debug.TTY;
42import org.graalvm.compiler.debug.TopLevelDebugConfig;
43import org.graalvm.compiler.debug.internal.method.MethodMetricsRootScopeInfo;
44import org.graalvm.compiler.hotspot.CompilationCounters.Options;
45import org.graalvm.compiler.hotspot.meta.HotSpotProviders;
46import org.graalvm.compiler.hotspot.phases.OnStackReplacementPhase;
47import org.graalvm.compiler.java.GraphBuilderPhase;
48import org.graalvm.compiler.lir.asm.CompilationResultBuilderFactory;
49import org.graalvm.compiler.lir.phases.LIRSuites;
50import org.graalvm.compiler.nodes.StructuredGraph;
51import org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions;
52import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration;
53import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration.Plugins;
54import org.graalvm.compiler.nodes.graphbuilderconf.IntrinsicContext;
55import org.graalvm.compiler.nodes.spi.Replacements;
56import org.graalvm.compiler.options.OptionValues;
57import org.graalvm.compiler.phases.OptimisticOptimizations;
58import org.graalvm.compiler.phases.OptimisticOptimizations.Optimization;
59import org.graalvm.compiler.phases.PhaseSuite;
60import org.graalvm.compiler.phases.tiers.HighTierContext;
61import org.graalvm.compiler.phases.tiers.Suites;
62
63import jdk.vm.ci.code.CompilationRequest;
64import jdk.vm.ci.code.CompilationRequestResult;
65import jdk.vm.ci.hotspot.HotSpotCodeCacheProvider;
66import jdk.vm.ci.hotspot.HotSpotCompilationRequest;
67import jdk.vm.ci.hotspot.HotSpotCompilationRequestResult;
68import jdk.vm.ci.hotspot.HotSpotJVMCIRuntimeProvider;
69import jdk.vm.ci.meta.DefaultProfilingInfo;
70import jdk.vm.ci.meta.JavaMethod;
71import jdk.vm.ci.meta.ProfilingInfo;
72import jdk.vm.ci.meta.ResolvedJavaMethod;
73import jdk.vm.ci.meta.SpeculationLog;
74import jdk.vm.ci.meta.TriState;
75import jdk.vm.ci.runtime.JVMCICompiler;
76
77public class HotSpotGraalCompiler implements GraalJVMCICompiler {
78
79    private final HotSpotJVMCIRuntimeProvider jvmciRuntime;
80    private final HotSpotGraalRuntimeProvider graalRuntime;
81    private final CompilationCounters compilationCounters;
82    private final BootstrapWatchDog bootstrapWatchDog;
83
84    HotSpotGraalCompiler(HotSpotJVMCIRuntimeProvider jvmciRuntime, HotSpotGraalRuntimeProvider graalRuntime) {
85        this.jvmciRuntime = jvmciRuntime;
86        this.graalRuntime = graalRuntime;
87        // It is sufficient to have one compilation counter object per Graal compiler object.
88        OptionValues options = graalRuntime.getOptions();
89        this.compilationCounters = Options.CompilationCountLimit.getValue(options) > 0 ? new CompilationCounters(options) : null;
90        this.bootstrapWatchDog = graalRuntime.isBootstrapping() && !GraalDebugConfig.Options.BootstrapInitializeOnly.getValue(options) ? BootstrapWatchDog.maybeCreate(graalRuntime) : null;
91    }
92
93    @Override
94    public HotSpotGraalRuntimeProvider getGraalRuntime() {
95        return graalRuntime;
96    }
97
98    @Override
99    @SuppressWarnings("try")
100    public CompilationRequestResult compileMethod(CompilationRequest request) {
101        OptionValues options = graalRuntime.getOptions();
102        if (graalRuntime.isBootstrapping()) {
103            if (GraalDebugConfig.Options.BootstrapInitializeOnly.getValue(options)) {
104                return HotSpotCompilationRequestResult.failure(String.format("Skip compilation because %s is enabled", GraalDebugConfig.Options.BootstrapInitializeOnly.getName()), true);
105            }
106            if (bootstrapWatchDog != null) {
107                if (bootstrapWatchDog.hitCriticalCompilationRateOrTimeout()) {
108                    // Drain the compilation queue to expedite completion of the bootstrap
109                    return HotSpotCompilationRequestResult.failure("hit critical bootstrap compilation rate or timeout", true);
110                }
111            }
112        }
113        ResolvedJavaMethod method = request.getMethod();
114        HotSpotCompilationRequest hsRequest = (HotSpotCompilationRequest) request;
115        try (CompilationWatchDog w1 = CompilationWatchDog.watch(method, hsRequest.getId(), options);
116                        BootstrapWatchDog.Watch w2 = bootstrapWatchDog == null ? null : bootstrapWatchDog.watch(request);
117                        CompilationAlarm alarm = CompilationAlarm.trackCompilationPeriod(options);) {
118            if (compilationCounters != null) {
119                compilationCounters.countCompilation(method);
120            }
121            // Ensure a debug configuration for this thread is initialized
122            DebugEnvironment.ensureInitialized(options, graalRuntime.getHostProviders().getSnippetReflection());
123            CompilationTask task = new CompilationTask(jvmciRuntime, this, hsRequest, true, true, options);
124            CompilationRequestResult r = null;
125            try (DebugConfigScope dcs = Debug.setConfig(new TopLevelDebugConfig());
126                            Debug.Scope s = Debug.methodMetricsScope("HotSpotGraalCompiler", MethodMetricsRootScopeInfo.create(method), true, method)) {
127                r = task.runCompilation();
128            }
129            assert r != null;
130            return r;
131        }
132    }
133
134    public void compileTheWorld() throws Throwable {
135        HotSpotCodeCacheProvider codeCache = (HotSpotCodeCacheProvider) jvmciRuntime.getHostJVMCIBackend().getCodeCache();
136        int iterations = CompileTheWorldOptions.CompileTheWorldIterations.getValue(graalRuntime.getOptions());
137        for (int i = 0; i < iterations; i++) {
138            codeCache.resetCompilationStatistics();
139            TTY.println("CompileTheWorld : iteration " + i);
140            this.graalRuntime.getVMConfig();
141            CompileTheWorld ctw = new CompileTheWorld(jvmciRuntime, this, graalRuntime.getOptions());
142            ctw.compile();
143        }
144        System.exit(0);
145    }
146
147    public CompilationResult compile(ResolvedJavaMethod method, int entryBCI, boolean useProfilingInfo, CompilationIdentifier compilationId, OptionValues options) {
148        HotSpotBackend backend = graalRuntime.getHostBackend();
149        HotSpotProviders providers = backend.getProviders();
150        final boolean isOSR = entryBCI != JVMCICompiler.INVOCATION_ENTRY_BCI;
151        StructuredGraph graph = method.isNative() || isOSR ? null : getIntrinsicGraph(method, providers, compilationId, options);
152
153        if (graph == null) {
154            SpeculationLog speculationLog = method.getSpeculationLog();
155            if (speculationLog != null) {
156                speculationLog.collectFailedSpeculations();
157            }
158            graph = new StructuredGraph.Builder(options, AllowAssumptions.ifTrue(OptAssumptions.getValue(options))).method(method).entryBCI(entryBCI).speculationLog(
159                            speculationLog).useProfilingInfo(useProfilingInfo).compilationId(compilationId).build();
160        }
161
162        Suites suites = getSuites(providers, options);
163        LIRSuites lirSuites = getLIRSuites(providers, options);
164        ProfilingInfo profilingInfo = useProfilingInfo ? method.getProfilingInfo(!isOSR, isOSR) : DefaultProfilingInfo.get(TriState.FALSE);
165        OptimisticOptimizations optimisticOpts = getOptimisticOpts(profilingInfo, options);
166
167        /*
168         * Cut off never executed code profiles if there is code, e.g. after the osr loop, that is
169         * never executed.
170         */
171        if (isOSR && !OnStackReplacementPhase.Options.DeoptAfterOSR.getValue(options)) {
172            optimisticOpts.remove(Optimization.RemoveNeverExecutedCode);
173        }
174        CompilationResult result = new CompilationResult();
175        result.setEntryBCI(entryBCI);
176        boolean shouldDebugNonSafepoints = providers.getCodeCache().shouldDebugNonSafepoints();
177        PhaseSuite<HighTierContext> graphBuilderSuite = configGraphBuilderSuite(providers.getSuites().getDefaultGraphBuilderSuite(), shouldDebugNonSafepoints, isOSR);
178        GraalCompiler.compileGraph(graph, method, providers, backend, graphBuilderSuite, optimisticOpts, profilingInfo, suites, lirSuites, result, CompilationResultBuilderFactory.Default);
179
180        if (!isOSR && useProfilingInfo) {
181            ProfilingInfo profile = profilingInfo;
182            profile.setCompilerIRSize(StructuredGraph.class, graph.getNodeCount());
183        }
184
185        return result;
186    }
187
188    /**
189     * Gets a graph produced from the intrinsic for a given method that can be compiled and
190     * installed for the method.
191     *
192     * @param method
193     * @param compilationId
194     * @param options
195     * @return an intrinsic graph that can be compiled and installed for {@code method} or null
196     */
197    @SuppressWarnings("try")
198    public StructuredGraph getIntrinsicGraph(ResolvedJavaMethod method, HotSpotProviders providers, CompilationIdentifier compilationId, OptionValues options) {
199        Replacements replacements = providers.getReplacements();
200        ResolvedJavaMethod substMethod = replacements.getSubstitutionMethod(method);
201        if (substMethod != null) {
202            assert !substMethod.equals(method);
203            StructuredGraph graph = new StructuredGraph.Builder(options, AllowAssumptions.YES).method(substMethod).compilationId(compilationId).build();
204            try (Debug.Scope scope = Debug.scope("GetIntrinsicGraph", graph)) {
205                Plugins plugins = new Plugins(providers.getGraphBuilderPlugins());
206                GraphBuilderConfiguration config = GraphBuilderConfiguration.getSnippetDefault(plugins);
207                IntrinsicContext initialReplacementContext = new IntrinsicContext(method, substMethod, replacements.getReplacementBytecodeProvider(), ROOT_COMPILATION);
208                new GraphBuilderPhase.Instance(providers.getMetaAccess(), providers.getStampProvider(), providers.getConstantReflection(), providers.getConstantFieldProvider(), config,
209                                OptimisticOptimizations.NONE, initialReplacementContext).apply(graph);
210                assert !graph.isFrozen();
211                return graph;
212            } catch (Throwable e) {
213                Debug.handle(e);
214            }
215        }
216        return null;
217    }
218
219    protected OptimisticOptimizations getOptimisticOpts(ProfilingInfo profilingInfo, OptionValues options) {
220        return new OptimisticOptimizations(profilingInfo, options);
221    }
222
223    protected Suites getSuites(HotSpotProviders providers, OptionValues options) {
224        return providers.getSuites().getDefaultSuites(options);
225    }
226
227    protected LIRSuites getLIRSuites(HotSpotProviders providers, OptionValues options) {
228        return providers.getSuites().getDefaultLIRSuites(options);
229    }
230
231    /**
232     * Reconfigures a given graph builder suite (GBS) if one of the given GBS parameter values is
233     * not the default.
234     *
235     * @param suite the graph builder suite
236     * @param shouldDebugNonSafepoints specifies if extra debug info should be generated (default is
237     *            false)
238     * @param isOSR specifies if extra OSR-specific post-processing is required (default is false)
239     * @return a new suite derived from {@code suite} if any of the GBS parameters did not have a
240     *         default value otherwise {@code suite}
241     */
242    protected PhaseSuite<HighTierContext> configGraphBuilderSuite(PhaseSuite<HighTierContext> suite, boolean shouldDebugNonSafepoints, boolean isOSR) {
243        if (shouldDebugNonSafepoints || isOSR) {
244            PhaseSuite<HighTierContext> newGbs = suite.copy();
245
246            if (shouldDebugNonSafepoints) {
247                GraphBuilderPhase graphBuilderPhase = (GraphBuilderPhase) newGbs.findPhase(GraphBuilderPhase.class).previous();
248                GraphBuilderConfiguration graphBuilderConfig = graphBuilderPhase.getGraphBuilderConfig();
249                graphBuilderConfig = graphBuilderConfig.withNodeSourcePosition(true);
250                GraphBuilderPhase newGraphBuilderPhase = new GraphBuilderPhase(graphBuilderConfig);
251                newGbs.findPhase(GraphBuilderPhase.class).set(newGraphBuilderPhase);
252            }
253            if (isOSR) {
254                // We must not clear non liveness for OSR compilations.
255                GraphBuilderPhase graphBuilderPhase = (GraphBuilderPhase) newGbs.findPhase(GraphBuilderPhase.class).previous();
256                GraphBuilderConfiguration graphBuilderConfig = graphBuilderPhase.getGraphBuilderConfig();
257                GraphBuilderPhase newGraphBuilderPhase = new GraphBuilderPhase(graphBuilderConfig);
258                newGbs.findPhase(GraphBuilderPhase.class).set(newGraphBuilderPhase);
259                newGbs.appendPhase(new OnStackReplacementPhase());
260            }
261            return newGbs;
262        }
263        return suite;
264    }
265
266    /**
267     * Converts {@code method} to a String with {@link JavaMethod#format(String)} and the format
268     * string {@code "%H.%n(%p)"}.
269     */
270    static String str(JavaMethod method) {
271        return method.format("%H.%n(%p)");
272    }
273
274    /**
275     * Wraps {@code obj} in a {@link Formatter} that standardizes formatting for certain objects.
276     */
277    static Formattable fmt(Object obj) {
278        return new Formattable() {
279            @Override
280            public void formatTo(Formatter buf, int flags, int width, int precision) {
281                if (obj instanceof Throwable) {
282                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
283                    ((Throwable) obj).printStackTrace(new PrintStream(baos));
284                    buf.format("%s", baos.toString());
285                } else if (obj instanceof StackTraceElement[]) {
286                    for (StackTraceElement e : (StackTraceElement[]) obj) {
287                        buf.format("\t%s%n", e);
288                    }
289                } else if (obj instanceof JavaMethod) {
290                    buf.format("%s", str((JavaMethod) obj));
291                } else {
292                    buf.format("%s", obj);
293                }
294            }
295        };
296    }
297}
298