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