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