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