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