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