1 /*
   2  * Copyright (c) 2011, 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  */
  23 package org.graalvm.compiler.printer;
  24 
  25 import java.io.BufferedOutputStream;
  26 import java.io.File;
  27 import java.io.FileNotFoundException;
  28 import java.io.FileOutputStream;
  29 import java.io.OutputStream;
  30 import java.nio.file.Path;
  31 import java.util.ArrayList;
  32 import java.util.Collections;
  33 import java.util.List;
  34 
  35 import org.graalvm.compiler.bytecode.BytecodeDisassembler;
  36 import org.graalvm.compiler.code.CompilationResult;
  37 import org.graalvm.compiler.code.DisassemblerProvider;
  38 import org.graalvm.compiler.core.common.alloc.Trace;
  39 import org.graalvm.compiler.core.common.alloc.TraceBuilderResult;
  40 import org.graalvm.compiler.core.common.cfg.AbstractBlockBase;
  41 import org.graalvm.compiler.core.gen.NodeLIRBuilder;
  42 import org.graalvm.compiler.debug.Debug;
  43 import org.graalvm.compiler.debug.DebugDumpHandler;
  44 import org.graalvm.compiler.debug.DebugDumpScope;
  45 import org.graalvm.compiler.debug.GraalDebugConfig.Options;
  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.java.BciBlockMapping;
  50 import org.graalvm.compiler.lir.LIR;
  51 import org.graalvm.compiler.lir.debug.IntervalDumper;
  52 import org.graalvm.compiler.nodes.StructuredGraph;
  53 import org.graalvm.compiler.nodes.StructuredGraph.ScheduleResult;
  54 import org.graalvm.compiler.nodes.cfg.ControlFlowGraph;
  55 import org.graalvm.compiler.options.UniquePathUtilities;
  56 import org.graalvm.compiler.serviceprovider.GraalServices;
  57 
  58 import jdk.vm.ci.code.CodeCacheProvider;
  59 import jdk.vm.ci.code.InstalledCode;
  60 import jdk.vm.ci.meta.JavaMethod;
  61 import jdk.vm.ci.meta.ResolvedJavaMethod;
  62 
  63 /**
  64  * Observes compilation events and uses {@link CFGPrinter} to produce a control flow graph for the
  65  * <a href="http://java.net/projects/c1visualizer/">C1 Visualizer</a>.
  66  */
  67 public class CFGPrinterObserver implements DebugDumpHandler {
  68 
  69     private CFGPrinter cfgPrinter;
  70     private File cfgFile;
  71     private JavaMethod curMethod;
  72     private List<String> curDecorators = Collections.emptyList();
  73     private final boolean dumpFrontend;
  74 
  75     public CFGPrinterObserver(boolean dumpFrontend) {
  76         this.dumpFrontend = dumpFrontend;
  77     }
  78 
  79     @Override
  80     public void dump(Object object, String message) {
  81         try {
  82             dumpSandboxed(object, message);
  83         } catch (Throwable ex) {
  84             TTY.println("CFGPrinter: Exception during output of " + message + ": " + ex);
  85             ex.printStackTrace();
  86         }
  87     }
  88 
  89     /**
  90      * Looks for the outer most method and its {@link DebugDumpScope#decorator}s in the current
  91      * debug scope and opens a new compilation scope if this pair does not match the current method
  92      * and decorator pair.
  93      */
  94     private boolean checkMethodScope() {
  95         JavaMethod method = null;
  96         ArrayList<String> decorators = new ArrayList<>();
  97         for (Object o : Debug.context()) {
  98             if (o instanceof JavaMethod) {
  99                 method = (JavaMethod) o;
 100                 decorators.clear();
 101             } else if (o instanceof StructuredGraph) {
 102                 StructuredGraph graph = (StructuredGraph) o;
 103                 if (graph.method() != null) {
 104                     method = graph.method();
 105                     decorators.clear();
 106                 }
 107             } else if (o instanceof DebugDumpScope) {
 108                 DebugDumpScope debugDumpScope = (DebugDumpScope) o;
 109                 if (debugDumpScope.decorator) {
 110                     decorators.add(debugDumpScope.name);
 111                 }
 112             }
 113         }
 114 
 115         if (method == null) {
 116             return false;
 117         }
 118 
 119         if (!method.equals(curMethod) || !curDecorators.equals(decorators)) {
 120             cfgPrinter.printCompilation(method);
 121             TTY.println("CFGPrinter: Dumping method %s to %s", method, cfgFile.getAbsolutePath());
 122         }
 123         curMethod = method;
 124         curDecorators = decorators;
 125         return true;
 126     }
 127 
 128     private static boolean isFrontendObject(Object object) {
 129         return object instanceof Graph || object instanceof BciBlockMapping;
 130     }
 131 
 132     private LIR lastLIR = null;
 133     private IntervalDumper delayedIntervals = null;
 134 
 135     public void dumpSandboxed(Object object, String message) {
 136         if (!dumpFrontend && isFrontendObject(object)) {
 137             return;
 138         }
 139 
 140         if (cfgPrinter == null) {
 141             cfgFile = getCFGPath().toFile();
 142             try {
 143                 /*
 144                  * Initializing a debug environment multiple times by calling
 145                  * DebugEnvironment#initialize will create new CFGPrinterObserver objects that refer
 146                  * to the same file path. This means the CFG file may be overridden by another
 147                  * instance. Appending to an existing CFG file is not an option as the writing
 148                  * happens buffered.
 149                  */
 150                 OutputStream out = new BufferedOutputStream(new FileOutputStream(cfgFile));
 151                 cfgPrinter = new CFGPrinter(out);
 152             } catch (FileNotFoundException e) {
 153                 throw new GraalError("Could not open " + cfgFile.getAbsolutePath());
 154             }
 155             TTY.println("CFGPrinter: Output to file %s", cfgFile.getAbsolutePath());
 156         }
 157 
 158         if (!checkMethodScope()) {
 159             return;
 160         }
 161         try {
 162             if (curMethod instanceof ResolvedJavaMethod) {
 163                 cfgPrinter.method = (ResolvedJavaMethod) curMethod;
 164             }
 165 
 166             if (object instanceof LIR) {
 167                 cfgPrinter.lir = (LIR) object;
 168             } else {
 169                 cfgPrinter.lir = Debug.contextLookup(LIR.class);
 170             }
 171             cfgPrinter.nodeLirGenerator = Debug.contextLookup(NodeLIRBuilder.class);
 172             if (cfgPrinter.nodeLirGenerator != null) {
 173                 cfgPrinter.target = cfgPrinter.nodeLirGenerator.getLIRGeneratorTool().target();
 174             }
 175             if (cfgPrinter.lir != null && cfgPrinter.lir.getControlFlowGraph() instanceof ControlFlowGraph) {
 176                 cfgPrinter.cfg = (ControlFlowGraph) cfgPrinter.lir.getControlFlowGraph();
 177             }
 178 
 179             CodeCacheProvider codeCache = Debug.contextLookup(CodeCacheProvider.class);
 180             if (codeCache != null) {
 181                 cfgPrinter.target = codeCache.getTarget();
 182             }
 183 
 184             if (object instanceof BciBlockMapping) {
 185                 BciBlockMapping blockMap = (BciBlockMapping) object;
 186                 cfgPrinter.printCFG(message, blockMap);
 187                 if (blockMap.code.getCode() != null) {
 188                     cfgPrinter.printBytecodes(new BytecodeDisassembler(false).disassemble(blockMap.code));
 189                 }
 190 
 191             } else if (object instanceof LIR) {
 192                 // Currently no node printing for lir
 193                 cfgPrinter.printCFG(message, cfgPrinter.lir.codeEmittingOrder(), false);
 194                 lastLIR = (LIR) object;
 195                 if (delayedIntervals != null) {
 196                     cfgPrinter.printIntervals(message, delayedIntervals);
 197                     delayedIntervals = null;
 198                 }
 199             } else if (object instanceof ScheduleResult) {
 200                 cfgPrinter.printSchedule(message, (ScheduleResult) object);
 201             } else if (object instanceof StructuredGraph) {
 202                 if (cfgPrinter.cfg == null) {
 203                     StructuredGraph graph = (StructuredGraph) object;
 204                     cfgPrinter.cfg = ControlFlowGraph.compute(graph, true, true, true, false);
 205                     cfgPrinter.printCFG(message, cfgPrinter.cfg.getBlocks(), true);
 206                 } else {
 207                     cfgPrinter.printCFG(message, cfgPrinter.cfg.getBlocks(), true);
 208                 }
 209 
 210             } else if (object instanceof CompilationResult) {
 211                 final CompilationResult compResult = (CompilationResult) object;
 212                 cfgPrinter.printMachineCode(disassemble(codeCache, compResult, null), message);
 213             } else if (object instanceof InstalledCode) {
 214                 CompilationResult compResult = Debug.contextLookup(CompilationResult.class);
 215                 if (compResult != null) {
 216                     cfgPrinter.printMachineCode(disassemble(codeCache, compResult, (InstalledCode) object), message);
 217                 }
 218             } else if (object instanceof IntervalDumper) {
 219                 if (lastLIR == cfgPrinter.lir) {
 220                     cfgPrinter.printIntervals(message, (IntervalDumper) object);
 221                 } else {
 222                     if (delayedIntervals != null) {
 223                         Debug.log("Some delayed intervals were dropped (%s)", delayedIntervals);
 224                     }
 225                     delayedIntervals = (IntervalDumper) object;
 226                 }
 227             } else if (object instanceof AbstractBlockBase<?>[]) {
 228                 cfgPrinter.printCFG(message, (AbstractBlockBase<?>[]) object, false);
 229             } else if (object instanceof Trace) {
 230                 cfgPrinter.printCFG(message, ((Trace) object).getBlocks(), false);
 231             } else if (object instanceof TraceBuilderResult) {
 232                 cfgPrinter.printTraces(message, (TraceBuilderResult) object);
 233             }
 234         } finally {
 235             cfgPrinter.target = null;
 236             cfgPrinter.lir = null;
 237             cfgPrinter.nodeLirGenerator = null;
 238             cfgPrinter.cfg = null;
 239             cfgPrinter.flush();
 240         }
 241     }
 242 
 243     public static Path getCFGPath() {
 244         return UniquePathUtilities.getPath(Options.PrintCFGFileName, Options.DumpPath, "cfg");
 245     }
 246 
 247     /** Lazy initialization to delay service lookup until disassembler is actually needed. */
 248     static class DisassemblerHolder {
 249         private static final DisassemblerProvider disassembler;
 250 
 251         static {
 252             DisassemblerProvider selected = null;
 253             for (DisassemblerProvider d : GraalServices.load(DisassemblerProvider.class)) {
 254                 String name = d.getName().toLowerCase();
 255                 if (name.contains("hcf") || name.contains("hexcodefile")) {
 256                     selected = d;
 257                     break;
 258                 }
 259             }
 260             if (selected == null) {
 261                 selected = new DisassemblerProvider() {
 262                     @Override
 263                     public String getName() {
 264                         return "nop";
 265                     }
 266                 };
 267             }
 268             disassembler = selected;
 269         }
 270     }
 271 
 272     private static String disassemble(CodeCacheProvider codeCache, CompilationResult compResult, InstalledCode installedCode) {
 273         DisassemblerProvider dis = DisassemblerHolder.disassembler;
 274         if (installedCode != null) {
 275             return dis.disassembleInstalledCode(codeCache, compResult, installedCode);
 276         }
 277         return dis.disassembleCompiledCode(codeCache, compResult);
 278     }
 279 
 280     @Override
 281     public void close() {
 282         if (cfgPrinter != null) {
 283             cfgPrinter.close();
 284             cfgPrinter = null;
 285             curDecorators = Collections.emptyList();
 286             curMethod = null;
 287         }
 288     }
 289 }