1 /*
   2  * Copyright (c) 2008, 2013, 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 sun.misc.Unsafe;
  29 import java.lang.reflect.Method;
  30 import java.util.Arrays;
  31 import sun.invoke.util.VerifyAccess;
  32 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  33 import static java.lang.invoke.LambdaForm.*;
  34 import static java.lang.invoke.LambdaForm.BasicType.*;
  35 import static java.lang.invoke.MethodTypeForm.*;
  36 import static java.lang.invoke.MethodHandleStatics.*;
  37 import java.lang.ref.WeakReference;
  38 import java.lang.reflect.Field;
  39 import sun.invoke.util.ValueConversions;
  40 import sun.invoke.util.VerifyType;
  41 import sun.invoke.util.Wrapper;
  42 
  43 /**
  44  * The flavor of method handle which implements a constant reference
  45  * to a class member.
  46  * @author jrose
  47  */
  48 class DirectMethodHandle extends MethodHandle {
  49     final MemberName member;
  50 
  51     // Constructors and factory methods in this class *must* be package scoped or private.
  52     private DirectMethodHandle(MethodType mtype, LambdaForm form, MemberName member) {
  53         super(mtype, form);
  54         if (!member.isResolved())  throw new InternalError();
  55 
  56         if (member.getDeclaringClass().isInterface() &&
  57                 member.isMethod() && !member.isAbstract()) {
  58             // Check for corner case: invokeinterface of Object method
  59             MemberName m = new MemberName(Object.class, member.getName(), member.getMethodType(), member.getReferenceKind());
  60             m = MemberName.getFactory().resolveOrNull(m.getReferenceKind(), m, null);
  61             if (m != null && m.isPublic()) {
  62                 member = m;
  63             }
  64         }
  65 
  66         this.member = member;
  67     }
  68 
  69     // Factory methods:
  70     static DirectMethodHandle make(byte refKind, Class<?> receiver, MemberName member) {
  71         MethodType mtype = member.getMethodOrFieldType();
  72         if (!member.isStatic()) {
  73             if (!member.getDeclaringClass().isAssignableFrom(receiver) || member.isConstructor())
  74                 throw new InternalError(member.toString());
  75             mtype = mtype.insertParameterTypes(0, receiver);
  76         }
  77         if (!member.isField()) {
  78             if (refKind == REF_invokeSpecial) {
  79                 member = member.asSpecial();
  80                 LambdaForm lform = preparedLambdaForm(member);
  81                 return new Special(mtype, lform, member);
  82             } else {
  83                 LambdaForm lform = preparedLambdaForm(member);
  84                 return new DirectMethodHandle(mtype, lform, member);
  85             }
  86         } else {
  87             LambdaForm lform = preparedFieldLambdaForm(member);
  88             if (member.isStatic()) {
  89                 long offset = MethodHandleNatives.staticFieldOffset(member);
  90                 Object base = MethodHandleNatives.staticFieldBase(member);
  91                 return new StaticAccessor(mtype, lform, member, base, offset);
  92             } else {
  93                 long offset = MethodHandleNatives.objectFieldOffset(member);
  94                 assert(offset == (int)offset);
  95                 return new Accessor(mtype, lform, member, (int)offset);
  96             }
  97         }
  98     }
  99     static DirectMethodHandle make(Class<?> receiver, MemberName member) {
 100         byte refKind = member.getReferenceKind();
 101         if (refKind == REF_invokeSpecial)
 102             refKind =  REF_invokeVirtual;
 103         return make(refKind, receiver, member);
 104     }
 105     static DirectMethodHandle make(MemberName member) {
 106         if (member.isConstructor())
 107             return makeAllocator(member);
 108         return make(member.getDeclaringClass(), member);
 109     }
 110     static DirectMethodHandle make(Method method) {
 111         return make(method.getDeclaringClass(), new MemberName(method));
 112     }
 113     static DirectMethodHandle make(Field field) {
 114         return make(field.getDeclaringClass(), new MemberName(field));
 115     }
 116     private static DirectMethodHandle makeAllocator(MemberName ctor) {
 117         assert(ctor.isConstructor() && ctor.getName().equals("<init>"));
 118         Class<?> instanceClass = ctor.getDeclaringClass();
 119         ctor = ctor.asConstructor();
 120         assert(ctor.isConstructor() && ctor.getReferenceKind() == REF_newInvokeSpecial) : ctor;
 121         MethodType mtype = ctor.getMethodType().changeReturnType(instanceClass);
 122         LambdaForm lform = preparedLambdaForm(ctor);
 123         MemberName init = ctor.asSpecial();
 124         assert(init.getMethodType().returnType() == void.class);
 125         return new Constructor(mtype, lform, ctor, init, instanceClass);
 126     }
 127 
 128     @Override
 129     String internalProperties() {
 130         return "/DMH="+member.toString();
 131     }
 132 
 133     //// Implementation methods.
 134     @Override
 135     MethodHandle viewAsType(MethodType newType) {
 136         return new DirectMethodHandle(newType, form, member);
 137     }
 138     @Override
 139     @ForceInline
 140     MemberName internalMemberName() {
 141         return member;
 142     }
 143 
 144     @Override
 145     MethodHandle bindArgument(int pos, BasicType basicType, Object value) {
 146         // If the member needs dispatching, do so.
 147         if (pos == 0 && basicType == L_TYPE) {
 148             DirectMethodHandle concrete = maybeRebind(value);
 149             if (concrete != null)
 150                 return concrete.bindReceiver(value);
 151         }
 152         return super.bindArgument(pos, basicType, value);
 153     }
 154 
 155     @Override
 156     MethodHandle bindReceiver(Object receiver) {
 157         // If the member needs dispatching, do so.
 158         DirectMethodHandle concrete = maybeRebind(receiver);
 159         if (concrete != null)
 160             return concrete.bindReceiver(receiver);
 161         return super.bindReceiver(receiver);
 162     }
 163 
 164     private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
 165 
 166     private DirectMethodHandle maybeRebind(Object receiver) {
 167         if (receiver != null) {
 168             switch (member.getReferenceKind()) {
 169             case REF_invokeInterface:
 170             case REF_invokeVirtual:
 171                 // Pre-dispatch the member.
 172                 Class<?> concreteClass = receiver.getClass();
 173                 MemberName concrete = new MemberName(concreteClass, member.getName(), member.getMethodType(), REF_invokeSpecial);
 174                 concrete = IMPL_NAMES.resolveOrNull(REF_invokeSpecial, concrete, concreteClass);
 175                 if (concrete != null)
 176                     return new DirectMethodHandle(type(), preparedLambdaForm(concrete), concrete);
 177                 break;
 178             }
 179         }
 180         return null;
 181     }
 182 
 183     /**
 184      * Create a LF which can invoke the given method.
 185      * Cache and share this structure among all methods with
 186      * the same basicType and refKind.
 187      */
 188     private static LambdaForm preparedLambdaForm(MemberName m) {
 189         assert(m.isInvocable()) : m;  // call preparedFieldLambdaForm instead
 190         MethodType mtype = m.getInvocationType().basicType();
 191         assert(!m.isMethodHandleInvoke() || "invokeBasic".equals(m.getName())) : m;
 192         int which;
 193         switch (m.getReferenceKind()) {
 194         case REF_invokeVirtual:    which = LF_INVVIRTUAL;    break;
 195         case REF_invokeStatic:     which = LF_INVSTATIC;     break;
 196         case REF_invokeSpecial:    which = LF_INVSPECIAL;    break;
 197         case REF_invokeInterface:  which = LF_INVINTERFACE;  break;
 198         case REF_newInvokeSpecial: which = LF_NEWINVSPECIAL; break;
 199         default:  throw new InternalError(m.toString());
 200         }
 201         if (which == LF_INVSTATIC && shouldBeInitialized(m)) {
 202             // precompute the barrier-free version:
 203             preparedLambdaForm(mtype, which);
 204             which = LF_INVSTATIC_INIT;
 205         }
 206         LambdaForm lform = preparedLambdaForm(mtype, which);
 207         maybeCompile(lform, m);
 208         assert(lform.methodType().dropParameterTypes(0, 1)
 209                 .equals(m.getInvocationType().basicType()))
 210                 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType());
 211         return lform;
 212     }
 213 
 214     private static LambdaForm preparedLambdaForm(MethodType mtype, int which) {
 215         LambdaForm lform = mtype.form().cachedLambdaForm(which);
 216         if (lform != null)  return lform;
 217         lform = makePreparedLambdaForm(mtype, which);
 218         return mtype.form().setCachedLambdaForm(which, lform);
 219     }
 220 
 221     private static LambdaForm makePreparedLambdaForm(MethodType mtype, int which) {
 222         boolean needsInit = (which == LF_INVSTATIC_INIT);
 223         boolean doesAlloc = (which == LF_NEWINVSPECIAL);
 224         String linkerName, lambdaName;
 225         switch (which) {
 226         case LF_INVVIRTUAL:    linkerName = "linkToVirtual";    lambdaName = "DMH.invokeVirtual";    break;
 227         case LF_INVSTATIC:     linkerName = "linkToStatic";     lambdaName = "DMH.invokeStatic";     break;
 228         case LF_INVSTATIC_INIT:linkerName = "linkToStatic";     lambdaName = "DMH.invokeStaticInit"; break;
 229         case LF_INVSPECIAL:    linkerName = "linkToSpecial";    lambdaName = "DMH.invokeSpecial";    break;
 230         case LF_INVINTERFACE:  linkerName = "linkToInterface";  lambdaName = "DMH.invokeInterface";  break;
 231         case LF_NEWINVSPECIAL: linkerName = "linkToSpecial";    lambdaName = "DMH.newInvokeSpecial"; break;
 232         default:  throw new InternalError("which="+which);
 233         }
 234         MethodType mtypeWithArg = mtype.appendParameterTypes(MemberName.class);
 235         if (doesAlloc)
 236             mtypeWithArg = mtypeWithArg
 237                     .insertParameterTypes(0, Object.class)  // insert newly allocated obj
 238                     .changeReturnType(void.class);          // <init> returns void
 239         MemberName linker = new MemberName(MethodHandle.class, linkerName, mtypeWithArg, REF_invokeStatic);
 240         try {
 241             linker = IMPL_NAMES.resolveOrFail(REF_invokeStatic, linker, null, NoSuchMethodException.class);
 242         } catch (ReflectiveOperationException ex) {
 243             throw newInternalError(ex);
 244         }
 245         final int DMH_THIS    = 0;
 246         final int ARG_BASE    = 1;
 247         final int ARG_LIMIT   = ARG_BASE + mtype.parameterCount();
 248         int nameCursor = ARG_LIMIT;
 249         final int NEW_OBJ     = (doesAlloc ? nameCursor++ : -1);
 250         final int GET_MEMBER  = nameCursor++;
 251         final int LINKER_CALL = nameCursor++;
 252         Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType());
 253         assert(names.length == nameCursor);
 254         if (doesAlloc) {
 255             // names = { argx,y,z,... new C, init method }
 256             names[NEW_OBJ] = new Name(Lazy.NF_allocateInstance, names[DMH_THIS]);
 257             names[GET_MEMBER] = new Name(Lazy.NF_constructorMethod, names[DMH_THIS]);
 258         } else if (needsInit) {
 259             names[GET_MEMBER] = new Name(Lazy.NF_internalMemberNameEnsureInit, names[DMH_THIS]);
 260         } else {
 261             names[GET_MEMBER] = new Name(Lazy.NF_internalMemberName, names[DMH_THIS]);
 262         }
 263         Object[] outArgs = Arrays.copyOfRange(names, ARG_BASE, GET_MEMBER+1, Object[].class);
 264         assert(outArgs[outArgs.length-1] == names[GET_MEMBER]);  // look, shifted args!
 265         int result = LambdaForm.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         lambdaName += "_" + shortenSignature(basicTypeSignature(mtype));
 274         LambdaForm lform = new LambdaForm(lambdaName, ARG_LIMIT, names, result);
 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     private static void maybeCompile(LambdaForm lform, MemberName m) {
 281         if (VerifyAccess.isSamePackage(m.getDeclaringClass(), MethodHandle.class))
 282             // Help along bootstrapping...
 283             lform.compileToBytecode();
 284     }
 285 
 286     /** Static wrapper for DirectMethodHandle.internalMemberName. */
 287     @ForceInline
 288     /*non-public*/ static Object internalMemberName(Object mh) {
 289         return ((DirectMethodHandle)mh).member;
 290     }
 291 
 292     /** Static wrapper for DirectMethodHandle.internalMemberName.
 293      * This one also forces initialization.
 294      */
 295     /*non-public*/ static Object internalMemberNameEnsureInit(Object mh) {
 296         DirectMethodHandle dmh = (DirectMethodHandle)mh;
 297         dmh.ensureInitialized();
 298         return dmh.member;
 299     }
 300 
 301     /*non-public*/ static
 302     boolean shouldBeInitialized(MemberName member) {
 303         switch (member.getReferenceKind()) {
 304         case REF_invokeStatic:
 305         case REF_getStatic:
 306         case REF_putStatic:
 307         case REF_newInvokeSpecial:
 308             break;
 309         default:
 310             // No need to initialize the class on this kind of member.
 311             return false;
 312         }
 313         Class<?> cls = member.getDeclaringClass();
 314         if (cls == ValueConversions.class ||
 315             cls == MethodHandleImpl.class ||
 316             cls == Invokers.class) {
 317             // These guys have lots of <clinit> DMH creation but we know
 318             // the MHs will not be used until the system is booted.
 319             return false;
 320         }
 321         if (VerifyAccess.isSamePackage(MethodHandle.class, cls) ||
 322             VerifyAccess.isSamePackage(ValueConversions.class, cls)) {
 323             // It is a system class.  It is probably in the process of
 324             // being initialized, but we will help it along just to be safe.
 325             if (UNSAFE.shouldBeInitialized(cls)) {
 326                 UNSAFE.ensureClassInitialized(cls);
 327             }
 328             return false;
 329         }
 330         return UNSAFE.shouldBeInitialized(cls);
 331     }
 332 
 333     private static class EnsureInitialized extends ClassValue<WeakReference<Thread>> {
 334         @Override
 335         protected WeakReference<Thread> computeValue(Class<?> type) {
 336             UNSAFE.ensureClassInitialized(type);
 337             if (UNSAFE.shouldBeInitialized(type))
 338                 // If the previous call didn't block, this can happen.
 339                 // We are executing inside <clinit>.
 340                 return new WeakReference<>(Thread.currentThread());
 341             return null;
 342         }
 343         static final EnsureInitialized INSTANCE = new EnsureInitialized();
 344     }
 345 
 346     private void ensureInitialized() {
 347         if (checkInitialized(member)) {
 348             // The coast is clear.  Delete the <clinit> barrier.
 349             if (member.isField())
 350                 updateForm(preparedFieldLambdaForm(member));
 351             else
 352                 updateForm(preparedLambdaForm(member));
 353         }
 354     }
 355     private static boolean checkInitialized(MemberName member) {
 356         Class<?> defc = member.getDeclaringClass();
 357         WeakReference<Thread> ref = EnsureInitialized.INSTANCE.get(defc);
 358         if (ref == null) {
 359             return true;  // the final state
 360         }
 361         Thread clinitThread = ref.get();
 362         // Somebody may still be running defc.<clinit>.
 363         if (clinitThread == Thread.currentThread()) {
 364             // If anybody is running defc.<clinit>, it is this thread.
 365             if (UNSAFE.shouldBeInitialized(defc))
 366                 // Yes, we are running it; keep the barrier for now.
 367                 return false;
 368         } else {
 369             // We are in a random thread.  Block.
 370             UNSAFE.ensureClassInitialized(defc);
 371         }
 372         assert(!UNSAFE.shouldBeInitialized(defc));
 373         // put it into the final state
 374         EnsureInitialized.INSTANCE.remove(defc);
 375         return true;
 376     }
 377 
 378     /*non-public*/ static void ensureInitialized(Object mh) {
 379         ((DirectMethodHandle)mh).ensureInitialized();
 380     }
 381 
 382     /** This subclass represents invokespecial instructions. */
 383     static class Special extends DirectMethodHandle {
 384         private Special(MethodType mtype, LambdaForm form, MemberName member) {
 385             super(mtype, form, member);
 386         }
 387         @Override
 388         boolean isInvokeSpecial() {
 389             return true;
 390         }
 391         @Override
 392         MethodHandle viewAsType(MethodType newType) {
 393             return new Special(newType, form, member);
 394         }
 395     }
 396 
 397     /** This subclass handles constructor references. */
 398     static class Constructor extends DirectMethodHandle {
 399         final MemberName initMethod;
 400         final Class<?>   instanceClass;
 401 
 402         private Constructor(MethodType mtype, LambdaForm form, MemberName constructor,
 403                             MemberName initMethod, Class<?> instanceClass) {
 404             super(mtype, form, constructor);
 405             this.initMethod = initMethod;
 406             this.instanceClass = instanceClass;
 407             assert(initMethod.isResolved());
 408         }
 409         @Override
 410         MethodHandle viewAsType(MethodType newType) {
 411             return new Constructor(newType, form, member, initMethod, instanceClass);
 412         }
 413     }
 414 
 415     /*non-public*/ static Object constructorMethod(Object mh) {
 416         Constructor dmh = (Constructor)mh;
 417         return dmh.initMethod;
 418     }
 419 
 420     /*non-public*/ static Object allocateInstance(Object mh) throws InstantiationException {
 421         Constructor dmh = (Constructor)mh;
 422         return UNSAFE.allocateInstance(dmh.instanceClass);
 423     }
 424 
 425     /** This subclass handles non-static field references. */
 426     static class Accessor extends DirectMethodHandle {
 427         final Class<?> fieldType;
 428         final int      fieldOffset;
 429         private Accessor(MethodType mtype, LambdaForm form, MemberName member,
 430                          int fieldOffset) {
 431             super(mtype, form, member);
 432             this.fieldType   = member.getFieldType();
 433             this.fieldOffset = fieldOffset;
 434         }
 435 
 436         @Override Object checkCast(Object obj) {
 437             return fieldType.cast(obj);
 438         }
 439         @Override
 440         MethodHandle viewAsType(MethodType newType) {
 441             return new Accessor(newType, form, member, fieldOffset);
 442         }
 443     }
 444 
 445     @ForceInline
 446     /*non-public*/ static long fieldOffset(Object accessorObj) {
 447         // Note: We return a long because that is what Unsafe.getObject likes.
 448         // We store a plain int because it is more compact.
 449         return ((Accessor)accessorObj).fieldOffset;
 450     }
 451 
 452     @ForceInline
 453     /*non-public*/ static Object checkBase(Object obj) {
 454         // Note that the object's class has already been verified,
 455         // since the parameter type of the Accessor method handle
 456         // is either member.getDeclaringClass or a subclass.
 457         // This was verified in DirectMethodHandle.make.
 458         // Therefore, the only remaining check is for null.
 459         // Since this check is *not* guaranteed by Unsafe.getInt
 460         // and its siblings, we need to make an explicit one here.
 461         obj.getClass();  // maybe throw NPE
 462         return obj;
 463     }
 464 
 465     /** This subclass handles static field references. */
 466     static class StaticAccessor extends DirectMethodHandle {
 467         final private Class<?> fieldType;
 468         final private Object   staticBase;
 469         final private long     staticOffset;
 470 
 471         private StaticAccessor(MethodType mtype, LambdaForm form, MemberName member,
 472                                Object staticBase, long staticOffset) {
 473             super(mtype, form, member);
 474             this.fieldType    = member.getFieldType();
 475             this.staticBase   = staticBase;
 476             this.staticOffset = staticOffset;
 477         }
 478 
 479         @Override Object checkCast(Object obj) {
 480             return fieldType.cast(obj);
 481         }
 482         @Override
 483         MethodHandle viewAsType(MethodType newType) {
 484             return new StaticAccessor(newType, form, member, staticBase, staticOffset);
 485         }
 486     }
 487 
 488     @ForceInline
 489     /*non-public*/ static Object nullCheck(Object obj) {
 490         obj.getClass();
 491         return obj;
 492     }
 493 
 494     @ForceInline
 495     /*non-public*/ static Object staticBase(Object accessorObj) {
 496         return ((StaticAccessor)accessorObj).staticBase;
 497     }
 498 
 499     @ForceInline
 500     /*non-public*/ static long staticOffset(Object accessorObj) {
 501         return ((StaticAccessor)accessorObj).staticOffset;
 502     }
 503 
 504     @ForceInline
 505     /*non-public*/ static Object checkCast(Object mh, Object obj) {
 506         return ((DirectMethodHandle) mh).checkCast(obj);
 507     }
 508 
 509     Object checkCast(Object obj) {
 510         return member.getReturnType().cast(obj);
 511     }
 512 
 513     // Caching machinery for field accessors:
 514     private static byte
 515             AF_GETFIELD        = 0,
 516             AF_PUTFIELD        = 1,
 517             AF_GETSTATIC       = 2,
 518             AF_PUTSTATIC       = 3,
 519             AF_GETSTATIC_INIT  = 4,
 520             AF_PUTSTATIC_INIT  = 5,
 521             AF_LIMIT           = 6;
 522     // Enumerate the different field kinds using Wrapper,
 523     // with an extra case added for checked references.
 524     private static int
 525             FT_LAST_WRAPPER    = Wrapper.values().length-1,
 526             FT_UNCHECKED_REF   = Wrapper.OBJECT.ordinal(),
 527             FT_CHECKED_REF     = FT_LAST_WRAPPER+1,
 528             FT_LIMIT           = FT_LAST_WRAPPER+2;
 529     private static int afIndex(byte formOp, boolean isVolatile, int ftypeKind) {
 530         return ((formOp * FT_LIMIT * 2)
 531                 + (isVolatile ? FT_LIMIT : 0)
 532                 + ftypeKind);
 533     }
 534     private static final LambdaForm[] ACCESSOR_FORMS
 535             = new LambdaForm[afIndex(AF_LIMIT, false, 0)];
 536     private static int ftypeKind(Class<?> ftype) {
 537         if (ftype.isPrimitive())
 538             return Wrapper.forPrimitiveType(ftype).ordinal();
 539         else if (VerifyType.isNullReferenceConversion(Object.class, ftype))
 540             return FT_UNCHECKED_REF;
 541         else
 542             return FT_CHECKED_REF;
 543     }
 544 
 545     /**
 546      * Create a LF which can access the given field.
 547      * Cache and share this structure among all fields with
 548      * the same basicType and refKind.
 549      */
 550     private static LambdaForm preparedFieldLambdaForm(MemberName m) {
 551         Class<?> ftype = m.getFieldType();
 552         boolean isVolatile = m.isVolatile();
 553         byte formOp;
 554         switch (m.getReferenceKind()) {
 555         case REF_getField:      formOp = AF_GETFIELD;    break;
 556         case REF_putField:      formOp = AF_PUTFIELD;    break;
 557         case REF_getStatic:     formOp = AF_GETSTATIC;   break;
 558         case REF_putStatic:     formOp = AF_PUTSTATIC;   break;
 559         default:  throw new InternalError(m.toString());
 560         }
 561         if (shouldBeInitialized(m)) {
 562             // precompute the barrier-free version:
 563             preparedFieldLambdaForm(formOp, isVolatile, ftype);
 564             assert((AF_GETSTATIC_INIT - AF_GETSTATIC) ==
 565                    (AF_PUTSTATIC_INIT - AF_PUTSTATIC));
 566             formOp += (AF_GETSTATIC_INIT - AF_GETSTATIC);
 567         }
 568         LambdaForm lform = preparedFieldLambdaForm(formOp, isVolatile, ftype);
 569         maybeCompile(lform, m);
 570         assert(lform.methodType().dropParameterTypes(0, 1)
 571                 .equals(m.getInvocationType().basicType()))
 572                 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType());
 573         return lform;
 574     }
 575     private static LambdaForm preparedFieldLambdaForm(byte formOp, boolean isVolatile, Class<?> ftype) {
 576         int afIndex = afIndex(formOp, isVolatile, ftypeKind(ftype));
 577         LambdaForm lform = ACCESSOR_FORMS[afIndex];
 578         if (lform != null)  return lform;
 579         lform = makePreparedFieldLambdaForm(formOp, isVolatile, ftypeKind(ftype));
 580         ACCESSOR_FORMS[afIndex] = lform;  // don't bother with a CAS
 581         return lform;
 582     }
 583 
 584     private static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftypeKind) {
 585         boolean isGetter  = (formOp & 1) == (AF_GETFIELD & 1);
 586         boolean isStatic  = (formOp >= AF_GETSTATIC);
 587         boolean needsInit = (formOp >= AF_GETSTATIC_INIT);
 588         boolean needsCast = (ftypeKind == FT_CHECKED_REF);
 589         Wrapper fw = (needsCast ? Wrapper.OBJECT : Wrapper.values()[ftypeKind]);
 590         Class<?> ft = fw.primitiveType();
 591         assert(ftypeKind(needsCast ? String.class : ft) == ftypeKind);
 592         String tname  = fw.primitiveSimpleName();
 593         String ctname = Character.toUpperCase(tname.charAt(0)) + tname.substring(1);
 594         if (isVolatile)  ctname += "Volatile";
 595         String getOrPut = (isGetter ? "get" : "put");
 596         String linkerName = (getOrPut + ctname);  // getObject, putIntVolatile, etc.
 597         MethodType linkerType;
 598         if (isGetter)
 599             linkerType = MethodType.methodType(ft, Object.class, long.class);
 600         else
 601             linkerType = MethodType.methodType(void.class, Object.class, long.class, ft);
 602         MemberName linker = new MemberName(Unsafe.class, linkerName, linkerType, REF_invokeVirtual);
 603         try {
 604             linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, NoSuchMethodException.class);
 605         } catch (ReflectiveOperationException ex) {
 606             throw newInternalError(ex);
 607         }
 608 
 609         // What is the external type of the lambda form?
 610         MethodType mtype;
 611         if (isGetter)
 612             mtype = MethodType.methodType(ft);
 613         else
 614             mtype = MethodType.methodType(void.class, ft);
 615         mtype = mtype.basicType();  // erase short to int, etc.
 616         if (!isStatic)
 617             mtype = mtype.insertParameterTypes(0, Object.class);
 618         final int DMH_THIS  = 0;
 619         final int ARG_BASE  = 1;
 620         final int ARG_LIMIT = ARG_BASE + mtype.parameterCount();
 621         // if this is for non-static access, the base pointer is stored at this index:
 622         final int OBJ_BASE  = isStatic ? -1 : ARG_BASE;
 623         // if this is for write access, the value to be written is stored at this index:
 624         final int SET_VALUE  = isGetter ? -1 : ARG_LIMIT - 1;
 625         int nameCursor = ARG_LIMIT;
 626         final int F_HOLDER  = (isStatic ? nameCursor++ : -1);  // static base if any
 627         final int F_OFFSET  = nameCursor++;  // Either static offset or field offset.
 628         final int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++ : -1);
 629         final int INIT_BAR  = (needsInit ? nameCursor++ : -1);
 630         final int PRE_CAST  = (needsCast && !isGetter ? nameCursor++ : -1);
 631         final int LINKER_CALL = nameCursor++;
 632         final int POST_CAST = (needsCast && isGetter ? nameCursor++ : -1);
 633         final int RESULT    = nameCursor-1;  // either the call or the cast
 634         Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType());
 635         if (needsInit)
 636             names[INIT_BAR] = new Name(Lazy.NF_ensureInitialized, names[DMH_THIS]);
 637         if (needsCast && !isGetter)
 638             names[PRE_CAST] = new Name(Lazy.NF_checkCast, names[DMH_THIS], names[SET_VALUE]);
 639         Object[] outArgs = new Object[1 + linkerType.parameterCount()];
 640         assert(outArgs.length == (isGetter ? 3 : 4));
 641         outArgs[0] = UNSAFE;
 642         if (isStatic) {
 643             outArgs[1] = names[F_HOLDER]  = new Name(Lazy.NF_staticBase, names[DMH_THIS]);
 644             outArgs[2] = names[F_OFFSET]  = new Name(Lazy.NF_staticOffset, names[DMH_THIS]);
 645         } else {
 646             outArgs[1] = names[OBJ_CHECK] = new Name(Lazy.NF_checkBase, names[OBJ_BASE]);
 647             outArgs[2] = names[F_OFFSET]  = new Name(Lazy.NF_fieldOffset, names[DMH_THIS]);
 648         }
 649         if (!isGetter) {
 650             outArgs[3] = (needsCast ? names[PRE_CAST] : names[SET_VALUE]);
 651         }
 652         for (Object a : outArgs)  assert(a != null);
 653         names[LINKER_CALL] = new Name(linker, outArgs);
 654         if (needsCast && isGetter)
 655             names[POST_CAST] = new Name(Lazy.NF_checkCast, names[DMH_THIS], names[LINKER_CALL]);
 656         for (Name n : names)  assert(n != null);
 657         String fieldOrStatic = (isStatic ? "Static" : "Field");
 658         String lambdaName = (linkerName + fieldOrStatic);  // significant only for debugging
 659         if (needsCast)  lambdaName += "Cast";
 660         if (needsInit)  lambdaName += "Init";
 661         return new LambdaForm(lambdaName, ARG_LIMIT, names, RESULT);
 662     }
 663 
 664     /**
 665      * Pre-initialized NamedFunctions for bootstrapping purposes.
 666      * Factored in an inner class to delay initialization until first usage.
 667      */
 668     private static class Lazy {
 669         static final NamedFunction
 670                 NF_internalMemberName,
 671                 NF_internalMemberNameEnsureInit,
 672                 NF_ensureInitialized,
 673                 NF_fieldOffset,
 674                 NF_checkBase,
 675                 NF_staticBase,
 676                 NF_staticOffset,
 677                 NF_checkCast,
 678                 NF_allocateInstance,
 679                 NF_constructorMethod;
 680         static {
 681             try {
 682                 NamedFunction nfs[] = {
 683                         NF_internalMemberName = new NamedFunction(DirectMethodHandle.class
 684                                 .getDeclaredMethod("internalMemberName", Object.class)),
 685                         NF_internalMemberNameEnsureInit = new NamedFunction(DirectMethodHandle.class
 686                                 .getDeclaredMethod("internalMemberNameEnsureInit", Object.class)),
 687                         NF_ensureInitialized = new NamedFunction(DirectMethodHandle.class
 688                                 .getDeclaredMethod("ensureInitialized", Object.class)),
 689                         NF_fieldOffset = new NamedFunction(DirectMethodHandle.class
 690                                 .getDeclaredMethod("fieldOffset", Object.class)),
 691                         NF_checkBase = new NamedFunction(DirectMethodHandle.class
 692                                 .getDeclaredMethod("checkBase", Object.class)),
 693                         NF_staticBase = new NamedFunction(DirectMethodHandle.class
 694                                 .getDeclaredMethod("staticBase", Object.class)),
 695                         NF_staticOffset = new NamedFunction(DirectMethodHandle.class
 696                                 .getDeclaredMethod("staticOffset", Object.class)),
 697                         NF_checkCast = new NamedFunction(DirectMethodHandle.class
 698                                 .getDeclaredMethod("checkCast", Object.class, Object.class)),
 699                         NF_allocateInstance = new NamedFunction(DirectMethodHandle.class
 700                                 .getDeclaredMethod("allocateInstance", Object.class)),
 701                         NF_constructorMethod = new NamedFunction(DirectMethodHandle.class
 702                                 .getDeclaredMethod("constructorMethod", Object.class))
 703                 };
 704                 for (NamedFunction nf : nfs) {
 705                     // Each nf must be statically invocable or we get tied up in our bootstraps.
 706                     assert(InvokerBytecodeGenerator.isStaticallyInvocable(nf.member)) : nf;
 707                     nf.resolve();
 708                 }
 709             } catch (ReflectiveOperationException ex) {
 710                 throw newInternalError(ex);
 711             }
 712         }
 713     }
 714 }