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 java.util.Objects.*;
  26 import static jdk.vm.ci.hotspot.HotSpotJVMCIRuntime.*;
  27 import static jdk.vm.ci.hotspot.UnsafeAccess.UNSAFE;
  28 
  29 import java.lang.annotation.*;
  30 import java.lang.reflect.*;
  31 import java.net.*;
  32 import java.nio.*;
  33 import java.util.*;
  34 
  35 import jdk.vm.ci.common.*;
  36 import jdk.vm.ci.meta.*;
  37 import jdk.vm.ci.meta.Assumptions.*;
  38 
  39 /**
  40  * Implementation of {@link JavaType} for resolved non-primitive HotSpot classes.
  41  */
  42 public final class HotSpotResolvedObjectTypeImpl extends HotSpotResolvedJavaType implements HotSpotResolvedObjectType, HotSpotProxified, MetaspaceWrapperObject {
  43 
  44     /**
  45      * The Java class this type represents.
  46      */
  47     private final Class<?> javaClass;
  48     private HashMap<Long, HotSpotResolvedJavaField> fieldCache;
  49     private HashMap<Long, HotSpotResolvedJavaMethodImpl> methodCache;
  50     private HotSpotResolvedJavaField[] instanceFields;
  51     private HotSpotResolvedObjectTypeImpl[] interfaces;
  52     private HotSpotConstantPool constantPool;
  53     final HotSpotJVMCIMetaAccessContext context;
  54     private HotSpotResolvedObjectType arrayOfType;
  55 
  56     /**
  57      * Gets the JVMCI mirror for a {@link Class} object.
  58      *
  59      * @return the {@link HotSpotResolvedJavaType} corresponding to {@code javaClass}
  60      */
  61     public static HotSpotResolvedObjectTypeImpl fromObjectClass(Class<?> javaClass) {
  62         return (HotSpotResolvedObjectTypeImpl) runtime().fromClass(javaClass);
  63     }
  64 
  65     /**
  66      * Gets the JVMCI mirror from a HotSpot type. Since {@link Class} is already a proxy for the
  67      * underlying Klass*, it is used instead of the raw Klass*.
  68      *
  69      * Called from the VM.
  70      *
  71      * @param javaClass a {@link Class} object
  72      * @return the {@link ResolvedJavaType} corresponding to {@code javaClass}
  73      */
  74     @SuppressWarnings("unused")
  75     private static HotSpotResolvedObjectTypeImpl fromMetaspace(Class<?> javaClass) {
  76         return fromObjectClass(javaClass);
  77     }
  78 
  79     /**
  80      * Creates the JVMCI mirror for a {@link Class} object.
  81      *
  82      * <p>
  83      * <b>NOTE</b>: Creating an instance of this class does not install the mirror for the
  84      * {@link Class} type. Use {@link #fromObjectClass(Class)} or {@link #fromMetaspace(Class)}
  85      * instead.
  86      * </p>
  87      *
  88      * @param javaClass the Class to create the mirror for
  89      * @param context
  90      */
  91     HotSpotResolvedObjectTypeImpl(Class<?> javaClass, HotSpotJVMCIMetaAccessContext context) {
  92         super(getSignatureName(javaClass));
  93         this.javaClass = javaClass;
  94         this.context = context;
  95         assert getName().charAt(0) != '[' || isArray() : getName();
  96     }
  97 
  98     /**
  99      * Returns the name of this type as it would appear in a signature.
 100      */
 101     private static String getSignatureName(Class<?> javaClass) {
 102         if (javaClass.isArray()) {
 103             return javaClass.getName().replace('.', '/');
 104         }
 105         return "L" + javaClass.getName().replace('.', '/') + ";";
 106     }
 107 
 108     /**
 109      * Gets the metaspace Klass for this type.
 110      */
 111     public long getMetaspaceKlass() {
 112         if (HotSpotJVMCIRuntime.getHostWordKind() == JavaKind.Long) {
 113             return UNSAFE.getLong(javaClass, (long) runtime().getConfig().klassOffset);
 114         }
 115         return UNSAFE.getInt(javaClass, (long) runtime().getConfig().klassOffset) & 0xFFFFFFFFL;
 116     }
 117 
 118     public long getMetaspacePointer() {
 119         return getMetaspaceKlass();
 120     }
 121 
 122     @Override
 123     public int getModifiers() {
 124         if (isArray()) {
 125             return (getElementalType().getModifiers() & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED)) | Modifier.FINAL | Modifier.ABSTRACT;
 126         } else {
 127             return getAccessFlags() & ModifiersProvider.jvmClassModifiers();
 128         }
 129     }
 130 
 131     public int getAccessFlags() {
 132         HotSpotVMConfig config = runtime().getConfig();
 133         return UNSAFE.getInt(getMetaspaceKlass() + config.klassAccessFlagsOffset);
 134     }
 135 
 136     @Override
 137     public HotSpotResolvedObjectType getArrayClass() {
 138         if (arrayOfType == null) {
 139             arrayOfType = fromObjectClass(Array.newInstance(mirror(), 0).getClass());
 140         }
 141         return arrayOfType;
 142     }
 143 
 144     @Override
 145     public ResolvedJavaType getComponentType() {
 146         Class<?> javaComponentType = mirror().getComponentType();
 147         return javaComponentType == null ? null : runtime().fromClass(javaComponentType);
 148     }
 149 
 150     @Override
 151     public AssumptionResult<ResolvedJavaType> findLeafConcreteSubtype() {
 152         HotSpotVMConfig config = runtime().getConfig();
 153         if (isArray()) {
 154             return getElementalType().isLeaf() ? new AssumptionResult<>(this) : null;
 155         } else if (isInterface()) {
 156             HotSpotResolvedObjectTypeImpl implementor = getSingleImplementor();
 157             /*
 158              * If the implementor field contains itself that indicates that the interface has more
 159              * than one implementors (see: InstanceKlass::add_implementor).
 160              */
 161             if (implementor == null || implementor.equals(this)) {
 162                 return null;
 163             }
 164 
 165             assert !implementor.isInterface();
 166             if (implementor.isAbstract() || !implementor.isLeafClass()) {
 167                 AssumptionResult<ResolvedJavaType> leafConcreteSubtype = implementor.findLeafConcreteSubtype();
 168                 if (leafConcreteSubtype != null) {
 169                     assert !leafConcreteSubtype.getResult().equals(implementor);
 170                     AssumptionResult<ResolvedJavaType> newResult = new AssumptionResult<>(leafConcreteSubtype.getResult(), new ConcreteSubtype(this, implementor));
 171                     // Accumulate leaf assumptions and return the combined result.
 172                     newResult.add(leafConcreteSubtype);
 173                     return newResult;
 174                 }
 175                 return null;
 176             }
 177 
 178             return new AssumptionResult<>(implementor, new LeafType(implementor), new ConcreteSubtype(this, implementor));
 179         } else {
 180             HotSpotResolvedObjectTypeImpl type = this;
 181             while (type.isAbstract()) {
 182                 HotSpotResolvedObjectTypeImpl subklass = type.getSubklass();
 183                 if (subklass == null || UNSAFE.getAddress(subklass.getMetaspaceKlass() + config.nextSiblingOffset) != 0) {
 184                     return null;
 185                 }
 186                 type = subklass;
 187             }
 188             if (type.isAbstract() || type.isInterface() || !type.isLeafClass()) {
 189                 return null;
 190             }
 191             if (this.isAbstract()) {
 192                 return new AssumptionResult<>(type, new LeafType(type), new ConcreteSubtype(this, type));
 193             } else {
 194                 assert this.equals(type);
 195                 return new AssumptionResult<>(type, new LeafType(type));
 196             }
 197         }
 198     }
 199 
 200     /**
 201      * Returns if type {@code type} is a leaf class. This is the case if the
 202      * {@code Klass::_subklass} field of the underlying class is zero.
 203      *
 204      * @return true if the type is a leaf class
 205      */
 206     private boolean isLeafClass() {
 207         return getSubklass() == null;
 208     }
 209 
 210     /**
 211      * Returns the {@code Klass::_subklass} field of the underlying metaspace klass for the given
 212      * type {@code type}.
 213      *
 214      * @return value of the subklass field as metaspace klass pointer
 215      */
 216     private HotSpotResolvedObjectTypeImpl getSubklass() {
 217         return runtime().getCompilerToVM().getResolvedJavaType(this, runtime().getConfig().subklassOffset, false);
 218     }
 219 
 220     @Override
 221     public HotSpotResolvedObjectTypeImpl getSuperclass() {
 222         Class<?> javaSuperclass = mirror().getSuperclass();
 223         return javaSuperclass == null ? null : fromObjectClass(javaSuperclass);
 224     }
 225 
 226     @Override
 227     public HotSpotResolvedObjectTypeImpl[] getInterfaces() {
 228         if (interfaces == null) {
 229             Class<?>[] javaInterfaces = mirror().getInterfaces();
 230             HotSpotResolvedObjectTypeImpl[] result = new HotSpotResolvedObjectTypeImpl[javaInterfaces.length];
 231             for (int i = 0; i < javaInterfaces.length; i++) {
 232                 result[i] = fromObjectClass(javaInterfaces[i]);
 233             }
 234             interfaces = result;
 235         }
 236         return interfaces;
 237     }
 238 
 239     @Override
 240     public HotSpotResolvedObjectTypeImpl getSingleImplementor() {
 241         if (!isInterface()) {
 242             throw new JVMCIError("Cannot call getSingleImplementor() on a non-interface type: %s", this);
 243         }
 244         return runtime().getCompilerToVM().getImplementor(this);
 245     }
 246 
 247     public HotSpotResolvedObjectTypeImpl getSupertype() {
 248         if (isArray()) {
 249             ResolvedJavaType componentType = getComponentType();
 250             if (mirror() == Object[].class || componentType.isPrimitive()) {
 251                 return fromObjectClass(Object.class);
 252             }
 253             return (HotSpotResolvedObjectTypeImpl) ((HotSpotResolvedObjectTypeImpl) componentType).getSupertype().getArrayClass();
 254         }
 255         if (isInterface()) {
 256             return fromObjectClass(Object.class);
 257         }
 258         return getSuperclass();
 259     }
 260 
 261     @Override
 262     public HotSpotResolvedObjectType findLeastCommonAncestor(ResolvedJavaType otherType) {
 263         if (otherType.isPrimitive()) {
 264             return null;
 265         } else {
 266             HotSpotResolvedObjectTypeImpl t1 = this;
 267             HotSpotResolvedObjectTypeImpl t2 = (HotSpotResolvedObjectTypeImpl) otherType;
 268             while (true) {
 269                 if (t1.isAssignableFrom(t2)) {
 270                     return t1;
 271                 }
 272                 if (t2.isAssignableFrom(t1)) {
 273                     return t2;
 274                 }
 275                 t1 = t1.getSupertype();
 276                 t2 = t2.getSupertype();
 277             }
 278         }
 279     }
 280 
 281     @Override
 282     public HotSpotResolvedObjectType asExactType() {
 283         return isLeaf() ? this : null;
 284     }
 285 
 286     @Override
 287     public JavaConstant getJavaClass() {
 288         return HotSpotObjectConstantImpl.forObject(mirror());
 289     }
 290 
 291     @Override
 292     public JavaConstant getObjectHub() {
 293         return klass();
 294     }
 295 
 296     @Override
 297     public AssumptionResult<Boolean> hasFinalizableSubclass() {
 298         assert !isArray();
 299         if (!runtime().getCompilerToVM().hasFinalizableSubclass(this)) {
 300             return new AssumptionResult<>(false, new NoFinalizableSubclass(this));
 301         }
 302         return new AssumptionResult<>(true);
 303     }
 304 
 305     @Override
 306     public boolean hasFinalizer() {
 307         HotSpotVMConfig config = runtime().getConfig();
 308         return (getAccessFlags() & config.klassHasFinalizerFlag) != 0;
 309     }
 310 
 311     @Override
 312     public boolean isPrimitive() {
 313         return false;
 314     }
 315 
 316     @Override
 317     public boolean isArray() {
 318         return mirror().isArray();
 319     }
 320 
 321     @Override
 322     public boolean isInitialized() {
 323         return isArray() ? true : getInitState() == runtime().getConfig().instanceKlassStateFullyInitialized;
 324     }
 325 
 326     @Override
 327     public boolean isLinked() {
 328         return isArray() ? true : getInitState() >= runtime().getConfig().instanceKlassStateLinked;
 329     }
 330 
 331     /**
 332      * Returns the value of the state field {@code InstanceKlass::_init_state} of the metaspace
 333      * klass.
 334      *
 335      * @return state field value of this type
 336      */
 337     private int getInitState() {
 338         assert !isArray() : "_init_state only exists in InstanceKlass";
 339         return UNSAFE.getByte(getMetaspaceKlass() + runtime().getConfig().instanceKlassInitStateOffset) & 0xFF;
 340     }
 341 
 342     @Override
 343     public void initialize() {
 344         if (!isInitialized()) {
 345             UNSAFE.ensureClassInitialized(mirror());
 346             assert isInitialized();
 347         }
 348     }
 349 
 350     @Override
 351     public boolean isInstance(JavaConstant obj) {
 352         if (obj.getJavaKind() == JavaKind.Object && !obj.isNull()) {
 353             return mirror().isInstance(((HotSpotObjectConstantImpl) obj).object());
 354         }
 355         return false;
 356     }
 357 
 358     @Override
 359     public boolean isInstanceClass() {
 360         return !isArray() && !isInterface();
 361     }
 362 
 363     @Override
 364     public boolean isInterface() {
 365         return mirror().isInterface();
 366     }
 367 
 368     @Override
 369     public boolean isAssignableFrom(ResolvedJavaType other) {
 370         assert other != null;
 371         if (other instanceof HotSpotResolvedObjectTypeImpl) {
 372             HotSpotResolvedObjectTypeImpl otherType = (HotSpotResolvedObjectTypeImpl) other;
 373             return mirror().isAssignableFrom(otherType.mirror());
 374         }
 375         return false;
 376     }
 377 
 378     @Override
 379     public boolean isJavaLangObject() {
 380         return javaClass.equals(Object.class);
 381     }
 382 
 383     @Override
 384     public JavaKind getJavaKind() {
 385         return JavaKind.Object;
 386     }
 387 
 388     @Override
 389     public ResolvedJavaMethod resolveConcreteMethod(ResolvedJavaMethod method, ResolvedJavaType callerType) {
 390         ResolvedJavaMethod resolvedMethod = resolveMethod(method, callerType);
 391         if (resolvedMethod == null || resolvedMethod.isAbstract()) {
 392             return null;
 393         }
 394         return resolvedMethod;
 395     }
 396 
 397     @Override
 398     public ResolvedJavaMethod resolveMethod(ResolvedJavaMethod method, ResolvedJavaType callerType) {
 399         assert !callerType.isArray();
 400         if (method.isConcrete() && method.getDeclaringClass().equals(this) && method.isPublic()) {
 401             return method;
 402         }
 403         if (!method.getDeclaringClass().isAssignableFrom(this)) {
 404             return null;
 405         }
 406         HotSpotResolvedJavaMethodImpl hotSpotMethod = (HotSpotResolvedJavaMethodImpl) method;
 407         HotSpotResolvedObjectTypeImpl hotSpotCallerType = (HotSpotResolvedObjectTypeImpl) callerType;
 408         return runtime().getCompilerToVM().resolveMethod(this, hotSpotMethod, hotSpotCallerType);
 409     }
 410 
 411     public HotSpotConstantPool getConstantPool() {
 412         if (constantPool == null) {
 413             constantPool = runtime().getCompilerToVM().getConstantPool(this, runtime().getConfig().instanceKlassConstantsOffset);
 414         }
 415         return constantPool;
 416     }
 417 
 418     /**
 419      * Gets the instance size of this type. If an instance of this type cannot be fast path
 420      * allocated, then the returned value is negative (its absolute value gives the size). Must not
 421      * be called if this is an array or interface type.
 422      */
 423     public int instanceSize() {
 424         assert !isArray();
 425         assert !isInterface();
 426 
 427         HotSpotVMConfig config = runtime().getConfig();
 428         final int layoutHelper = layoutHelper();
 429         assert layoutHelper > config.klassLayoutHelperNeutralValue : "must be instance";
 430 
 431         // See: Klass::layout_helper_size_in_bytes
 432         int size = layoutHelper & ~config.klassLayoutHelperInstanceSlowPathBit;
 433 
 434         // See: Klass::layout_helper_needs_slow_path
 435         boolean needsSlowPath = (layoutHelper & config.klassLayoutHelperInstanceSlowPathBit) != 0;
 436 
 437         return needsSlowPath ? -size : size;
 438     }
 439 
 440     public int layoutHelper() {
 441         HotSpotVMConfig config = runtime().getConfig();
 442         return UNSAFE.getInt(getMetaspaceKlass() + config.klassLayoutHelperOffset);
 443     }
 444 
 445     synchronized HotSpotResolvedJavaMethod createMethod(long metaspaceMethod) {
 446         HotSpotResolvedJavaMethodImpl method = null;
 447         if (methodCache == null) {
 448             methodCache = new HashMap<>(8);
 449         } else {
 450             method = methodCache.get(metaspaceMethod);
 451         }
 452         if (method == null) {
 453             method = new HotSpotResolvedJavaMethodImpl(this, metaspaceMethod);
 454             methodCache.put(metaspaceMethod, method);
 455             context.add(method);
 456         }
 457         return method;
 458     }
 459 
 460     public int getVtableLength() {
 461         HotSpotVMConfig config = runtime().getConfig();
 462         if (isInterface() || isArray()) {
 463             /* Everything has the core vtable of java.lang.Object */
 464             return config.baseVtableLength();
 465         }
 466         int result = UNSAFE.getInt(getMetaspaceKlass() + config.instanceKlassVtableLengthOffset) / (config.vtableEntrySize / config.heapWordSize);
 467         assert result >= config.baseVtableLength() : UNSAFE.getInt(getMetaspaceKlass() + config.instanceKlassVtableLengthOffset) + " " + config.vtableEntrySize;
 468         return result;
 469     }
 470 
 471     public synchronized HotSpotResolvedJavaField createField(String fieldName, JavaType type, long offset, int rawFlags) {
 472         HotSpotResolvedJavaField result = null;
 473 
 474         final int flags = rawFlags & ModifiersProvider.jvmFieldModifiers();
 475 
 476         final long id = offset + ((long) flags << 32);
 477 
 478         // Must cache the fields, because the local load elimination only works if the
 479         // objects from two field lookups are identical.
 480         if (fieldCache == null) {
 481             fieldCache = new HashMap<>(8);
 482         } else {
 483             result = fieldCache.get(id);
 484         }
 485 
 486         if (result == null) {
 487             result = new HotSpotResolvedJavaFieldImpl(this, fieldName, type, offset, rawFlags);
 488             fieldCache.put(id, result);
 489         } else {
 490             assert result.getName().equals(fieldName);
 491             // assert result.getType().equals(type);
 492             assert result.offset() == offset;
 493             assert result.getModifiers() == flags;
 494         }
 495 
 496         return result;
 497     }
 498 
 499     @Override
 500     public AssumptionResult<ResolvedJavaMethod> findUniqueConcreteMethod(ResolvedJavaMethod method) {
 501         HotSpotResolvedJavaMethod hmethod = (HotSpotResolvedJavaMethod) method;
 502         HotSpotResolvedObjectType declaredHolder = hmethod.getDeclaringClass();
 503         /*
 504          * Sometimes the receiver type in the graph hasn't stabilized to a subtype of declared
 505          * holder, usually because of phis, so make sure that the type is related to the declared
 506          * type before using it for lookup. Unlinked types should also be ignored because we can't
 507          * resolve the proper method to invoke. Generally unlinked types in invokes should result in
 508          * a deopt instead since they can't really be used if they aren't linked yet.
 509          */
 510         if (!declaredHolder.isAssignableFrom(this) || this.isArray() || this.equals(declaredHolder) || !isLinked() || isInterface()) {
 511             ResolvedJavaMethod result = hmethod.uniqueConcreteMethod(declaredHolder);
 512             if (result != null) {
 513                 return new AssumptionResult<>(result, new ConcreteMethod(method, declaredHolder, result));
 514             }
 515             return null;
 516         }
 517         /*
 518          * The holder may be a subtype of the declaredHolder so make sure to resolve the method to
 519          * the correct method for the subtype.
 520          */
 521         HotSpotResolvedJavaMethod resolvedMethod = (HotSpotResolvedJavaMethod) resolveMethod(hmethod, this);
 522         if (resolvedMethod == null) {
 523             // The type isn't known to implement the method.
 524             return null;
 525         }
 526 
 527         ResolvedJavaMethod result = resolvedMethod.uniqueConcreteMethod(this);
 528         if (result != null) {
 529             return new AssumptionResult<>(result, new ConcreteMethod(method, this, result));
 530         }
 531         return null;
 532     }
 533 
 534     /**
 535      * This class represents the field information for one field contained in the fields array of an
 536      * {@code InstanceKlass}. The implementation is similar to the native {@code FieldInfo} class.
 537      */
 538     private class FieldInfo {
 539         /**
 540          * Native pointer into the array of Java shorts.
 541          */
 542         private final long metaspaceData;
 543 
 544         /**
 545          * Creates a field info for the field in the fields array at index {@code index}.
 546          *
 547          * @param index index to the fields array
 548          */
 549         public FieldInfo(int index) {
 550             HotSpotVMConfig config = runtime().getConfig();
 551             // Get Klass::_fields
 552             final long metaspaceFields = UNSAFE.getAddress(getMetaspaceKlass() + config.instanceKlassFieldsOffset);
 553             assert config.fieldInfoFieldSlots == 6 : "revisit the field parsing code";
 554             metaspaceData = metaspaceFields + config.arrayU2DataOffset + config.fieldInfoFieldSlots * Short.BYTES * index;
 555         }
 556 
 557         private int getAccessFlags() {
 558             return readFieldSlot(runtime().getConfig().fieldInfoAccessFlagsOffset);
 559         }
 560 
 561         private int getNameIndex() {
 562             return readFieldSlot(runtime().getConfig().fieldInfoNameIndexOffset);
 563         }
 564 
 565         private int getSignatureIndex() {
 566             return readFieldSlot(runtime().getConfig().fieldInfoSignatureIndexOffset);
 567         }
 568 
 569         public int getOffset() {
 570             HotSpotVMConfig config = runtime().getConfig();
 571             final int lowPacked = readFieldSlot(config.fieldInfoLowPackedOffset);
 572             final int highPacked = readFieldSlot(config.fieldInfoHighPackedOffset);
 573             final int offset = ((highPacked << Short.SIZE) | lowPacked) >> config.fieldInfoTagSize;
 574             return offset;
 575         }
 576 
 577         /**
 578          * Helper method to read an entry (slot) from the field array. Currently field info is laid
 579          * on top an array of Java shorts.
 580          */
 581         private int readFieldSlot(int index) {
 582             return UNSAFE.getChar(metaspaceData + Short.BYTES * index);
 583         }
 584 
 585         /**
 586          * Returns the name of this field as a {@link String}. If the field is an internal field the
 587          * name index is pointing into the vmSymbols table.
 588          */
 589         public String getName() {
 590             final int nameIndex = getNameIndex();
 591             return isInternal() ? HotSpotVmSymbols.symbolAt(nameIndex) : getConstantPool().lookupUtf8(nameIndex);
 592         }
 593 
 594         /**
 595          * Returns the signature of this field as {@link String}. If the field is an internal field
 596          * the signature index is pointing into the vmSymbols table.
 597          */
 598         public String getSignature() {
 599             final int signatureIndex = getSignatureIndex();
 600             return isInternal() ? HotSpotVmSymbols.symbolAt(signatureIndex) : getConstantPool().lookupUtf8(signatureIndex);
 601         }
 602 
 603         public JavaType getType() {
 604             String signature = getSignature();
 605             return runtime().lookupType(signature, HotSpotResolvedObjectTypeImpl.this, false);
 606         }
 607 
 608         private boolean isInternal() {
 609             return (getAccessFlags() & runtime().getConfig().jvmAccFieldInternal) != 0;
 610         }
 611 
 612         public boolean isStatic() {
 613             return Modifier.isStatic(getAccessFlags());
 614         }
 615 
 616         public boolean hasGenericSignature() {
 617             return (getAccessFlags() & runtime().getConfig().jvmAccFieldHasGenericSignature) != 0;
 618         }
 619     }
 620 
 621     private static class OffsetComparator implements java.util.Comparator<HotSpotResolvedJavaField> {
 622         @Override
 623         public int compare(HotSpotResolvedJavaField o1, HotSpotResolvedJavaField o2) {
 624             return o1.offset() - o2.offset();
 625         }
 626     }
 627 
 628     @Override
 629     public ResolvedJavaField[] getInstanceFields(boolean includeSuperclasses) {
 630         if (instanceFields == null) {
 631             if (isArray() || isInterface()) {
 632                 instanceFields = new HotSpotResolvedJavaField[0];
 633             } else {
 634                 final int fieldCount = getFieldCount();
 635                 ArrayList<HotSpotResolvedJavaField> fieldsArray = new ArrayList<>(fieldCount);
 636 
 637                 for (int i = 0; i < fieldCount; i++) {
 638                     FieldInfo field = new FieldInfo(i);
 639 
 640                     // We are only interested in instance fields.
 641                     if (!field.isStatic()) {
 642                         HotSpotResolvedJavaField resolvedJavaField = createField(field.getName(), field.getType(), field.getOffset(), field.getAccessFlags());
 643                         fieldsArray.add(resolvedJavaField);
 644                     }
 645                 }
 646 
 647                 fieldsArray.sort(new OffsetComparator());
 648 
 649                 HotSpotResolvedJavaField[] myFields = fieldsArray.toArray(new HotSpotResolvedJavaField[0]);
 650 
 651                 if (mirror() != Object.class) {
 652                     HotSpotResolvedJavaField[] superFields = (HotSpotResolvedJavaField[]) getSuperclass().getInstanceFields(true);
 653                     HotSpotResolvedJavaField[] fields = Arrays.copyOf(superFields, superFields.length + myFields.length);
 654                     System.arraycopy(myFields, 0, fields, superFields.length, myFields.length);
 655                     instanceFields = fields;
 656                 } else {
 657                     assert myFields.length == 0 : "java.lang.Object has fields!";
 658                     instanceFields = myFields;
 659                 }
 660 
 661             }
 662         }
 663         if (!includeSuperclasses) {
 664             int myFieldsStart = 0;
 665             while (myFieldsStart < instanceFields.length && !instanceFields[myFieldsStart].getDeclaringClass().equals(this)) {
 666                 myFieldsStart++;
 667             }
 668             if (myFieldsStart == 0) {
 669                 return instanceFields;
 670             }
 671             if (myFieldsStart == instanceFields.length) {
 672                 return new HotSpotResolvedJavaField[0];
 673             }
 674             return Arrays.copyOfRange(instanceFields, myFieldsStart, instanceFields.length);
 675         }
 676         return instanceFields;
 677     }
 678 
 679     @Override
 680     public ResolvedJavaField[] getStaticFields() {
 681         if (isArray()) {
 682             return new HotSpotResolvedJavaField[0];
 683         } else {
 684             final int fieldCount = getFieldCount();
 685             ArrayList<HotSpotResolvedJavaField> fieldsArray = new ArrayList<>(fieldCount);
 686 
 687             for (int i = 0; i < fieldCount; i++) {
 688                 FieldInfo field = new FieldInfo(i);
 689 
 690                 // We are only interested in static fields.
 691                 if (field.isStatic()) {
 692                     HotSpotResolvedJavaField resolvedJavaField = createField(field.getName(), field.getType(), field.getOffset(), field.getAccessFlags());
 693                     fieldsArray.add(resolvedJavaField);
 694                 }
 695             }
 696 
 697             fieldsArray.sort(new OffsetComparator());
 698             return fieldsArray.toArray(new HotSpotResolvedJavaField[fieldsArray.size()]);
 699         }
 700     }
 701 
 702     /**
 703      * Returns the actual field count of this class's internal {@code InstanceKlass::_fields} array
 704      * by walking the array and discounting the generic signature slots at the end of the array.
 705      *
 706      * <p>
 707      * See {@code FieldStreamBase::init_generic_signature_start_slot}
 708      */
 709     private int getFieldCount() {
 710         HotSpotVMConfig config = runtime().getConfig();
 711         final long metaspaceFields = UNSAFE.getAddress(getMetaspaceKlass() + config.instanceKlassFieldsOffset);
 712         int metaspaceFieldsLength = UNSAFE.getInt(metaspaceFields + config.arrayU1LengthOffset);
 713         int fieldCount = 0;
 714 
 715         for (int i = 0, index = 0; i < metaspaceFieldsLength; i += config.fieldInfoFieldSlots, index++) {
 716             FieldInfo field = new FieldInfo(index);
 717             if (field.hasGenericSignature()) {
 718                 metaspaceFieldsLength--;
 719             }
 720             fieldCount++;
 721         }
 722         return fieldCount;
 723     }
 724 
 725     @Override
 726     public Class<?> mirror() {
 727         return javaClass;
 728     }
 729 
 730     @Override
 731     public String getSourceFileName() {
 732         HotSpotVMConfig config = runtime().getConfig();
 733         final int sourceFileNameIndex = UNSAFE.getChar(getMetaspaceKlass() + config.instanceKlassSourceFileNameIndexOffset);
 734         if (sourceFileNameIndex == 0) {
 735             return null;
 736         }
 737         return getConstantPool().lookupUtf8(sourceFileNameIndex);
 738     }
 739 
 740     @Override
 741     public Annotation[] getAnnotations() {
 742         return mirror().getAnnotations();
 743     }
 744 
 745     @Override
 746     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 747         return mirror().getAnnotation(annotationClass);
 748     }
 749 
 750     /**
 751      * Performs a fast-path check that this type is resolved in the context of a given accessing
 752      * class. A negative result does not mean this type is not resolved with respect to
 753      * {@code accessingClass}. That can only be determined by
 754      * {@linkplain HotSpotJVMCIRuntime#lookupType(String, HotSpotResolvedObjectType, boolean)
 755      * re-resolving} the type.
 756      */
 757     public boolean isDefinitelyResolvedWithRespectTo(ResolvedJavaType accessingClass) {
 758         assert accessingClass != null;
 759         ResolvedJavaType elementType = getElementalType();
 760         if (elementType.isPrimitive()) {
 761             // Primitive type resolution is context free.
 762             return true;
 763         }
 764         if (elementType.getName().startsWith("Ljava/")) {
 765             // Classes in a java.* package can only be defined by the
 766             // boot class loader. This is enforced by ClassLoader.preDefineClass()
 767             assert mirror().getClassLoader() == null;
 768             return true;
 769         }
 770         ClassLoader thisCl = mirror().getClassLoader();
 771         ClassLoader accessingClassCl = ((HotSpotResolvedObjectTypeImpl) accessingClass).mirror().getClassLoader();
 772         return thisCl == accessingClassCl;
 773     }
 774 
 775     @Override
 776     public ResolvedJavaType resolve(ResolvedJavaType accessingClass) {
 777         if (isDefinitelyResolvedWithRespectTo(requireNonNull(accessingClass))) {
 778             return this;
 779         }
 780         HotSpotResolvedObjectTypeImpl accessingType = (HotSpotResolvedObjectTypeImpl) accessingClass;
 781         return (ResolvedJavaType) runtime().lookupType(getName(), accessingType, true);
 782     }
 783 
 784     /**
 785      * Gets the metaspace Klass boxed in a {@link JavaConstant}.
 786      */
 787     public JavaConstant klass() {
 788         return HotSpotMetaspaceConstantImpl.forMetaspaceObject(runtime().getHostJVMCIBackend().getTarget().wordKind, getMetaspaceKlass(), this, false);
 789     }
 790 
 791     public boolean isPrimaryType() {
 792         return runtime().getConfig().secondarySuperCacheOffset != superCheckOffset();
 793     }
 794 
 795     public int superCheckOffset() {
 796         HotSpotVMConfig config = runtime().getConfig();
 797         return UNSAFE.getInt(getMetaspaceKlass() + config.superCheckOffsetOffset);
 798     }
 799 
 800     public long prototypeMarkWord() {
 801         HotSpotVMConfig config = runtime().getConfig();
 802         if (isArray()) {
 803             return config.arrayPrototypeMarkWord();
 804         } else {
 805             return UNSAFE.getAddress(getMetaspaceKlass() + config.prototypeMarkWordOffset);
 806         }
 807     }
 808 
 809     @Override
 810     public ResolvedJavaField findInstanceFieldWithOffset(long offset, JavaKind expectedEntryKind) {
 811         ResolvedJavaField[] declaredFields = getInstanceFields(true);
 812         for (ResolvedJavaField field : declaredFields) {
 813             HotSpotResolvedJavaField resolvedField = (HotSpotResolvedJavaField) field;
 814             long resolvedFieldOffset = resolvedField.offset();
 815             // @formatter:off
 816             if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN  &&
 817                             expectedEntryKind.isPrimitive() &&
 818                             !expectedEntryKind.equals(JavaKind.Void) &&
 819                             resolvedField.getJavaKind().isPrimitive()) {
 820                 resolvedFieldOffset +=
 821                                 resolvedField.getJavaKind().getByteCount() -
 822                                 Math.min(resolvedField.getJavaKind().getByteCount(), 4 + expectedEntryKind.getByteCount());
 823             }
 824             if (resolvedFieldOffset == offset) {
 825                 return field;
 826             }
 827             // @formatter:on
 828         }
 829         return null;
 830     }
 831 
 832     @Override
 833     public URL getClassFilePath() {
 834         Class<?> cls = mirror();
 835         return cls.getResource(MetaUtil.getSimpleName(cls, true).replace('.', '$') + ".class");
 836     }
 837 
 838     @Override
 839     public boolean isLocal() {
 840         return mirror().isLocalClass();
 841     }
 842 
 843     @Override
 844     public boolean isMember() {
 845         return mirror().isMemberClass();
 846     }
 847 
 848     @Override
 849     public HotSpotResolvedObjectTypeImpl getEnclosingType() {
 850         final Class<?> encl = mirror().getEnclosingClass();
 851         return encl == null ? null : fromObjectClass(encl);
 852     }
 853 
 854     @Override
 855     public ResolvedJavaMethod[] getDeclaredConstructors() {
 856         Constructor<?>[] constructors = mirror().getDeclaredConstructors();
 857         ResolvedJavaMethod[] result = new ResolvedJavaMethod[constructors.length];
 858         for (int i = 0; i < constructors.length; i++) {
 859             result[i] = runtime().getHostJVMCIBackend().getMetaAccess().lookupJavaMethod(constructors[i]);
 860             assert result[i].isConstructor();
 861         }
 862         return result;
 863     }
 864 
 865     @Override
 866     public ResolvedJavaMethod[] getDeclaredMethods() {
 867         Method[] methods = mirror().getDeclaredMethods();
 868         ResolvedJavaMethod[] result = new ResolvedJavaMethod[methods.length];
 869         for (int i = 0; i < methods.length; i++) {
 870             result[i] = runtime().getHostJVMCIBackend().getMetaAccess().lookupJavaMethod(methods[i]);
 871             assert !result[i].isConstructor();
 872         }
 873         return result;
 874     }
 875 
 876     public ResolvedJavaMethod getClassInitializer() {
 877         return runtime().getCompilerToVM().getClassInitializer(this);
 878     }
 879 
 880     @Override
 881     public String toString() {
 882         return "HotSpotType<" + getName() + ", resolved>";
 883     }
 884 
 885     @Override
 886     public boolean isTrustedInterfaceType() {
 887         return TrustedInterface.class.isAssignableFrom(mirror());
 888     }
 889 }