1 /*
   2  * Copyright (c) 2013, 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.replacements;
  26 
  27 import static org.graalvm.compiler.nodeinfo.NodeCycles.CYCLES_IGNORED;
  28 import static org.graalvm.compiler.nodeinfo.NodeSize.SIZE_IGNORED;
  29 import static org.graalvm.compiler.replacements.SnippetTemplate.DEFAULT_REPLACER;
  30 
  31 import java.lang.reflect.Field;
  32 import java.util.Arrays;
  33 
  34 import org.graalvm.compiler.api.replacements.Fold;
  35 import org.graalvm.compiler.api.replacements.Snippet;
  36 import org.graalvm.compiler.api.replacements.Snippet.ConstantParameter;
  37 import org.graalvm.compiler.api.replacements.SnippetReflectionProvider;
  38 import org.graalvm.compiler.core.common.type.StampFactory;
  39 import org.graalvm.compiler.debug.DebugHandlersFactory;
  40 import org.graalvm.compiler.debug.GraalError;
  41 import org.graalvm.compiler.graph.NodeClass;
  42 import org.graalvm.compiler.nodeinfo.NodeInfo;
  43 import org.graalvm.compiler.nodes.FixedWithNextNode;
  44 import org.graalvm.compiler.nodes.NamedLocationIdentity;
  45 import org.graalvm.compiler.nodes.StructuredGraph;
  46 import org.graalvm.compiler.nodes.ValueNode;
  47 import org.graalvm.compiler.nodes.spi.Lowerable;
  48 import org.graalvm.compiler.nodes.spi.LoweringTool;
  49 import org.graalvm.compiler.options.OptionValues;
  50 import org.graalvm.compiler.phases.util.Providers;
  51 import org.graalvm.compiler.replacements.SnippetTemplate.AbstractTemplates;
  52 import org.graalvm.compiler.replacements.SnippetTemplate.Arguments;
  53 import org.graalvm.compiler.replacements.SnippetTemplate.SnippetInfo;
  54 import org.graalvm.compiler.word.ObjectAccess;
  55 import jdk.internal.vm.compiler.word.LocationIdentity;
  56 
  57 import jdk.vm.ci.code.TargetDescription;
  58 import sun.misc.Unsafe;
  59 
  60 /**
  61  * This node can be used to add a counter to the code that will estimate the dynamic number of calls
  62  * by adding an increment to the compiled code. This should of course only be used for
  63  * debugging/testing purposes.
  64  *
  65  * A unique counter will be created for each unique name passed to the constructor. Depending on the
  66  * value of withContext, the name of the root method is added to the counter's name.
  67  */
  68 @NodeInfo(cycles = CYCLES_IGNORED, size = SIZE_IGNORED)
  69 public class SnippetCounterNode extends FixedWithNextNode implements Lowerable {
  70 
  71     public static final NodeClass<SnippetCounterNode> TYPE = NodeClass.create(SnippetCounterNode.class);
  72 
  73     @Input protected ValueNode increment;
  74 
  75     protected final SnippetCounter counter;
  76 
  77     public SnippetCounterNode(SnippetCounter counter, ValueNode increment) {
  78         super(TYPE, StampFactory.forVoid());
  79         this.counter = counter;
  80         this.increment = increment;
  81     }
  82 
  83     public SnippetCounter getCounter() {
  84         return counter;
  85     }
  86 
  87     public ValueNode getIncrement() {
  88         return increment;
  89     }
  90 
  91     @NodeIntrinsic
  92     public static native void add(@ConstantNodeParameter SnippetCounter counter, int increment);
  93 
  94     public static void increment(@ConstantNodeParameter SnippetCounter counter) {
  95         add(counter, 1);
  96     }
  97 
  98     @Override
  99     public void lower(LoweringTool tool) {
 100         if (graph().getGuardsStage().areFrameStatesAtDeopts()) {
 101             SnippetCounterSnippets.Templates templates = tool.getReplacements().getSnippetTemplateCache(SnippetCounterSnippets.Templates.class);
 102             templates.lower(this, tool);
 103         }
 104     }
 105 
 106     /**
 107      * Add {@link #SNIPPET_COUNTER_LOCATION} to {@code privateLocations} if it isn't already there.
 108      *
 109      * @param privateLocations
 110      * @return a copy of privateLocations with any needed locations added
 111      */
 112     public static LocationIdentity[] addSnippetCounters(LocationIdentity[] privateLocations) {
 113         for (LocationIdentity location : privateLocations) {
 114             if (location.equals(SNIPPET_COUNTER_LOCATION)) {
 115                 return privateLocations;
 116             }
 117         }
 118         LocationIdentity[] result = Arrays.copyOf(privateLocations, privateLocations.length + 1);
 119         result[result.length - 1] = SnippetCounterNode.SNIPPET_COUNTER_LOCATION;
 120         return result;
 121     }
 122 
 123     /**
 124      * We do not want to use the {@link LocationIdentity} of the {@link SnippetCounter#value()}
 125      * field, so that the usage in snippets is always possible. If a method accesses the counter via
 126      * the field and the snippet, the result might not be correct though.
 127      */
 128     public static final LocationIdentity SNIPPET_COUNTER_LOCATION = NamedLocationIdentity.mutable("SnippetCounter");
 129 
 130     static class SnippetCounterSnippets implements Snippets {
 131 
 132         @Fold
 133         static int countOffset() {
 134             try {
 135                 return (int) UNSAFE.objectFieldOffset(SnippetCounter.class.getDeclaredField("value"));
 136             } catch (Exception e) {
 137                 throw new GraalError(e);
 138             }
 139         }
 140 
 141         @Snippet
 142         public static void add(@ConstantParameter SnippetCounter counter, int increment) {
 143             long loadedValue = ObjectAccess.readLong(counter, countOffset(), SNIPPET_COUNTER_LOCATION);
 144             ObjectAccess.writeLong(counter, countOffset(), loadedValue + increment, SNIPPET_COUNTER_LOCATION);
 145         }
 146 
 147         public static class Templates extends AbstractTemplates {
 148 
 149             private final SnippetInfo add = snippet(SnippetCounterSnippets.class, "add", SNIPPET_COUNTER_LOCATION);
 150 
 151             Templates(OptionValues options, Iterable<DebugHandlersFactory> factories, Providers providers, SnippetReflectionProvider snippetReflection, TargetDescription target) {
 152                 super(options, factories, providers, snippetReflection, target);
 153             }
 154 
 155             public void lower(SnippetCounterNode counter, LoweringTool tool) {
 156                 StructuredGraph graph = counter.graph();
 157                 Arguments args = new Arguments(add, graph.getGuardsStage(), tool.getLoweringStage());
 158                 args.addConst("counter", counter.getCounter());
 159                 args.add("increment", counter.getIncrement());
 160 
 161                 template(counter, args).instantiate(providers.getMetaAccess(), counter, DEFAULT_REPLACER, args);
 162             }
 163         }
 164     }
 165 
 166     private static final Unsafe UNSAFE = initUnsafe();
 167 
 168     private static Unsafe initUnsafe() {
 169         try {
 170             return Unsafe.getUnsafe();
 171         } catch (SecurityException se) {
 172             try {
 173                 Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
 174                 theUnsafe.setAccessible(true);
 175                 return (Unsafe) theUnsafe.get(Unsafe.class);
 176             } catch (Exception e) {
 177                 throw new RuntimeException("exception while trying to get Unsafe", e);
 178             }
 179         }
 180     }
 181 }