1 /*
   2  * Copyright (c) 2011, 2018, 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  */
  23 
  24 
  25 package org.graalvm.compiler.printer;
  26 
  27 import static org.graalvm.compiler.debug.DebugConfig.asJavaMethod;
  28 
  29 import java.io.IOException;
  30 import java.nio.channels.ClosedByInterruptException;
  31 import java.util.ArrayList;
  32 import java.util.Arrays;
  33 import java.util.Collections;
  34 import java.util.Date;
  35 import java.util.HashMap;
  36 import java.util.List;
  37 import java.util.Map;
  38 import java.util.WeakHashMap;
  39 
  40 import org.graalvm.compiler.debug.DebugContext;
  41 import org.graalvm.compiler.debug.DebugDumpHandler;
  42 import org.graalvm.compiler.debug.DebugDumpScope;
  43 import org.graalvm.compiler.debug.DebugOptions;
  44 import org.graalvm.compiler.debug.GraalError;
  45 import org.graalvm.compiler.debug.TTY;
  46 import org.graalvm.compiler.debug.DebugOptions.PrintGraphTarget;
  47 import org.graalvm.compiler.graph.Graph;
  48 import org.graalvm.compiler.nodes.StructuredGraph;
  49 import org.graalvm.compiler.options.OptionValues;
  50 import org.graalvm.compiler.phases.contract.NodeCostUtil;
  51 import org.graalvm.compiler.serviceprovider.GraalServices;
  52 
  53 import jdk.vm.ci.meta.JavaMethod;
  54 import jdk.vm.ci.meta.ResolvedJavaMethod;
  55 
  56 //JaCoCo Exclude
  57 
  58 /**
  59  * Observes compilation events and uses {@link BinaryGraphPrinter} to generate a graph
  60  * representation that can be inspected with the Graph Visualizer.
  61  */
  62 public class GraphPrinterDumpHandler implements DebugDumpHandler {
  63 
  64     private static final int FAILURE_LIMIT = 8;
  65     private final GraphPrinterSupplier printerSupplier;
  66     protected GraphPrinter printer;
  67     private List<String> previousInlineContext;
  68     private int[] dumpIds = {};
  69     private int failuresCount;
  70     private Map<Graph, List<String>> inlineContextMap;
  71     private final String jvmArguments;
  72     private final String sunJavaCommand;
  73 
  74     @FunctionalInterface
  75     public interface GraphPrinterSupplier {
  76         GraphPrinter get(DebugContext ctx, Graph graph) throws IOException;
  77     }
  78 
  79     /**
  80      * Creates a new {@link GraphPrinterDumpHandler}.
  81      *
  82      * @param printerSupplier Supplier used to create the GraphPrinter. Should supply an optional or
  83      *            null in case of failure.
  84      */
  85     public GraphPrinterDumpHandler(GraphPrinterSupplier printerSupplier) {
  86         this.printerSupplier = printerSupplier;
  87         /* Add the JVM and Java arguments to the graph properties to help identify it. */
  88         this.jvmArguments = jvmArguments();
  89         this.sunJavaCommand = System.getProperty("sun.java.command");
  90     }
  91 
  92     private static String jvmArguments() {
  93         List<String> inputArguments = GraalServices.getInputArguments();
  94         if (inputArguments != null) {
  95             return String.join(" ", inputArguments);
  96         }
  97         return "unknown";
  98     }
  99 
 100     private void ensureInitialized(DebugContext ctx, Graph graph) {
 101         if (printer == null) {
 102             if (failuresCount >= FAILURE_LIMIT) {
 103                 return;
 104             }
 105             previousInlineContext = new ArrayList<>();
 106             inlineContextMap = new WeakHashMap<>();
 107             DebugContext debug = graph.getDebug();
 108             try {
 109                 printer = printerSupplier.get(ctx, graph);
 110             } catch (IOException e) {
 111                 handleException(debug, e);
 112             }
 113         }
 114     }
 115 
 116     private int nextDumpId() {
 117         int depth = previousInlineContext.size();
 118         if (dumpIds.length < depth) {
 119             dumpIds = Arrays.copyOf(dumpIds, depth);
 120         }
 121         return dumpIds[depth - 1]++;
 122     }
 123 
 124     @Override
 125     @SuppressWarnings("try")
 126     public void dump(DebugContext debug, Object object, final String format, Object... arguments) {
 127         OptionValues options = debug.getOptions();
 128         if (object instanceof Graph && DebugOptions.PrintGraph.getValue(options) != PrintGraphTarget.Disable) {
 129             final Graph graph = (Graph) object;
 130             ensureInitialized(debug, graph);
 131             if (printer == null) {
 132                 return;
 133             }
 134 
 135             // Get all current JavaMethod instances in the context.
 136             List<String> inlineContext = getInlineContext(graph);
 137 
 138             if (inlineContext != previousInlineContext) {
 139                 Map<Object, Object> properties = new HashMap<>();
 140                 properties.put("graph", graph.toString());
 141                 addCompilationId(properties, graph);
 142                 if (inlineContext.equals(previousInlineContext)) {
 143                     /*
 144                      * two different graphs have the same inline context, so make sure they appear
 145                      * in different folders by closing and reopening the top scope.
 146                      */
 147                     int inlineDepth = previousInlineContext.size() - 1;
 148                     closeScope(debug, inlineDepth);
 149                     openScope(debug, inlineContext.get(inlineDepth), inlineDepth, properties);
 150                 } else {
 151                     // Check for method scopes that must be closed since the previous dump.
 152                     for (int i = 0; i < previousInlineContext.size(); ++i) {
 153                         if (i >= inlineContext.size() || !inlineContext.get(i).equals(previousInlineContext.get(i))) {
 154                             for (int inlineDepth = previousInlineContext.size() - 1; inlineDepth >= i; --inlineDepth) {
 155                                 closeScope(debug, inlineDepth);
 156                             }
 157                             break;
 158                         }
 159                     }
 160                     // Check for method scopes that must be opened since the previous dump.
 161                     for (int i = 0; i < inlineContext.size(); ++i) {
 162                         if (i >= previousInlineContext.size() || !inlineContext.get(i).equals(previousInlineContext.get(i))) {
 163                             for (int inlineDepth = i; inlineDepth < inlineContext.size(); ++inlineDepth) {
 164                                 openScope(debug, inlineContext.get(inlineDepth), inlineDepth, inlineDepth == inlineContext.size() - 1 ? properties : null);
 165                             }
 166                             break;
 167                         }
 168                     }
 169                 }
 170             }
 171 
 172             // Save inline context for next dump.
 173             previousInlineContext = inlineContext;
 174 
 175             // Capture before creating the sandbox
 176             String currentScopeName = debug.getCurrentScopeName();
 177             try (DebugContext.Scope s = debug.sandbox("PrintingGraph", null)) {
 178                 // Finally, output the graph.
 179                 Map<Object, Object> properties = new HashMap<>();
 180                 properties.put("graph", graph.toString());
 181                 properties.put("scope", currentScopeName);
 182                 if (graph instanceof StructuredGraph) {
 183                     properties.put("compilationIdentifier", ((StructuredGraph) graph).compilationId());
 184                     try {
 185                         int size = NodeCostUtil.computeGraphSize((StructuredGraph) graph);
 186                         properties.put("node-cost graph size", size);
 187                     } catch (Throwable t) {
 188                         properties.put("node-cost-exception", t.getMessage());
 189                     }
 190                 }
 191                 printer.print(debug, graph, properties, nextDumpId(), format, arguments);
 192             } catch (IOException e) {
 193                 handleException(debug, e);
 194             } catch (Throwable e) {
 195                 throw debug.handle(e);
 196             }
 197         }
 198     }
 199 
 200     void handleException(DebugContext debug, IOException e) {
 201         if (debug != null && DebugOptions.DumpingErrorsAreFatal.getValue(debug.getOptions())) {
 202             throw new GraalError(e);
 203         }
 204         if (e instanceof ClosedByInterruptException) {
 205             /*
 206              * The current dumping was aborted by an interrupt so treat this as a transient failure.
 207              */
 208             failuresCount = 0;
 209         } else {
 210             failuresCount++;
 211         }
 212         printer = null;
 213         e.printStackTrace(TTY.out);
 214         if (failuresCount > FAILURE_LIMIT) {
 215             TTY.println("Too many failures with dumping. Disabling dump in thread " + Thread.currentThread());
 216         }
 217     }
 218 
 219     private static void addCompilationId(Map<Object, Object> properties, final Graph graph) {
 220         if (graph instanceof StructuredGraph) {
 221             properties.put("compilationId", ((StructuredGraph) graph).compilationId());
 222         }
 223     }
 224 
 225     private List<String> getInlineContext(Graph graph) {
 226         List<String> result = inlineContextMap.get(graph);
 227         if (result == null) {
 228             result = new ArrayList<>();
 229             Object lastMethodOrGraph = null;
 230             boolean graphSeen = false;
 231             DebugContext debug = graph.getDebug();
 232             for (Object o : debug.context()) {
 233                 if (o == graph) {
 234                     graphSeen = true;
 235                 }
 236 
 237                 if (o instanceof DebugDumpScope) {
 238                     DebugDumpScope debugDumpScope = (DebugDumpScope) o;
 239                     if (debugDumpScope.decorator && !result.isEmpty()) {
 240                         result.set(result.size() - 1, debugDumpScope.name + ":" + result.get(result.size() - 1));
 241                     } else {
 242                         result.add(debugDumpScope.name);
 243                     }
 244                 } else {
 245                     addMethodContext(result, o, lastMethodOrGraph);
 246                 }
 247                 if (o instanceof JavaMethod || o instanceof Graph) {
 248                     lastMethodOrGraph = o;
 249                 }
 250             }
 251             if (result.size() == 2 && result.get(1).startsWith("TruffleGraal")) {
 252                 result.clear();
 253                 result.add("Graal Graphs");
 254             }
 255             if (result.isEmpty()) {
 256                 result.add(graph.toString());
 257                 graphSeen = true;
 258             }
 259             // Reverse list such that inner method comes after outer method.
 260             Collections.reverse(result);
 261             if (!graphSeen) {
 262                 /*
 263                  * The graph isn't in any context but is being processed within another graph so add
 264                  * it to the end of the scopes.
 265                  */
 266                 if (asJavaMethod(graph) != null) {
 267                     addMethodContext(result, graph, lastMethodOrGraph);
 268                 } else {
 269                     result.add(graph.toString());
 270                 }
 271             }
 272             inlineContextMap.put(graph, result);
 273         }
 274         return result;
 275     }
 276 
 277     private static void addMethodContext(List<String> result, Object o, Object lastMethodOrGraph) {
 278         JavaMethod method = asJavaMethod(o);
 279         if (method != null) {
 280             /*
 281              * Include the current method in the context if there was no previous JavaMethod or
 282              * JavaMethodContext or if the method is different or if the method is the same but it
 283              * comes from two different graphs. This ensures that recursive call patterns are
 284              * handled properly.
 285              */
 286             if (lastMethodOrGraph == null || asJavaMethod(lastMethodOrGraph) == null || !asJavaMethod(lastMethodOrGraph).equals(method) ||
 287                             (lastMethodOrGraph != o && lastMethodOrGraph instanceof Graph && o instanceof Graph)) {
 288                 result.add(method.format("%H.%n(%p)"));
 289             } else {
 290                 /*
 291                  * This prevents multiple adjacent method context objects for the same method from
 292                  * resulting in multiple IGV tree levels. This works on the assumption that real
 293                  * inlining debug scopes will have a graph context object between the inliner and
 294                  * inlinee context objects.
 295                  */
 296             }
 297         }
 298     }
 299 
 300     private void openScope(DebugContext debug, String name, int inlineDepth, Map<Object, Object> properties) {
 301         try {
 302             Map<Object, Object> props = properties;
 303             if (inlineDepth == 0) {
 304                 /* Include some VM specific properties at the root. */
 305                 if (props == null) {
 306                     props = new HashMap<>();
 307                 }
 308                 props.put("jvmArguments", jvmArguments);
 309                 if (sunJavaCommand != null) {
 310                     props.put("sun.java.command", sunJavaCommand);
 311                 }
 312                 props.put("date", new Date().toString());
 313             }
 314             printer.beginGroup(debug, name, name, debug.contextLookup(ResolvedJavaMethod.class), -1, props);
 315         } catch (IOException e) {
 316             handleException(debug, e);
 317         }
 318     }
 319 
 320     private void closeScope(DebugContext debug, int inlineDepth) {
 321         dumpIds[inlineDepth] = 0;
 322         try {
 323             if (printer != null) {
 324                 printer.endGroup();
 325             }
 326         } catch (IOException e) {
 327             handleException(debug, e);
 328         }
 329     }
 330 
 331     @Override
 332     public void close() {
 333         if (previousInlineContext != null) {
 334             for (int inlineDepth = 0; inlineDepth < previousInlineContext.size(); inlineDepth++) {
 335                 closeScope(null, inlineDepth);
 336             }
 337         }
 338         if (printer != null) {
 339             printer.close();
 340             printer = null;
 341         }
 342     }
 343 }