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