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