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