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