1 /*
   2  * Copyright (c) 2011, 2015, 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 jdk.vm.ci.hotspot;
  24 
  25 import static jdk.vm.ci.hotspot.HotSpotJVMCIRuntimeProvider.getArrayBaseOffset;
  26 import static jdk.vm.ci.hotspot.HotSpotJVMCIRuntimeProvider.getArrayIndexScale;
  27 
  28 import java.lang.reflect.Array;
  29 
  30 import jdk.vm.ci.meta.Constant;
  31 import jdk.vm.ci.meta.ConstantReflectionProvider;
  32 import jdk.vm.ci.meta.JavaConstant;
  33 import jdk.vm.ci.meta.JavaKind;
  34 import jdk.vm.ci.meta.JavaType;
  35 import jdk.vm.ci.meta.MemoryAccessProvider;
  36 import jdk.vm.ci.meta.MethodHandleAccessProvider;
  37 import jdk.vm.ci.meta.ResolvedJavaField;
  38 import jdk.vm.ci.meta.ResolvedJavaType;
  39 
  40 /**
  41  * HotSpot implementation of {@link ConstantReflectionProvider}.
  42  */
  43 public class HotSpotConstantReflectionProvider implements ConstantReflectionProvider, HotSpotProxified {
  44 
  45     private static final String TrustFinalDefaultFieldsProperty = "jvmci.TrustFinalDefaultFields";
  46 
  47     /**
  48      * Determines whether to treat {@code final} fields with default values as constant.
  49      */
  50     private static final boolean TrustFinalDefaultFields = HotSpotJVMCIRuntime.getBooleanProperty(TrustFinalDefaultFieldsProperty, true);
  51 
  52     protected final HotSpotJVMCIRuntimeProvider runtime;
  53     protected final HotSpotMethodHandleAccessProvider methodHandleAccess;
  54     protected final HotSpotMemoryAccessProviderImpl memoryAccess;
  55 
  56     public HotSpotConstantReflectionProvider(HotSpotJVMCIRuntimeProvider runtime) {
  57         this.runtime = runtime;
  58         this.methodHandleAccess = new HotSpotMethodHandleAccessProvider(this);
  59         this.memoryAccess = new HotSpotMemoryAccessProviderImpl(runtime);
  60     }
  61 
  62     public MethodHandleAccessProvider getMethodHandleAccess() {
  63         return methodHandleAccess;
  64     }
  65 
  66     @Override
  67     public MemoryAccessProvider getMemoryAccessProvider() {
  68         return memoryAccess;
  69     }
  70 
  71     @Override
  72     public Boolean constantEquals(Constant x, Constant y) {
  73         if (x == y) {
  74             return true;
  75         } else if (x instanceof HotSpotObjectConstantImpl) {
  76             return y instanceof HotSpotObjectConstantImpl && ((HotSpotObjectConstantImpl) x).object() == ((HotSpotObjectConstantImpl) y).object();
  77         } else {
  78             return x.equals(y);
  79         }
  80     }
  81 
  82     @Override
  83     public Integer readArrayLength(JavaConstant array) {
  84         if (array.getJavaKind() != JavaKind.Object || array.isNull()) {
  85             return null;
  86         }
  87 
  88         Object arrayObject = ((HotSpotObjectConstantImpl) array).object();
  89         if (!arrayObject.getClass().isArray()) {
  90             return null;
  91         }
  92         return Array.getLength(arrayObject);
  93     }
  94 
  95     public JavaConstant readConstantArrayElement(JavaConstant array, int index) {
  96         if (array instanceof HotSpotObjectConstantImpl && ((HotSpotObjectConstantImpl) array).getStableDimension() > 0) {
  97             JavaConstant element = readArrayElement(array, index);
  98             if (element != null && (((HotSpotObjectConstantImpl) array).isDefaultStable() || !element.isDefaultForKind())) {
  99                 return element;
 100             }
 101         }
 102         return null;
 103     }
 104 
 105     /**
 106      * Try to convert {@code offset} into an an index into {@code array}.
 107      *
 108      * @return the computed index or -1 if the offset isn't within the array
 109      */
 110     private int indexForOffset(JavaConstant array, long offset) {
 111         if (array.getJavaKind() != JavaKind.Object || array.isNull()) {
 112             return -1;
 113         }
 114         Class<?> componentType = ((HotSpotObjectConstantImpl) array).object().getClass().getComponentType();
 115         JavaKind kind = runtime.getHostJVMCIBackend().getMetaAccess().lookupJavaType(componentType).getJavaKind();
 116         int arraybase = getArrayBaseOffset(kind);
 117         int scale = getArrayIndexScale(kind);
 118         if (offset < arraybase) {
 119             return -1;
 120         }
 121         long index = offset - arraybase;
 122         if (index % scale != 0) {
 123             return -1;
 124         }
 125         long result = index / scale;
 126         if (result >= Integer.MAX_VALUE) {
 127             return -1;
 128         }
 129         return (int) result;
 130     }
 131 
 132     public JavaConstant readConstantArrayElementForOffset(JavaConstant array, long offset) {
 133         if (array instanceof HotSpotObjectConstantImpl && ((HotSpotObjectConstantImpl) array).getStableDimension() > 0) {
 134             return readConstantArrayElement(array, indexForOffset(array, offset));
 135         }
 136         return null;
 137     }
 138 
 139     @Override
 140     public JavaConstant readArrayElement(JavaConstant array, int index) {
 141         if (array.getJavaKind() != JavaKind.Object || array.isNull()) {
 142             return null;
 143         }
 144         Object a = ((HotSpotObjectConstantImpl) array).object();
 145 
 146         if (index < 0 || index >= Array.getLength(a)) {
 147             return null;
 148         }
 149 
 150         if (a instanceof Object[]) {
 151             Object element = ((Object[]) a)[index];
 152             if (((HotSpotObjectConstantImpl) array).getStableDimension() > 1) {
 153                 return HotSpotObjectConstantImpl.forStableArray(element, ((HotSpotObjectConstantImpl) array).getStableDimension() - 1, ((HotSpotObjectConstantImpl) array).isDefaultStable());
 154             } else {
 155                 return HotSpotObjectConstantImpl.forObject(element);
 156             }
 157         } else {
 158             return JavaConstant.forBoxedPrimitive(Array.get(a, index));
 159         }
 160     }
 161 
 162     /**
 163      * Check if the constant is a boxed value that is guaranteed to be cached by the platform.
 164      * Otherwise the generated code might be the only reference to the boxed value and since object
 165      * references from nmethods are weak this can cause GC problems.
 166      *
 167      * @param source
 168      * @return true if the box is cached
 169      */
 170     private static boolean isBoxCached(JavaConstant source) {
 171         switch (source.getJavaKind()) {
 172             case Boolean:
 173                 return true;
 174             case Char:
 175                 return source.asInt() <= 127;
 176             case Byte:
 177             case Short:
 178             case Int:
 179                 return source.asInt() >= -128 && source.asInt() <= 127;
 180             case Long:
 181                 return source.asLong() >= -128 && source.asLong() <= 127;
 182             case Float:
 183             case Double:
 184                 return false;
 185             default:
 186                 throw new IllegalArgumentException("unexpected kind " + source.getJavaKind());
 187         }
 188     }
 189 
 190     @Override
 191     public JavaConstant boxPrimitive(JavaConstant source) {
 192         if (!source.getJavaKind().isPrimitive() || !isBoxCached(source)) {
 193             return null;
 194         }
 195         return HotSpotObjectConstantImpl.forObject(source.asBoxedPrimitive());
 196     }
 197 
 198     @Override
 199     public JavaConstant unboxPrimitive(JavaConstant source) {
 200         if (!source.getJavaKind().isObject()) {
 201             return null;
 202         }
 203         if (source.isNull()) {
 204             return null;
 205         }
 206         return JavaConstant.forBoxedPrimitive(((HotSpotObjectConstantImpl) source).object());
 207     }
 208 
 209     public JavaConstant forString(String value) {
 210         return HotSpotObjectConstantImpl.forObject(value);
 211     }
 212 
 213     public JavaConstant forObject(Object value) {
 214         return HotSpotObjectConstantImpl.forObject(value);
 215     }
 216 
 217     @Override
 218     public ResolvedJavaType asJavaType(Constant constant) {
 219         if (constant instanceof HotSpotObjectConstant) {
 220             Object obj = ((HotSpotObjectConstantImpl) constant).object();
 221             if (obj instanceof Class) {
 222                 return runtime.getHostJVMCIBackend().getMetaAccess().lookupJavaType((Class<?>) obj);
 223             }
 224         }
 225         if (constant instanceof HotSpotMetaspaceConstant) {
 226             MetaspaceWrapperObject obj = HotSpotMetaspaceConstantImpl.getMetaspaceObject(constant);
 227             if (obj instanceof HotSpotResolvedObjectTypeImpl) {
 228                 return (ResolvedJavaType) obj;
 229             }
 230         }
 231         return null;
 232     }
 233 
 234     private static final String SystemClassName = "Ljava/lang/System;";
 235 
 236     /**
 237      * Determines if a static field is constant for the purpose of
 238      * {@link #readConstantFieldValue(ResolvedJavaField, JavaConstant)}.
 239      */
 240     protected boolean isStaticFieldConstant(HotSpotResolvedJavaField staticField) {
 241         if (staticField.isFinal() || staticField.isStable()) {
 242             ResolvedJavaType holder = staticField.getDeclaringClass();
 243             if (holder.isInitialized() && !holder.getName().equals(SystemClassName)) {
 244                 return true;
 245             }
 246         }
 247         return false;
 248     }
 249 
 250     /**
 251      * Determines if a value read from a {@code final} instance field is considered constant. The
 252      * implementation in {@link HotSpotConstantReflectionProvider} returns true if {@code value} is
 253      * not the {@link JavaConstant#isDefaultForKind default value} for its kind or if
 254      * {@link #TrustFinalDefaultFields} is true.
 255      *
 256      * @param value a value read from a {@code final} instance field
 257      * @param receiverClass the {@link Object#getClass() class} of object from which the
 258      *            {@code value} was read
 259      */
 260     protected boolean isFinalInstanceFieldValueConstant(JavaConstant value, Class<?> receiverClass) {
 261         return !value.isDefaultForKind() || TrustFinalDefaultFields;
 262     }
 263 
 264     /**
 265      * Determines if a value read from a {@link Stable} instance field is considered constant. The
 266      * implementation in {@link HotSpotConstantReflectionProvider} returns true if {@code value} is
 267      * not the {@link JavaConstant#isDefaultForKind default value} for its kind.
 268      *
 269      * @param value a value read from a {@link Stable} field
 270      * @param receiverClass the {@link Object#getClass() class} of object from which the
 271      *            {@code value} was read
 272      */
 273     protected boolean isStableInstanceFieldValueConstant(JavaConstant value, Class<?> receiverClass) {
 274         return !value.isDefaultForKind();
 275     }
 276 
 277     public JavaConstant readConstantFieldValue(ResolvedJavaField field, JavaConstant receiver) {
 278         HotSpotResolvedJavaField hotspotField = (HotSpotResolvedJavaField) field;
 279 
 280         if (hotspotField.isStatic()) {
 281             if (isStaticFieldConstant(hotspotField)) {
 282                 JavaConstant value = readFieldValue(field, receiver);
 283                 if (hotspotField.isFinal() || !value.isDefaultForKind()) {
 284                     return value;
 285                 }
 286             }
 287         } else {
 288             /*
 289              * for non-static final fields, we must assume that they are only initialized if they
 290              * have a non-default value.
 291              */
 292             Object object = receiver.isNull() ? null : ((HotSpotObjectConstantImpl) receiver).object();
 293 
 294             // Canonicalization may attempt to process an unsafe read before
 295             // processing a guard (e.g. a null check or a type check) for this read
 296             // so we need to check the object being read
 297             if (object != null) {
 298                 if (hotspotField.isFinal()) {
 299                     if (hotspotField.isInObject(object)) {
 300                         JavaConstant value = readFieldValue(field, receiver);
 301                         if (isFinalInstanceFieldValueConstant(value, object.getClass())) {
 302                             return value;
 303                         }
 304                     }
 305                 } else if (hotspotField.isStable()) {
 306                     if (hotspotField.isInObject(object)) {
 307                         JavaConstant value = readFieldValue(field, receiver);
 308                         if (isStableInstanceFieldValueConstant(value, object.getClass())) {
 309                             return value;
 310                         }
 311                     }
 312                 }
 313             }
 314         }
 315         return null;
 316     }
 317 
 318     public JavaConstant readFieldValue(ResolvedJavaField field, JavaConstant receiver) {
 319         HotSpotResolvedJavaField hotspotField = (HotSpotResolvedJavaField) field;
 320         if (!hotspotField.isStable()) {
 321             return readNonStableFieldValue(field, receiver);
 322         } else {
 323             return readStableFieldValue(field, receiver, hotspotField.isDefaultStable());
 324         }
 325     }
 326 
 327     private JavaConstant readNonStableFieldValue(ResolvedJavaField field, JavaConstant receiver) {
 328         HotSpotResolvedJavaField hotspotField = (HotSpotResolvedJavaField) field;
 329         if (hotspotField.isStatic()) {
 330             HotSpotResolvedJavaType holder = (HotSpotResolvedJavaType) hotspotField.getDeclaringClass();
 331             if (holder.isInitialized()) {
 332                 return memoryAccess.readUnsafeConstant(hotspotField.getJavaKind(), HotSpotObjectConstantImpl.forObject(holder.mirror()), hotspotField.offset());
 333             }
 334         } else {
 335             if (receiver.isNonNull() && hotspotField.isInObject(((HotSpotObjectConstantImpl) receiver).object())) {
 336                 return memoryAccess.readUnsafeConstant(hotspotField.getJavaKind(), receiver, hotspotField.offset());
 337             }
 338         }
 339         return null;
 340     }
 341 
 342     public JavaConstant readStableFieldValue(ResolvedJavaField field, JavaConstant receiver, boolean isDefaultStable) {
 343         JavaConstant fieldValue = readNonStableFieldValue(field, receiver);
 344         if (fieldValue.isNonNull()) {
 345             JavaType declaredType = field.getType();
 346             if (declaredType.getComponentType() != null) {
 347                 int stableDimension = getArrayDimension(declaredType);
 348                 return HotSpotObjectConstantImpl.forStableArray(((HotSpotObjectConstantImpl) fieldValue).object(), stableDimension, isDefaultStable);
 349             }
 350         }
 351         return fieldValue;
 352     }
 353 
 354     private static int getArrayDimension(JavaType type) {
 355         int dimensions = 0;
 356         JavaType componentType = type;
 357         while ((componentType = componentType.getComponentType()) != null) {
 358             dimensions++;
 359         }
 360         return dimensions;
 361     }
 362 }