1 /*
  2  * Copyright (c) 2008, 2020, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.lang.invoke;
 27 
 28 import jdk.internal.misc.Unsafe;
 29 import jdk.internal.vm.annotation.ForceInline;
 30 import jdk.internal.vm.annotation.Stable;
 31 import sun.invoke.util.ValueConversions;
 32 import sun.invoke.util.VerifyAccess;
 33 import sun.invoke.util.VerifyType;
 34 import sun.invoke.util.Wrapper;
 35 
 36 import java.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 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 = refc.isPrimitiveClass() ? refc.asValueType() : 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.getReturnType() == 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().isPrimitiveClass()) : 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() {
177         return "\n& 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 = new LambdaForm(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 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                 String msg = String.format("Receiver class %s is not a subclass of caller class %s",
422                                            recv.getClass().getName(), caller.getName());
423                 throw new IncompatibleClassChangeError(msg);
424             }
425             return recv;
426         }
427     }
428 
429     /** This subclass represents invokeinterface instructions. */
430     static class Interface extends DirectMethodHandle {
431         private final Class<?> refc;
432         private Interface(MethodType mtype, LambdaForm form, MemberName member, boolean crackable, Class<?> refc) {
433             super(mtype, form, member, crackable);
434             assert(refc.isInterface()) : refc;
435             this.refc = refc;
436         }
437         @Override
438         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
439             return new Interface(mt, lf, member, crackable, refc);
440         }
441         @Override
442         MethodHandle viewAsType(MethodType newType, boolean strict) {
443             assert(viewAsTypeChecks(newType, strict));
444             return new Interface(newType, form, member, false, refc);
445         }
446         @Override
447         Object checkReceiver(Object recv) {
448             if (!refc.isInstance(recv)) {
449                 String msg = String.format("Receiver class %s does not implement the requested interface %s",
450                                            recv.getClass().getName(), refc.getName());
451                 throw new IncompatibleClassChangeError(msg);
452             }
453             return recv;
454         }
455     }
456 
457     /** Used for interface receiver type checks, by Interface and Special modes. */
458     Object checkReceiver(Object recv) {
459         throw new InternalError("Should only be invoked on a subclass");
460     }
461 
462     /** This subclass handles constructor references. */
463     static class Constructor extends DirectMethodHandle {
464         final MemberName initMethod;
465         final Class<?>   instanceClass;
466 
467         private Constructor(MethodType mtype, LambdaForm form, MemberName constructor,
468                             boolean crackable, MemberName initMethod, Class<?> instanceClass) {
469             super(mtype, form, constructor, crackable);
470             this.initMethod = initMethod;
471             this.instanceClass = instanceClass;
472             assert(initMethod.isResolved());
473         }
474         @Override
475         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
476             return new Constructor(mt, lf, member, crackable, initMethod, instanceClass);
477         }
478         @Override
479         MethodHandle viewAsType(MethodType newType, boolean strict) {
480             assert(viewAsTypeChecks(newType, strict));
481             return new Constructor(newType, form, member, false, initMethod, instanceClass);
482         }
483     }
484 
485     /*non-public*/
486     static Object constructorMethod(Object mh) {
487         Constructor dmh = (Constructor)mh;
488         return dmh.initMethod;
489     }
490 
491     /*non-public*/
492     static Object allocateInstance(Object mh) throws InstantiationException {
493         Constructor dmh = (Constructor)mh;
494         return UNSAFE.allocateInstance(dmh.instanceClass);
495     }
496 
497     /** This subclass handles non-static field references. */
498     static class Accessor extends DirectMethodHandle {
499         final Class<?> fieldType;
500         final int      fieldOffset;
501         private Accessor(MethodType mtype, LambdaForm form, MemberName member,
502                          boolean crackable, int fieldOffset) {
503             super(mtype, form, member, crackable);
504             this.fieldType   = member.getFieldType();
505             this.fieldOffset = fieldOffset;
506         }
507 
508         @Override Object checkCast(Object obj) {
509             return fieldType.cast(obj);
510         }
511         @Override
512         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
513             return new Accessor(mt, lf, member, crackable, fieldOffset);
514         }
515         @Override
516         MethodHandle viewAsType(MethodType newType, boolean strict) {
517             assert(viewAsTypeChecks(newType, strict));
518             return new Accessor(newType, form, member, false, fieldOffset);
519         }
520     }
521 
522     @ForceInline
523     /*non-public*/
524     static long fieldOffset(Object accessorObj) {
525         // Note: We return a long because that is what Unsafe.getObject likes.
526         // We store a plain int because it is more compact.
527         return ((Accessor)accessorObj).fieldOffset;
528     }
529 
530     @ForceInline
531     /*non-public*/
532     static Object checkBase(Object obj) {
533         // Note that the object's class has already been verified,
534         // since the parameter type of the Accessor method handle
535         // is either member.getDeclaringClass or a subclass.
536         // This was verified in DirectMethodHandle.make.
537         // Therefore, the only remaining check is for null.
538         // Since this check is *not* guaranteed by Unsafe.getInt
539         // and its siblings, we need to make an explicit one here.
540         return Objects.requireNonNull(obj);
541     }
542 
543     static class StaticAccessor extends DirectMethodHandle {
544         final Class<?> fieldType;
545         final Object staticBase;
546         final long staticOffset;
547 
548         private StaticAccessor(MethodType mtype, LambdaForm form, MemberName member,
549                                boolean crackable, Object staticBase, long staticOffset) {
550             super(mtype, form, member, crackable);
551             this.fieldType    = member.getFieldType();
552             this.staticBase   = staticBase;
553             this.staticOffset = staticOffset;
554         }
555 
556         @Override Object checkCast(Object obj) {
557             return fieldType.cast(obj);
558         }
559         @Override
560         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
561             return new StaticAccessor(mt, lf, member, crackable, staticBase, staticOffset);
562         }
563         @Override
564         MethodHandle viewAsType(MethodType newType, boolean strict) {
565             assert(viewAsTypeChecks(newType, strict));
566             return new StaticAccessor(newType, form, member, false, staticBase, staticOffset);
567         }
568     }
569 
570     @ForceInline
571     /*non-public*/
572     static Object nullCheck(Object obj) {
573         return Objects.requireNonNull(obj);
574     }
575 
576     @ForceInline
577     /*non-public*/
578     static Object staticBase(Object accessorObj) {
579         return ((StaticAccessor)accessorObj).staticBase;
580     }
581 
582     @ForceInline
583     /*non-public*/
584     static long staticOffset(Object accessorObj) {
585         return ((StaticAccessor)accessorObj).staticOffset;
586     }
587 
588     @ForceInline
589     /*non-public*/
590     static Object checkCast(Object mh, Object obj) {
591         return ((DirectMethodHandle) mh).checkCast(obj);
592     }
593 
594     @ForceInline
595     /*non-public*/ static Class<?> fieldType(Object accessorObj) {
596         return ((Accessor) accessorObj).fieldType;
597     }
598 
599     @ForceInline
600     /*non-public*/ static Class<?> staticFieldType(Object accessorObj) {
601         return ((StaticAccessor) accessorObj).fieldType;
602     }
603 
604     Object checkCast(Object obj) {
605         return member.getReturnType().cast(obj);
606     }
607 
608     // Caching machinery for field accessors:
609     static final byte
610             AF_GETFIELD        = 0,
611             AF_PUTFIELD        = 1,
612             AF_GETSTATIC       = 2,
613             AF_PUTSTATIC       = 3,
614             AF_GETSTATIC_INIT  = 4,
615             AF_PUTSTATIC_INIT  = 5,
616             AF_LIMIT           = 6;
617     // Enumerate the different field kinds using Wrapper,
618     // with an extra case added for checked references and value field access
619     static final int
620             FT_LAST_WRAPPER     = Wrapper.COUNT-1,
621             FT_UNCHECKED_REF    = Wrapper.OBJECT.ordinal(),
622             FT_CHECKED_REF      = FT_LAST_WRAPPER+1,
623             FT_CHECKED_VALUE    = FT_LAST_WRAPPER+2,  // flattened and non-flattened
624             FT_LIMIT            = FT_LAST_WRAPPER+4;
625     private static int afIndex(byte formOp, boolean isVolatile, boolean isFlatValue, int ftypeKind) {
626         return ((formOp * FT_LIMIT * 2)
627                 + (isVolatile ? FT_LIMIT : 0)
628                 + (isFlatValue ? 1 : 0)
629                 + ftypeKind);
630     }
631     @Stable
632     private static final LambdaForm[] ACCESSOR_FORMS
633             = new LambdaForm[afIndex(AF_LIMIT, false, false, 0)];
634     static int ftypeKind(Class<?> ftype, boolean isValue) {
635         if (ftype.isPrimitive())
636             return Wrapper.forPrimitiveType(ftype).ordinal();
637         else if (VerifyType.isNullReferenceConversion(Object.class, ftype)) {
638             return FT_UNCHECKED_REF;
639         } else
640             // null check for value type in addition to check cast
641             return isValue ? FT_CHECKED_VALUE : FT_CHECKED_REF;
642     }
643 
644     /**
645      * Create a LF which can access the given field.
646      * Cache and share this structure among all fields with
647      * the same basicType and refKind.
648      */
649     private static LambdaForm preparedFieldLambdaForm(MemberName m) {
650         Class<?> ftype = m.getFieldType();
651         boolean isVolatile = m.isVolatile();
652         byte formOp = switch (m.getReferenceKind()) {
653             case REF_getField  -> AF_GETFIELD;
654             case REF_putField  -> AF_PUTFIELD;
655             case REF_getStatic -> AF_GETSTATIC;
656             case REF_putStatic -> AF_PUTSTATIC;
657             default -> throw new InternalError(m.toString());
658         };
659         if (shouldBeInitialized(m)) {
660             // precompute the barrier-free version:
661             preparedFieldLambdaForm(formOp, m.isVolatile(), m.isInlineableField(), m.isFlattened(), ftype);
662             assert((AF_GETSTATIC_INIT - AF_GETSTATIC) ==
663                    (AF_PUTSTATIC_INIT - AF_PUTSTATIC));
664             formOp += (AF_GETSTATIC_INIT - AF_GETSTATIC);
665         }
666         LambdaForm lform = preparedFieldLambdaForm(formOp, m.isVolatile(), m.isInlineableField(), m.isFlattened(), ftype);
667         maybeCompile(lform, m);
668         assert(lform.methodType().dropParameterTypes(0, 1)
669                 .equals(m.getInvocationType().basicType()))
670                 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType());
671         return lform;
672     }
673 
674     private static LambdaForm preparedFieldLambdaForm(byte formOp, boolean isVolatile, boolean isValue, boolean isFlatValue, Class<?> ftype) {
675         int ftypeKind = ftypeKind(ftype, isValue);
676         int afIndex = afIndex(formOp, isVolatile, isFlatValue, ftypeKind);
677         LambdaForm lform = ACCESSOR_FORMS[afIndex];
678         if (lform != null)  return lform;
679         lform = makePreparedFieldLambdaForm(formOp, isVolatile, isValue, isFlatValue, ftypeKind);
680         ACCESSOR_FORMS[afIndex] = lform;  // don't bother with a CAS
681         return lform;
682     }
683 
684     private static final Wrapper[] ALL_WRAPPERS = Wrapper.values();
685 
686     private static Kind getFieldKind(boolean isGetter, boolean isVolatile, boolean isFlatValue, Wrapper wrapper) {
687         if (isGetter) {
688             if (isVolatile) {
689                 switch (wrapper) {
690                     case BOOLEAN: return GET_BOOLEAN_VOLATILE;
691                     case BYTE:    return GET_BYTE_VOLATILE;
692                     case SHORT:   return GET_SHORT_VOLATILE;
693                     case CHAR:    return GET_CHAR_VOLATILE;
694                     case INT:     return GET_INT_VOLATILE;
695                     case LONG:    return GET_LONG_VOLATILE;
696                     case FLOAT:   return GET_FLOAT_VOLATILE;
697                     case DOUBLE:  return GET_DOUBLE_VOLATILE;
698                     case OBJECT:  return isFlatValue ? GET_VALUE_VOLATILE : GET_REFERENCE_VOLATILE;
699                 }
700             } else {
701                 switch (wrapper) {
702                     case BOOLEAN: return GET_BOOLEAN;
703                     case BYTE:    return GET_BYTE;
704                     case SHORT:   return GET_SHORT;
705                     case CHAR:    return GET_CHAR;
706                     case INT:     return GET_INT;
707                     case LONG:    return GET_LONG;
708                     case FLOAT:   return GET_FLOAT;
709                     case DOUBLE:  return GET_DOUBLE;
710                     case OBJECT:  return isFlatValue ? GET_VALUE : GET_REFERENCE;
711                 }
712             }
713         } else {
714             if (isVolatile) {
715                 switch (wrapper) {
716                     case BOOLEAN: return PUT_BOOLEAN_VOLATILE;
717                     case BYTE:    return PUT_BYTE_VOLATILE;
718                     case SHORT:   return PUT_SHORT_VOLATILE;
719                     case CHAR:    return PUT_CHAR_VOLATILE;
720                     case INT:     return PUT_INT_VOLATILE;
721                     case LONG:    return PUT_LONG_VOLATILE;
722                     case FLOAT:   return PUT_FLOAT_VOLATILE;
723                     case DOUBLE:  return PUT_DOUBLE_VOLATILE;
724                     case OBJECT:  return isFlatValue ? PUT_VALUE_VOLATILE : PUT_REFERENCE_VOLATILE;
725                 }
726             } else {
727                 switch (wrapper) {
728                     case BOOLEAN: return PUT_BOOLEAN;
729                     case BYTE:    return PUT_BYTE;
730                     case SHORT:   return PUT_SHORT;
731                     case CHAR:    return PUT_CHAR;
732                     case INT:     return PUT_INT;
733                     case LONG:    return PUT_LONG;
734                     case FLOAT:   return PUT_FLOAT;
735                     case DOUBLE:  return PUT_DOUBLE;
736                     case OBJECT:  return isFlatValue ? PUT_VALUE : PUT_REFERENCE;
737                 }
738             }
739         }
740         throw new AssertionError("Invalid arguments");
741     }
742 
743     /** invoked by GenerateJLIClassesHelper */
744     static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftype) {
745         return makePreparedFieldLambdaForm(formOp, isVolatile, false, false, ftype);
746     }
747 
748     private static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, boolean isValue, boolean isFlatValue, int ftypeKind) {
749         boolean isGetter  = (formOp & 1) == (AF_GETFIELD & 1);
750         boolean isStatic  = (formOp >= AF_GETSTATIC);
751         boolean needsInit = (formOp >= AF_GETSTATIC_INIT);
752         boolean needsCast = (ftypeKind == FT_CHECKED_REF || ftypeKind == FT_CHECKED_VALUE);
753         Wrapper fw = (needsCast ? Wrapper.OBJECT : ALL_WRAPPERS[ftypeKind]);
754         Class<?> ft = fw.primitiveType();
755         assert(needsCast ? true : ftypeKind(ft, isValue) == ftypeKind);
756 
757         // getObject, putIntVolatile, etc.
758         Kind kind = getFieldKind(isGetter, isVolatile, isFlatValue, fw);
759 
760         MethodType linkerType;
761         boolean hasValueTypeArg = isGetter ? isValue : isFlatValue;
762         if (isGetter) {
763             linkerType = isValue ? MethodType.methodType(ft, Object.class, long.class, Class.class)
764                                  : MethodType.methodType(ft, Object.class, long.class);
765         } else {
766             linkerType = isFlatValue ? MethodType.methodType(void.class, Object.class, long.class, Class.class, ft)
767                                      : MethodType.methodType(void.class, Object.class, long.class, ft);
768         }
769         MemberName linker = new MemberName(Unsafe.class, kind.methodName, linkerType, REF_invokeVirtual);
770         try {
771             linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, LM_TRUSTED,
772                                               NoSuchMethodException.class);
773         } catch (ReflectiveOperationException ex) {
774             throw newInternalError(ex);
775         }
776 
777         // What is the external type of the lambda form?
778         MethodType mtype;
779         if (isGetter)
780             mtype = MethodType.methodType(ft);
781         else
782             mtype = MethodType.methodType(void.class, ft);
783         mtype = mtype.basicType();  // erase short to int, etc.
784         if (!isStatic)
785             mtype = mtype.insertParameterTypes(0, Object.class);
786         final int DMH_THIS  = 0;
787         final int ARG_BASE  = 1;
788         final int ARG_LIMIT = ARG_BASE + mtype.parameterCount();
789         // if this is for non-static access, the base pointer is stored at this index:
790         final int OBJ_BASE  = isStatic ? -1 : ARG_BASE;
791         // if this is for write access, the value to be written is stored at this index:
792         final int SET_VALUE  = isGetter ? -1 : ARG_LIMIT - 1;
793         int nameCursor = ARG_LIMIT;
794         final int F_HOLDER  = (isStatic ? nameCursor++ : -1);  // static base if any
795         final int F_OFFSET  = nameCursor++;  // Either static offset or field offset.
796         final int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++ : -1);
797         final int U_HOLDER  = nameCursor++;  // UNSAFE holder
798         final int INIT_BAR  = (needsInit ? nameCursor++ : -1);
799         final int VALUE_TYPE = (hasValueTypeArg ? nameCursor++ : -1);
800         final int PRE_CAST  = (needsCast && !isGetter ? nameCursor++ : -1);
801         final int LINKER_CALL = nameCursor++;
802         final int POST_CAST = (needsCast && isGetter ? nameCursor++ : -1);
803         final int RESULT    = nameCursor-1;  // either the call or the cast
804         Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType());
805         if (needsInit)
806             names[INIT_BAR] = new Name(getFunction(NF_ensureInitialized), names[DMH_THIS]);
807         if (needsCast && !isGetter)
808             names[PRE_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[SET_VALUE]);
809         Object[] outArgs = new Object[1 + linkerType.parameterCount()];
810         assert (outArgs.length == (isGetter ? 3 : 4) + (hasValueTypeArg ? 1 : 0));
811         outArgs[0] = names[U_HOLDER] = new Name(getFunction(NF_UNSAFE));
812         if (isStatic) {
813             outArgs[1] = names[F_HOLDER]  = new Name(getFunction(NF_staticBase), names[DMH_THIS]);
814             outArgs[2] = names[F_OFFSET]  = new Name(getFunction(NF_staticOffset), names[DMH_THIS]);
815         } else {
816             outArgs[1] = names[OBJ_CHECK] = new Name(getFunction(NF_checkBase), names[OBJ_BASE]);
817             outArgs[2] = names[F_OFFSET]  = new Name(getFunction(NF_fieldOffset), names[DMH_THIS]);
818         }
819         int x = 3;
820         if (hasValueTypeArg) {
821             outArgs[x++] = names[VALUE_TYPE] = isStatic ? new Name(getFunction(NF_staticFieldType), names[DMH_THIS])
822                                                         : new Name(getFunction(NF_fieldType), names[DMH_THIS]);
823         }
824         if (!isGetter) {
825             outArgs[x] = (needsCast ? names[PRE_CAST] : names[SET_VALUE]);
826         }
827         for (Object a : outArgs)  assert(a != null);
828         names[LINKER_CALL] = new Name(linker, outArgs);
829         if (needsCast && isGetter)
830             names[POST_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[LINKER_CALL]);
831         for (Name n : names)  assert(n != null);
832 
833         LambdaForm form;
834         if (needsCast || needsInit) {
835             // can't use the pre-generated form when casting and/or initializing
836             form = new LambdaForm(ARG_LIMIT, names, RESULT);
837         } else {
838             form = new LambdaForm(ARG_LIMIT, names, RESULT, kind);
839         }
840 
841         if (LambdaForm.debugNames()) {
842             // add some detail to the lambdaForm debugname,
843             // significant only for debugging
844             StringBuilder nameBuilder = new StringBuilder(kind.methodName);
845             if (isStatic) {
846                 nameBuilder.append("Static");
847             } else {
848                 nameBuilder.append("Field");
849             }
850             if (needsCast) {
851                 nameBuilder.append("Cast");
852             }
853             if (needsInit) {
854                 nameBuilder.append("Init");
855             }
856             LambdaForm.associateWithDebugName(form, nameBuilder.toString());
857         }
858         return form;
859     }
860 
861     /**
862      * Pre-initialized NamedFunctions for bootstrapping purposes.
863      */
864     static final byte NF_internalMemberName = 0,
865             NF_internalMemberNameEnsureInit = 1,
866             NF_ensureInitialized = 2,
867             NF_fieldOffset = 3,
868             NF_checkBase = 4,
869             NF_staticBase = 5,
870             NF_staticOffset = 6,
871             NF_checkCast = 7,
872             NF_allocateInstance = 8,
873             NF_constructorMethod = 9,
874             NF_UNSAFE = 10,
875             NF_checkReceiver = 11,
876             NF_fieldType = 12,
877             NF_staticFieldType = 13,
878             NF_LIMIT = 14;
879 
880     private static final @Stable NamedFunction[] NFS = new NamedFunction[NF_LIMIT];
881 
882     private static NamedFunction getFunction(byte func) {
883         NamedFunction nf = NFS[func];
884         if (nf != null) {
885             return nf;
886         }
887         // Each nf must be statically invocable or we get tied up in our bootstraps.
888         nf = NFS[func] = createFunction(func);
889         assert(InvokerBytecodeGenerator.isStaticallyInvocable(nf));
890         return nf;
891     }
892 
893     private static final MethodType CLS_OBJ_TYPE = MethodType.methodType(Class.class, Object.class);
894 
895     private static final MethodType OBJ_OBJ_TYPE = MethodType.methodType(Object.class, Object.class);
896 
897     private static final MethodType LONG_OBJ_TYPE = MethodType.methodType(long.class, Object.class);
898 
899     private static NamedFunction createFunction(byte func) {
900         try {
901             switch (func) {
902                 case NF_internalMemberName:
903                     return getNamedFunction("internalMemberName", OBJ_OBJ_TYPE);
904                 case NF_internalMemberNameEnsureInit:
905                     return getNamedFunction("internalMemberNameEnsureInit", OBJ_OBJ_TYPE);
906                 case NF_ensureInitialized:
907                     return getNamedFunction("ensureInitialized", MethodType.methodType(void.class, Object.class));
908                 case NF_fieldOffset:
909                     return getNamedFunction("fieldOffset", LONG_OBJ_TYPE);
910                 case NF_checkBase:
911                     return getNamedFunction("checkBase", OBJ_OBJ_TYPE);
912                 case NF_staticBase:
913                     return getNamedFunction("staticBase", OBJ_OBJ_TYPE);
914                 case NF_staticOffset:
915                     return getNamedFunction("staticOffset", LONG_OBJ_TYPE);
916                 case NF_checkCast:
917                     return getNamedFunction("checkCast", MethodType.methodType(Object.class, Object.class, Object.class));
918                 case NF_allocateInstance:
919                     return getNamedFunction("allocateInstance", OBJ_OBJ_TYPE);
920                 case NF_constructorMethod:
921                     return getNamedFunction("constructorMethod", OBJ_OBJ_TYPE);
922                 case NF_UNSAFE:
923                     MemberName member = new MemberName(MethodHandleStatics.class, "UNSAFE", Unsafe.class, REF_getField);
924                     return new NamedFunction(
925                             MemberName.getFactory().resolveOrFail(REF_getField, member,
926                                                                   DirectMethodHandle.class, LM_TRUSTED,
927                                                                   NoSuchMethodException.class));
928                 case NF_checkReceiver:
929                     member = new MemberName(DirectMethodHandle.class, "checkReceiver", OBJ_OBJ_TYPE, REF_invokeVirtual);
930                     return new NamedFunction(
931                         MemberName.getFactory().resolveOrFail(REF_invokeVirtual, member,
932                                                               DirectMethodHandle.class, LM_TRUSTED,
933                                                               NoSuchMethodException.class));
934                 case NF_fieldType:
935                     return getNamedFunction("fieldType", CLS_OBJ_TYPE);
936                 case NF_staticFieldType:
937                     return getNamedFunction("staticFieldType", CLS_OBJ_TYPE);
938                 default:
939                     throw newInternalError("Unknown function: " + func);
940             }
941         } catch (ReflectiveOperationException ex) {
942             throw newInternalError(ex);
943         }
944     }
945 
946     private static NamedFunction getNamedFunction(String name, MethodType type)
947         throws ReflectiveOperationException
948     {
949         MemberName member = new MemberName(DirectMethodHandle.class, name, type, REF_invokeStatic);
950         return new NamedFunction(
951                 MemberName.getFactory().resolveOrFail(REF_invokeStatic, member,
952                                                       DirectMethodHandle.class, LM_TRUSTED,
953                                                       NoSuchMethodException.class));
954     }
955 
956     static {
957         // The Holder class will contain pre-generated DirectMethodHandles resolved
958         // speculatively using MemberName.getFactory().resolveOrNull. However, that
959         // doesn't initialize the class, which subtly breaks inlining etc. By forcing
960         // initialization of the Holder class we avoid these issues.
961         UNSAFE.ensureClassInitialized(Holder.class);
962     }
963 
964     /* Placeholder class for DirectMethodHandles generated ahead of time */
965     final class Holder {}
966 }