1 /*
   2  * Copyright (c) 2008, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import jdk.internal.misc.Unsafe;
  29 import jdk.internal.vm.annotation.ForceInline;
  30 import jdk.internal.vm.annotation.Stable;
  31 import sun.invoke.util.ValueConversions;
  32 import sun.invoke.util.VerifyAccess;
  33 import sun.invoke.util.VerifyType;
  34 import sun.invoke.util.Wrapper;
  35 
  36 import java.lang.ref.WeakReference;
  37 import java.util.Arrays;
  38 import java.util.Objects;
  39 
  40 import static java.lang.invoke.LambdaForm.*;
  41 import static java.lang.invoke.LambdaForm.Kind.*;
  42 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  43 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
  44 import static java.lang.invoke.MethodHandleStatics.newInternalError;
  45 import static java.lang.invoke.MethodTypeForm.*;
  46 
  47 /**
  48  * The flavor of method handle which implements a constant reference
  49  * to a class member.
  50  * @author jrose
  51  */
  52 class DirectMethodHandle extends MethodHandle {
  53     final MemberName member;
  54 
  55     // Constructors and factory methods in this class *must* be package scoped or private.
  56     private DirectMethodHandle(MethodType mtype, LambdaForm form, MemberName member) {
  57         super(mtype, form);
  58         if (!member.isResolved())  throw new InternalError();
  59 
  60         if (member.getDeclaringClass().isInterface() &&
  61             member.getReferenceKind() == REF_invokeInterface &&
  62             member.isMethod() && !member.isAbstract()) {
  63             // Check for corner case: invokeinterface of Object method
  64             MemberName m = new MemberName(Object.class, member.getName(), member.getMethodType(), member.getReferenceKind());
  65             m = MemberName.getFactory().resolveOrNull(m.getReferenceKind(), m, null);
  66             if (m != null && m.isPublic()) {
  67                 assert(member.getReferenceKind() == m.getReferenceKind());  // else this.form is wrong
  68                 member = m;
  69             }
  70         }
  71 
  72         this.member = member;
  73     }
  74 
  75     // Factory methods:
  76     static DirectMethodHandle make(byte refKind, Class<?> refc, MemberName member, Class<?> callerClass) {
  77         MethodType mtype = member.getMethodOrFieldType();
  78         if (!member.isStatic()) {
  79             if (!member.getDeclaringClass().isAssignableFrom(refc) || member.isConstructor())
  80                 throw new InternalError(member.toString());
  81             mtype = mtype.insertParameterTypes(0, refc);
  82         }
  83         if (!member.isField()) {
  84             switch (refKind) {
  85                 case REF_invokeSpecial: {
  86                     member = member.asSpecial();
  87                     LambdaForm lform = preparedLambdaForm(member, callerClass);
  88                     Class<?> checkClass = refc;  // Class to use for receiver type check
  89                     if (callerClass != null) {
  90                         checkClass = callerClass;  // potentially strengthen to caller class
  91                     }
  92                     return new Special(mtype, lform, member, checkClass);
  93                 }
  94                 case REF_invokeInterface: {
  95                     LambdaForm lform = preparedLambdaForm(member, callerClass);
  96                     return new Interface(mtype, lform, member, refc);
  97                 }
  98                 default: {
  99                     LambdaForm lform = preparedLambdaForm(member, callerClass);
 100                     return new DirectMethodHandle(mtype, lform, member);
 101                 }
 102             }
 103         } else {
 104             LambdaForm lform = preparedFieldLambdaForm(member);
 105             if (member.isStatic()) {
 106                 long offset = MethodHandleNatives.staticFieldOffset(member);
 107                 Object base = MethodHandleNatives.staticFieldBase(member);
 108                 return new StaticAccessor(mtype, lform, member, base, offset);
 109             } else {
 110                 long offset = MethodHandleNatives.objectFieldOffset(member);
 111                 assert(offset == (int)offset);
 112                 return new Accessor(mtype, lform, member, (int)offset);
 113             }
 114         }
 115     }
 116     static DirectMethodHandle make(Class<?> refc, MemberName member) {
 117         byte refKind = member.getReferenceKind();
 118         if (refKind == REF_invokeSpecial)
 119             refKind =  REF_invokeVirtual;
 120         return make(refKind, refc, member, null /* no callerClass context */);
 121     }
 122     static DirectMethodHandle make(MemberName member) {
 123         if (member.isConstructor())
 124             return makeAllocator(member);
 125         return make(member.getDeclaringClass(), member);
 126     }
 127     private static DirectMethodHandle makeAllocator(MemberName ctor) {
 128         assert(ctor.isConstructor() && ctor.getName().equals("<init>"));
 129         Class<?> instanceClass = ctor.getDeclaringClass();
 130         ctor = ctor.asConstructor();
 131         assert(ctor.isConstructor() && ctor.getReferenceKind() == REF_newInvokeSpecial) : ctor;
 132         MethodType mtype = ctor.getMethodType().changeReturnType(instanceClass);
 133         LambdaForm lform = preparedLambdaForm(ctor);
 134         MemberName init = ctor.asSpecial();
 135         assert(init.getMethodType().returnType() == void.class);
 136         return new Constructor(mtype, lform, ctor, init, instanceClass);
 137     }
 138 
 139     @Override
 140     BoundMethodHandle rebind() {
 141         return BoundMethodHandle.makeReinvoker(this);
 142     }
 143 
 144     @Override
 145     MethodHandle copyWith(MethodType mt, LambdaForm lf) {
 146         assert(this.getClass() == DirectMethodHandle.class);  // must override in subclasses
 147         return new DirectMethodHandle(mt, lf, member);
 148     }
 149 
 150     @Override
 151     String internalProperties() {
 152         return "\n& DMH.MN="+internalMemberName();
 153     }
 154 
 155     //// Implementation methods.
 156     @Override
 157     @ForceInline
 158     MemberName internalMemberName() {
 159         return member;
 160     }
 161 
 162     private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
 163 
 164     /**
 165      * Create a LF which can invoke the given method.
 166      * Cache and share this structure among all methods with
 167      * the same basicType and refKind.
 168      */
 169     private static LambdaForm preparedLambdaForm(MemberName m, Class<?> callerClass) {
 170         assert(m.isInvocable()) : m;  // call preparedFieldLambdaForm instead
 171         MethodType mtype = m.getInvocationType().basicType();
 172         assert(!m.isMethodHandleInvoke()) : m;
 173         int which;
 174         switch (m.getReferenceKind()) {
 175         case REF_invokeVirtual:    which = LF_INVVIRTUAL;    break;
 176         case REF_invokeStatic:     which = LF_INVSTATIC;     break;
 177         case REF_invokeSpecial:    which = LF_INVSPECIAL;    break;
 178         case REF_invokeInterface:  which = LF_INVINTERFACE;  break;
 179         case REF_newInvokeSpecial: which = LF_NEWINVSPECIAL; break;
 180         default:  throw new InternalError(m.toString());
 181         }
 182         if (which == LF_INVSTATIC && shouldBeInitialized(m)) {
 183             // precompute the barrier-free version:
 184             preparedLambdaForm(mtype, which);
 185             which = LF_INVSTATIC_INIT;
 186         }
 187         if (which == LF_INVSPECIAL && callerClass != null && callerClass.isInterface()) {
 188             which = LF_INVSPECIAL_IFC;
 189         }
 190         LambdaForm lform = preparedLambdaForm(mtype, which);
 191         maybeCompile(lform, m);
 192         assert(lform.methodType().dropParameterTypes(0, 1)
 193                 .equals(m.getInvocationType().basicType()))
 194                 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType());
 195         return lform;
 196     }
 197 
 198     private static LambdaForm preparedLambdaForm(MemberName m) {
 199         return preparedLambdaForm(m, null);
 200     }
 201 
 202     private static LambdaForm preparedLambdaForm(MethodType mtype, int which) {
 203         LambdaForm lform = mtype.form().cachedLambdaForm(which);
 204         if (lform != null)  return lform;
 205         lform = makePreparedLambdaForm(mtype, which);
 206         return mtype.form().setCachedLambdaForm(which, lform);
 207     }
 208 
 209     static LambdaForm makePreparedLambdaForm(MethodType mtype, int which) {
 210         boolean needsInit = (which == LF_INVSTATIC_INIT);
 211         boolean doesAlloc = (which == LF_NEWINVSPECIAL);
 212         boolean needsReceiverCheck = (which == LF_INVINTERFACE ||
 213                                       which == LF_INVSPECIAL_IFC);
 214 
 215         String linkerName;
 216         LambdaForm.Kind kind;
 217         switch (which) {
 218         case LF_INVVIRTUAL:    linkerName = "linkToVirtual";   kind = DIRECT_INVOKE_VIRTUAL;     break;
 219         case LF_INVSTATIC:     linkerName = "linkToStatic";    kind = DIRECT_INVOKE_STATIC;      break;
 220         case LF_INVSTATIC_INIT:linkerName = "linkToStatic";    kind = DIRECT_INVOKE_STATIC_INIT; break;
 221         case LF_INVSPECIAL_IFC:linkerName = "linkToSpecial";   kind = DIRECT_INVOKE_SPECIAL_IFC; break;
 222         case LF_INVSPECIAL:    linkerName = "linkToSpecial";   kind = DIRECT_INVOKE_SPECIAL;     break;
 223         case LF_INVINTERFACE:  linkerName = "linkToInterface"; kind = DIRECT_INVOKE_INTERFACE;   break;
 224         case LF_NEWINVSPECIAL: linkerName = "linkToSpecial";   kind = DIRECT_NEW_INVOKE_SPECIAL; break;
 225         default:  throw new InternalError("which="+which);
 226         }
 227 
 228         MethodType mtypeWithArg = mtype.appendParameterTypes(MemberName.class);
 229         if (doesAlloc)
 230             mtypeWithArg = mtypeWithArg
 231                     .insertParameterTypes(0, Object.class)  // insert newly allocated obj
 232                     .changeReturnType(void.class);          // <init> returns void
 233         MemberName linker = new MemberName(MethodHandle.class, linkerName, mtypeWithArg, REF_invokeStatic);
 234         try {
 235             linker = IMPL_NAMES.resolveOrFail(REF_invokeStatic, linker, null, NoSuchMethodException.class);
 236         } catch (ReflectiveOperationException ex) {
 237             throw newInternalError(ex);
 238         }
 239         final int DMH_THIS    = 0;
 240         final int ARG_BASE    = 1;
 241         final int ARG_LIMIT   = ARG_BASE + mtype.parameterCount();
 242         int nameCursor = ARG_LIMIT;
 243         final int NEW_OBJ     = (doesAlloc ? nameCursor++ : -1);
 244         final int GET_MEMBER  = nameCursor++;
 245         final int CHECK_RECEIVER = (needsReceiverCheck ? nameCursor++ : -1);
 246         final int LINKER_CALL = nameCursor++;
 247         Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType());
 248         assert(names.length == nameCursor);
 249         if (doesAlloc) {
 250             // names = { argx,y,z,... new C, init method }
 251             names[NEW_OBJ] = new Name(getFunction(NF_allocateInstance), names[DMH_THIS]);
 252             names[GET_MEMBER] = new Name(getFunction(NF_constructorMethod), names[DMH_THIS]);
 253         } else if (needsInit) {
 254             names[GET_MEMBER] = new Name(getFunction(NF_internalMemberNameEnsureInit), names[DMH_THIS]);
 255         } else {
 256             names[GET_MEMBER] = new Name(getFunction(NF_internalMemberName), names[DMH_THIS]);
 257         }
 258         assert(findDirectMethodHandle(names[GET_MEMBER]) == names[DMH_THIS]);
 259         Object[] outArgs = Arrays.copyOfRange(names, ARG_BASE, GET_MEMBER+1, Object[].class);
 260         if (needsReceiverCheck) {
 261             names[CHECK_RECEIVER] = new Name(getFunction(NF_checkReceiver), names[DMH_THIS], names[ARG_BASE]);
 262             outArgs[0] = names[CHECK_RECEIVER];
 263         }
 264         assert(outArgs[outArgs.length-1] == names[GET_MEMBER]);  // look, shifted args!
 265         int result = LAST_RESULT;
 266         if (doesAlloc) {
 267             assert(outArgs[outArgs.length-2] == names[NEW_OBJ]);  // got to move this one
 268             System.arraycopy(outArgs, 0, outArgs, 1, outArgs.length-2);
 269             outArgs[0] = names[NEW_OBJ];
 270             result = NEW_OBJ;
 271         }
 272         names[LINKER_CALL] = new Name(linker, outArgs);
 273         LambdaForm lform = new LambdaForm(ARG_LIMIT, names, result, kind);
 274 
 275         // This is a tricky bit of code.  Don't send it through the LF interpreter.
 276         lform.compileToBytecode();
 277         return lform;
 278     }
 279 
 280     /* assert */ static Object findDirectMethodHandle(Name name) {
 281         if (name.function.equals(getFunction(NF_internalMemberName)) ||
 282             name.function.equals(getFunction(NF_internalMemberNameEnsureInit)) ||
 283             name.function.equals(getFunction(NF_constructorMethod))) {
 284             assert(name.arguments.length == 1);
 285             return name.arguments[0];
 286         }
 287         return null;
 288     }
 289 
 290     private static void maybeCompile(LambdaForm lform, MemberName m) {
 291         if (lform.vmentry == null && VerifyAccess.isSamePackage(m.getDeclaringClass(), MethodHandle.class))
 292             // Help along bootstrapping...
 293             lform.compileToBytecode();
 294     }
 295 
 296     /** Static wrapper for DirectMethodHandle.internalMemberName. */
 297     @ForceInline
 298     /*non-public*/ static Object internalMemberName(Object mh) {
 299         return ((DirectMethodHandle)mh).member;
 300     }
 301 
 302     /** Static wrapper for DirectMethodHandle.internalMemberName.
 303      * This one also forces initialization.
 304      */
 305     /*non-public*/ static Object internalMemberNameEnsureInit(Object mh) {
 306         DirectMethodHandle dmh = (DirectMethodHandle)mh;
 307         dmh.ensureInitialized();
 308         return dmh.member;
 309     }
 310 
 311     /*non-public*/ static
 312     boolean shouldBeInitialized(MemberName member) {
 313         switch (member.getReferenceKind()) {
 314         case REF_invokeStatic:
 315         case REF_getStatic:
 316         case REF_putStatic:
 317         case REF_newInvokeSpecial:
 318             break;
 319         default:
 320             // No need to initialize the class on this kind of member.
 321             return false;
 322         }
 323         Class<?> cls = member.getDeclaringClass();
 324         if (cls == ValueConversions.class ||
 325             cls == MethodHandleImpl.class ||
 326             cls == Invokers.class) {
 327             // These guys have lots of <clinit> DMH creation but we know
 328             // the MHs will not be used until the system is booted.
 329             return false;
 330         }
 331         if (VerifyAccess.isSamePackage(MethodHandle.class, cls) ||
 332             VerifyAccess.isSamePackage(ValueConversions.class, cls)) {
 333             // It is a system class.  It is probably in the process of
 334             // being initialized, but we will help it along just to be safe.
 335             if (UNSAFE.shouldBeInitialized(cls)) {
 336                 UNSAFE.ensureClassInitialized(cls);
 337             }
 338             return false;
 339         }
 340         return UNSAFE.shouldBeInitialized(cls);
 341     }
 342 
 343     private static class EnsureInitialized extends ClassValue<WeakReference<Thread>> {
 344         @Override
 345         protected WeakReference<Thread> computeValue(Class<?> type) {
 346             UNSAFE.ensureClassInitialized(type);
 347             if (UNSAFE.shouldBeInitialized(type))
 348                 // If the previous call didn't block, this can happen.
 349                 // We are executing inside <clinit>.
 350                 return new WeakReference<>(Thread.currentThread());
 351             return null;
 352         }
 353         static final EnsureInitialized INSTANCE = new EnsureInitialized();
 354     }
 355 
 356     private void ensureInitialized() {
 357         if (checkInitialized(member)) {
 358             // The coast is clear.  Delete the <clinit> barrier.
 359             if (member.isField())
 360                 updateForm(preparedFieldLambdaForm(member));
 361             else
 362                 updateForm(preparedLambdaForm(member));
 363         }
 364     }
 365     private static boolean checkInitialized(MemberName member) {
 366         Class<?> defc = member.getDeclaringClass();
 367         WeakReference<Thread> ref = EnsureInitialized.INSTANCE.get(defc);
 368         if (ref == null) {
 369             return true;  // the final state
 370         }
 371         Thread clinitThread = ref.get();
 372         // Somebody may still be running defc.<clinit>.
 373         if (clinitThread == Thread.currentThread()) {
 374             // If anybody is running defc.<clinit>, it is this thread.
 375             if (UNSAFE.shouldBeInitialized(defc))
 376                 // Yes, we are running it; keep the barrier for now.
 377                 return false;
 378         } else {
 379             // We are in a random thread.  Block.
 380             UNSAFE.ensureClassInitialized(defc);
 381         }
 382         assert(!UNSAFE.shouldBeInitialized(defc));
 383         // put it into the final state
 384         EnsureInitialized.INSTANCE.remove(defc);
 385         return true;
 386     }
 387 
 388     /*non-public*/ static void ensureInitialized(Object mh) {
 389         ((DirectMethodHandle)mh).ensureInitialized();
 390     }
 391 
 392     /** This subclass represents invokespecial instructions. */
 393     static class Special extends DirectMethodHandle {
 394         private final Class<?> caller;
 395         private Special(MethodType mtype, LambdaForm form, MemberName member, Class<?> caller) {
 396             super(mtype, form, member);
 397             this.caller = caller;
 398         }
 399         @Override
 400         boolean isInvokeSpecial() {
 401             return true;
 402         }
 403         @Override
 404         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
 405             return new Special(mt, lf, member, caller);
 406         }
 407         Object checkReceiver(Object recv) {
 408             if (!caller.isInstance(recv)) {
 409                 String msg = String.format("Receiver class %s is not a subclass of caller class %s",
 410                                            recv.getClass().getName(), caller.getName());
 411                 throw new IncompatibleClassChangeError(msg);
 412             }
 413             return recv;
 414         }
 415     }
 416 
 417     /** This subclass represents invokeinterface instructions. */
 418     static class Interface extends DirectMethodHandle {
 419         private final Class<?> refc;
 420         private Interface(MethodType mtype, LambdaForm form, MemberName member, Class<?> refc) {
 421             super(mtype, form, member);
 422             assert refc.isInterface() : refc;
 423             this.refc = refc;
 424         }
 425         @Override
 426         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
 427             return new Interface(mt, lf, member, refc);
 428         }
 429         @Override
 430         Object checkReceiver(Object recv) {
 431             if (!refc.isInstance(recv)) {
 432                 String msg = String.format("Receiver class %s does not implement the requested interface %s",
 433                                            recv.getClass().getName(), refc.getName());
 434                 throw new IncompatibleClassChangeError(msg);
 435             }
 436             return recv;
 437         }
 438     }
 439 
 440     /** Used for interface receiver type checks, by Interface and Special modes. */
 441     Object checkReceiver(Object recv) {
 442         throw new InternalError("Should only be invoked on a subclass");
 443     }
 444 
 445 
 446     /** This subclass handles constructor references. */
 447     static class Constructor extends DirectMethodHandle {
 448         final MemberName initMethod;
 449         final Class<?>   instanceClass;
 450 
 451         private Constructor(MethodType mtype, LambdaForm form, MemberName constructor,
 452                             MemberName initMethod, Class<?> instanceClass) {
 453             super(mtype, form, constructor);
 454             this.initMethod = initMethod;
 455             this.instanceClass = instanceClass;
 456             assert(initMethod.isResolved());
 457         }
 458         @Override
 459         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
 460             return new Constructor(mt, lf, member, initMethod, instanceClass);
 461         }
 462     }
 463 
 464     /*non-public*/ static Object constructorMethod(Object mh) {
 465         Constructor dmh = (Constructor)mh;
 466         return dmh.initMethod;
 467     }
 468 
 469     /*non-public*/ static Object allocateInstance(Object mh) throws InstantiationException {
 470         Constructor dmh = (Constructor)mh;
 471         return UNSAFE.allocateInstance(dmh.instanceClass);
 472     }
 473 
 474     /** This subclass handles non-static field references. */
 475     static class Accessor extends DirectMethodHandle {
 476         final Class<?> fieldType;
 477         final int      fieldOffset;
 478         private Accessor(MethodType mtype, LambdaForm form, MemberName member,
 479                          int fieldOffset) {
 480             super(mtype, form, member);
 481             this.fieldType   = member.getFieldType();
 482             this.fieldOffset = fieldOffset;
 483         }
 484 
 485         @Override Object checkCast(Object obj) {
 486             return fieldType.cast(obj);
 487         }
 488         @Override
 489         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
 490             return new Accessor(mt, lf, member, fieldOffset);
 491         }
 492     }
 493 
 494     @ForceInline
 495     /*non-public*/ static long fieldOffset(Object accessorObj) {
 496         // Note: We return a long because that is what Unsafe.getObject likes.
 497         // We store a plain int because it is more compact.
 498         return ((Accessor)accessorObj).fieldOffset;
 499     }
 500 
 501     @ForceInline
 502     /*non-public*/ static Object checkBase(Object obj) {
 503         // Note that the object's class has already been verified,
 504         // since the parameter type of the Accessor method handle
 505         // is either member.getDeclaringClass or a subclass.
 506         // This was verified in DirectMethodHandle.make.
 507         // Therefore, the only remaining check is for null.
 508         // Since this check is *not* guaranteed by Unsafe.getInt
 509         // and its siblings, we need to make an explicit one here.
 510         return Objects.requireNonNull(obj);
 511     }
 512 
 513     /** This subclass handles static field references. */
 514     static class StaticAccessor extends DirectMethodHandle {
 515         private final Class<?> fieldType;
 516         private final Object   staticBase;
 517         private final long     staticOffset;
 518 
 519         private StaticAccessor(MethodType mtype, LambdaForm form, MemberName member,
 520                                Object staticBase, long staticOffset) {
 521             super(mtype, form, member);
 522             this.fieldType    = member.getFieldType();
 523             this.staticBase   = staticBase;
 524             this.staticOffset = staticOffset;
 525         }
 526 
 527         @Override Object checkCast(Object obj) {
 528             return fieldType.cast(obj);
 529         }
 530         @Override
 531         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
 532             return new StaticAccessor(mt, lf, member, staticBase, staticOffset);
 533         }
 534     }
 535 
 536     @ForceInline
 537     /*non-public*/ static Object nullCheck(Object obj) {
 538         return Objects.requireNonNull(obj);
 539     }
 540 
 541     @ForceInline
 542     /*non-public*/ static Object staticBase(Object accessorObj) {
 543         return ((StaticAccessor)accessorObj).staticBase;
 544     }
 545 
 546     @ForceInline
 547     /*non-public*/ static long staticOffset(Object accessorObj) {
 548         return ((StaticAccessor)accessorObj).staticOffset;
 549     }
 550 
 551     @ForceInline
 552     /*non-public*/ static Object checkCast(Object mh, Object obj) {
 553         return ((DirectMethodHandle) mh).checkCast(obj);
 554     }
 555 
 556     Object checkCast(Object obj) {
 557         return member.getReturnType().cast(obj);
 558     }
 559 
 560     // Caching machinery for field accessors:
 561     static final byte
 562             AF_GETFIELD        = 0,
 563             AF_PUTFIELD        = 1,
 564             AF_GETSTATIC       = 2,
 565             AF_PUTSTATIC       = 3,
 566             AF_GETSTATIC_INIT  = 4,
 567             AF_PUTSTATIC_INIT  = 5,
 568             AF_LIMIT           = 6;
 569     // Enumerate the different field kinds using Wrapper,
 570     // with an extra case added for checked references.
 571     static final int
 572             FT_LAST_WRAPPER    = Wrapper.COUNT-1,
 573             FT_UNCHECKED_REF   = Wrapper.OBJECT.ordinal(),
 574             FT_CHECKED_REF     = FT_LAST_WRAPPER+1,
 575             FT_LIMIT           = FT_LAST_WRAPPER+2;
 576     private static int afIndex(byte formOp, boolean isVolatile, int ftypeKind) {
 577         return ((formOp * FT_LIMIT * 2)
 578                 + (isVolatile ? FT_LIMIT : 0)
 579                 + ftypeKind);
 580     }
 581     @Stable
 582     private static final LambdaForm[] ACCESSOR_FORMS
 583             = new LambdaForm[afIndex(AF_LIMIT, false, 0)];
 584     static int ftypeKind(Class<?> ftype) {
 585         if (ftype.isPrimitive())
 586             return Wrapper.forPrimitiveType(ftype).ordinal();
 587         else if (VerifyType.isNullReferenceConversion(Object.class, ftype))
 588             return FT_UNCHECKED_REF;
 589         else
 590             return FT_CHECKED_REF;
 591     }
 592 
 593     /**
 594      * Create a LF which can access the given field.
 595      * Cache and share this structure among all fields with
 596      * the same basicType and refKind.
 597      */
 598     private static LambdaForm preparedFieldLambdaForm(MemberName m) {
 599         Class<?> ftype = m.getFieldType();
 600         boolean isVolatile = m.isVolatile();
 601         byte formOp;
 602         switch (m.getReferenceKind()) {
 603         case REF_getField:      formOp = AF_GETFIELD;    break;
 604         case REF_putField:      formOp = AF_PUTFIELD;    break;
 605         case REF_getStatic:     formOp = AF_GETSTATIC;   break;
 606         case REF_putStatic:     formOp = AF_PUTSTATIC;   break;
 607         default:  throw new InternalError(m.toString());
 608         }
 609         if (shouldBeInitialized(m)) {
 610             // precompute the barrier-free version:
 611             preparedFieldLambdaForm(formOp, isVolatile, ftype);
 612             assert((AF_GETSTATIC_INIT - AF_GETSTATIC) ==
 613                    (AF_PUTSTATIC_INIT - AF_PUTSTATIC));
 614             formOp += (AF_GETSTATIC_INIT - AF_GETSTATIC);
 615         }
 616         LambdaForm lform = preparedFieldLambdaForm(formOp, isVolatile, ftype);
 617         maybeCompile(lform, m);
 618         assert(lform.methodType().dropParameterTypes(0, 1)
 619                 .equals(m.getInvocationType().basicType()))
 620                 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType());
 621         return lform;
 622     }
 623     private static LambdaForm preparedFieldLambdaForm(byte formOp, boolean isVolatile, Class<?> ftype) {
 624         int ftypeKind = ftypeKind(ftype);
 625         int afIndex = afIndex(formOp, isVolatile, ftypeKind);
 626         LambdaForm lform = ACCESSOR_FORMS[afIndex];
 627         if (lform != null)  return lform;
 628         lform = makePreparedFieldLambdaForm(formOp, isVolatile, ftypeKind);
 629         ACCESSOR_FORMS[afIndex] = lform;  // don't bother with a CAS
 630         return lform;
 631     }
 632 
 633     private static final Wrapper[] ALL_WRAPPERS = Wrapper.values();
 634 
 635     private static Kind getFieldKind(boolean isGetter, boolean isVolatile, Wrapper wrapper) {
 636         if (isGetter) {
 637             if (isVolatile) {
 638                 switch (wrapper) {
 639                     case BOOLEAN: return GET_BOOLEAN_VOLATILE;
 640                     case BYTE:    return GET_BYTE_VOLATILE;
 641                     case SHORT:   return GET_SHORT_VOLATILE;
 642                     case CHAR:    return GET_CHAR_VOLATILE;
 643                     case INT:     return GET_INT_VOLATILE;
 644                     case LONG:    return GET_LONG_VOLATILE;
 645                     case FLOAT:   return GET_FLOAT_VOLATILE;
 646                     case DOUBLE:  return GET_DOUBLE_VOLATILE;
 647                     case OBJECT:  return GET_OBJECT_VOLATILE;
 648                 }
 649             } else {
 650                 switch (wrapper) {
 651                     case BOOLEAN: return GET_BOOLEAN;
 652                     case BYTE:    return GET_BYTE;
 653                     case SHORT:   return GET_SHORT;
 654                     case CHAR:    return GET_CHAR;
 655                     case INT:     return GET_INT;
 656                     case LONG:    return GET_LONG;
 657                     case FLOAT:   return GET_FLOAT;
 658                     case DOUBLE:  return GET_DOUBLE;
 659                     case OBJECT:  return GET_OBJECT;
 660                 }
 661             }
 662         } else {
 663             if (isVolatile) {
 664                 switch (wrapper) {
 665                     case BOOLEAN: return PUT_BOOLEAN_VOLATILE;
 666                     case BYTE:    return PUT_BYTE_VOLATILE;
 667                     case SHORT:   return PUT_SHORT_VOLATILE;
 668                     case CHAR:    return PUT_CHAR_VOLATILE;
 669                     case INT:     return PUT_INT_VOLATILE;
 670                     case LONG:    return PUT_LONG_VOLATILE;
 671                     case FLOAT:   return PUT_FLOAT_VOLATILE;
 672                     case DOUBLE:  return PUT_DOUBLE_VOLATILE;
 673                     case OBJECT:  return PUT_OBJECT_VOLATILE;
 674                 }
 675             } else {
 676                 switch (wrapper) {
 677                     case BOOLEAN: return PUT_BOOLEAN;
 678                     case BYTE:    return PUT_BYTE;
 679                     case SHORT:   return PUT_SHORT;
 680                     case CHAR:    return PUT_CHAR;
 681                     case INT:     return PUT_INT;
 682                     case LONG:    return PUT_LONG;
 683                     case FLOAT:   return PUT_FLOAT;
 684                     case DOUBLE:  return PUT_DOUBLE;
 685                     case OBJECT:  return PUT_OBJECT;
 686                 }
 687             }
 688         }
 689         throw new AssertionError("Invalid arguments");
 690     }
 691 
 692     static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftypeKind) {
 693         boolean isGetter  = (formOp & 1) == (AF_GETFIELD & 1);
 694         boolean isStatic  = (formOp >= AF_GETSTATIC);
 695         boolean needsInit = (formOp >= AF_GETSTATIC_INIT);
 696         boolean needsCast = (ftypeKind == FT_CHECKED_REF);
 697         Wrapper fw = (needsCast ? Wrapper.OBJECT : ALL_WRAPPERS[ftypeKind]);
 698         Class<?> ft = fw.primitiveType();
 699         assert(ftypeKind(needsCast ? String.class : ft) == ftypeKind);
 700 
 701         // getObject, putIntVolatile, etc.
 702         Kind kind = getFieldKind(isGetter, isVolatile, fw);
 703 
 704         MethodType linkerType;
 705         if (isGetter)
 706             linkerType = MethodType.methodType(ft, Object.class, long.class);
 707         else
 708             linkerType = MethodType.methodType(void.class, Object.class, long.class, ft);
 709         MemberName linker = new MemberName(Unsafe.class, kind.methodName, linkerType, REF_invokeVirtual);
 710         try {
 711             linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, NoSuchMethodException.class);
 712         } catch (ReflectiveOperationException ex) {
 713             throw newInternalError(ex);
 714         }
 715 
 716         // What is the external type of the lambda form?
 717         MethodType mtype;
 718         if (isGetter)
 719             mtype = MethodType.methodType(ft);
 720         else
 721             mtype = MethodType.methodType(void.class, ft);
 722         mtype = mtype.basicType();  // erase short to int, etc.
 723         if (!isStatic)
 724             mtype = mtype.insertParameterTypes(0, Object.class);
 725         final int DMH_THIS  = 0;
 726         final int ARG_BASE  = 1;
 727         final int ARG_LIMIT = ARG_BASE + mtype.parameterCount();
 728         // if this is for non-static access, the base pointer is stored at this index:
 729         final int OBJ_BASE  = isStatic ? -1 : ARG_BASE;
 730         // if this is for write access, the value to be written is stored at this index:
 731         final int SET_VALUE  = isGetter ? -1 : ARG_LIMIT - 1;
 732         int nameCursor = ARG_LIMIT;
 733         final int F_HOLDER  = (isStatic ? nameCursor++ : -1);  // static base if any
 734         final int F_OFFSET  = nameCursor++;  // Either static offset or field offset.
 735         final int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++ : -1);
 736         final int U_HOLDER  = nameCursor++;  // UNSAFE holder
 737         final int INIT_BAR  = (needsInit ? nameCursor++ : -1);
 738         final int PRE_CAST  = (needsCast && !isGetter ? nameCursor++ : -1);
 739         final int LINKER_CALL = nameCursor++;
 740         final int POST_CAST = (needsCast && isGetter ? nameCursor++ : -1);
 741         final int RESULT    = nameCursor-1;  // either the call or the cast
 742         Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType());
 743         if (needsInit)
 744             names[INIT_BAR] = new Name(getFunction(NF_ensureInitialized), names[DMH_THIS]);
 745         if (needsCast && !isGetter)
 746             names[PRE_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[SET_VALUE]);
 747         Object[] outArgs = new Object[1 + linkerType.parameterCount()];
 748         assert(outArgs.length == (isGetter ? 3 : 4));
 749         outArgs[0] = names[U_HOLDER] = new Name(getFunction(NF_UNSAFE));
 750         if (isStatic) {
 751             outArgs[1] = names[F_HOLDER]  = new Name(getFunction(NF_staticBase), names[DMH_THIS]);
 752             outArgs[2] = names[F_OFFSET]  = new Name(getFunction(NF_staticOffset), names[DMH_THIS]);
 753         } else {
 754             outArgs[1] = names[OBJ_CHECK] = new Name(getFunction(NF_checkBase), names[OBJ_BASE]);
 755             outArgs[2] = names[F_OFFSET]  = new Name(getFunction(NF_fieldOffset), names[DMH_THIS]);
 756         }
 757         if (!isGetter) {
 758             outArgs[3] = (needsCast ? names[PRE_CAST] : names[SET_VALUE]);
 759         }
 760         for (Object a : outArgs)  assert(a != null);
 761         names[LINKER_CALL] = new Name(linker, outArgs);
 762         if (needsCast && isGetter)
 763             names[POST_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[LINKER_CALL]);
 764         for (Name n : names)  assert(n != null);
 765 
 766         LambdaForm form;
 767         if (needsCast || needsInit) {
 768             // can't use the pre-generated form when casting and/or initializing
 769             form = new LambdaForm(ARG_LIMIT, names, RESULT);
 770         } else {
 771             form = new LambdaForm(ARG_LIMIT, names, RESULT, kind);
 772         }
 773 
 774         if (LambdaForm.debugNames()) {
 775             // add some detail to the lambdaForm debugname,
 776             // significant only for debugging
 777             StringBuilder nameBuilder = new StringBuilder(kind.methodName);
 778             if (isStatic) {
 779                 nameBuilder.append("Static");
 780             } else {
 781                 nameBuilder.append("Field");
 782             }
 783             if (needsCast) {
 784                 nameBuilder.append("Cast");
 785             }
 786             if (needsInit) {
 787                 nameBuilder.append("Init");
 788             }
 789             LambdaForm.associateWithDebugName(form, nameBuilder.toString());
 790         }
 791         return form;
 792     }
 793 
 794     /**
 795      * Pre-initialized NamedFunctions for bootstrapping purposes.
 796      */
 797     static final byte NF_internalMemberName = 0,
 798             NF_internalMemberNameEnsureInit = 1,
 799             NF_ensureInitialized = 2,
 800             NF_fieldOffset = 3,
 801             NF_checkBase = 4,
 802             NF_staticBase = 5,
 803             NF_staticOffset = 6,
 804             NF_checkCast = 7,
 805             NF_allocateInstance = 8,
 806             NF_constructorMethod = 9,
 807             NF_UNSAFE = 10,
 808             NF_checkReceiver = 11,
 809             NF_LIMIT = 12;
 810 
 811     private static final @Stable NamedFunction[] NFS = new NamedFunction[NF_LIMIT];
 812 
 813     private static NamedFunction getFunction(byte func) {
 814         NamedFunction nf = NFS[func];
 815         if (nf != null) {
 816             return nf;
 817         }
 818         // Each nf must be statically invocable or we get tied up in our bootstraps.
 819         nf = NFS[func] = createFunction(func);
 820         assert(InvokerBytecodeGenerator.isStaticallyInvocable(nf));
 821         return nf;
 822     }
 823 
 824     private static final MethodType OBJ_OBJ_TYPE = MethodType.methodType(Object.class, Object.class);
 825 
 826     private static final MethodType LONG_OBJ_TYPE = MethodType.methodType(long.class, Object.class);
 827 
 828     private static NamedFunction createFunction(byte func) {
 829         try {
 830             switch (func) {
 831                 case NF_internalMemberName:
 832                     return getNamedFunction("internalMemberName", OBJ_OBJ_TYPE);
 833                 case NF_internalMemberNameEnsureInit:
 834                     return getNamedFunction("internalMemberNameEnsureInit", OBJ_OBJ_TYPE);
 835                 case NF_ensureInitialized:
 836                     return getNamedFunction("ensureInitialized", MethodType.methodType(void.class, Object.class));
 837                 case NF_fieldOffset:
 838                     return getNamedFunction("fieldOffset", LONG_OBJ_TYPE);
 839                 case NF_checkBase:
 840                     return getNamedFunction("checkBase", OBJ_OBJ_TYPE);
 841                 case NF_staticBase:
 842                     return getNamedFunction("staticBase", OBJ_OBJ_TYPE);
 843                 case NF_staticOffset:
 844                     return getNamedFunction("staticOffset", LONG_OBJ_TYPE);
 845                 case NF_checkCast:
 846                     return getNamedFunction("checkCast", MethodType.methodType(Object.class, Object.class, Object.class));
 847                 case NF_allocateInstance:
 848                     return getNamedFunction("allocateInstance", OBJ_OBJ_TYPE);
 849                 case NF_constructorMethod:
 850                     return getNamedFunction("constructorMethod", OBJ_OBJ_TYPE);
 851                 case NF_UNSAFE:
 852                     MemberName member = new MemberName(MethodHandleStatics.class, "UNSAFE", Unsafe.class, REF_getField);
 853                     return new NamedFunction(
 854                             MemberName.getFactory()
 855                                     .resolveOrFail(REF_getField, member, DirectMethodHandle.class, NoSuchMethodException.class));
 856                 case NF_checkReceiver:
 857                     member = new MemberName(DirectMethodHandle.class, "checkReceiver", OBJ_OBJ_TYPE, REF_invokeVirtual);
 858                     return new NamedFunction(
 859                         MemberName.getFactory()
 860                             .resolveOrFail(REF_invokeVirtual, member, DirectMethodHandle.class, NoSuchMethodException.class));
 861                 default:
 862                     throw newInternalError("Unknown function: " + func);
 863             }
 864         } catch (ReflectiveOperationException ex) {
 865             throw newInternalError(ex);
 866         }
 867     }
 868 
 869     private static NamedFunction getNamedFunction(String name, MethodType type)
 870         throws ReflectiveOperationException
 871     {
 872         MemberName member = new MemberName(DirectMethodHandle.class, name, type, REF_invokeStatic);
 873         return new NamedFunction(
 874             MemberName.getFactory()
 875                 .resolveOrFail(REF_invokeStatic, member, DirectMethodHandle.class, NoSuchMethodException.class));
 876     }
 877 
 878     static {
 879         // The Holder class will contain pre-generated DirectMethodHandles resolved
 880         // speculatively using MemberName.getFactory().resolveOrNull. However, that
 881         // doesn't initialize the class, which subtly breaks inlining etc. By forcing
 882         // initialization of the Holder class we avoid these issues.
 883         UNSAFE.ensureClassInitialized(Holder.class);
 884     }
 885 
 886     /* Placeholder class for DirectMethodHandles generated ahead of time */
 887     final class Holder {}
 888 }