1 /*
   2  * Copyright (c) 2008, 2011, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/symbolTable.hpp"
  27 #include "compiler/compileBroker.hpp"
  28 #include "interpreter/interpreter.hpp"
  29 #include "interpreter/oopMapCache.hpp"
  30 #include "memory/allocation.inline.hpp"
  31 #include "memory/oopFactory.hpp"
  32 #include "prims/methodHandles.hpp"
  33 #include "prims/methodHandleWalk.hpp"
  34 #include "runtime/compilationPolicy.hpp"
  35 #include "runtime/javaCalls.hpp"
  36 #include "runtime/reflection.hpp"
  37 #include "runtime/signature.hpp"
  38 #include "runtime/stubRoutines.hpp"
  39 
  40 /*
  41  * JSR 292 reference implementation: method handles
  42  */
  43 
  44 bool MethodHandles::_enabled = false; // set true after successful native linkage
  45 
  46 MethodHandleEntry* MethodHandles::_entries[MethodHandles::_EK_LIMIT] = {NULL};
  47 const char*        MethodHandles::_entry_names[_EK_LIMIT+1] = {
  48   "raise_exception",
  49   "invokestatic",               // how a MH emulates invokestatic
  50   "invokespecial",              // ditto for the other invokes...
  51   "invokevirtual",
  52   "invokeinterface",
  53   "bound_ref",                  // these are for BMH...
  54   "bound_int",
  55   "bound_long",
  56   "bound_ref_direct",           // (direct versions have a direct methodOop)
  57   "bound_int_direct",
  58   "bound_long_direct",
  59 
  60   // starting at _adapter_mh_first:
  61   "adapter_retype_only",       // these are for AMH...
  62   "adapter_retype_raw",
  63   "adapter_check_cast",
  64   "adapter_prim_to_prim",
  65   "adapter_ref_to_prim",
  66   "adapter_prim_to_ref",
  67   "adapter_swap_args",
  68   "adapter_rot_args",
  69   "adapter_dup_args",
  70   "adapter_drop_args",
  71   "adapter_collect_args",
  72   "adapter_spread_args",
  73   "adapter_fold_args",
  74   "adapter_unused_13",
  75 
  76   // optimized adapter types:
  77   "adapter_swap_args/1",
  78   "adapter_swap_args/2",
  79   "adapter_rot_args/1,up",
  80   "adapter_rot_args/1,down",
  81   "adapter_rot_args/2,up",
  82   "adapter_rot_args/2,down",
  83   "adapter_prim_to_prim/i2i",
  84   "adapter_prim_to_prim/l2i",
  85   "adapter_prim_to_prim/d2f",
  86   "adapter_prim_to_prim/i2l",
  87   "adapter_prim_to_prim/f2d",
  88   "adapter_ref_to_prim/unboxi",
  89   "adapter_ref_to_prim/unboxl",
  90 
  91   // return value handlers for collect/filter/fold adapters:
  92   "return/ref",
  93   "return/int",
  94   "return/long",
  95   "return/float",
  96   "return/double",
  97   "return/void",
  98   "return/S0/ref",
  99   "return/S1/ref",
 100   "return/S2/ref",
 101   "return/S3/ref",
 102   "return/S4/ref",
 103   "return/S5/ref",
 104   "return/any",
 105 
 106   // spreading (array length cases 0, 1, ...)
 107   "adapter_spread/0",
 108   "adapter_spread/1/ref",
 109   "adapter_spread/2/ref",
 110   "adapter_spread/3/ref",
 111   "adapter_spread/4/ref",
 112   "adapter_spread/5/ref",
 113   "adapter_spread/ref",
 114   "adapter_spread/byte",
 115   "adapter_spread/char",
 116   "adapter_spread/short",
 117   "adapter_spread/int",
 118   "adapter_spread/long",
 119   "adapter_spread/float",
 120   "adapter_spread/double",
 121 
 122   // blocking filter/collect conversions:
 123   "adapter_collect/ref",
 124   "adapter_collect/int",
 125   "adapter_collect/long",
 126   "adapter_collect/float",
 127   "adapter_collect/double",
 128   "adapter_collect/void",
 129   "adapter_collect/0/ref",
 130   "adapter_collect/1/ref",
 131   "adapter_collect/2/ref",
 132   "adapter_collect/3/ref",
 133   "adapter_collect/4/ref",
 134   "adapter_collect/5/ref",
 135   "adapter_filter/S0/ref",
 136   "adapter_filter/S1/ref",
 137   "adapter_filter/S2/ref",
 138   "adapter_filter/S3/ref",
 139   "adapter_filter/S4/ref",
 140   "adapter_filter/S5/ref",
 141   "adapter_collect/2/S0/ref",
 142   "adapter_collect/2/S1/ref",
 143   "adapter_collect/2/S2/ref",
 144   "adapter_collect/2/S3/ref",
 145   "adapter_collect/2/S4/ref",
 146   "adapter_collect/2/S5/ref",
 147 
 148   // blocking fold conversions:
 149   "adapter_fold/ref",
 150   "adapter_fold/int",
 151   "adapter_fold/long",
 152   "adapter_fold/float",
 153   "adapter_fold/double",
 154   "adapter_fold/void",
 155   "adapter_fold/1/ref",
 156   "adapter_fold/2/ref",
 157   "adapter_fold/3/ref",
 158   "adapter_fold/4/ref",
 159   "adapter_fold/5/ref",
 160 
 161   "adapter_opt_profiling",
 162 
 163   NULL
 164 };
 165 
 166 // Adapters.
 167 MethodHandlesAdapterBlob* MethodHandles::_adapter_code = NULL;
 168 
 169 jobject MethodHandles::_raise_exception_method;
 170 
 171 address MethodHandles::_adapter_return_handlers[CONV_TYPE_MASK+1];
 172 
 173 #ifdef ASSERT
 174 bool MethodHandles::spot_check_entry_names() {
 175   assert(!strcmp(entry_name(_invokestatic_mh), "invokestatic"), "");
 176   assert(!strcmp(entry_name(_bound_ref_mh), "bound_ref"), "");
 177   assert(!strcmp(entry_name(_adapter_retype_only), "adapter_retype_only"), "");
 178   assert(!strcmp(entry_name(_adapter_fold_args), "adapter_fold_args"), "");
 179   assert(!strcmp(entry_name(_adapter_opt_unboxi), "adapter_ref_to_prim/unboxi"), "");
 180   assert(!strcmp(entry_name(_adapter_opt_spread_char), "adapter_spread/char"), "");
 181   assert(!strcmp(entry_name(_adapter_opt_spread_double), "adapter_spread/double"), "");
 182   assert(!strcmp(entry_name(_adapter_opt_collect_int), "adapter_collect/int"), "");
 183   assert(!strcmp(entry_name(_adapter_opt_collect_0_ref), "adapter_collect/0/ref"), "");
 184   assert(!strcmp(entry_name(_adapter_opt_collect_2_S3_ref), "adapter_collect/2/S3/ref"), "");
 185   assert(!strcmp(entry_name(_adapter_opt_filter_S5_ref), "adapter_filter/S5/ref"), "");
 186   assert(!strcmp(entry_name(_adapter_opt_fold_3_ref), "adapter_fold/3/ref"), "");
 187   assert(!strcmp(entry_name(_adapter_opt_fold_void), "adapter_fold/void"), "");
 188   return true;
 189 }
 190 #endif
 191 
 192 
 193 //------------------------------------------------------------------------------
 194 // MethodHandles::generate_adapters
 195 //
 196 void MethodHandles::generate_adapters() {
 197 #ifdef TARGET_ARCH_NYI_6939861
 198   if (FLAG_IS_DEFAULT(UseRicochetFrames))  UseRicochetFrames = false;
 199 #endif
 200   if (!EnableInvokeDynamic || SystemDictionary::MethodHandle_klass() == NULL)  return;
 201 
 202   assert(_adapter_code == NULL, "generate only once");
 203 
 204   ResourceMark rm;
 205   TraceTime timer("MethodHandles adapters generation", TraceStartupTime);
 206   _adapter_code = MethodHandlesAdapterBlob::create(adapter_code_size);
 207   if (_adapter_code == NULL)
 208     vm_exit_out_of_memory(adapter_code_size, "CodeCache: no room for MethodHandles adapters");
 209   CodeBuffer code(_adapter_code);
 210   MethodHandlesAdapterGenerator g(&code);
 211   g.generate();
 212 }
 213 
 214 //------------------------------------------------------------------------------
 215 // MethodHandlesAdapterGenerator::generate
 216 //
 217 void MethodHandlesAdapterGenerator::generate() {
 218   // Generate generic method handle adapters.
 219   for (MethodHandles::EntryKind ek = MethodHandles::_EK_FIRST;
 220        ek < MethodHandles::_EK_LIMIT;
 221        ek = MethodHandles::EntryKind(1 + (int)ek)) {
 222     if (MethodHandles::ek_supported(ek)) {
 223       StubCodeMark mark(this, "MethodHandle", MethodHandles::entry_name(ek));
 224       MethodHandles::generate_method_handle_stub(_masm, ek);
 225     }
 226   }
 227 }
 228 
 229 
 230 #ifdef TARGET_ARCH_NYI_6939861
 231 // these defs belong in methodHandles_<arch>.cpp
 232 frame MethodHandles::ricochet_frame_sender(const frame& fr, RegisterMap *map) {
 233   ShouldNotCallThis();
 234   return fr;
 235 }
 236 void MethodHandles::ricochet_frame_oops_do(const frame& fr, OopClosure* f, const RegisterMap* reg_map) {
 237   ShouldNotCallThis();
 238 }
 239 #endif //TARGET_ARCH_NYI_6939861
 240 
 241 
 242 //------------------------------------------------------------------------------
 243 // MethodHandles::ek_supported
 244 //
 245 bool MethodHandles::ek_supported(MethodHandles::EntryKind ek) {
 246   MethodHandles::EntryKind ek_orig = MethodHandles::ek_original_kind(ek);
 247   switch (ek_orig) {
 248   case _adapter_unused_13:
 249     return false;  // not defined yet
 250   case _adapter_prim_to_ref:
 251     return UseRicochetFrames && conv_op_supported(java_lang_invoke_AdapterMethodHandle::OP_PRIM_TO_REF);
 252   case _adapter_collect_args:
 253     return UseRicochetFrames && conv_op_supported(java_lang_invoke_AdapterMethodHandle::OP_COLLECT_ARGS);
 254   case _adapter_fold_args:
 255     return UseRicochetFrames && conv_op_supported(java_lang_invoke_AdapterMethodHandle::OP_FOLD_ARGS);
 256   case _adapter_opt_return_any:
 257     return UseRicochetFrames;
 258 #ifdef TARGET_ARCH_NYI_6939861
 259   // ports before 6939861 supported only three kinds of spread ops
 260   case _adapter_spread_args:
 261     // restrict spreads to three kinds:
 262     switch (ek) {
 263     case _adapter_opt_spread_0:
 264     case _adapter_opt_spread_1:
 265     case _adapter_opt_spread_more:
 266       break;
 267     default:
 268       return false;
 269       break;
 270     }
 271     break;
 272 #endif //TARGET_ARCH_NYI_6939861
 273   }
 274   return true;
 275 }
 276 
 277 
 278 void MethodHandles::set_enabled(bool z) {
 279   if (_enabled != z) {
 280     guarantee(z && EnableInvokeDynamic, "can only enable once, and only if -XX:+EnableInvokeDynamic");
 281     _enabled = z;
 282   }
 283 }
 284 
 285 // Note: A method which does not have a TRAPS argument cannot block in the GC
 286 // or throw exceptions.  Such methods are used in this file to do something quick
 287 // and local, like parse a data structure.  For speed, such methods work on plain
 288 // oops, not handles.  Trapping methods uniformly operate on handles.
 289 
 290 methodHandle MethodHandles::decode_vmtarget(oop vmtarget, int vmindex, oop mtype,
 291                                             KlassHandle& receiver_limit_result, int& decode_flags_result) {
 292   if (vmtarget == NULL)  return methodHandle();
 293   assert(methodOopDesc::nonvirtual_vtable_index < 0, "encoding");
 294   if (vmindex < 0) {
 295     // this DMH performs no dispatch; it is directly bound to a methodOop
 296     // A MemberName may either be directly bound to a methodOop,
 297     // or it may use the klass/index form; both forms mean the same thing.
 298     methodOop m = decode_methodOop(methodOop(vmtarget), decode_flags_result);
 299     if ((decode_flags_result & _dmf_has_receiver) != 0
 300         && java_lang_invoke_MethodType::is_instance(mtype)) {
 301       // Extract receiver type restriction from mtype.ptypes[0].
 302       objArrayOop ptypes = java_lang_invoke_MethodType::ptypes(mtype);
 303       oop ptype0 = (ptypes == NULL || ptypes->length() < 1) ? oop(NULL) : ptypes->obj_at(0);
 304       if (java_lang_Class::is_instance(ptype0))
 305         receiver_limit_result = java_lang_Class::as_klassOop(ptype0);
 306     }
 307     if (vmindex == methodOopDesc::nonvirtual_vtable_index) {
 308       // this DMH can be an "invokespecial" version
 309       decode_flags_result &= ~_dmf_does_dispatch;
 310     } else {
 311       assert(vmindex == methodOopDesc::invalid_vtable_index, "random vmindex?");
 312     }
 313     return m;
 314   } else {
 315     assert(vmtarget->is_klass(), "must be class or interface");
 316     decode_flags_result |= MethodHandles::_dmf_does_dispatch;
 317     decode_flags_result |= MethodHandles::_dmf_has_receiver;
 318     receiver_limit_result = (klassOop)vmtarget;
 319     Klass* tk = Klass::cast((klassOop)vmtarget);
 320     if (tk->is_interface()) {
 321       // an itable linkage is <interface, itable index>
 322       decode_flags_result |= MethodHandles::_dmf_from_interface;
 323       return klassItable::method_for_itable_index((klassOop)vmtarget, vmindex);
 324     } else {
 325       if (!tk->oop_is_instance())
 326         tk = instanceKlass::cast(SystemDictionary::Object_klass());
 327       return ((instanceKlass*)tk)->method_at_vtable(vmindex);
 328     }
 329   }
 330 }
 331 
 332 // MemberName and DirectMethodHandle have the same linkage to the JVM internals.
 333 // (MemberName is the non-operational name used for queries and setup.)
 334 
 335 methodHandle MethodHandles::decode_DirectMethodHandle(oop mh, KlassHandle& receiver_limit_result, int& decode_flags_result) {
 336   oop vmtarget = java_lang_invoke_DirectMethodHandle::vmtarget(mh);
 337   int vmindex  = java_lang_invoke_DirectMethodHandle::vmindex(mh);
 338   oop mtype    = java_lang_invoke_DirectMethodHandle::type(mh);
 339   return decode_vmtarget(vmtarget, vmindex, mtype, receiver_limit_result, decode_flags_result);
 340 }
 341 
 342 methodHandle MethodHandles::decode_BoundMethodHandle(oop mh, KlassHandle& receiver_limit_result, int& decode_flags_result) {
 343   assert(java_lang_invoke_BoundMethodHandle::is_instance(mh), "");
 344   assert(mh->klass() != SystemDictionary::AdapterMethodHandle_klass(), "");
 345   for (oop bmh = mh;;) {
 346     // Bound MHs can be stacked to bind several arguments.
 347     oop target = java_lang_invoke_MethodHandle::vmtarget(bmh);
 348     if (target == NULL)  return methodHandle();
 349     decode_flags_result |= MethodHandles::_dmf_binds_argument;
 350     klassOop tk = target->klass();
 351     if (tk == SystemDictionary::BoundMethodHandle_klass()) {
 352       bmh = target;
 353       continue;
 354     } else {
 355       if (java_lang_invoke_MethodHandle::is_subclass(tk)) {
 356         //assert(tk == SystemDictionary::DirectMethodHandle_klass(), "end of BMH chain must be DMH");
 357         return decode_MethodHandle(target, receiver_limit_result, decode_flags_result);
 358       } else {
 359         // Optimized case:  binding a receiver to a non-dispatched DMH
 360         // short-circuits directly to the methodOop.
 361         // (It might be another argument besides a receiver also.)
 362         assert(target->is_method(), "must be a simple method");
 363         decode_flags_result |= MethodHandles::_dmf_binds_method;
 364         methodOop m = (methodOop) target;
 365         if (!m->is_static())
 366           decode_flags_result |= MethodHandles::_dmf_has_receiver;
 367         return m;
 368       }
 369     }
 370   }
 371 }
 372 
 373 methodHandle MethodHandles::decode_AdapterMethodHandle(oop mh, KlassHandle& receiver_limit_result, int& decode_flags_result) {
 374   assert(mh->klass() == SystemDictionary::AdapterMethodHandle_klass(), "");
 375   for (oop amh = mh;;) {
 376     // Adapter MHs can be stacked to convert several arguments.
 377     int conv_op = adapter_conversion_op(java_lang_invoke_AdapterMethodHandle::conversion(amh));
 378     decode_flags_result |= (_dmf_adapter_lsb << conv_op) & _DMF_ADAPTER_MASK;
 379     oop target = java_lang_invoke_MethodHandle::vmtarget(amh);
 380     if (target == NULL)  return methodHandle();
 381     klassOop tk = target->klass();
 382     if (tk == SystemDictionary::AdapterMethodHandle_klass()) {
 383       amh = target;
 384       continue;
 385     } else {
 386       // must be a BMH (which will bind some more arguments) or a DMH (for the final call)
 387       return MethodHandles::decode_MethodHandle(target, receiver_limit_result, decode_flags_result);
 388     }
 389   }
 390 }
 391 
 392 methodHandle MethodHandles::decode_MethodHandle(oop mh, KlassHandle& receiver_limit_result, int& decode_flags_result) {
 393   if (mh == NULL)  return methodHandle();
 394   klassOop mhk = mh->klass();
 395   assert(java_lang_invoke_MethodHandle::is_subclass(mhk), "must be a MethodHandle");
 396   if (mhk == SystemDictionary::DirectMethodHandle_klass()) {
 397     return decode_DirectMethodHandle(mh, receiver_limit_result, decode_flags_result);
 398   } else if (mhk == SystemDictionary::BoundMethodHandle_klass()) {
 399     return decode_BoundMethodHandle(mh, receiver_limit_result, decode_flags_result);
 400   } else if (mhk == SystemDictionary::AdapterMethodHandle_klass()) {
 401     return decode_AdapterMethodHandle(mh, receiver_limit_result, decode_flags_result);
 402   } else if (java_lang_invoke_BoundMethodHandle::is_subclass(mhk)) {
 403     // could be a JavaMethodHandle (but not an adapter MH)
 404     return decode_BoundMethodHandle(mh, receiver_limit_result, decode_flags_result);
 405   } else {
 406     assert(false, "cannot parse this MH");
 407     return methodHandle();  // random MH?
 408   }
 409 }
 410 
 411 methodOop MethodHandles::decode_methodOop(methodOop m, int& decode_flags_result) {
 412   assert(m->is_method(), "");
 413   if (m->is_static()) {
 414     // check that signature begins '(L' or '([' (not '(I', '()', etc.)
 415     Symbol* sig = m->signature();
 416     BasicType recv_bt = char2type(sig->byte_at(1));
 417     // Note: recv_bt might be T_ILLEGAL if byte_at(2) is ')'
 418     assert(sig->byte_at(0) == '(', "must be method sig");
 419 //     if (recv_bt == T_OBJECT || recv_bt == T_ARRAY)
 420 //       decode_flags_result |= _dmf_has_receiver;
 421   } else {
 422     // non-static method
 423     decode_flags_result |= _dmf_has_receiver;
 424     if (!m->can_be_statically_bound() && !m->is_initializer()) {
 425       decode_flags_result |= _dmf_does_dispatch;
 426       if (Klass::cast(m->method_holder())->is_interface())
 427         decode_flags_result |= _dmf_from_interface;
 428     }
 429   }
 430   return m;
 431 }
 432 
 433 
 434 // A trusted party is handing us a cookie to determine a method.
 435 // Let's boil it down to the method oop they really want.
 436 methodHandle MethodHandles::decode_method(oop x, KlassHandle& receiver_limit_result, int& decode_flags_result) {
 437   decode_flags_result = 0;
 438   receiver_limit_result = KlassHandle();
 439   klassOop xk = x->klass();
 440   if (xk == Universe::methodKlassObj()) {
 441     return decode_methodOop((methodOop) x, decode_flags_result);
 442   } else if (xk == SystemDictionary::MemberName_klass()) {
 443     // Note: This only works if the MemberName has already been resolved.
 444     return decode_MemberName(x, receiver_limit_result, decode_flags_result);
 445   } else if (java_lang_invoke_MethodHandle::is_subclass(xk)) {
 446     return decode_MethodHandle(x, receiver_limit_result, decode_flags_result);
 447   } else if (xk == SystemDictionary::reflect_Method_klass()) {
 448     oop clazz  = java_lang_reflect_Method::clazz(x);
 449     int slot   = java_lang_reflect_Method::slot(x);
 450     klassOop k = java_lang_Class::as_klassOop(clazz);
 451     if (k != NULL && Klass::cast(k)->oop_is_instance())
 452       return decode_methodOop(instanceKlass::cast(k)->method_with_idnum(slot),
 453                               decode_flags_result);
 454   } else if (xk == SystemDictionary::reflect_Constructor_klass()) {
 455     oop clazz  = java_lang_reflect_Constructor::clazz(x);
 456     int slot   = java_lang_reflect_Constructor::slot(x);
 457     klassOop k = java_lang_Class::as_klassOop(clazz);
 458     if (k != NULL && Klass::cast(k)->oop_is_instance())
 459       return decode_methodOop(instanceKlass::cast(k)->method_with_idnum(slot),
 460                               decode_flags_result);
 461   } else {
 462     // unrecognized object
 463     assert(!x->is_method(), "already checked");
 464     assert(!java_lang_invoke_MemberName::is_instance(x), "already checked");
 465   }
 466   return methodHandle();
 467 }
 468 
 469 
 470 int MethodHandles::decode_MethodHandle_stack_pushes(oop mh) {
 471   if (mh->klass() == SystemDictionary::DirectMethodHandle_klass())
 472     return 0;                   // no push/pop
 473   int this_vmslots = java_lang_invoke_MethodHandle::vmslots(mh);
 474   int last_vmslots = 0;
 475   oop last_mh = mh;
 476   for (;;) {
 477     oop target = java_lang_invoke_MethodHandle::vmtarget(last_mh);
 478     if (target->klass() == SystemDictionary::DirectMethodHandle_klass()) {
 479       last_vmslots = java_lang_invoke_MethodHandle::vmslots(target);
 480       break;
 481     } else if (!java_lang_invoke_MethodHandle::is_instance(target)) {
 482       // might be klass or method
 483       assert(target->is_method(), "must get here with a direct ref to method");
 484       last_vmslots = methodOop(target)->size_of_parameters();
 485       break;
 486     }
 487     last_mh = target;
 488   }
 489   // If I am called with fewer VM slots than my ultimate callee,
 490   // it must be that I push the additionally needed slots.
 491   // Likewise if am called with more VM slots, I will pop them.
 492   return (last_vmslots - this_vmslots);
 493 }
 494 
 495 
 496 // MemberName support
 497 
 498 // import java_lang_invoke_MemberName.*
 499 enum {
 500   IS_METHOD      = java_lang_invoke_MemberName::MN_IS_METHOD,
 501   IS_CONSTRUCTOR = java_lang_invoke_MemberName::MN_IS_CONSTRUCTOR,
 502   IS_FIELD       = java_lang_invoke_MemberName::MN_IS_FIELD,
 503   IS_TYPE        = java_lang_invoke_MemberName::MN_IS_TYPE,
 504   SEARCH_SUPERCLASSES = java_lang_invoke_MemberName::MN_SEARCH_SUPERCLASSES,
 505   SEARCH_INTERFACES   = java_lang_invoke_MemberName::MN_SEARCH_INTERFACES,
 506   ALL_KINDS      = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE,
 507   VM_INDEX_UNINITIALIZED = java_lang_invoke_MemberName::VM_INDEX_UNINITIALIZED
 508 };
 509 
 510 Handle MethodHandles::new_MemberName(TRAPS) {
 511   Handle empty;
 512   instanceKlassHandle k(THREAD, SystemDictionary::MemberName_klass());
 513   if (!k->is_initialized())  k->initialize(CHECK_(empty));
 514   return Handle(THREAD, k->allocate_instance(THREAD));
 515 }
 516 
 517 void MethodHandles::init_MemberName(oop mname_oop, oop target_oop) {
 518   if (target_oop->klass() == SystemDictionary::reflect_Field_klass()) {
 519     oop clazz = java_lang_reflect_Field::clazz(target_oop); // fd.field_holder()
 520     int slot  = java_lang_reflect_Field::slot(target_oop);  // fd.index()
 521     int mods  = java_lang_reflect_Field::modifiers(target_oop);
 522     klassOop k = java_lang_Class::as_klassOop(clazz);
 523     int offset = instanceKlass::cast(k)->offset_from_fields(slot);
 524     init_MemberName(mname_oop, k, accessFlags_from(mods), offset);
 525   } else {
 526     KlassHandle receiver_limit; int decode_flags = 0;
 527     methodHandle m = MethodHandles::decode_method(target_oop, receiver_limit, decode_flags);
 528     bool do_dispatch = ((decode_flags & MethodHandles::_dmf_does_dispatch) != 0);
 529     init_MemberName(mname_oop, m(), do_dispatch);
 530   }
 531 }
 532 
 533 void MethodHandles::init_MemberName(oop mname_oop, methodOop m, bool do_dispatch) {
 534   int flags = ((m->is_initializer() ? IS_CONSTRUCTOR : IS_METHOD)
 535                | (jushort)( m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS ));
 536   oop vmtarget = m;
 537   int vmindex  = methodOopDesc::invalid_vtable_index;  // implies no info yet
 538   if (!do_dispatch || (flags & IS_CONSTRUCTOR) || m->can_be_statically_bound())
 539     vmindex = methodOopDesc::nonvirtual_vtable_index; // implies never any dispatch
 540   assert(vmindex != VM_INDEX_UNINITIALIZED, "Java sentinel value");
 541   java_lang_invoke_MemberName::set_vmtarget(mname_oop, vmtarget);
 542   java_lang_invoke_MemberName::set_vmindex(mname_oop,  vmindex);
 543   java_lang_invoke_MemberName::set_flags(mname_oop,    flags);
 544   java_lang_invoke_MemberName::set_clazz(mname_oop,    Klass::cast(m->method_holder())->java_mirror());
 545 }
 546 
 547 void MethodHandles::init_MemberName(oop mname_oop, klassOop field_holder, AccessFlags mods, int offset) {
 548   int flags = (IS_FIELD | (jushort)( mods.as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS ));
 549   oop vmtarget = field_holder;
 550   int vmindex  = offset;  // determines the field uniquely when combined with static bit
 551   assert(vmindex != VM_INDEX_UNINITIALIZED, "bad alias on vmindex");
 552   java_lang_invoke_MemberName::set_vmtarget(mname_oop, vmtarget);
 553   java_lang_invoke_MemberName::set_vmindex(mname_oop,  vmindex);
 554   java_lang_invoke_MemberName::set_flags(mname_oop,    flags);
 555   java_lang_invoke_MemberName::set_clazz(mname_oop,    Klass::cast(field_holder)->java_mirror());
 556 }
 557 
 558 
 559 methodHandle MethodHandles::decode_MemberName(oop mname, KlassHandle& receiver_limit_result, int& decode_flags_result) {
 560   methodHandle empty;
 561   int flags  = java_lang_invoke_MemberName::flags(mname);
 562   if ((flags & (IS_METHOD | IS_CONSTRUCTOR)) == 0)  return empty;  // not invocable
 563   oop vmtarget = java_lang_invoke_MemberName::vmtarget(mname);
 564   int vmindex  = java_lang_invoke_MemberName::vmindex(mname);
 565   if (vmindex == VM_INDEX_UNINITIALIZED)  return empty;  // not resolved
 566   methodHandle m = decode_vmtarget(vmtarget, vmindex, NULL, receiver_limit_result, decode_flags_result);
 567   oop clazz = java_lang_invoke_MemberName::clazz(mname);
 568   if (clazz != NULL && java_lang_Class::is_instance(clazz)) {
 569     klassOop klass = java_lang_Class::as_klassOop(clazz);
 570     if (klass != NULL)  receiver_limit_result = klass;
 571   }
 572   return m;
 573 }
 574 
 575 // convert the external string or reflective type to an internal signature
 576 Symbol* MethodHandles::convert_to_signature(oop type_str, bool polymorphic, TRAPS) {
 577   if (java_lang_invoke_MethodType::is_instance(type_str)) {
 578     return java_lang_invoke_MethodType::as_signature(type_str, polymorphic, CHECK_NULL);
 579   } else if (java_lang_Class::is_instance(type_str)) {
 580     return java_lang_Class::as_signature(type_str, false, CHECK_NULL);
 581   } else if (java_lang_String::is_instance(type_str)) {
 582     if (polymorphic) {
 583       return java_lang_String::as_symbol(type_str, CHECK_NULL);
 584     } else {
 585       return java_lang_String::as_symbol_or_null(type_str);
 586     }
 587   } else {
 588     THROW_MSG_(vmSymbols::java_lang_InternalError(), "unrecognized type", NULL);
 589   }
 590 }
 591 
 592 // An unresolved member name is a mere symbolic reference.
 593 // Resolving it plants a vmtarget/vmindex in it,
 594 // which refers dirctly to JVM internals.
 595 void MethodHandles::resolve_MemberName(Handle mname, TRAPS) {
 596   assert(java_lang_invoke_MemberName::is_instance(mname()), "");
 597 #ifdef ASSERT
 598   // If this assert throws, renegotiate the sentinel value used by the Java code,
 599   // so that it is distinct from any valid vtable index value, and any special
 600   // values defined in methodOopDesc::VtableIndexFlag.
 601   // The point of the slop is to give the Java code and the JVM some room
 602   // to independently specify sentinel values.
 603   const int sentinel_slop  = 10;
 604   const int sentinel_limit = methodOopDesc::highest_unused_vtable_index_value - sentinel_slop;
 605   assert(VM_INDEX_UNINITIALIZED < sentinel_limit, "Java sentinel != JVM sentinels");
 606 #endif
 607   if (java_lang_invoke_MemberName::vmindex(mname()) != VM_INDEX_UNINITIALIZED)
 608     return;  // already resolved
 609   Handle defc_oop(THREAD, java_lang_invoke_MemberName::clazz(mname()));
 610   Handle name_str(THREAD, java_lang_invoke_MemberName::name( mname()));
 611   Handle type_str(THREAD, java_lang_invoke_MemberName::type( mname()));
 612   int    flags    =       java_lang_invoke_MemberName::flags(mname());
 613 
 614   if (defc_oop.is_null() || name_str.is_null() || type_str.is_null()) {
 615     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to resolve");
 616   }
 617 
 618   instanceKlassHandle defc;
 619   {
 620     klassOop defc_klassOop = java_lang_Class::as_klassOop(defc_oop());
 621     if (defc_klassOop == NULL)  return;  // a primitive; no resolution possible
 622     if (!Klass::cast(defc_klassOop)->oop_is_instance()) {
 623       if (!Klass::cast(defc_klassOop)->oop_is_array())  return;
 624       defc_klassOop = SystemDictionary::Object_klass();
 625     }
 626     defc = instanceKlassHandle(THREAD, defc_klassOop);
 627   }
 628   if (defc.is_null()) {
 629     THROW_MSG(vmSymbols::java_lang_InternalError(), "primitive class");
 630   }
 631   defc->link_class(CHECK);  // possible safepoint
 632 
 633   // convert the external string name to an internal symbol
 634   TempNewSymbol name = java_lang_String::as_symbol_or_null(name_str());
 635   if (name == NULL)  return;  // no such name
 636   if (name == vmSymbols::class_initializer_name())
 637     return; // illegal name
 638 
 639   Handle polymorphic_method_type;
 640   bool polymorphic_signature = false;
 641   if ((flags & ALL_KINDS) == IS_METHOD &&
 642       (defc() == SystemDictionary::MethodHandle_klass() &&
 643        methodOopDesc::is_method_handle_invoke_name(name))) {
 644     polymorphic_signature = true;
 645   }
 646 
 647   // convert the external string or reflective type to an internal signature
 648   TempNewSymbol type = convert_to_signature(type_str(), polymorphic_signature, CHECK);
 649   if (java_lang_invoke_MethodType::is_instance(type_str()) && polymorphic_signature) {
 650     polymorphic_method_type = type_str;  // preserve exactly
 651   }
 652   if (type == NULL)  return;  // no such signature exists in the VM
 653 
 654   // Time to do the lookup.
 655   switch (flags & ALL_KINDS) {
 656   case IS_METHOD:
 657     {
 658       CallInfo result;
 659       {
 660         EXCEPTION_MARK;
 661         if ((flags & JVM_ACC_STATIC) != 0) {
 662           LinkResolver::resolve_static_call(result,
 663                         defc, name, type, KlassHandle(), false, false, THREAD);
 664         } else if (defc->is_interface()) {
 665           LinkResolver::resolve_interface_call(result, Handle(), defc,
 666                         defc, name, type, KlassHandle(), false, false, THREAD);
 667         } else {
 668           LinkResolver::resolve_virtual_call(result, Handle(), defc,
 669                         defc, name, type, KlassHandle(), false, false, THREAD);
 670         }
 671         if (HAS_PENDING_EXCEPTION) {
 672           CLEAR_PENDING_EXCEPTION;
 673           break;  // go to second chance
 674         }
 675       }
 676       methodHandle m = result.resolved_method();
 677       oop vmtarget = NULL;
 678       int vmindex = methodOopDesc::nonvirtual_vtable_index;
 679       if (defc->is_interface()) {
 680         vmindex = klassItable::compute_itable_index(m());
 681         assert(vmindex >= 0, "");
 682       } else if (result.has_vtable_index()) {
 683         vmindex = result.vtable_index();
 684         assert(vmindex >= 0, "");
 685       }
 686       assert(vmindex != VM_INDEX_UNINITIALIZED, "");
 687       if (vmindex < 0) {
 688         assert(result.is_statically_bound(), "");
 689         vmtarget = m();
 690       } else {
 691         vmtarget = result.resolved_klass()->as_klassOop();
 692       }
 693       int mods = (m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS);
 694       java_lang_invoke_MemberName::set_vmtarget(mname(), vmtarget);
 695       java_lang_invoke_MemberName::set_vmindex(mname(),  vmindex);
 696       java_lang_invoke_MemberName::set_modifiers(mname(), mods);
 697       DEBUG_ONLY(KlassHandle junk1; int junk2);
 698       assert(decode_MemberName(mname(), junk1, junk2) == result.resolved_method(),
 699              "properly stored for later decoding");
 700       return;
 701     }
 702   case IS_CONSTRUCTOR:
 703     {
 704       CallInfo result;
 705       {
 706         EXCEPTION_MARK;
 707         if (name == vmSymbols::object_initializer_name()) {
 708           LinkResolver::resolve_special_call(result,
 709                         defc, name, type, KlassHandle(), false, THREAD);
 710         } else {
 711           break;                // will throw after end of switch
 712         }
 713         if (HAS_PENDING_EXCEPTION) {
 714           CLEAR_PENDING_EXCEPTION;
 715           return;
 716         }
 717       }
 718       assert(result.is_statically_bound(), "");
 719       methodHandle m = result.resolved_method();
 720       oop vmtarget = m();
 721       int vmindex  = methodOopDesc::nonvirtual_vtable_index;
 722       int mods     = (m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS);
 723       java_lang_invoke_MemberName::set_vmtarget(mname(), vmtarget);
 724       java_lang_invoke_MemberName::set_vmindex(mname(),  vmindex);
 725       java_lang_invoke_MemberName::set_modifiers(mname(), mods);
 726       DEBUG_ONLY(KlassHandle junk1; int junk2);
 727       assert(decode_MemberName(mname(), junk1, junk2) == result.resolved_method(),
 728              "properly stored for later decoding");
 729       return;
 730     }
 731   case IS_FIELD:
 732     {
 733       // This is taken from LinkResolver::resolve_field, sans access checks.
 734       fieldDescriptor fd; // find_field initializes fd if found
 735       KlassHandle sel_klass(THREAD, instanceKlass::cast(defc())->find_field(name, type, &fd));
 736       // check if field exists; i.e., if a klass containing the field def has been selected
 737       if (sel_klass.is_null())  return;
 738       oop vmtarget = sel_klass->as_klassOop();
 739       int vmindex  = fd.offset();
 740       int mods     = (fd.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS);
 741       if (vmindex == VM_INDEX_UNINITIALIZED)  break;  // should not happen
 742       java_lang_invoke_MemberName::set_vmtarget(mname(),  vmtarget);
 743       java_lang_invoke_MemberName::set_vmindex(mname(),   vmindex);
 744       java_lang_invoke_MemberName::set_modifiers(mname(), mods);
 745       return;
 746     }
 747   default:
 748     THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
 749   }
 750 
 751   // Second chance.
 752   if (polymorphic_method_type.not_null()) {
 753     // Look on a non-null class loader.
 754     Handle cur_class_loader;
 755     const int nptypes = java_lang_invoke_MethodType::ptype_count(polymorphic_method_type());
 756     for (int i = 0; i <= nptypes; i++) {
 757       oop type_mirror;
 758       if (i < nptypes)  type_mirror = java_lang_invoke_MethodType::ptype(polymorphic_method_type(), i);
 759       else              type_mirror = java_lang_invoke_MethodType::rtype(polymorphic_method_type());
 760       klassOop example_type = java_lang_Class::as_klassOop(type_mirror);
 761       if (example_type == NULL)  continue;
 762       oop class_loader = Klass::cast(example_type)->class_loader();
 763       if (class_loader == NULL || class_loader == cur_class_loader())  continue;
 764       cur_class_loader = Handle(THREAD, class_loader);
 765       methodOop m = SystemDictionary::find_method_handle_invoke(name,
 766                                                                 type,
 767                                                                 KlassHandle(THREAD, example_type),
 768                                                                 THREAD);
 769       if (HAS_PENDING_EXCEPTION) {
 770         CLEAR_PENDING_EXCEPTION;
 771         m = NULL;
 772         // try again with a different class loader...
 773       }
 774       if (m != NULL &&
 775           m->is_method_handle_invoke() &&
 776           java_lang_invoke_MethodType::equals(polymorphic_method_type(), m->method_handle_type())) {
 777         int mods = (m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS);
 778         java_lang_invoke_MemberName::set_vmtarget(mname(),  m);
 779         java_lang_invoke_MemberName::set_vmindex(mname(),   m->vtable_index());
 780         java_lang_invoke_MemberName::set_modifiers(mname(), mods);
 781         return;
 782       }
 783     }
 784   }
 785 }
 786 
 787 // Conversely, a member name which is only initialized from JVM internals
 788 // may have null defc, name, and type fields.
 789 // Resolving it plants a vmtarget/vmindex in it,
 790 // which refers directly to JVM internals.
 791 void MethodHandles::expand_MemberName(Handle mname, int suppress, TRAPS) {
 792   assert(java_lang_invoke_MemberName::is_instance(mname()), "");
 793   oop vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
 794   int vmindex  = java_lang_invoke_MemberName::vmindex(mname());
 795   if (vmtarget == NULL || vmindex == VM_INDEX_UNINITIALIZED) {
 796     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to expand");
 797   }
 798 
 799   bool have_defc = (java_lang_invoke_MemberName::clazz(mname()) != NULL);
 800   bool have_name = (java_lang_invoke_MemberName::name(mname()) != NULL);
 801   bool have_type = (java_lang_invoke_MemberName::type(mname()) != NULL);
 802   int flags      = java_lang_invoke_MemberName::flags(mname());
 803 
 804   if (suppress != 0) {
 805     if (suppress & _suppress_defc)  have_defc = true;
 806     if (suppress & _suppress_name)  have_name = true;
 807     if (suppress & _suppress_type)  have_type = true;
 808   }
 809 
 810   if (have_defc && have_name && have_type)  return;  // nothing needed
 811 
 812   switch (flags & ALL_KINDS) {
 813   case IS_METHOD:
 814   case IS_CONSTRUCTOR:
 815     {
 816       KlassHandle receiver_limit; int decode_flags = 0;
 817       methodHandle m = decode_vmtarget(vmtarget, vmindex, NULL, receiver_limit, decode_flags);
 818       if (m.is_null())  break;
 819       if (!have_defc) {
 820         klassOop defc = m->method_holder();
 821         if (receiver_limit.not_null() && receiver_limit() != defc
 822             && Klass::cast(receiver_limit())->is_subtype_of(defc))
 823           defc = receiver_limit();
 824         java_lang_invoke_MemberName::set_clazz(mname(), Klass::cast(defc)->java_mirror());
 825       }
 826       if (!have_name) {
 827         //not java_lang_String::create_from_symbol; let's intern member names
 828         Handle name = StringTable::intern(m->name(), CHECK);
 829         java_lang_invoke_MemberName::set_name(mname(), name());
 830       }
 831       if (!have_type) {
 832         Handle type = java_lang_String::create_from_symbol(m->signature(), CHECK);
 833         java_lang_invoke_MemberName::set_type(mname(), type());
 834       }
 835       return;
 836     }
 837   case IS_FIELD:
 838     {
 839       // This is taken from LinkResolver::resolve_field, sans access checks.
 840       if (!vmtarget->is_klass())  break;
 841       if (!Klass::cast((klassOop) vmtarget)->oop_is_instance())  break;
 842       instanceKlassHandle defc(THREAD, (klassOop) vmtarget);
 843       bool is_static = ((flags & JVM_ACC_STATIC) != 0);
 844       fieldDescriptor fd; // find_field initializes fd if found
 845       if (!defc->find_field_from_offset(vmindex, is_static, &fd))
 846         break;                  // cannot expand
 847       if (!have_defc) {
 848         java_lang_invoke_MemberName::set_clazz(mname(), defc->java_mirror());
 849       }
 850       if (!have_name) {
 851         //not java_lang_String::create_from_symbol; let's intern member names
 852         Handle name = StringTable::intern(fd.name(), CHECK);
 853         java_lang_invoke_MemberName::set_name(mname(), name());
 854       }
 855       if (!have_type) {
 856         Handle type = java_lang_String::create_from_symbol(fd.signature(), CHECK);
 857         java_lang_invoke_MemberName::set_type(mname(), type());
 858       }
 859       return;
 860     }
 861   }
 862   THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
 863 }
 864 
 865 int MethodHandles::find_MemberNames(klassOop k,
 866                                     Symbol* name, Symbol* sig,
 867                                     int mflags, klassOop caller,
 868                                     int skip, objArrayOop results) {
 869   DEBUG_ONLY(No_Safepoint_Verifier nsv);
 870   // this code contains no safepoints!
 871 
 872   // %%% take caller into account!
 873 
 874   if (k == NULL || !Klass::cast(k)->oop_is_instance())  return -1;
 875 
 876   int rfill = 0, rlimit = results->length(), rskip = skip;
 877   // overflow measurement:
 878   int overflow = 0, overflow_limit = MAX2(1000, rlimit);
 879 
 880   int match_flags = mflags;
 881   bool search_superc = ((match_flags & SEARCH_SUPERCLASSES) != 0);
 882   bool search_intfc  = ((match_flags & SEARCH_INTERFACES)   != 0);
 883   bool local_only = !(search_superc | search_intfc);
 884   bool classes_only = false;
 885 
 886   if (name != NULL) {
 887     if (name->utf8_length() == 0)  return 0; // a match is not possible
 888   }
 889   if (sig != NULL) {
 890     if (sig->utf8_length() == 0)  return 0; // a match is not possible
 891     if (sig->byte_at(0) == '(')
 892       match_flags &= ~(IS_FIELD | IS_TYPE);
 893     else
 894       match_flags &= ~(IS_CONSTRUCTOR | IS_METHOD);
 895   }
 896 
 897   if ((match_flags & IS_TYPE) != 0) {
 898     // NYI, and Core Reflection works quite well for this query
 899   }
 900 
 901   if ((match_flags & IS_FIELD) != 0) {
 902     for (FieldStream st(k, local_only, !search_intfc); !st.eos(); st.next()) {
 903       if (name != NULL && st.name() != name)
 904           continue;
 905       if (sig != NULL && st.signature() != sig)
 906         continue;
 907       // passed the filters
 908       if (rskip > 0) {
 909         --rskip;
 910       } else if (rfill < rlimit) {
 911         oop result = results->obj_at(rfill++);
 912         if (!java_lang_invoke_MemberName::is_instance(result))
 913           return -99;  // caller bug!
 914         MethodHandles::init_MemberName(result, st.klass()->as_klassOop(), st.access_flags(), st.offset());
 915       } else if (++overflow >= overflow_limit) {
 916         match_flags = 0; break; // got tired of looking at overflow
 917       }
 918     }
 919   }
 920 
 921   if ((match_flags & (IS_METHOD | IS_CONSTRUCTOR)) != 0) {
 922     // watch out for these guys:
 923     Symbol* init_name   = vmSymbols::object_initializer_name();
 924     Symbol* clinit_name = vmSymbols::class_initializer_name();
 925     if (name == clinit_name)  clinit_name = NULL; // hack for exposing <clinit>
 926     bool negate_name_test = false;
 927     // fix name so that it captures the intention of IS_CONSTRUCTOR
 928     if (!(match_flags & IS_METHOD)) {
 929       // constructors only
 930       if (name == NULL) {
 931         name = init_name;
 932       } else if (name != init_name) {
 933         return 0;               // no constructors of this method name
 934       }
 935     } else if (!(match_flags & IS_CONSTRUCTOR)) {
 936       // methods only
 937       if (name == NULL) {
 938         name = init_name;
 939         negate_name_test = true; // if we see the name, we *omit* the entry
 940       } else if (name == init_name) {
 941         return 0;               // no methods of this constructor name
 942       }
 943     } else {
 944       // caller will accept either sort; no need to adjust name
 945     }
 946     for (MethodStream st(k, local_only, !search_intfc); !st.eos(); st.next()) {
 947       methodOop m = st.method();
 948       Symbol* m_name = m->name();
 949       if (m_name == clinit_name)
 950         continue;
 951       if (name != NULL && ((m_name != name) ^ negate_name_test))
 952           continue;
 953       if (sig != NULL && m->signature() != sig)
 954         continue;
 955       // passed the filters
 956       if (rskip > 0) {
 957         --rskip;
 958       } else if (rfill < rlimit) {
 959         oop result = results->obj_at(rfill++);
 960         if (!java_lang_invoke_MemberName::is_instance(result))
 961           return -99;  // caller bug!
 962         MethodHandles::init_MemberName(result, m, true);
 963       } else if (++overflow >= overflow_limit) {
 964         match_flags = 0; break; // got tired of looking at overflow
 965       }
 966     }
 967   }
 968 
 969   // return number of elements we at leasted wanted to initialize
 970   return rfill + overflow;
 971 }
 972 
 973 
 974 // Decode this java.lang.Class object into an instanceKlass, if possible.
 975 // Throw IAE if not
 976 instanceKlassHandle MethodHandles::resolve_instance_klass(oop java_mirror_oop, TRAPS) {
 977   instanceKlassHandle empty;
 978   klassOop caller = NULL;
 979   if (java_lang_Class::is_instance(java_mirror_oop)) {
 980     caller = java_lang_Class::as_klassOop(java_mirror_oop);
 981   }
 982   if (caller == NULL || !Klass::cast(caller)->oop_is_instance()) {
 983     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), "not a class", empty);
 984   }
 985   return instanceKlassHandle(THREAD, caller);
 986 }
 987 
 988 
 989 
 990 // Decode the vmtarget field of a method handle.
 991 // Sanitize out methodOops, klassOops, and any other non-Java data.
 992 // This is for debugging and reflection.
 993 oop MethodHandles::encode_target(Handle mh, int format, TRAPS) {
 994   assert(java_lang_invoke_MethodHandle::is_instance(mh()), "must be a MH");
 995   if (format == ETF_FORCE_DIRECT_HANDLE ||
 996       format == ETF_COMPILE_DIRECT_HANDLE) {
 997     // Internal function for stress testing.
 998     Handle mt = java_lang_invoke_MethodHandle::type(mh());
 999     int invocation_count = 10000;
1000     TempNewSymbol signature = java_lang_invoke_MethodType::as_signature(mt(), true, CHECK_NULL);
1001     bool omit_receiver_argument = true;
1002     MethodHandleCompiler mhc(mh, vmSymbols::invoke_name(), signature, invocation_count, omit_receiver_argument, CHECK_NULL);
1003     methodHandle m = mhc.compile(CHECK_NULL);
1004     if (StressMethodHandleWalk && Verbose || PrintMiscellaneous) {
1005       tty->print_cr("MethodHandleNatives.getTarget(%s)",
1006                     format == ETF_FORCE_DIRECT_HANDLE ? "FORCE_DIRECT" : "COMPILE_DIRECT");
1007       if (Verbose) {
1008         m->print_codes();
1009       }
1010     }
1011     if (StressMethodHandleWalk) {
1012       InterpreterOopMap mask;
1013       OopMapCache::compute_one_oop_map(m, m->code_size() - 1, &mask);
1014     }
1015     if ((format == ETF_COMPILE_DIRECT_HANDLE ||
1016          CompilationPolicy::must_be_compiled(m))
1017         && !instanceKlass::cast(m->method_holder())->is_not_initialized()
1018         && CompilationPolicy::can_be_compiled(m)) {
1019       // Force compilation
1020       CompileBroker::compile_method(m, InvocationEntryBci,
1021                                     CompilationPolicy::policy()->initial_compile_level(),
1022                                     methodHandle(), 0, "MethodHandleNatives.getTarget",
1023                                     CHECK_NULL);
1024     }
1025     // Now wrap m in a DirectMethodHandle.
1026     instanceKlassHandle dmh_klass(THREAD, SystemDictionary::DirectMethodHandle_klass());
1027     Handle dmh = dmh_klass->allocate_instance_handle(CHECK_NULL);
1028     JavaValue ignore_result(T_VOID);
1029     Symbol* init_name = vmSymbols::object_initializer_name();
1030     Symbol* init_sig  = vmSymbols::notifyGenericMethodType_signature();
1031     JavaCalls::call_special(&ignore_result, dmh,
1032                             SystemDictionaryHandles::MethodHandle_klass(), init_name, init_sig,
1033                             java_lang_invoke_MethodHandle::type(mh()), CHECK_NULL);
1034     MethodHandles::init_DirectMethodHandle(dmh, m, false, CHECK_NULL);
1035     return dmh();
1036   }
1037   if (format == ETF_HANDLE_OR_METHOD_NAME) {
1038     oop target = java_lang_invoke_MethodHandle::vmtarget(mh());
1039     if (target == NULL) {
1040       return NULL;                // unformed MH
1041     }
1042     klassOop tklass = target->klass();
1043     if (Klass::cast(tklass)->is_subclass_of(SystemDictionary::Object_klass())) {
1044       return target;              // target is another MH (or something else?)
1045     }
1046   }
1047   if (format == ETF_DIRECT_HANDLE) {
1048     oop target = mh();
1049     for (;;) {
1050       if (target->klass() == SystemDictionary::DirectMethodHandle_klass()) {
1051         return target;
1052       }
1053       if (!java_lang_invoke_MethodHandle::is_instance(target)){
1054         return NULL;                // unformed MH
1055       }
1056       target = java_lang_invoke_MethodHandle::vmtarget(target);
1057     }
1058   }
1059   // cases of metadata in MH.vmtarget:
1060   // - AMH can have methodOop for static invoke with bound receiver
1061   // - DMH can have methodOop for static invoke (on variable receiver)
1062   // - DMH can have klassOop for dispatched (non-static) invoke
1063   KlassHandle receiver_limit; int decode_flags = 0;
1064   methodHandle m = decode_MethodHandle(mh(), receiver_limit, decode_flags);
1065   if (m.is_null())  return NULL;
1066   switch (format) {
1067   case ETF_REFLECT_METHOD:
1068     // same as jni_ToReflectedMethod:
1069     if (m->is_initializer()) {
1070       return Reflection::new_constructor(m, THREAD);
1071     } else {
1072       return Reflection::new_method(m, UseNewReflection, false, THREAD);
1073     }
1074 
1075   case ETF_HANDLE_OR_METHOD_NAME:   // method, not handle
1076   case ETF_METHOD_NAME:
1077     {
1078       if (SystemDictionary::MemberName_klass() == NULL)  break;
1079       instanceKlassHandle mname_klass(THREAD, SystemDictionary::MemberName_klass());
1080       mname_klass->initialize(CHECK_NULL);
1081       Handle mname = mname_klass->allocate_instance_handle(CHECK_NULL);  // possible safepoint
1082       java_lang_invoke_MemberName::set_vmindex(mname(), VM_INDEX_UNINITIALIZED);
1083       bool do_dispatch = ((decode_flags & MethodHandles::_dmf_does_dispatch) != 0);
1084       init_MemberName(mname(), m(), do_dispatch);
1085       expand_MemberName(mname, 0, CHECK_NULL);
1086       return mname();
1087     }
1088   }
1089 
1090   // Unknown format code.
1091   char msg[50];
1092   jio_snprintf(msg, sizeof(msg), "unknown getTarget format=%d", format);
1093   THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), msg);
1094 }
1095 
1096 static const char* always_null_names[] = {
1097   "java/lang/Void",
1098   "java/lang/Null",
1099   //"java/lang/Nothing",
1100   "sun/dyn/empty/Empty",
1101   "sun/invoke/empty/Empty",
1102   NULL
1103 };
1104 
1105 static bool is_always_null_type(klassOop klass) {
1106   if (klass == NULL)  return false;  // safety
1107   if (!Klass::cast(klass)->oop_is_instance())  return false;
1108   instanceKlass* ik = instanceKlass::cast(klass);
1109   // Must be on the boot class path:
1110   if (ik->class_loader() != NULL)  return false;
1111   // Check the name.
1112   Symbol* name = ik->name();
1113   for (int i = 0; ; i++) {
1114     const char* test_name = always_null_names[i];
1115     if (test_name == NULL)  break;
1116     if (name->equals(test_name))
1117       return true;
1118   }
1119   return false;
1120 }
1121 
1122 bool MethodHandles::class_cast_needed(klassOop src, klassOop dst) {
1123   if (dst == NULL)  return true;
1124   if (src == NULL)  return (dst != SystemDictionary::Object_klass());
1125   if (src == dst || dst == SystemDictionary::Object_klass())
1126     return false;                               // quickest checks
1127   Klass* srck = Klass::cast(src);
1128   Klass* dstk = Klass::cast(dst);
1129   if (dstk->is_interface()) {
1130     // interface receivers can safely be viewed as untyped,
1131     // because interface calls always include a dynamic check
1132     //dstk = Klass::cast(SystemDictionary::Object_klass());
1133     return false;
1134   }
1135   if (srck->is_interface()) {
1136     // interface arguments must be viewed as untyped
1137     //srck = Klass::cast(SystemDictionary::Object_klass());
1138     return true;
1139   }
1140   if (is_always_null_type(src)) {
1141     // some source types are known to be never instantiated;
1142     // they represent references which are always null
1143     // such null references never fail to convert safely
1144     return false;
1145   }
1146   return !srck->is_subclass_of(dstk->as_klassOop());
1147 }
1148 
1149 static oop object_java_mirror() {
1150   return Klass::cast(SystemDictionary::Object_klass())->java_mirror();
1151 }
1152 
1153 bool MethodHandles::is_float_fixed_reinterpretation_cast(BasicType src, BasicType dst) {
1154   if (src == T_FLOAT)   return dst == T_INT;
1155   if (src == T_INT)     return dst == T_FLOAT;
1156   if (src == T_DOUBLE)  return dst == T_LONG;
1157   if (src == T_LONG)    return dst == T_DOUBLE;
1158   return false;
1159 }
1160 
1161 bool MethodHandles::same_basic_type_for_arguments(BasicType src,
1162                                                   BasicType dst,
1163                                                   bool raw,
1164                                                   bool for_return) {
1165   if (for_return) {
1166     // return values can always be forgotten:
1167     if (dst == T_VOID)  return true;
1168     if (src == T_VOID)  return raw && (dst == T_INT);
1169     // We allow caller to receive a garbage int, which is harmless.
1170     // This trick is pulled by trusted code (see VerifyType.canPassRaw).
1171   }
1172   assert(src != T_VOID && dst != T_VOID, "should not be here");
1173   if (src == dst)  return true;
1174   if (type2size[src] != type2size[dst])  return false;
1175   if (src == T_OBJECT || dst == T_OBJECT)  return false;
1176   if (raw)  return true;  // bitwise reinterpretation; caller guarantees safety
1177   // allow reinterpretation casts for integral widening
1178   if (is_subword_type(src)) { // subwords can fit in int or other subwords
1179     if (dst == T_INT)         // any subword fits in an int
1180       return true;
1181     if (src == T_BOOLEAN)     // boolean fits in any subword
1182       return is_subword_type(dst);
1183     if (src == T_BYTE && dst == T_SHORT)
1184       return true;            // remaining case: byte fits in short
1185   }
1186   // allow float/fixed reinterpretation casts
1187   if (is_float_fixed_reinterpretation_cast(src, dst))
1188     return true;
1189   return false;
1190 }
1191 
1192 const char* MethodHandles::check_method_receiver(methodOop m,
1193                                                  klassOop passed_recv_type) {
1194   assert(!m->is_static(), "caller resp.");
1195   if (passed_recv_type == NULL)
1196     return "receiver type is primitive";
1197   if (class_cast_needed(passed_recv_type, m->method_holder())) {
1198     Klass* formal = Klass::cast(m->method_holder());
1199     return SharedRuntime::generate_class_cast_message("receiver type",
1200                                                       formal->external_name());
1201   }
1202   return NULL;                  // checks passed
1203 }
1204 
1205 // Verify that m's signature can be called type-safely by a method handle
1206 // of the given method type 'mtype'.
1207 // It takes a TRAPS argument because it must perform symbol lookups.
1208 void MethodHandles::verify_method_signature(methodHandle m,
1209                                             Handle mtype,
1210                                             int first_ptype_pos,
1211                                             KlassHandle insert_ptype,
1212                                             TRAPS) {
1213   Handle mhi_type;
1214   if (m->is_method_handle_invoke()) {
1215     // use this more exact typing instead of the symbolic signature:
1216     mhi_type = Handle(THREAD, m->method_handle_type());
1217   }
1218   objArrayHandle ptypes(THREAD, java_lang_invoke_MethodType::ptypes(mtype()));
1219   int pnum = first_ptype_pos;
1220   int pmax = ptypes->length();
1221   int anum = 0;                 // method argument
1222   const char* err = NULL;
1223   ResourceMark rm(THREAD);
1224   for (SignatureStream ss(m->signature()); !ss.is_done(); ss.next()) {
1225     oop ptype_oop = NULL;
1226     if (ss.at_return_type()) {
1227       if (pnum != pmax)
1228         { err = "too many arguments"; break; }
1229       ptype_oop = java_lang_invoke_MethodType::rtype(mtype());
1230     } else {
1231       if (pnum >= pmax)
1232         { err = "not enough arguments"; break; }
1233       if (pnum >= 0)
1234         ptype_oop = ptypes->obj_at(pnum);
1235       else if (insert_ptype.is_null())
1236         ptype_oop = NULL;
1237       else
1238         ptype_oop = insert_ptype->java_mirror();
1239       pnum += 1;
1240       anum += 1;
1241     }
1242     KlassHandle pklass;
1243     BasicType   ptype = T_OBJECT;
1244     bool   have_ptype = false;
1245     // missing ptype_oop does not match any non-reference; use Object to report the error
1246     pklass = SystemDictionaryHandles::Object_klass();
1247     if (ptype_oop != NULL) {
1248       have_ptype = true;
1249       klassOop pklass_oop = NULL;
1250       ptype = java_lang_Class::as_BasicType(ptype_oop, &pklass_oop);
1251       pklass = KlassHandle(THREAD, pklass_oop);
1252     }
1253     ptype_oop = NULL; //done with this
1254     KlassHandle aklass;
1255     BasicType   atype = ss.type();
1256     if (atype == T_ARRAY)  atype = T_OBJECT; // fold all refs to T_OBJECT
1257     if (atype == T_OBJECT) {
1258       if (!have_ptype) {
1259         // null matches any reference
1260         continue;
1261       }
1262       if (mhi_type.is_null()) {
1263         // If we fail to resolve types at this point, we will usually throw an error.
1264         TempNewSymbol name = ss.as_symbol_or_null();
1265         if (name != NULL) {
1266           instanceKlass* mk = instanceKlass::cast(m->method_holder());
1267           Handle loader(THREAD, mk->class_loader());
1268           Handle domain(THREAD, mk->protection_domain());
1269           klassOop aklass_oop = SystemDictionary::resolve_or_null(name, loader, domain, CHECK);
1270           if (aklass_oop != NULL)
1271             aklass = KlassHandle(THREAD, aklass_oop);
1272           if (aklass.is_null() &&
1273               pklass.not_null() &&
1274               loader.is_null() &&
1275               pklass->name() == name)
1276             // accept name equivalence here, since that's the best we can do
1277             aklass = pklass;
1278         }
1279       } else {
1280         // for method handle invokers we don't look at the name in the signature
1281         oop atype_oop;
1282         if (ss.at_return_type())
1283           atype_oop = java_lang_invoke_MethodType::rtype(mhi_type());
1284         else
1285           atype_oop = java_lang_invoke_MethodType::ptype(mhi_type(), anum-1);
1286         klassOop aklass_oop = NULL;
1287         atype = java_lang_Class::as_BasicType(atype_oop, &aklass_oop);
1288         aklass = KlassHandle(THREAD, aklass_oop);
1289       }
1290     }
1291     if (!ss.at_return_type()) {
1292       err = check_argument_type_change(ptype, pklass(), atype, aklass(), anum);
1293     } else {
1294       err = check_return_type_change(atype, aklass(), ptype, pklass()); // note reversal!
1295     }
1296     if (err != NULL)  break;
1297   }
1298 
1299   if (err != NULL) {
1300 #ifndef PRODUCT
1301     if (PrintMiscellaneous && (Verbose || WizardMode)) {
1302       tty->print("*** verify_method_signature failed: ");
1303       java_lang_invoke_MethodType::print_signature(mtype(), tty);
1304       tty->cr();
1305       tty->print_cr("    first_ptype_pos = %d, insert_ptype = "UINTX_FORMAT, first_ptype_pos, insert_ptype());
1306       tty->print("    Failing method: ");
1307       m->print();
1308     }
1309 #endif //PRODUCT
1310     THROW_MSG(vmSymbols::java_lang_InternalError(), err);
1311   }
1312 }
1313 
1314 // Main routine for verifying the MethodHandle.type of a proposed
1315 // direct or bound-direct method handle.
1316 void MethodHandles::verify_method_type(methodHandle m,
1317                                        Handle mtype,
1318                                        bool has_bound_recv,
1319                                        KlassHandle bound_recv_type,
1320                                        TRAPS) {
1321   bool m_needs_receiver = !m->is_static();
1322 
1323   const char* err = NULL;
1324 
1325   int first_ptype_pos = m_needs_receiver ? 1 : 0;
1326   if (has_bound_recv) {
1327     first_ptype_pos -= 1;  // ptypes do not include the bound argument; start earlier in them
1328     if (m_needs_receiver && bound_recv_type.is_null())
1329       { err = "bound receiver is not an object"; goto die; }
1330   }
1331 
1332   if (m_needs_receiver && err == NULL) {
1333     objArrayOop ptypes = java_lang_invoke_MethodType::ptypes(mtype());
1334     if (ptypes->length() < first_ptype_pos)
1335       { err = "receiver argument is missing"; goto die; }
1336     if (has_bound_recv)
1337       err = check_method_receiver(m(), bound_recv_type->as_klassOop());
1338     else
1339       err = check_method_receiver(m(), java_lang_Class::as_klassOop(ptypes->obj_at(first_ptype_pos-1)));
1340     if (err != NULL)  goto die;
1341   }
1342 
1343   // Check the other arguments for mistypes.
1344   verify_method_signature(m, mtype, first_ptype_pos, bound_recv_type, CHECK);
1345   return;
1346 
1347  die:
1348   THROW_MSG(vmSymbols::java_lang_InternalError(), err);
1349 }
1350 
1351 void MethodHandles::verify_vmslots(Handle mh, TRAPS) {
1352   // Verify vmslots.
1353   int check_slots = argument_slot_count(java_lang_invoke_MethodHandle::type(mh()));
1354   if (java_lang_invoke_MethodHandle::vmslots(mh()) != check_slots) {
1355     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in BMH");
1356   }
1357 }
1358 
1359 void MethodHandles::verify_vmargslot(Handle mh, int argnum, int argslot, TRAPS) {
1360   // Verify that argslot points at the given argnum.
1361   int check_slot = argument_slot(java_lang_invoke_MethodHandle::type(mh()), argnum);
1362   if (argslot != check_slot || argslot < 0) {
1363     ResourceMark rm;
1364     const char* fmt = "for argnum of %d, vmargslot is %d, should be %d";
1365     size_t msglen = strlen(fmt) + 3*11 + 1;
1366     char* msg = NEW_RESOURCE_ARRAY(char, msglen);
1367     jio_snprintf(msg, msglen, fmt, argnum, argslot, check_slot);
1368     THROW_MSG(vmSymbols::java_lang_InternalError(), msg);
1369   }
1370 }
1371 
1372 // Verify the correspondence between two method types.
1373 // Apart from the advertised changes, caller method type X must
1374 // be able to invoke the callee method Y type with no violations
1375 // of type integrity.
1376 // Return NULL if all is well, else a short error message.
1377 const char* MethodHandles::check_method_type_change(oop src_mtype, int src_beg, int src_end,
1378                                                     int insert_argnum, oop insert_type,
1379                                                     int change_argnum, oop change_type,
1380                                                     int delete_argnum,
1381                                                     oop dst_mtype, int dst_beg, int dst_end,
1382                                                     bool raw) {
1383   objArrayOop src_ptypes = java_lang_invoke_MethodType::ptypes(src_mtype);
1384   objArrayOop dst_ptypes = java_lang_invoke_MethodType::ptypes(dst_mtype);
1385 
1386   int src_max = src_ptypes->length();
1387   int dst_max = dst_ptypes->length();
1388 
1389   if (src_end == -1)  src_end = src_max;
1390   if (dst_end == -1)  dst_end = dst_max;
1391 
1392   assert(0 <= src_beg && src_beg <= src_end && src_end <= src_max, "oob");
1393   assert(0 <= dst_beg && dst_beg <= dst_end && dst_end <= dst_max, "oob");
1394 
1395   // pending actions; set to -1 when done:
1396   int ins_idx = insert_argnum, chg_idx = change_argnum, del_idx = delete_argnum;
1397 
1398   const char* err = NULL;
1399 
1400   // Walk along each array of parameter types, including a virtual
1401   // NULL end marker at the end of each.
1402   for (int src_idx = src_beg, dst_idx = dst_beg;
1403        (src_idx <= src_end && dst_idx <= dst_end);
1404        src_idx++, dst_idx++) {
1405     oop src_type = (src_idx == src_end) ? oop(NULL) : src_ptypes->obj_at(src_idx);
1406     oop dst_type = (dst_idx == dst_end) ? oop(NULL) : dst_ptypes->obj_at(dst_idx);
1407     bool fix_null_src_type = false;
1408 
1409     // Perform requested edits.
1410     if (ins_idx == src_idx) {
1411       // note that the inserted guy is never affected by a change or deletion
1412       ins_idx = -1;
1413       src_type = insert_type;
1414       fix_null_src_type = true;
1415       --src_idx;                // back up to process src type on next loop
1416       src_idx = src_end;
1417     } else {
1418       // note that the changed guy can be immediately deleted
1419       if (chg_idx == src_idx) {
1420         chg_idx = -1;
1421         assert(src_idx < src_end, "oob");
1422         src_type = change_type;
1423         fix_null_src_type = true;
1424       }
1425       if (del_idx == src_idx) {
1426         del_idx = -1;
1427         assert(src_idx < src_end, "oob");
1428         --dst_idx;
1429         continue;               // rerun loop after skipping this position
1430       }
1431     }
1432 
1433     if (src_type == NULL && fix_null_src_type)
1434       // explicit null in this case matches any dest reference
1435       src_type = (java_lang_Class::is_primitive(dst_type) ? object_java_mirror() : dst_type);
1436 
1437     // Compare the two argument types.
1438     if (src_type != dst_type) {
1439       if (src_type == NULL)  return "not enough arguments";
1440       if (dst_type == NULL)  return "too many arguments";
1441       err = check_argument_type_change(src_type, dst_type, dst_idx, raw);
1442       if (err != NULL)  return err;
1443     }
1444   }
1445 
1446   // Now compare return types also.
1447   oop src_rtype = java_lang_invoke_MethodType::rtype(src_mtype);
1448   oop dst_rtype = java_lang_invoke_MethodType::rtype(dst_mtype);
1449   if (src_rtype != dst_rtype) {
1450     err = check_return_type_change(dst_rtype, src_rtype, raw); // note reversal!
1451     if (err != NULL)  return err;
1452   }
1453 
1454   assert(err == NULL, "");
1455   return NULL;  // all is well
1456 }
1457 
1458 
1459 const char* MethodHandles::check_argument_type_change(BasicType src_type,
1460                                                       klassOop src_klass,
1461                                                       BasicType dst_type,
1462                                                       klassOop dst_klass,
1463                                                       int argnum,
1464                                                       bool raw) {
1465   const char* err = NULL;
1466   const bool for_return = (argnum < 0);
1467 
1468   // just in case:
1469   if (src_type == T_ARRAY)  src_type = T_OBJECT;
1470   if (dst_type == T_ARRAY)  dst_type = T_OBJECT;
1471 
1472   // Produce some nice messages if VerifyMethodHandles is turned on:
1473   if (!same_basic_type_for_arguments(src_type, dst_type, raw, for_return)) {
1474     if (src_type == T_OBJECT) {
1475       if (raw && is_java_primitive(dst_type))
1476         return NULL;    // ref-to-prim discards ref and returns zero
1477       err = (!for_return
1478              ? "type mismatch: passing a %s for method argument #%d, which expects primitive %s"
1479              : "type mismatch: returning a %s, but caller expects primitive %s");
1480     } else if (dst_type == T_OBJECT) {
1481       err = (!for_return
1482              ? "type mismatch: passing a primitive %s for method argument #%d, which expects %s"
1483              : "type mismatch: returning a primitive %s, but caller expects %s");
1484     } else {
1485       err = (!for_return
1486              ? "type mismatch: passing a %s for method argument #%d, which expects %s"
1487              : "type mismatch: returning a %s, but caller expects %s");
1488     }
1489   } else if (src_type == T_OBJECT && dst_type == T_OBJECT &&
1490              class_cast_needed(src_klass, dst_klass)) {
1491     if (!class_cast_needed(dst_klass, src_klass)) {
1492       if (raw)
1493         return NULL;    // reverse cast is OK; the MH target is trusted to enforce it
1494       err = (!for_return
1495              ? "cast required: passing a %s for method argument #%d, which expects %s"
1496              : "cast required: returning a %s, but caller expects %s");
1497     } else {
1498       err = (!for_return
1499              ? "reference mismatch: passing a %s for method argument #%d, which expects %s"
1500              : "reference mismatch: returning a %s, but caller expects %s");
1501     }
1502   } else {
1503     // passed the obstacle course
1504     return NULL;
1505   }
1506 
1507   // format, format, format
1508   const char* src_name = type2name(src_type);
1509   const char* dst_name = type2name(dst_type);
1510   if (src_name == NULL)  src_name = "unknown type";
1511   if (dst_name == NULL)  dst_name = "unknown type";
1512   if (src_type == T_OBJECT)
1513     src_name = (src_klass != NULL) ? Klass::cast(src_klass)->external_name() : "an unresolved class";
1514   if (dst_type == T_OBJECT)
1515     dst_name = (dst_klass != NULL) ? Klass::cast(dst_klass)->external_name() : "an unresolved class";
1516 
1517   size_t msglen = strlen(err) + strlen(src_name) + strlen(dst_name) + (argnum < 10 ? 1 : 11);
1518   char* msg = NEW_RESOURCE_ARRAY(char, msglen + 1);
1519   if (!for_return) {
1520     assert(strstr(err, "%d") != NULL, "");
1521     jio_snprintf(msg, msglen, err, src_name, argnum, dst_name);
1522   } else {
1523     assert(strstr(err, "%d") == NULL, "");
1524     jio_snprintf(msg, msglen, err, src_name,         dst_name);
1525   }
1526   return msg;
1527 }
1528 
1529 // Compute the depth within the stack of the given argument, i.e.,
1530 // the combined size of arguments to the right of the given argument.
1531 // For the last argument (ptypes.length-1) this will be zero.
1532 // For the first argument (0) this will be the size of all
1533 // arguments but that one.  For the special number -1, this
1534 // will be the size of all arguments, including the first.
1535 // If the argument is neither -1 nor a valid argument index,
1536 // then return a negative number.  Otherwise, the result
1537 // is in the range [0..vmslots] inclusive.
1538 int MethodHandles::argument_slot(oop method_type, int arg) {
1539   objArrayOop ptypes = java_lang_invoke_MethodType::ptypes(method_type);
1540   int argslot = 0;
1541   int len = ptypes->length();
1542   if (arg < -1 || arg >= len)  return -99;
1543   for (int i = len-1; i > arg; i--) {
1544     BasicType bt = java_lang_Class::as_BasicType(ptypes->obj_at(i));
1545     argslot += type2size[bt];
1546   }
1547   assert(argument_slot_to_argnum(method_type, argslot) == arg, "inverse works");
1548   return argslot;
1549 }
1550 
1551 // Given a slot number, return the argument number.
1552 int MethodHandles::argument_slot_to_argnum(oop method_type, int query_argslot) {
1553   objArrayOop ptypes = java_lang_invoke_MethodType::ptypes(method_type);
1554   int argslot = 0;
1555   int len = ptypes->length();
1556   for (int i = len-1; i >= 0; i--) {
1557     if (query_argslot == argslot)  return i;
1558     BasicType bt = java_lang_Class::as_BasicType(ptypes->obj_at(i));
1559     argslot += type2size[bt];
1560   }
1561   // return pseudo-arg deepest in stack:
1562   if (query_argslot == argslot)  return -1;
1563   return -99;                   // oob slot, or splitting a double-slot arg
1564 }
1565 
1566 methodHandle MethodHandles::dispatch_decoded_method(methodHandle m,
1567                                                     KlassHandle receiver_limit,
1568                                                     int decode_flags,
1569                                                     KlassHandle receiver_klass,
1570                                                     TRAPS) {
1571   assert((decode_flags & ~_DMF_DIRECT_MASK) == 0, "must be direct method reference");
1572   assert((decode_flags & _dmf_has_receiver) != 0, "must have a receiver or first reference argument");
1573 
1574   if (!m->is_static() &&
1575       (receiver_klass.is_null() || !receiver_klass->is_subtype_of(m->method_holder())))
1576     // given type does not match class of method, or receiver is null!
1577     // caller should have checked this, but let's be extra careful...
1578     return methodHandle();
1579 
1580   if (receiver_limit.not_null() &&
1581       (receiver_klass.not_null() && !receiver_klass->is_subtype_of(receiver_limit())))
1582     // given type is not limited to the receiver type
1583     // note that a null receiver can match any reference value, for a static method
1584     return methodHandle();
1585 
1586   if (!(decode_flags & MethodHandles::_dmf_does_dispatch)) {
1587     // pre-dispatched or static method (null receiver is OK for static)
1588     return m;
1589 
1590   } else if (receiver_klass.is_null()) {
1591     // null receiver value; cannot dispatch
1592     return methodHandle();
1593 
1594   } else if (!(decode_flags & MethodHandles::_dmf_from_interface)) {
1595     // perform virtual dispatch
1596     int vtable_index = m->vtable_index();
1597     guarantee(vtable_index >= 0, "valid vtable index");
1598 
1599     // receiver_klass might be an arrayKlassOop but all vtables start at
1600     // the same place. The cast is to avoid virtual call and assertion.
1601     // See also LinkResolver::runtime_resolve_virtual_method.
1602     instanceKlass* inst = (instanceKlass*)Klass::cast(receiver_klass());
1603     DEBUG_ONLY(inst->verify_vtable_index(vtable_index));
1604     methodOop m_oop = inst->method_at_vtable(vtable_index);
1605     return methodHandle(THREAD, m_oop);
1606 
1607   } else {
1608     // perform interface dispatch
1609     int itable_index = klassItable::compute_itable_index(m());
1610     guarantee(itable_index >= 0, "valid itable index");
1611     instanceKlass* inst = instanceKlass::cast(receiver_klass());
1612     methodOop m_oop = inst->method_at_itable(m->method_holder(), itable_index, THREAD);
1613     return methodHandle(THREAD, m_oop);
1614   }
1615 }
1616 
1617 void MethodHandles::verify_DirectMethodHandle(Handle mh, methodHandle m, TRAPS) {
1618   // Verify type.
1619   Handle mtype(THREAD, java_lang_invoke_MethodHandle::type(mh()));
1620   verify_method_type(m, mtype, false, KlassHandle(), CHECK);
1621 
1622   // Verify vmslots.
1623   if (java_lang_invoke_MethodHandle::vmslots(mh()) != m->size_of_parameters()) {
1624     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in DMH");
1625   }
1626 }
1627 
1628 void MethodHandles::init_DirectMethodHandle(Handle mh, methodHandle m, bool do_dispatch, TRAPS) {
1629   // Check arguments.
1630   if (mh.is_null() || m.is_null() ||
1631       (!do_dispatch && m->is_abstract())) {
1632     THROW(vmSymbols::java_lang_InternalError());
1633   }
1634 
1635   java_lang_invoke_MethodHandle::init_vmslots(mh());
1636 
1637   if (VerifyMethodHandles) {
1638     // The privileged code which invokes this routine should not make
1639     // a mistake about types, but it's better to verify.
1640     verify_DirectMethodHandle(mh, m, CHECK);
1641   }
1642 
1643   // Finally, after safety checks are done, link to the target method.
1644   // We will follow the same path as the latter part of
1645   // InterpreterRuntime::resolve_invoke(), which first finds the method
1646   // and then decides how to populate the constant pool cache entry
1647   // that links the interpreter calls to the method.  We need the same
1648   // bits, and will use the same calling sequence code.
1649 
1650   int    vmindex = methodOopDesc::garbage_vtable_index;
1651   Handle vmtarget;
1652 
1653   instanceKlass::cast(m->method_holder())->link_class(CHECK);
1654 
1655   MethodHandleEntry* me = NULL;
1656   if (do_dispatch && Klass::cast(m->method_holder())->is_interface()) {
1657     // We are simulating an invokeinterface instruction.
1658     // (We might also be simulating an invokevirtual on a miranda method,
1659     // but it is safe to treat it as an invokeinterface.)
1660     assert(!m->can_be_statically_bound(), "no final methods on interfaces");
1661     vmindex = klassItable::compute_itable_index(m());
1662     assert(vmindex >= 0, "(>=0) == do_dispatch");
1663     // Set up same bits as ConstantPoolCacheEntry::set_interface_call().
1664     vmtarget = m->method_holder(); // the interface
1665     me = MethodHandles::entry(MethodHandles::_invokeinterface_mh);
1666   } else if (!do_dispatch || m->can_be_statically_bound()) {
1667     // We are simulating an invokestatic or invokespecial instruction.
1668     // Set up the method pointer, just like ConstantPoolCacheEntry::set_method().
1669     vmtarget = m;
1670     // this does not help dispatch, but it will make it possible to parse this MH:
1671     vmindex  = methodOopDesc::nonvirtual_vtable_index;
1672     assert(vmindex < 0, "(>=0) == do_dispatch");
1673     if (!m->is_static()) {
1674       me = MethodHandles::entry(MethodHandles::_invokespecial_mh);
1675     } else {
1676       me = MethodHandles::entry(MethodHandles::_invokestatic_mh);
1677       // Part of the semantics of a static call is an initialization barrier.
1678       // For a DMH, it is done now, when the handle is created.
1679       Klass* k = Klass::cast(m->method_holder());
1680       if (k->should_be_initialized()) {
1681         k->initialize(CHECK);  // possible safepoint
1682       }
1683     }
1684   } else {
1685     // We are simulating an invokevirtual instruction.
1686     // Set up the vtable index, just like ConstantPoolCacheEntry::set_method().
1687     // The key logic is LinkResolver::runtime_resolve_virtual_method.
1688     vmindex  = m->vtable_index();
1689     vmtarget = m->method_holder();
1690     me = MethodHandles::entry(MethodHandles::_invokevirtual_mh);
1691   }
1692 
1693   if (me == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
1694 
1695   java_lang_invoke_DirectMethodHandle::set_vmtarget(mh(), vmtarget());
1696   java_lang_invoke_DirectMethodHandle::set_vmindex( mh(), vmindex);
1697   DEBUG_ONLY(KlassHandle rlimit; int flags);
1698   assert(MethodHandles::decode_method(mh(), rlimit, flags) == m,
1699          "properly stored for later decoding");
1700   DEBUG_ONLY(bool actual_do_dispatch = ((flags & _dmf_does_dispatch) != 0));
1701   assert(!(actual_do_dispatch && !do_dispatch),
1702          "do not perform dispatch if !do_dispatch specified");
1703   assert(actual_do_dispatch == (vmindex >= 0), "proper later decoding of do_dispatch");
1704   assert(decode_MethodHandle_stack_pushes(mh()) == 0, "DMH does not move stack");
1705 
1706   // Done!
1707   java_lang_invoke_MethodHandle::set_vmentry(mh(), me);
1708 }
1709 
1710 void MethodHandles::verify_BoundMethodHandle_with_receiver(Handle mh,
1711                                                            methodHandle m,
1712                                                            TRAPS) {
1713   // Verify type.
1714   KlassHandle bound_recv_type;
1715   {
1716     oop receiver = java_lang_invoke_BoundMethodHandle::argument(mh());
1717     if (receiver != NULL)
1718       bound_recv_type = KlassHandle(THREAD, receiver->klass());
1719   }
1720   Handle mtype(THREAD, java_lang_invoke_MethodHandle::type(mh()));
1721   verify_method_type(m, mtype, true, bound_recv_type, CHECK);
1722 
1723   int receiver_pos = m->size_of_parameters() - 1;
1724 
1725   // Verify MH.vmargslot, which should point at the bound receiver.
1726   verify_vmargslot(mh, -1, java_lang_invoke_BoundMethodHandle::vmargslot(mh()), CHECK);
1727   //verify_vmslots(mh, CHECK);
1728 
1729   // Verify vmslots.
1730   if (java_lang_invoke_MethodHandle::vmslots(mh()) != receiver_pos) {
1731     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in BMH (receiver)");
1732   }
1733 }
1734 
1735 // Initialize a BMH with a receiver bound directly to a methodOop.
1736 void MethodHandles::init_BoundMethodHandle_with_receiver(Handle mh,
1737                                                          methodHandle original_m,
1738                                                          KlassHandle receiver_limit,
1739                                                          int decode_flags,
1740                                                          TRAPS) {
1741   // Check arguments.
1742   if (mh.is_null() || original_m.is_null()) {
1743     THROW(vmSymbols::java_lang_InternalError());
1744   }
1745 
1746   KlassHandle receiver_klass;
1747   {
1748     oop receiver_oop = java_lang_invoke_BoundMethodHandle::argument(mh());
1749     if (receiver_oop != NULL)
1750       receiver_klass = KlassHandle(THREAD, receiver_oop->klass());
1751   }
1752   methodHandle m = dispatch_decoded_method(original_m,
1753                                            receiver_limit, decode_flags,
1754                                            receiver_klass,
1755                                            CHECK);
1756   if (m.is_null())      { THROW(vmSymbols::java_lang_InternalError()); }
1757   if (m->is_abstract()) { THROW(vmSymbols::java_lang_AbstractMethodError()); }
1758 
1759   java_lang_invoke_MethodHandle::init_vmslots(mh());
1760   int vmargslot = m->size_of_parameters() - 1;
1761   assert(java_lang_invoke_BoundMethodHandle::vmargslot(mh()) == vmargslot, "");
1762 
1763   if (VerifyMethodHandles) {
1764     verify_BoundMethodHandle_with_receiver(mh, m, CHECK);
1765   }
1766 
1767   java_lang_invoke_BoundMethodHandle::set_vmtarget(mh(), m());
1768 
1769   DEBUG_ONLY(KlassHandle junk1; int junk2);
1770   assert(MethodHandles::decode_method(mh(), junk1, junk2) == m, "properly stored for later decoding");
1771   assert(decode_MethodHandle_stack_pushes(mh()) == 1, "BMH pushes one stack slot");
1772 
1773   // Done!
1774   java_lang_invoke_MethodHandle::set_vmentry(mh(), MethodHandles::entry(MethodHandles::_bound_ref_direct_mh));
1775 }
1776 
1777 void MethodHandles::verify_BoundMethodHandle(Handle mh, Handle target, int argnum,
1778                                              bool direct_to_method, TRAPS) {
1779   ResourceMark rm;
1780   Handle ptype_handle(THREAD,
1781                            java_lang_invoke_MethodType::ptype(java_lang_invoke_MethodHandle::type(target()), argnum));
1782   KlassHandle ptype_klass;
1783   BasicType ptype = java_lang_Class::as_BasicType(ptype_handle(), &ptype_klass);
1784   int slots_pushed = type2size[ptype];
1785 
1786   oop argument = java_lang_invoke_BoundMethodHandle::argument(mh());
1787 
1788   const char* err = NULL;
1789 
1790   switch (ptype) {
1791   case T_OBJECT:
1792     if (argument != NULL)
1793       // we must implicitly convert from the arg type to the outgoing ptype
1794       err = check_argument_type_change(T_OBJECT, argument->klass(), ptype, ptype_klass(), argnum);
1795     break;
1796 
1797   case T_ARRAY: case T_VOID:
1798     assert(false, "array, void do not appear here");
1799   default:
1800     if (ptype != T_INT && !is_subword_type(ptype)) {
1801       err = "unexpected parameter type";
1802       break;
1803     }
1804     // check subrange of Integer.value, if necessary
1805     if (argument == NULL || argument->klass() != SystemDictionary::Integer_klass()) {
1806       err = "bound integer argument must be of type java.lang.Integer";
1807       break;
1808     }
1809     if (ptype != T_INT) {
1810       int value_offset = java_lang_boxing_object::value_offset_in_bytes(T_INT);
1811       jint value = argument->int_field(value_offset);
1812       int vminfo = adapter_unbox_subword_vminfo(ptype);
1813       jint subword = truncate_subword_from_vminfo(value, vminfo);
1814       if (value != subword) {
1815         err = "bound subword value does not fit into the subword type";
1816         break;
1817       }
1818     }
1819     break;
1820   case T_FLOAT:
1821   case T_DOUBLE:
1822   case T_LONG:
1823     {
1824       // we must implicitly convert from the unboxed arg type to the outgoing ptype
1825       BasicType argbox = java_lang_boxing_object::basic_type(argument);
1826       if (argbox != ptype) {
1827         err = check_argument_type_change(T_OBJECT, (argument == NULL
1828                                                     ? SystemDictionary::Object_klass()
1829                                                     : argument->klass()),
1830                                          ptype, ptype_klass(), argnum);
1831         assert(err != NULL, "this must be an error");
1832       }
1833       break;
1834     }
1835   }
1836 
1837   if (err == NULL) {
1838     DEBUG_ONLY(int this_pushes = decode_MethodHandle_stack_pushes(mh()));
1839     if (direct_to_method) {
1840       assert(this_pushes == slots_pushed, "BMH pushes one or two stack slots");
1841     } else {
1842       int target_pushes = decode_MethodHandle_stack_pushes(target());
1843       assert(this_pushes == slots_pushed + target_pushes, "BMH stack motion must be correct");
1844     }
1845   }
1846 
1847   if (err == NULL) {
1848     // Verify the rest of the method type.
1849     err = check_method_type_insertion(java_lang_invoke_MethodHandle::type(mh()),
1850                                       argnum, ptype_handle(),
1851                                       java_lang_invoke_MethodHandle::type(target()));
1852   }
1853 
1854   if (err != NULL) {
1855     THROW_MSG(vmSymbols::java_lang_InternalError(), err);
1856   }
1857 }
1858 
1859 void MethodHandles::init_BoundMethodHandle(Handle mh, Handle target, int argnum, TRAPS) {
1860   // Check arguments.
1861   if (mh.is_null() || target.is_null() || !java_lang_invoke_MethodHandle::is_instance(target())) {
1862     THROW(vmSymbols::java_lang_InternalError());
1863   }
1864 
1865   java_lang_invoke_MethodHandle::init_vmslots(mh());
1866   int argslot = java_lang_invoke_BoundMethodHandle::vmargslot(mh());
1867 
1868   if (VerifyMethodHandles) {
1869     int insert_after = argnum - 1;
1870     verify_vmargslot(mh, insert_after, argslot, CHECK);
1871     verify_vmslots(mh, CHECK);
1872   }
1873 
1874   // Get bound type and required slots.
1875   BasicType ptype;
1876   {
1877     oop ptype_oop = java_lang_invoke_MethodType::ptype(java_lang_invoke_MethodHandle::type(target()), argnum);
1878     ptype = java_lang_Class::as_BasicType(ptype_oop);
1879   }
1880   int slots_pushed = type2size[ptype];
1881 
1882   // If (a) the target is a direct non-dispatched method handle,
1883   // or (b) the target is a dispatched direct method handle and we
1884   // are binding the receiver, cut out the middle-man.
1885   // Do this by decoding the DMH and using its methodOop directly as vmtarget.
1886   bool direct_to_method = false;
1887   if (OptimizeMethodHandles &&
1888       target->klass() == SystemDictionary::DirectMethodHandle_klass() &&
1889       (argnum != 0 || java_lang_invoke_BoundMethodHandle::argument(mh()) != NULL) &&
1890       (argnum == 0 || java_lang_invoke_DirectMethodHandle::vmindex(target()) < 0)) {
1891     KlassHandle receiver_limit; int decode_flags = 0;
1892     methodHandle m = decode_method(target(), receiver_limit, decode_flags);
1893     if (m.is_null()) { THROW_MSG(vmSymbols::java_lang_InternalError(), "DMH failed to decode"); }
1894     DEBUG_ONLY(int m_vmslots = m->size_of_parameters() - slots_pushed); // pos. of 1st arg.
1895     assert(java_lang_invoke_BoundMethodHandle::vmslots(mh()) == m_vmslots, "type w/ m sig");
1896     if (argnum == 0 && (decode_flags & _dmf_has_receiver) != 0) {
1897       init_BoundMethodHandle_with_receiver(mh, m,
1898                                            receiver_limit, decode_flags,
1899                                            CHECK);
1900       return;
1901     }
1902 
1903     // Even if it is not a bound receiver, we still might be able
1904     // to bind another argument and still invoke the methodOop directly.
1905     if (!(decode_flags & _dmf_does_dispatch)) {
1906       direct_to_method = true;
1907       java_lang_invoke_BoundMethodHandle::set_vmtarget(mh(), m());
1908     }
1909   }
1910   if (!direct_to_method)
1911     java_lang_invoke_BoundMethodHandle::set_vmtarget(mh(), target());
1912 
1913   if (VerifyMethodHandles) {
1914     verify_BoundMethodHandle(mh, target, argnum, direct_to_method, CHECK);
1915   }
1916 
1917   // Next question:  Is this a ref, int, or long bound value?
1918   MethodHandleEntry* me = NULL;
1919   if (ptype == T_OBJECT) {
1920     if (direct_to_method)  me = MethodHandles::entry(_bound_ref_direct_mh);
1921     else                   me = MethodHandles::entry(_bound_ref_mh);
1922   } else if (slots_pushed == 2) {
1923     if (direct_to_method)  me = MethodHandles::entry(_bound_long_direct_mh);
1924     else                   me = MethodHandles::entry(_bound_long_mh);
1925   } else if (slots_pushed == 1) {
1926     if (direct_to_method)  me = MethodHandles::entry(_bound_int_direct_mh);
1927     else                   me = MethodHandles::entry(_bound_int_mh);
1928   } else {
1929     assert(false, "");
1930   }
1931 
1932   // Done!
1933   java_lang_invoke_MethodHandle::set_vmentry(mh(), me);
1934 }
1935 
1936 static void throw_InternalError_for_bad_conversion(int conversion, const char* err, TRAPS) {
1937   char msg[200];
1938   jio_snprintf(msg, sizeof(msg), "bad adapter (conversion=0x%08x): %s", conversion, err);
1939   THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), msg);
1940 }
1941 
1942 void MethodHandles::verify_AdapterMethodHandle(Handle mh, int argnum, TRAPS) {
1943   ResourceMark rm;
1944   jint conversion = java_lang_invoke_AdapterMethodHandle::conversion(mh());
1945   int  argslot    = java_lang_invoke_AdapterMethodHandle::vmargslot(mh());
1946 
1947   verify_vmargslot(mh, argnum, argslot, CHECK);
1948   verify_vmslots(mh, CHECK);
1949 
1950   jint conv_op    = adapter_conversion_op(conversion);
1951   if (!conv_op_valid(conv_op)) {
1952     throw_InternalError_for_bad_conversion(conversion, "unknown conversion op", THREAD);
1953     return;
1954   }
1955   EntryKind ek = adapter_entry_kind(conv_op);
1956 
1957   int stack_move = adapter_conversion_stack_move(conversion);
1958   BasicType src  = adapter_conversion_src_type(conversion);
1959   BasicType dest = adapter_conversion_dest_type(conversion);
1960   int vminfo     = adapter_conversion_vminfo(conversion); // should be zero
1961 
1962   Handle argument(THREAD,  java_lang_invoke_AdapterMethodHandle::argument(mh()));
1963   Handle target(THREAD,    java_lang_invoke_AdapterMethodHandle::vmtarget(mh()));
1964   Handle src_mtype(THREAD, java_lang_invoke_MethodHandle::type(mh()));
1965   Handle dst_mtype(THREAD, java_lang_invoke_MethodHandle::type(target()));
1966   Handle arg_mtype;
1967 
1968   const char* err = NULL;
1969 
1970   if (err == NULL) {
1971     // Check that the correct argument is supplied, but only if it is required.
1972     switch (ek) {
1973     case _adapter_check_cast:     // target type of cast
1974     case _adapter_ref_to_prim:    // wrapper type from which to unbox
1975     case _adapter_spread_args:    // array type to spread from
1976       if (!java_lang_Class::is_instance(argument())
1977           || java_lang_Class::is_primitive(argument()))
1978         { err = "adapter requires argument of type java.lang.Class"; break; }
1979       if (ek == _adapter_spread_args) {
1980         // Make sure it is a suitable collection type.  (Array, for now.)
1981         Klass* ak = Klass::cast(java_lang_Class::as_klassOop(argument()));
1982         if (!ak->oop_is_array())
1983           { err = "spread adapter requires argument representing an array class"; break; }
1984         BasicType et = arrayKlass::cast(ak->as_klassOop())->element_type();
1985         if (et != dest && stack_move <= 0)
1986           { err = "spread adapter requires array class argument of correct type"; break; }
1987       }
1988       break;
1989     case _adapter_prim_to_ref:    // boxer MH to use
1990     case _adapter_collect_args:   // method handle which collects the args
1991     case _adapter_fold_args:      // method handle which collects the args
1992       if (!UseRicochetFrames) {
1993         { err = "box/collect/fold operators are not supported"; break; }
1994       }
1995       if (!java_lang_invoke_MethodHandle::is_instance(argument()))
1996         { err = "MethodHandle adapter argument required"; break; }
1997       arg_mtype = Handle(THREAD, java_lang_invoke_MethodHandle::type(argument()));
1998       break;
1999     default:
2000       if (argument.not_null())
2001         { err = "adapter has spurious argument"; break; }
2002       break;
2003     }
2004   }
2005 
2006   if (err == NULL) {
2007     // Check that the src/dest types are supplied if needed.
2008     // Also check relevant parameter or return types.
2009     switch (ek) {
2010     case _adapter_check_cast:
2011       if (src != T_OBJECT || dest != T_OBJECT) {
2012         err = "adapter requires object src/dest conversion subfields";
2013       }
2014       break;
2015     case _adapter_prim_to_prim:
2016       if (!is_java_primitive(src) || !is_java_primitive(dest) || src == dest) {
2017         err = "adapter requires primitive src/dest conversion subfields"; break;
2018       }
2019       if ( (src == T_FLOAT || src == T_DOUBLE) && !(dest == T_FLOAT || dest == T_DOUBLE) ||
2020           !(src == T_FLOAT || src == T_DOUBLE) &&  (dest == T_FLOAT || dest == T_DOUBLE)) {
2021         err = "adapter cannot convert beween floating and fixed-point"; break;
2022       }
2023       break;
2024     case _adapter_ref_to_prim:
2025       if (src != T_OBJECT || !is_java_primitive(dest)
2026           || argument() != Klass::cast(SystemDictionary::box_klass(dest))->java_mirror()) {
2027         err = "adapter requires primitive dest conversion subfield"; break;
2028       }
2029       break;
2030     case _adapter_prim_to_ref:
2031       if (!is_java_primitive(src) || dest != T_OBJECT) {
2032         err = "adapter requires primitive src conversion subfield"; break;
2033       }
2034       break;
2035     case _adapter_swap_args:
2036       {
2037         if (!src || !dest) {
2038           err = "adapter requires src/dest conversion subfields for swap"; break;
2039         }
2040         int src_size  = type2size[src];
2041         if (src_size != type2size[dest]) {
2042           err = "adapter requires equal sizes for src/dest"; break;
2043         }
2044         int src_slot   = argslot;
2045         int dest_slot  = vminfo;
2046         int src_arg    = argnum;
2047         int dest_arg   = argument_slot_to_argnum(src_mtype(), dest_slot);
2048         verify_vmargslot(mh, dest_arg, dest_slot, CHECK);
2049         if (!(dest_slot >= src_slot + src_size) &&
2050             !(src_slot >= dest_slot + src_size)) {
2051           err = "source, destination slots must be distinct"; break;
2052         } else if (!(src_slot > dest_slot)) {
2053           err = "source of swap must be deeper in stack"; break;
2054         }
2055         err = check_argument_type_change(java_lang_invoke_MethodType::ptype(src_mtype(), dest_arg),
2056                                          java_lang_invoke_MethodType::ptype(dst_mtype(), src_arg),
2057                                          dest_arg);
2058         if (err == NULL)
2059           err = check_argument_type_change(java_lang_invoke_MethodType::ptype(src_mtype(), src_arg),
2060                                            java_lang_invoke_MethodType::ptype(dst_mtype(), dest_arg),
2061                                            src_arg);
2062         break;
2063       }
2064     case _adapter_rot_args:
2065       {
2066         if (!src || !dest) {
2067           err = "adapter requires src/dest conversion subfields for rotate"; break;
2068         }
2069         int src_slot   = argslot;
2070         int limit_raw  = vminfo;
2071         bool rot_down  = (src_slot < limit_raw);
2072         int limit_bias = (rot_down ? MethodHandles::OP_ROT_ARGS_DOWN_LIMIT_BIAS : 0);
2073         int limit_slot = limit_raw - limit_bias;
2074         int src_arg    = argnum;
2075         int limit_arg  = argument_slot_to_argnum(src_mtype(), limit_slot);
2076         verify_vmargslot(mh, limit_arg, limit_slot, CHECK);
2077         if (src_slot == limit_slot) {
2078           err = "source, destination slots must be distinct"; break;
2079         }
2080         if (!rot_down) {  // rotate slots up == shift arguments left
2081           // limit_slot is an inclusive lower limit
2082           assert((src_slot > limit_slot) && (src_arg < limit_arg), "");
2083           // rotate up: [limit_slot..src_slot-ss] --> [limit_slot+ss..src_slot]
2084           // that is:   [src_arg+1..limit_arg] --> [src_arg..limit_arg-1]
2085           for (int i = src_arg+1; i <= limit_arg && err == NULL; i++) {
2086             err = check_argument_type_change(java_lang_invoke_MethodType::ptype(src_mtype(), i),
2087                                              java_lang_invoke_MethodType::ptype(dst_mtype(), i-1),
2088                                              i);
2089           }
2090         } else { // rotate slots down == shfit arguments right
2091           // limit_slot is an exclusive upper limit
2092           assert((src_slot < limit_slot - limit_bias) && (src_arg > limit_arg + limit_bias), "");
2093           // rotate down: [src_slot+ss..limit_slot) --> [src_slot..limit_slot-ss)
2094           // that is:     (limit_arg..src_arg-1] --> (dst_arg+1..src_arg]
2095           for (int i = limit_arg+1; i <= src_arg-1 && err == NULL; i++) {
2096             err = check_argument_type_change(java_lang_invoke_MethodType::ptype(src_mtype(), i),
2097                                              java_lang_invoke_MethodType::ptype(dst_mtype(), i+1),
2098                                              i);
2099           }
2100         }
2101         if (err == NULL) {
2102           int dest_arg = (rot_down ? limit_arg+1 : limit_arg);
2103           err = check_argument_type_change(java_lang_invoke_MethodType::ptype(src_mtype(), src_arg),
2104                                            java_lang_invoke_MethodType::ptype(dst_mtype(), dest_arg),
2105                                            src_arg);
2106         }
2107       }
2108       break;
2109     case _adapter_spread_args:
2110     case _adapter_collect_args:
2111     case _adapter_fold_args:
2112       {
2113         bool is_spread = (ek == _adapter_spread_args);
2114         bool is_fold   = (ek == _adapter_fold_args);
2115         BasicType coll_type = is_spread ? src : dest;
2116         BasicType elem_type = is_spread ? dest : src;
2117         // coll_type is type of args in collected form (or T_VOID if none)
2118         // elem_type is common type of args in spread form (or T_VOID if missing or heterogeneous)
2119         if (coll_type == 0 || elem_type == 0) {
2120           err = "adapter requires src/dest subfields for spread or collect"; break;
2121         }
2122         if (is_spread && coll_type != T_OBJECT) {
2123           err = "spread adapter requires object type for argument bundle"; break;
2124         }
2125         Handle spread_mtype = (is_spread ? dst_mtype : src_mtype);
2126         int spread_slot = argslot;
2127         int spread_arg  = argnum;
2128         int slots_pushed = stack_move / stack_move_unit();
2129         int coll_slot_count = type2size[coll_type];
2130         int spread_slot_count = (is_spread ? slots_pushed : -slots_pushed) + coll_slot_count;
2131         if (is_fold)  spread_slot_count = argument_slot_count(arg_mtype());
2132         if (!is_spread) {
2133           int init_slots = argument_slot_count(src_mtype());
2134           int coll_slots = argument_slot_count(arg_mtype());
2135           if (spread_slot_count > init_slots ||
2136               spread_slot_count != coll_slots) {
2137             err = "collect adapter has inconsistent arg counts"; break;
2138           }
2139           int next_slots = argument_slot_count(dst_mtype());
2140           int unchanged_slots_in  = (init_slots - spread_slot_count);
2141           int unchanged_slots_out = (next_slots - coll_slot_count - (is_fold ? spread_slot_count : 0));
2142           if (unchanged_slots_in != unchanged_slots_out) {
2143             err = "collect adapter continuation has inconsistent arg counts"; break;
2144           }
2145         }
2146       }
2147       break;
2148     default:
2149       if (src != 0 || dest != 0) {
2150         err = "adapter has spurious src/dest conversion subfields"; break;
2151       }
2152       break;
2153     }
2154   }
2155 
2156   if (err == NULL) {
2157     // Check the stack_move subfield.
2158     // It must always report the net change in stack size, positive or negative.
2159     int slots_pushed = stack_move / stack_move_unit();
2160     switch (ek) {
2161     case _adapter_prim_to_prim:
2162     case _adapter_ref_to_prim:
2163     case _adapter_prim_to_ref:
2164       if (slots_pushed != type2size[dest] - type2size[src]) {
2165         err = "wrong stack motion for primitive conversion";
2166       }
2167       break;
2168     case _adapter_dup_args:
2169       if (slots_pushed <= 0) {
2170         err = "adapter requires conversion subfield slots_pushed > 0";
2171       }
2172       break;
2173     case _adapter_drop_args:
2174       if (slots_pushed >= 0) {
2175         err = "adapter requires conversion subfield slots_pushed < 0";
2176       }
2177       break;
2178     case _adapter_collect_args:
2179     case _adapter_fold_args:
2180       if (slots_pushed > 2) {
2181         err = "adapter requires conversion subfield slots_pushed <= 2";
2182       }
2183       break;
2184     case _adapter_spread_args:
2185       if (slots_pushed < -1) {
2186         err = "adapter requires conversion subfield slots_pushed >= -1";
2187       }
2188       break;
2189     default:
2190       if (stack_move != 0) {
2191         err = "adapter has spurious stack_move conversion subfield";
2192       }
2193       break;
2194     }
2195     if (err == NULL && stack_move != slots_pushed * stack_move_unit()) {
2196       err = "stack_move conversion subfield must be multiple of stack_move_unit";
2197     }
2198   }
2199 
2200   if (err == NULL) {
2201     // Make sure this adapter's stack pushing is accurately recorded.
2202     int slots_pushed = stack_move / stack_move_unit();
2203     int this_vmslots = java_lang_invoke_MethodHandle::vmslots(mh());
2204     int target_vmslots = java_lang_invoke_MethodHandle::vmslots(target());
2205     int target_pushes = decode_MethodHandle_stack_pushes(target());
2206     if (slots_pushed != (target_vmslots - this_vmslots)) {
2207       err = "stack_move inconsistent with previous and current MethodType vmslots";
2208     } else {
2209       int this_pushes = decode_MethodHandle_stack_pushes(mh());
2210       if (slots_pushed + target_pushes != this_pushes) {
2211         if (this_pushes == 0)
2212           err = "adapter push count not initialized";
2213         else
2214           err = "adapter push count is wrong";
2215       }
2216     }
2217 
2218     // While we're at it, check that the stack motion decoder works:
2219     DEBUG_ONLY(int this_pushes = decode_MethodHandle_stack_pushes(mh()));
2220     assert(this_pushes == slots_pushed + target_pushes, "AMH stack motion must be correct");
2221   }
2222 
2223   if (err == NULL && vminfo != 0) {
2224     switch (ek) {
2225     case _adapter_swap_args:
2226     case _adapter_rot_args:
2227     case _adapter_prim_to_ref:
2228     case _adapter_collect_args:
2229     case _adapter_fold_args:
2230       break;                // OK
2231     default:
2232       err = "vminfo subfield is reserved to the JVM";
2233     }
2234   }
2235 
2236   // Do additional ad hoc checks.
2237   if (err == NULL) {
2238     switch (ek) {
2239     case _adapter_retype_only:
2240       err = check_method_type_passthrough(src_mtype(), dst_mtype(), false);
2241       break;
2242 
2243     case _adapter_retype_raw:
2244       err = check_method_type_passthrough(src_mtype(), dst_mtype(), true);
2245       break;
2246 
2247     case _adapter_check_cast:
2248       {
2249         // The actual value being checked must be a reference:
2250         err = check_argument_type_change(java_lang_invoke_MethodType::ptype(src_mtype(), argnum),
2251                                          object_java_mirror(), argnum);
2252         if (err != NULL)  break;
2253 
2254         // The output of the cast must fit with the destination argument:
2255         Handle cast_class = argument;
2256         err = check_method_type_conversion(src_mtype(),
2257                                            argnum, cast_class(),
2258                                            dst_mtype());
2259       }
2260       break;
2261 
2262       // %%% TO DO: continue in remaining cases to verify src/dst_mtype if VerifyMethodHandles
2263     }
2264   }
2265 
2266   if (err != NULL) {
2267     throw_InternalError_for_bad_conversion(conversion, err, THREAD);
2268     return;
2269   }
2270 
2271 }
2272 
2273 void MethodHandles::init_AdapterMethodHandle(Handle mh, Handle target, int argnum, TRAPS) {
2274   Handle argument   = java_lang_invoke_AdapterMethodHandle::argument(mh());
2275   int    argslot    = java_lang_invoke_AdapterMethodHandle::vmargslot(mh());
2276   jint   conversion = java_lang_invoke_AdapterMethodHandle::conversion(mh());
2277   jint   conv_op    = adapter_conversion_op(conversion);
2278 
2279   // adjust the adapter code to the internal EntryKind enumeration:
2280   EntryKind ek_orig = adapter_entry_kind(conv_op);
2281   EntryKind ek_opt  = ek_orig;  // may be optimized
2282   EntryKind ek_try;             // temp
2283 
2284   // Finalize the vmtarget field (Java initialized it to null).
2285   if (!java_lang_invoke_MethodHandle::is_instance(target())) {
2286     throw_InternalError_for_bad_conversion(conversion, "bad target", THREAD);
2287     return;
2288   }
2289   java_lang_invoke_AdapterMethodHandle::set_vmtarget(mh(), target());
2290 
2291   int stack_move = adapter_conversion_stack_move(conversion);
2292   BasicType src  = adapter_conversion_src_type(conversion);
2293   BasicType dest = adapter_conversion_dest_type(conversion);
2294   int vminfo     = adapter_conversion_vminfo(conversion); // should be zero
2295 
2296   int slots_pushed = stack_move / stack_move_unit();
2297 
2298   if (VerifyMethodHandles) {
2299     verify_AdapterMethodHandle(mh, argnum, CHECK);
2300   }
2301 
2302   const char* err = NULL;
2303 
2304   if (!conv_op_supported(conv_op)) {
2305     err = "adapter not yet implemented in the JVM";
2306   }
2307 
2308   // Now it's time to finish the case analysis and pick a MethodHandleEntry.
2309   switch (ek_orig) {
2310   case _adapter_retype_only:
2311   case _adapter_retype_raw:
2312   case _adapter_check_cast:
2313   case _adapter_dup_args:
2314   case _adapter_drop_args:
2315     // these work fine via general case code
2316     break;
2317 
2318   case _adapter_prim_to_prim:
2319     {
2320       // Non-subword cases are {int,float,long,double} -> {int,float,long,double}.
2321       // And, the {float,double} -> {int,long} cases must be handled by Java.
2322       switch (type2size[src] *4+ type2size[dest]) {
2323       case 1 *4+ 1:
2324         assert(src == T_INT || is_subword_type(src), "source is not float");
2325         // Subword-related cases are int -> {boolean,byte,char,short}.
2326         ek_opt = _adapter_opt_i2i;
2327         vminfo = adapter_prim_to_prim_subword_vminfo(dest);
2328         break;
2329       case 2 *4+ 1:
2330         if (src == T_LONG && (dest == T_INT || is_subword_type(dest))) {
2331           ek_opt = _adapter_opt_l2i;
2332           vminfo = adapter_prim_to_prim_subword_vminfo(dest);
2333         } else if (src == T_DOUBLE && dest == T_FLOAT) {
2334           ek_opt = _adapter_opt_d2f;
2335         } else {
2336           goto throw_not_impl;        // runs user code, hence could block
2337         }
2338         break;
2339       case 1 *4+ 2:
2340         if ((src == T_INT || is_subword_type(src)) && dest == T_LONG) {
2341           ek_opt = _adapter_opt_i2l;
2342         } else if (src == T_FLOAT && dest == T_DOUBLE) {
2343           ek_opt = _adapter_opt_f2d;
2344         } else {
2345           goto throw_not_impl;        // runs user code, hence could block
2346         }
2347         break;
2348       default:
2349         goto throw_not_impl;        // runs user code, hence could block
2350         break;
2351       }
2352     }
2353     break;
2354 
2355   case _adapter_ref_to_prim:
2356     {
2357       switch (type2size[dest]) {
2358       case 1:
2359         ek_opt = _adapter_opt_unboxi;
2360         vminfo = adapter_unbox_subword_vminfo(dest);
2361         break;
2362       case 2:
2363         ek_opt = _adapter_opt_unboxl;
2364         break;
2365       default:
2366         goto throw_not_impl;
2367         break;
2368       }
2369     }
2370     break;
2371 
2372   case _adapter_prim_to_ref:
2373     {
2374       assert(UseRicochetFrames, "else don't come here");
2375       // vminfo will be the location to insert the return value
2376       vminfo = argslot;
2377       ek_opt = _adapter_opt_collect_ref;
2378       ensure_vmlayout_field(target, CHECK);
2379       // for MethodHandleWalk:
2380       if (java_lang_invoke_AdapterMethodHandle::is_instance(argument()))
2381         ensure_vmlayout_field(argument, CHECK);
2382       if (!OptimizeMethodHandles)  break;
2383       switch (type2size[src]) {
2384       case 1:
2385         ek_try = EntryKind(_adapter_opt_filter_S0_ref + argslot);
2386         if (ek_try < _adapter_opt_collect_LAST &&
2387             ek_adapter_opt_collect_slot(ek_try) == argslot) {
2388           assert(ek_adapter_opt_collect_count(ek_try) == 1 &&
2389                  ek_adapter_opt_collect_type(ek_try) == T_OBJECT, "");
2390           ek_opt = ek_try;
2391           break;
2392         }
2393         // else downgrade to variable slot:
2394         ek_opt = _adapter_opt_collect_1_ref;
2395         break;
2396       case 2:
2397         ek_try = EntryKind(_adapter_opt_collect_2_S0_ref + argslot);
2398         if (ek_try < _adapter_opt_collect_LAST &&
2399             ek_adapter_opt_collect_slot(ek_try) == argslot) {
2400           assert(ek_adapter_opt_collect_count(ek_try) == 2 &&
2401                  ek_adapter_opt_collect_type(ek_try) == T_OBJECT, "");
2402           ek_opt = ek_try;
2403           break;
2404         }
2405         // else downgrade to variable slot:
2406         ek_opt = _adapter_opt_collect_2_ref;
2407         break;
2408       default:
2409         goto throw_not_impl;
2410         break;
2411       }
2412     }
2413     break;
2414 
2415   case _adapter_swap_args:
2416   case _adapter_rot_args:
2417     {
2418       int swap_slots = type2size[src];
2419       int src_slot   = argslot;
2420       int dest_slot  = vminfo;
2421       int rotate     = (ek_orig == _adapter_swap_args) ? 0 : (src_slot > dest_slot) ? 1 : -1;
2422       switch (swap_slots) {
2423       case 1:
2424         ek_opt = (!rotate    ? _adapter_opt_swap_1 :
2425                   rotate > 0 ? _adapter_opt_rot_1_up : _adapter_opt_rot_1_down);
2426         break;
2427       case 2:
2428         ek_opt = (!rotate    ? _adapter_opt_swap_2 :
2429                   rotate > 0 ? _adapter_opt_rot_2_up : _adapter_opt_rot_2_down);
2430         break;
2431       default:
2432         goto throw_not_impl;
2433         break;
2434       }
2435     }
2436     break;
2437 
2438   case _adapter_spread_args:
2439     {
2440 #ifdef TARGET_ARCH_NYI_6939861
2441       // ports before 6939861 supported only three kinds of spread ops
2442       if (!UseRicochetFrames) {
2443         int array_size   = slots_pushed + 1;
2444         assert(array_size >= 0, "");
2445         vminfo = array_size;
2446         switch (array_size) {
2447         case 0:   ek_opt = _adapter_opt_spread_0;       break;
2448         case 1:   ek_opt = _adapter_opt_spread_1;       break;
2449         default:  ek_opt = _adapter_opt_spread_more;    break;
2450         }
2451         break;
2452       }
2453 #endif //TARGET_ARCH_NYI_6939861
2454       // vminfo will be the required length of the array
2455       int array_size = (slots_pushed + 1) / (type2size[dest] == 2 ? 2 : 1);
2456       vminfo = array_size;
2457       // general case
2458       switch (dest) {
2459       case T_BOOLEAN : // fall through to T_BYTE:
2460       case T_BYTE    : ek_opt = _adapter_opt_spread_byte;    break;
2461       case T_CHAR    : ek_opt = _adapter_opt_spread_char;    break;
2462       case T_SHORT   : ek_opt = _adapter_opt_spread_short;   break;
2463       case T_INT     : ek_opt = _adapter_opt_spread_int;     break;
2464       case T_LONG    : ek_opt = _adapter_opt_spread_long;    break;
2465       case T_FLOAT   : ek_opt = _adapter_opt_spread_float;   break;
2466       case T_DOUBLE  : ek_opt = _adapter_opt_spread_double;  break;
2467       case T_OBJECT  : ek_opt = _adapter_opt_spread_ref;     break;
2468       case T_VOID    : if (array_size != 0)  goto throw_not_impl;
2469                        ek_opt = _adapter_opt_spread_ref;     break;
2470       default        : goto throw_not_impl;
2471       }
2472       assert(array_size == 0 ||  // it doesn't matter what the spreader is
2473              (ek_adapter_opt_spread_count(ek_opt) == -1 &&
2474               (ek_adapter_opt_spread_type(ek_opt) == dest ||
2475                (ek_adapter_opt_spread_type(ek_opt) == T_BYTE && dest == T_BOOLEAN))),
2476              err_msg("dest=%d ek_opt=%d", dest, ek_opt));
2477 
2478       if (array_size <= 0) {
2479         // since the general case does not handle length 0, this case is required:
2480         ek_opt = _adapter_opt_spread_0;
2481         break;
2482       }
2483       if (dest == T_OBJECT) {
2484         ek_try = EntryKind(_adapter_opt_spread_1_ref - 1 + array_size);
2485         if (ek_try < _adapter_opt_spread_LAST &&
2486             ek_adapter_opt_spread_count(ek_try) == array_size) {
2487           assert(ek_adapter_opt_spread_type(ek_try) == dest, "");
2488           ek_opt = ek_try;
2489           break;
2490         }
2491       }
2492       break;
2493     }
2494     break;
2495 
2496   case _adapter_collect_args:
2497     {
2498       assert(UseRicochetFrames, "else don't come here");
2499       int elem_slots = argument_slot_count(java_lang_invoke_MethodHandle::type(argument()));
2500       // vminfo will be the location to insert the return value
2501       vminfo = argslot;
2502       ensure_vmlayout_field(target, CHECK);
2503       ensure_vmlayout_field(argument, CHECK);
2504 
2505       // general case:
2506       switch (dest) {
2507       default       : if (!is_subword_type(dest))  goto throw_not_impl;
2508                     // else fall through:
2509       case T_INT    : ek_opt = _adapter_opt_collect_int;     break;
2510       case T_LONG   : ek_opt = _adapter_opt_collect_long;    break;
2511       case T_FLOAT  : ek_opt = _adapter_opt_collect_float;   break;
2512       case T_DOUBLE : ek_opt = _adapter_opt_collect_double;  break;
2513       case T_OBJECT : ek_opt = _adapter_opt_collect_ref;     break;
2514       case T_VOID   : ek_opt = _adapter_opt_collect_void;    break;
2515       }
2516       assert(ek_adapter_opt_collect_slot(ek_opt) == -1 &&
2517              ek_adapter_opt_collect_count(ek_opt) == -1 &&
2518              (ek_adapter_opt_collect_type(ek_opt) == dest ||
2519               ek_adapter_opt_collect_type(ek_opt) == T_INT && is_subword_type(dest)),
2520              "");
2521 
2522       if (dest == T_OBJECT && elem_slots == 1 && OptimizeMethodHandles) {
2523         // filter operation on a ref
2524         ek_try = EntryKind(_adapter_opt_filter_S0_ref + argslot);
2525         if (ek_try < _adapter_opt_collect_LAST &&
2526             ek_adapter_opt_collect_slot(ek_try) == argslot) {
2527           assert(ek_adapter_opt_collect_count(ek_try) == elem_slots &&
2528                  ek_adapter_opt_collect_type(ek_try) == dest, "");
2529           ek_opt = ek_try;
2530           break;
2531         }
2532         ek_opt = _adapter_opt_collect_1_ref;
2533         break;
2534       }
2535 
2536       if (dest == T_OBJECT && elem_slots == 2 && OptimizeMethodHandles) {
2537         // filter of two arguments
2538         ek_try = EntryKind(_adapter_opt_collect_2_S0_ref + argslot);
2539         if (ek_try < _adapter_opt_collect_LAST &&
2540             ek_adapter_opt_collect_slot(ek_try) == argslot) {
2541           assert(ek_adapter_opt_collect_count(ek_try) == elem_slots &&
2542                  ek_adapter_opt_collect_type(ek_try) == dest, "");
2543           ek_opt = ek_try;
2544           break;
2545         }
2546         ek_opt = _adapter_opt_collect_2_ref;
2547         break;
2548       }
2549 
2550       if (dest == T_OBJECT && OptimizeMethodHandles) {
2551         // try to use a fixed length adapter
2552         ek_try = EntryKind(_adapter_opt_collect_0_ref + elem_slots);
2553         if (ek_try < _adapter_opt_collect_LAST &&
2554             ek_adapter_opt_collect_count(ek_try) == elem_slots) {
2555           assert(ek_adapter_opt_collect_slot(ek_try) == -1 &&
2556                  ek_adapter_opt_collect_type(ek_try) == dest, "");
2557           ek_opt = ek_try;
2558           break;
2559         }
2560       }
2561 
2562       break;
2563     }
2564 
2565   case _adapter_fold_args:
2566     {
2567       assert(UseRicochetFrames, "else don't come here");
2568       int elem_slots = argument_slot_count(java_lang_invoke_MethodHandle::type(argument()));
2569       // vminfo will be the location to insert the return value
2570       vminfo = argslot + elem_slots;
2571       ensure_vmlayout_field(target, CHECK);
2572       ensure_vmlayout_field(argument, CHECK);
2573 
2574       switch (dest) {
2575       default       : if (!is_subword_type(dest))  goto throw_not_impl;
2576                     // else fall through:
2577       case T_INT    : ek_opt = _adapter_opt_fold_int;     break;
2578       case T_LONG   : ek_opt = _adapter_opt_fold_long;    break;
2579       case T_FLOAT  : ek_opt = _adapter_opt_fold_float;   break;
2580       case T_DOUBLE : ek_opt = _adapter_opt_fold_double;  break;
2581       case T_OBJECT : ek_opt = _adapter_opt_fold_ref;     break;
2582       case T_VOID   : ek_opt = _adapter_opt_fold_void;    break;
2583       }
2584       assert(ek_adapter_opt_collect_slot(ek_opt) == -1 &&
2585              ek_adapter_opt_collect_count(ek_opt) == -1 &&
2586              (ek_adapter_opt_collect_type(ek_opt) == dest ||
2587               ek_adapter_opt_collect_type(ek_opt) == T_INT && is_subword_type(dest)),
2588              "");
2589 
2590       if (dest == T_OBJECT && elem_slots == 0 && OptimizeMethodHandles) {
2591         // if there are no args, just pretend it's a collect
2592         ek_opt = _adapter_opt_collect_0_ref;
2593         break;
2594       }
2595 
2596       if (dest == T_OBJECT && OptimizeMethodHandles) {
2597         // try to use a fixed length adapter
2598         ek_try = EntryKind(_adapter_opt_fold_1_ref - 1 + elem_slots);
2599         if (ek_try < _adapter_opt_fold_LAST &&
2600             ek_adapter_opt_collect_count(ek_try) == elem_slots) {
2601           assert(ek_adapter_opt_collect_slot(ek_try) == -1 &&
2602                  ek_adapter_opt_collect_type(ek_try) == dest, "");
2603           ek_opt = ek_try;
2604           break;
2605         }
2606       }
2607 
2608       break;
2609     }
2610 
2611   default:
2612     // should have failed much earlier; must be a missing case here
2613     assert(false, "incomplete switch");
2614     // and fall through:
2615 
2616   throw_not_impl:
2617     if (err == NULL)
2618       err = "unknown adapter type";
2619     break;
2620   }
2621 
2622   if (err == NULL && (vminfo & CONV_VMINFO_MASK) != vminfo) {
2623     // should not happen, since vminfo is used to encode arg/slot indexes < 255
2624     err = "vminfo overflow";
2625   }
2626 
2627   if (err == NULL && !have_entry(ek_opt)) {
2628     err = "adapter stub for this kind of method handle is missing";
2629   }
2630 
2631   if (err == NULL && ek_opt == ek_orig) {
2632     switch (ek_opt) {
2633     case _adapter_prim_to_prim:
2634     case _adapter_ref_to_prim:
2635     case _adapter_prim_to_ref:
2636     case _adapter_swap_args:
2637     case _adapter_rot_args:
2638     case _adapter_collect_args:
2639     case _adapter_fold_args:
2640     case _adapter_spread_args:
2641       // should be handled completely by optimized cases; see above
2642       err = "init_AdapterMethodHandle should not issue this";
2643       break;
2644     }
2645   }
2646 
2647   if (err != NULL) {
2648     throw_InternalError_for_bad_conversion(conversion, err_msg("%s: conv_op %d ek_opt %d", err, conv_op, ek_opt), THREAD);
2649     return;
2650   }
2651 
2652   // Rebuild the conversion value; maybe parts of it were changed.
2653   jint new_conversion = adapter_conversion(conv_op, src, dest, stack_move, vminfo);
2654 
2655   // Finalize the conversion field.  (Note that it is final to Java code.)
2656   java_lang_invoke_AdapterMethodHandle::set_conversion(mh(), new_conversion);
2657 
2658   if (java_lang_invoke_CountingMethodHandle::is_instance(mh())) {
2659     assert(ek_orig == _adapter_retype_only, "only one handled");
2660     ek_opt = _adapter_opt_profiling;
2661   }
2662 
2663   // Done!
2664   java_lang_invoke_MethodHandle::set_vmentry(mh(), entry(ek_opt));
2665 
2666   // There should be enough memory barriers on exit from native methods
2667   // to ensure that the MH is fully initialized to all threads before
2668   // Java code can publish it in global data structures.
2669 }
2670 
2671 void MethodHandles::ensure_vmlayout_field(Handle target, TRAPS) {
2672   Handle mtype(THREAD, java_lang_invoke_MethodHandle::type(target()));
2673   Handle mtform(THREAD, java_lang_invoke_MethodType::form(mtype()));
2674   if (mtform.is_null()) { THROW(vmSymbols::java_lang_InternalError()); }
2675   if (java_lang_invoke_MethodTypeForm::vmlayout_offset_in_bytes() > 0) {
2676     if (java_lang_invoke_MethodTypeForm::vmlayout(mtform()) == NULL) {
2677       // fill it in
2678       Handle erased_mtype(THREAD, java_lang_invoke_MethodTypeForm::erasedType(mtform()));
2679       TempNewSymbol erased_signature
2680         = java_lang_invoke_MethodType::as_signature(erased_mtype(), /*intern:*/true, CHECK);
2681       methodOop cookie
2682         = SystemDictionary::find_method_handle_invoke(vmSymbols::invokeExact_name(),
2683                                                       erased_signature,
2684                                                       SystemDictionaryHandles::Object_klass(),
2685                                                       THREAD);
2686       java_lang_invoke_MethodTypeForm::init_vmlayout(mtform(), cookie);
2687     }
2688   }
2689 }
2690 
2691 #ifdef ASSERT
2692 
2693 extern "C"
2694 void print_method_handle(oop mh);
2695 
2696 static void stress_method_handle_walk_impl(Handle mh, TRAPS) {
2697   if (StressMethodHandleWalk) {
2698     // Exercise the MethodHandleWalk code in various ways and validate
2699     // the resulting method oop.  Some of these produce output so they
2700     // are guarded under Verbose.
2701     ResourceMark rm;
2702     HandleMark hm;
2703     if (Verbose) {
2704       print_method_handle(mh());
2705     }
2706     TempNewSymbol name = SymbolTable::new_symbol("invoke", CHECK);
2707     Handle mt = java_lang_invoke_MethodHandle::type(mh());
2708     TempNewSymbol signature = java_lang_invoke_MethodType::as_signature(mt(), true, CHECK);
2709     MethodHandleCompiler mhc(mh, name, signature, 10000, false, CHECK);
2710     methodHandle m = mhc.compile(CHECK);
2711     if (Verbose) {
2712       m->print_codes();
2713     }
2714     InterpreterOopMap mask;
2715     OopMapCache::compute_one_oop_map(m, m->code_size() - 1, &mask);
2716     // compile to object code if -Xcomp or WizardMode
2717     if ((WizardMode ||
2718          CompilationPolicy::must_be_compiled(m))
2719         && !instanceKlass::cast(m->method_holder())->is_not_initialized()
2720         && CompilationPolicy::can_be_compiled(m)) {
2721       // Force compilation
2722       CompileBroker::compile_method(m, InvocationEntryBci,
2723                                     CompilationPolicy::policy()->initial_compile_level(),
2724                                     methodHandle(), 0, "StressMethodHandleWalk",
2725                                     CHECK);
2726     }
2727   }
2728 }
2729 
2730 static void stress_method_handle_walk(Handle mh, TRAPS) {
2731   stress_method_handle_walk_impl(mh, THREAD);
2732   if (HAS_PENDING_EXCEPTION) {
2733     oop ex = PENDING_EXCEPTION;
2734     CLEAR_PENDING_EXCEPTION;
2735     tty->print("StressMethodHandleWalk: ");
2736     java_lang_Throwable::print(ex, tty);
2737     tty->cr();
2738   }
2739 }
2740 #else
2741 
2742 static void stress_method_handle_walk(Handle mh, TRAPS) {}
2743 
2744 #endif
2745 
2746 //
2747 // Here are the native methods on sun.invoke.MethodHandleImpl.
2748 // They are the private interface between this JVM and the HotSpot-specific
2749 // Java code that implements JSR 292 method handles.
2750 //
2751 // Note:  We use a JVM_ENTRY macro to define each of these, for this is the way
2752 // that intrinsic (non-JNI) native methods are defined in HotSpot.
2753 //
2754 
2755 // direct method handles for invokestatic or invokespecial
2756 // void init(DirectMethodHandle self, MemberName ref, boolean doDispatch, Class<?> caller);
2757 JVM_ENTRY(void, MHN_init_DMH(JNIEnv *env, jobject igcls, jobject mh_jh,
2758                              jobject target_jh, jboolean do_dispatch, jobject caller_jh)) {
2759   ResourceMark rm;              // for error messages
2760 
2761   // This is the guy we are initializing:
2762   if (mh_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "self is null"); }
2763   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
2764 
2765   // Early returns out of this method leave the DMH in an unfinished state.
2766   assert(java_lang_invoke_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
2767 
2768   // which method are we really talking about?
2769   if (target_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "target is null"); }
2770   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
2771   if (java_lang_invoke_MemberName::is_instance(target()) &&
2772       java_lang_invoke_MemberName::vmindex(target()) == VM_INDEX_UNINITIALIZED) {
2773     MethodHandles::resolve_MemberName(target, CHECK);
2774   }
2775 
2776   KlassHandle receiver_limit; int decode_flags = 0;
2777   methodHandle m = MethodHandles::decode_method(target(), receiver_limit, decode_flags);
2778   if (m.is_null()) { THROW_MSG(vmSymbols::java_lang_InternalError(), "no such method"); }
2779 
2780   // The trusted Java code that calls this method should already have performed
2781   // access checks on behalf of the given caller.  But, we can verify this.
2782   if (VerifyMethodHandles && caller_jh != NULL) {
2783     KlassHandle caller(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(caller_jh)));
2784     // If this were a bytecode, the first access check would be against
2785     // the "reference class" mentioned in the CONSTANT_Methodref.
2786     // We don't know at this point which class that was, and if we
2787     // check against m.method_holder we might get the wrong answer.
2788     // So we just make sure to handle this check when the resolution
2789     // happens, when we call resolve_MemberName.
2790     //
2791     // (A public class can inherit public members from private supers,
2792     // and it would be wrong to check access against the private super
2793     // if the original symbolic reference was against the public class.)
2794     //
2795     // If there were a bytecode, the next step would be to lookup the method
2796     // in the reference class, then then check the method's access bits.
2797     // Emulate LinkResolver::check_method_accessability.
2798     klassOop resolved_klass = m->method_holder();
2799     if (!Reflection::verify_field_access(caller->as_klassOop(),
2800                                          resolved_klass, resolved_klass,
2801                                          m->access_flags(),
2802                                          true)) {
2803       // %%% following cutout belongs in Reflection::verify_field_access?
2804       bool same_pm = Reflection::is_same_package_member(caller->as_klassOop(),
2805                                                         resolved_klass, THREAD);
2806       if (!same_pm) {
2807         THROW_MSG(vmSymbols::java_lang_InternalError(), m->name_and_sig_as_C_string());
2808       }
2809     }
2810   }
2811 
2812   MethodHandles::init_DirectMethodHandle(mh, m, (do_dispatch != JNI_FALSE), CHECK);
2813   stress_method_handle_walk(mh, CHECK);
2814 }
2815 JVM_END
2816 
2817 // bound method handles
2818 JVM_ENTRY(void, MHN_init_BMH(JNIEnv *env, jobject igcls, jobject mh_jh,
2819                              jobject target_jh, int argnum)) {
2820   ResourceMark rm;              // for error messages
2821 
2822   // This is the guy we are initializing:
2823   if (mh_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "self is null"); }
2824   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
2825 
2826   // Early returns out of this method leave the BMH in an unfinished state.
2827   assert(java_lang_invoke_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
2828 
2829   if (target_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "target is null"); }
2830   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
2831 
2832   if (!java_lang_invoke_MethodHandle::is_instance(target())) {
2833     // Target object is a reflective method.  (%%% Do we need this alternate path?)
2834     Untested("init_BMH of non-MH");
2835     if (argnum != 0) { THROW(vmSymbols::java_lang_InternalError()); }
2836     KlassHandle receiver_limit; int decode_flags = 0;
2837     methodHandle m = MethodHandles::decode_method(target(), receiver_limit, decode_flags);
2838     MethodHandles::init_BoundMethodHandle_with_receiver(mh, m,
2839                                                        receiver_limit,
2840                                                        decode_flags,
2841                                                        CHECK);
2842   } else {
2843     // Build a BMH on top of a DMH or another BMH:
2844     MethodHandles::init_BoundMethodHandle(mh, target, argnum, CHECK);
2845   }
2846 
2847   if (StressMethodHandleWalk) {
2848     if (mh->klass() == SystemDictionary::BoundMethodHandle_klass())
2849       stress_method_handle_walk(mh, CHECK);
2850     // else don't, since the subclass has not yet initialized its own fields
2851   }
2852 }
2853 JVM_END
2854 
2855 // adapter method handles
2856 JVM_ENTRY(void, MHN_init_AMH(JNIEnv *env, jobject igcls, jobject mh_jh,
2857                              jobject target_jh, int argnum)) {
2858   // This is the guy we are initializing:
2859   if (mh_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "self is null"); }
2860   if (target_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "target is null"); }
2861   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
2862   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
2863 
2864   // Early returns out of this method leave the AMH in an unfinished state.
2865   assert(java_lang_invoke_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
2866 
2867   MethodHandles::init_AdapterMethodHandle(mh, target, argnum, CHECK);
2868   stress_method_handle_walk(mh, CHECK);
2869 }
2870 JVM_END
2871 
2872 // method type forms
2873 JVM_ENTRY(void, MHN_init_MT(JNIEnv *env, jobject igcls, jobject erased_jh)) {
2874   if (erased_jh == NULL)  return;
2875   if (TraceMethodHandles) {
2876     tty->print("creating MethodType form ");
2877     if (WizardMode || Verbose) {   // Warning: this calls Java code on the MH!
2878       // call Object.toString()
2879       Symbol* name = vmSymbols::toString_name();
2880       Symbol* sig = vmSymbols::void_string_signature();
2881       JavaCallArguments args(Handle(THREAD, JNIHandles::resolve_non_null(erased_jh)));
2882       JavaValue result(T_OBJECT);
2883       JavaCalls::call_virtual(&result, SystemDictionary::Object_klass(), name, sig,
2884                               &args, CHECK);
2885       Handle str(THREAD, (oop)result.get_jobject());
2886       java_lang_String::print(str, tty);
2887     }
2888     tty->cr();
2889   }
2890 }
2891 JVM_END
2892 
2893 // debugging and reflection
2894 JVM_ENTRY(jobject, MHN_getTarget(JNIEnv *env, jobject igcls, jobject mh_jh, jint format)) {
2895   Handle mh(THREAD, JNIHandles::resolve(mh_jh));
2896   if (!java_lang_invoke_MethodHandle::is_instance(mh())) {
2897     THROW_NULL(vmSymbols::java_lang_IllegalArgumentException());
2898   }
2899   oop target = MethodHandles::encode_target(mh, format, CHECK_NULL);
2900   return JNIHandles::make_local(THREAD, target);
2901 }
2902 JVM_END
2903 
2904 JVM_ENTRY(jint, MHN_getConstant(JNIEnv *env, jobject igcls, jint which)) {
2905   switch (which) {
2906   case MethodHandles::GC_JVM_PUSH_LIMIT:
2907     guarantee(MethodHandlePushLimit >= 2 && MethodHandlePushLimit <= 0xFF,
2908               "MethodHandlePushLimit parameter must be in valid range");
2909     return MethodHandlePushLimit;
2910   case MethodHandles::GC_JVM_STACK_MOVE_UNIT:
2911     // return number of words per slot, signed according to stack direction
2912     return MethodHandles::stack_move_unit();
2913   case MethodHandles::GC_CONV_OP_IMPLEMENTED_MASK:
2914     return MethodHandles::adapter_conversion_ops_supported_mask();
2915   case MethodHandles::GC_COUNT_GWT:
2916 #ifdef COMPILER2
2917     return true;
2918 #else
2919     return false;
2920 #endif
2921   }
2922   return 0;
2923 }
2924 JVM_END
2925 
2926 #ifndef PRODUCT
2927 #define EACH_NAMED_CON(template) \
2928   /* hold back this one until JDK stabilizes */ \
2929   /* template(MethodHandles,GC_JVM_PUSH_LIMIT) */  \
2930   /* hold back this one until JDK stabilizes */ \
2931   /* template(MethodHandles,GC_JVM_STACK_MOVE_UNIT) */ \
2932   /* hold back this one until JDK stabilizes */ \
2933   /* template(MethodHandles,GC_OP_ROT_ARGS_DOWN_LIMIT_BIAS) */ \
2934     template(MethodHandles,ETF_HANDLE_OR_METHOD_NAME) \
2935     template(MethodHandles,ETF_DIRECT_HANDLE) \
2936     template(MethodHandles,ETF_METHOD_NAME) \
2937     template(MethodHandles,ETF_REFLECT_METHOD) \
2938     template(java_lang_invoke_MemberName,MN_IS_METHOD) \
2939     template(java_lang_invoke_MemberName,MN_IS_CONSTRUCTOR) \
2940     template(java_lang_invoke_MemberName,MN_IS_FIELD) \
2941     template(java_lang_invoke_MemberName,MN_IS_TYPE) \
2942     template(java_lang_invoke_MemberName,MN_SEARCH_SUPERCLASSES) \
2943     template(java_lang_invoke_MemberName,MN_SEARCH_INTERFACES) \
2944     template(java_lang_invoke_MemberName,VM_INDEX_UNINITIALIZED) \
2945     template(java_lang_invoke_AdapterMethodHandle,OP_RETYPE_ONLY) \
2946     template(java_lang_invoke_AdapterMethodHandle,OP_RETYPE_RAW) \
2947     template(java_lang_invoke_AdapterMethodHandle,OP_CHECK_CAST) \
2948     template(java_lang_invoke_AdapterMethodHandle,OP_PRIM_TO_PRIM) \
2949     template(java_lang_invoke_AdapterMethodHandle,OP_REF_TO_PRIM) \
2950     template(java_lang_invoke_AdapterMethodHandle,OP_PRIM_TO_REF) \
2951     template(java_lang_invoke_AdapterMethodHandle,OP_SWAP_ARGS) \
2952     template(java_lang_invoke_AdapterMethodHandle,OP_ROT_ARGS) \
2953     template(java_lang_invoke_AdapterMethodHandle,OP_DUP_ARGS) \
2954     template(java_lang_invoke_AdapterMethodHandle,OP_DROP_ARGS) \
2955     template(java_lang_invoke_AdapterMethodHandle,OP_COLLECT_ARGS) \
2956     template(java_lang_invoke_AdapterMethodHandle,OP_SPREAD_ARGS) \
2957       /* hold back this one until JDK stabilizes */ \
2958       /*template(java_lang_invoke_AdapterMethodHandle,CONV_OP_LIMIT)*/  \
2959     template(java_lang_invoke_AdapterMethodHandle,CONV_OP_MASK) \
2960     template(java_lang_invoke_AdapterMethodHandle,CONV_VMINFO_MASK) \
2961     template(java_lang_invoke_AdapterMethodHandle,CONV_VMINFO_SHIFT) \
2962     template(java_lang_invoke_AdapterMethodHandle,CONV_OP_SHIFT) \
2963     template(java_lang_invoke_AdapterMethodHandle,CONV_DEST_TYPE_SHIFT) \
2964     template(java_lang_invoke_AdapterMethodHandle,CONV_SRC_TYPE_SHIFT) \
2965     template(java_lang_invoke_AdapterMethodHandle,CONV_STACK_MOVE_SHIFT) \
2966     template(java_lang_invoke_AdapterMethodHandle,CONV_STACK_MOVE_MASK) \
2967     /*end*/
2968 
2969 #define ONE_PLUS(scope,value) 1+
2970 static const int con_value_count = EACH_NAMED_CON(ONE_PLUS) 0;
2971 #define VALUE_COMMA(scope,value) scope::value,
2972 static const int con_values[con_value_count+1] = { EACH_NAMED_CON(VALUE_COMMA) 0 };
2973 #define STRING_NULL(scope,value) #value "\0"
2974 static const char con_names[] = { EACH_NAMED_CON(STRING_NULL) };
2975 
2976 #undef ONE_PLUS
2977 #undef VALUE_COMMA
2978 #undef STRING_NULL
2979 #undef EACH_NAMED_CON
2980 #endif
2981 
2982 JVM_ENTRY(jint, MHN_getNamedCon(JNIEnv *env, jobject igcls, jint which, jobjectArray box_jh)) {
2983 #ifndef PRODUCT
2984   if (which >= 0 && which < con_value_count) {
2985     int con = con_values[which];
2986     objArrayHandle box(THREAD, (objArrayOop) JNIHandles::resolve(box_jh));
2987     if (box.not_null() && box->klass() == Universe::objectArrayKlassObj() && box->length() > 0) {
2988       const char* str = &con_names[0];
2989       for (int i = 0; i < which; i++)
2990         str += strlen(str) + 1;   // skip name and null
2991       oop name = java_lang_String::create_oop_from_str(str, CHECK_0);  // possible safepoint
2992       box->obj_at_put(0, name);
2993     }
2994     return con;
2995   }
2996 #endif
2997   return 0;
2998 }
2999 JVM_END
3000 
3001 // void init(MemberName self, AccessibleObject ref)
3002 JVM_ENTRY(void, MHN_init_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jobject target_jh)) {
3003   if (mname_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
3004   if (target_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "target is null"); }
3005   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
3006   oop target_oop = JNIHandles::resolve_non_null(target_jh);
3007   MethodHandles::init_MemberName(mname(), target_oop);
3008 }
3009 JVM_END
3010 
3011 // void expand(MemberName self)
3012 JVM_ENTRY(void, MHN_expand_Mem(JNIEnv *env, jobject igcls, jobject mname_jh)) {
3013   if (mname_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
3014   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
3015   MethodHandles::expand_MemberName(mname, 0, CHECK);
3016 }
3017 JVM_END
3018 
3019 // void resolve(MemberName self, Class<?> caller)
3020 JVM_ENTRY(void, MHN_resolve_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jclass caller_jh)) {
3021   if (mname_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
3022   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
3023 
3024   // The trusted Java code that calls this method should already have performed
3025   // access checks on behalf of the given caller.  But, we can verify this.
3026   if (VerifyMethodHandles && caller_jh != NULL) {
3027     klassOop reference_klass = java_lang_Class::as_klassOop(java_lang_invoke_MemberName::clazz(mname()));
3028     if (reference_klass != NULL) {
3029       // Emulate LinkResolver::check_klass_accessability.
3030       klassOop caller = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(caller_jh));
3031       if (!Reflection::verify_class_access(caller,
3032                                            reference_klass,
3033                                            true)) {
3034         THROW_MSG(vmSymbols::java_lang_InternalError(), Klass::cast(reference_klass)->external_name());
3035       }
3036     }
3037   }
3038 
3039   MethodHandles::resolve_MemberName(mname, CHECK);
3040 }
3041 JVM_END
3042 
3043 //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
3044 //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
3045 JVM_ENTRY(jint, MHN_getMembers(JNIEnv *env, jobject igcls,
3046                                jclass clazz_jh, jstring name_jh, jstring sig_jh,
3047                                int mflags, jclass caller_jh, jint skip, jobjectArray results_jh)) {
3048   if (clazz_jh == NULL || results_jh == NULL)  return -1;
3049   KlassHandle k(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(clazz_jh)));
3050 
3051   objArrayHandle results(THREAD, (objArrayOop) JNIHandles::resolve(results_jh));
3052   if (results.is_null() || !results->is_objArray())  return -1;
3053 
3054   TempNewSymbol name = NULL;
3055   TempNewSymbol sig = NULL;
3056   if (name_jh != NULL) {
3057     name = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(name_jh));
3058     if (name == NULL)  return 0; // a match is not possible
3059   }
3060   if (sig_jh != NULL) {
3061     sig = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(sig_jh));
3062     if (sig == NULL)  return 0; // a match is not possible
3063   }
3064 
3065   KlassHandle caller;
3066   if (caller_jh != NULL) {
3067     oop caller_oop = JNIHandles::resolve_non_null(caller_jh);
3068     if (!java_lang_Class::is_instance(caller_oop))  return -1;
3069     caller = KlassHandle(THREAD, java_lang_Class::as_klassOop(caller_oop));
3070   }
3071 
3072   if (name != NULL && sig != NULL && results.not_null()) {
3073     // try a direct resolve
3074     // %%% TO DO
3075   }
3076 
3077   int res = MethodHandles::find_MemberNames(k(), name, sig, mflags,
3078                                             caller(), skip, results());
3079   // TO DO: expand at least some of the MemberNames, to avoid massive callbacks
3080   return res;
3081 }
3082 JVM_END
3083 
3084 methodOop MethodHandles::resolve_raise_exception_method(TRAPS) {
3085   if (_raise_exception_method != NULL) {
3086     // no need to do it twice
3087     return raise_exception_method();
3088   }
3089   // LinkResolver::resolve_invokedynamic can reach this point
3090   // because an invokedynamic has failed very early (7049415)
3091   KlassHandle MHN_klass = SystemDictionaryHandles::MethodHandleNatives_klass();
3092   if (MHN_klass.not_null()) {
3093     TempNewSymbol raiseException_name = SymbolTable::new_symbol("raiseException", CHECK_NULL);
3094     TempNewSymbol raiseException_sig = SymbolTable::new_symbol("(ILjava/lang/Object;Ljava/lang/Object;)V", CHECK_NULL);
3095     methodOop raiseException_method  = instanceKlass::cast(MHN_klass->as_klassOop())
3096                   ->find_method(raiseException_name, raiseException_sig);
3097     if (raiseException_method != NULL && raiseException_method->is_static()) {
3098       return raiseException_method;
3099     }
3100   }
3101   // not found; let the caller deal with it
3102   return NULL;
3103 }
3104 void MethodHandles::raise_exception(int code, oop actual, oop required, TRAPS) {
3105   methodOop raiseException_method = resolve_raise_exception_method(CHECK);
3106   if (raiseException_method != NULL &&
3107       instanceKlass::cast(raiseException_method->method_holder())->is_not_initialized()) {
3108     instanceKlass::cast(raiseException_method->method_holder())->initialize(CHECK);
3109     // it had better be resolved by now, or maybe JSR 292 failed to load
3110     raiseException_method = raise_exception_method();
3111   }
3112   if (raiseException_method == NULL) {
3113     THROW_MSG(vmSymbols::java_lang_InternalError(), "no raiseException method");
3114   }
3115   JavaCallArguments args;
3116   args.push_int(code);
3117   args.push_oop(actual);
3118   args.push_oop(required);
3119   JavaValue result(T_VOID);
3120   JavaCalls::call(&result, raiseException_method, &args, CHECK);
3121 }
3122 
3123 JVM_ENTRY(jobject, MH_invoke_UOE(JNIEnv *env, jobject igmh, jobjectArray igargs)) {
3124     TempNewSymbol UOE_name = SymbolTable::new_symbol("java/lang/UnsupportedOperationException", CHECK_NULL);
3125     THROW_MSG_NULL(UOE_name, "MethodHandle.invoke cannot be invoked reflectively");
3126     return NULL;
3127 }
3128 JVM_END
3129 
3130 JVM_ENTRY(jobject, MH_invokeExact_UOE(JNIEnv *env, jobject igmh, jobjectArray igargs)) {
3131     TempNewSymbol UOE_name = SymbolTable::new_symbol("java/lang/UnsupportedOperationException", CHECK_NULL);
3132     THROW_MSG_NULL(UOE_name, "MethodHandle.invokeExact cannot be invoked reflectively");
3133     return NULL;
3134 }
3135 JVM_END
3136 
3137 
3138 /// JVM_RegisterMethodHandleMethods
3139 
3140 #define LANG "Ljava/lang/"
3141 #define JLINV "Ljava/lang/invoke/"
3142 
3143 #define OBJ   LANG"Object;"
3144 #define CLS   LANG"Class;"
3145 #define STRG  LANG"String;"
3146 #define MT    JLINV"MethodType;"
3147 #define MH    JLINV"MethodHandle;"
3148 #define MEM   JLINV"MemberName;"
3149 #define AMH   JLINV"AdapterMethodHandle;"
3150 #define BMH   JLINV"BoundMethodHandle;"
3151 #define DMH   JLINV"DirectMethodHandle;"
3152 
3153 #define CC (char*)  /*cast a literal from (const char*)*/
3154 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
3155 
3156 // These are the native methods on sun.invoke.MethodHandleNatives.
3157 static JNINativeMethod methods[] = {
3158   // void init(MemberName self, AccessibleObject ref)
3159   {CC"init",                    CC"("AMH""MH"I)V",              FN_PTR(MHN_init_AMH)},
3160   {CC"init",                    CC"("BMH""OBJ"I)V",             FN_PTR(MHN_init_BMH)},
3161   {CC"init",                    CC"("DMH""OBJ"Z"CLS")V",        FN_PTR(MHN_init_DMH)},
3162   {CC"init",                    CC"("MT")V",                    FN_PTR(MHN_init_MT)},
3163   {CC"init",                    CC"("MEM""OBJ")V",              FN_PTR(MHN_init_Mem)},
3164   {CC"expand",                  CC"("MEM")V",                   FN_PTR(MHN_expand_Mem)},
3165   {CC"resolve",                 CC"("MEM""CLS")V",              FN_PTR(MHN_resolve_Mem)},
3166   {CC"getTarget",               CC"("MH"I)"OBJ,                 FN_PTR(MHN_getTarget)},
3167   {CC"getConstant",             CC"(I)I",                       FN_PTR(MHN_getConstant)},
3168   //  static native int getNamedCon(int which, Object[] name)
3169   {CC"getNamedCon",             CC"(I["OBJ")I",                 FN_PTR(MHN_getNamedCon)},
3170   //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
3171   //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
3172   {CC"getMembers",              CC"("CLS""STRG""STRG"I"CLS"I["MEM")I",  FN_PTR(MHN_getMembers)}
3173 };
3174 
3175 static JNINativeMethod invoke_methods[] = {
3176   // void init(MemberName self, AccessibleObject ref)
3177   {CC"invoke",                  CC"(["OBJ")"OBJ,                FN_PTR(MH_invoke_UOE)},
3178   {CC"invokeExact",             CC"(["OBJ")"OBJ,                FN_PTR(MH_invokeExact_UOE)}
3179 };
3180 
3181 // This one function is exported, used by NativeLookup.
3182 
3183 JVM_ENTRY(void, JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass MHN_class)) {
3184   assert(MethodHandles::spot_check_entry_names(), "entry enum is OK");
3185 
3186   if (!EnableInvokeDynamic) {
3187     warning("JSR 292 is disabled in this JVM.  Use -XX:+UnlockDiagnosticVMOptions -XX:+EnableInvokeDynamic to enable.");
3188     return;  // bind nothing
3189   }
3190 
3191   bool enable_MH = true;
3192 
3193   {
3194     ThreadToNativeFromVM ttnfv(thread);
3195 
3196     int status = env->RegisterNatives(MHN_class, methods, sizeof(methods)/sizeof(JNINativeMethod));
3197     if (!env->ExceptionOccurred()) {
3198       const char* L_MH_name = (JLINV "MethodHandle");
3199       const char* MH_name = L_MH_name+1;
3200       jclass MH_class = env->FindClass(MH_name);
3201       status = env->RegisterNatives(MH_class, invoke_methods, sizeof(invoke_methods)/sizeof(JNINativeMethod));
3202     }
3203     if (env->ExceptionOccurred()) {
3204       MethodHandles::set_enabled(false);
3205       warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
3206       enable_MH = false;
3207       env->ExceptionClear();
3208     }
3209   }
3210 
3211   if (enable_MH) {
3212     methodOop raiseException_method = MethodHandles::resolve_raise_exception_method(CHECK);
3213     if (raiseException_method != NULL) {
3214       MethodHandles::set_raise_exception_method(raiseException_method);
3215     } else {
3216       warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
3217       enable_MH = false;
3218     }
3219   }
3220 
3221   if (enable_MH) {
3222     MethodHandles::generate_adapters();
3223     MethodHandles::set_enabled(true);
3224   }
3225 }
3226 JVM_END