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 "interpreter/rewriter.hpp"
  27 #include "memory/oopFactory.hpp"
  28 #include "prims/methodHandleWalk.hpp"
  29 
  30 /*
  31  * JSR 292 reference implementation: method handle structure analysis
  32  */
  33 
  34 #ifdef PRODUCT
  35 #define print_method_handle(mh) {}
  36 #else //PRODUCT
  37 extern "C" void print_method_handle(oop mh);
  38 #endif //PRODUCT
  39 
  40 // -----------------------------------------------------------------------------
  41 // MethodHandleChain
  42 
  43 void MethodHandleChain::set_method_handle(Handle mh, TRAPS) {
  44   if (!java_lang_invoke_MethodHandle::is_instance(mh()))  lose("bad method handle", CHECK);
  45 
  46   // set current method handle and unpack partially
  47   _method_handle = mh;
  48   _is_last       = false;
  49   _is_bound      = false;
  50   _arg_slot      = -1;
  51   _arg_type      = T_VOID;
  52   _conversion    = -1;
  53   _last_invoke   = Bytecodes::_nop;  //arbitrary non-garbage
  54 
  55   if (java_lang_invoke_DirectMethodHandle::is_instance(mh())) {
  56     set_last_method(mh(), THREAD);
  57     return;
  58   }
  59   if (java_lang_invoke_AdapterMethodHandle::is_instance(mh())) {
  60     _conversion = AdapterMethodHandle_conversion();
  61     assert(_conversion != -1, "bad conv value");
  62     assert(java_lang_invoke_BoundMethodHandle::is_instance(mh()), "also BMH");
  63   }
  64   if (java_lang_invoke_BoundMethodHandle::is_instance(mh())) {
  65     if (!is_adapter())          // keep AMH and BMH separate in this model
  66       _is_bound = true;
  67     _arg_slot = BoundMethodHandle_vmargslot();
  68     oop target = MethodHandle_vmtarget_oop();
  69     if (!is_bound() || java_lang_invoke_MethodHandle::is_instance(target)) {
  70       _arg_type = compute_bound_arg_type(target, NULL, _arg_slot, CHECK);
  71     } else if (target != NULL && target->is_method()) {
  72       methodOop m = (methodOop) target;
  73       _arg_type = compute_bound_arg_type(NULL, m, _arg_slot, CHECK);
  74       set_last_method(mh(), CHECK);
  75     } else {
  76       _is_bound = false;  // lose!
  77     }
  78   }
  79   if (is_bound() && _arg_type == T_VOID) {
  80     lose("bad vmargslot", CHECK);
  81   }
  82   if (!is_bound() && !is_adapter()) {
  83     lose("unrecognized MH type", CHECK);
  84   }
  85 }
  86 
  87 
  88 void MethodHandleChain::set_last_method(oop target, TRAPS) {
  89   _is_last = true;
  90   KlassHandle receiver_limit; int flags = 0;
  91   _last_method = MethodHandles::decode_method(target, receiver_limit, flags);
  92   if ((flags & MethodHandles::_dmf_has_receiver) == 0)
  93     _last_invoke = Bytecodes::_invokestatic;
  94   else if ((flags & MethodHandles::_dmf_does_dispatch) == 0)
  95     _last_invoke = Bytecodes::_invokespecial;
  96   else if ((flags & MethodHandles::_dmf_from_interface) != 0)
  97     _last_invoke = Bytecodes::_invokeinterface;
  98   else
  99     _last_invoke = Bytecodes::_invokevirtual;
 100 }
 101 
 102 
 103 BasicType MethodHandleChain::compute_bound_arg_type(oop target, methodOop m, int arg_slot, TRAPS) {
 104   // There is no direct indication of whether the argument is primitive or not.
 105   // It is implied by the _vmentry code, and by the MethodType of the target.
 106   BasicType arg_type = T_VOID;
 107   if (target != NULL) {
 108     oop mtype = java_lang_invoke_MethodHandle::type(target);
 109     int arg_num = MethodHandles::argument_slot_to_argnum(mtype, arg_slot);
 110     if (arg_num >= 0) {
 111       oop ptype = java_lang_invoke_MethodType::ptype(mtype, arg_num);
 112       arg_type = java_lang_Class::as_BasicType(ptype);
 113     }
 114   } else if (m != NULL) {
 115     // figure out the argument type from the slot
 116     // FIXME: make this explicit in the MH
 117     int cur_slot = m->size_of_parameters();
 118     if (arg_slot >= cur_slot)
 119       return T_VOID;
 120     if (!m->is_static()) {
 121       cur_slot -= type2size[T_OBJECT];
 122       if (cur_slot == arg_slot)
 123         return T_OBJECT;
 124     }
 125     ResourceMark rm(THREAD);
 126     for (SignatureStream ss(m->signature()); !ss.is_done(); ss.next()) {
 127       BasicType bt = ss.type();
 128       cur_slot -= type2size[bt];
 129       if (cur_slot <= arg_slot) {
 130         if (cur_slot == arg_slot)
 131           arg_type = bt;
 132         break;
 133       }
 134     }
 135   }
 136   if (arg_type == T_ARRAY)
 137     arg_type = T_OBJECT;
 138   return arg_type;
 139 }
 140 
 141 
 142 void MethodHandleChain::lose(const char* msg, TRAPS) {
 143   _lose_message = msg;
 144   if (!THREAD->is_Java_thread() || ((JavaThread*)THREAD)->thread_state() != _thread_in_vm) {
 145     // throw a preallocated exception
 146     THROW_OOP(Universe::virtual_machine_error_instance());
 147   }
 148   THROW_MSG(vmSymbols::java_lang_InternalError(), msg);
 149 }
 150 
 151 
 152 // -----------------------------------------------------------------------------
 153 // MethodHandleWalker
 154 
 155 Bytecodes::Code MethodHandleWalker::conversion_code(BasicType src, BasicType dest) {
 156   if (is_subword_type(src)) {
 157     src = T_INT;          // all subword src types act like int
 158   }
 159   if (src == dest) {
 160     return Bytecodes::_nop;
 161   }
 162 
 163 #define SRC_DEST(s,d) (((int)(s) << 4) + (int)(d))
 164   switch (SRC_DEST(src, dest)) {
 165   case SRC_DEST(T_INT, T_LONG):           return Bytecodes::_i2l;
 166   case SRC_DEST(T_INT, T_FLOAT):          return Bytecodes::_i2f;
 167   case SRC_DEST(T_INT, T_DOUBLE):         return Bytecodes::_i2d;
 168   case SRC_DEST(T_INT, T_BYTE):           return Bytecodes::_i2b;
 169   case SRC_DEST(T_INT, T_CHAR):           return Bytecodes::_i2c;
 170   case SRC_DEST(T_INT, T_SHORT):          return Bytecodes::_i2s;
 171 
 172   case SRC_DEST(T_LONG, T_INT):           return Bytecodes::_l2i;
 173   case SRC_DEST(T_LONG, T_FLOAT):         return Bytecodes::_l2f;
 174   case SRC_DEST(T_LONG, T_DOUBLE):        return Bytecodes::_l2d;
 175 
 176   case SRC_DEST(T_FLOAT, T_INT):          return Bytecodes::_f2i;
 177   case SRC_DEST(T_FLOAT, T_LONG):         return Bytecodes::_f2l;
 178   case SRC_DEST(T_FLOAT, T_DOUBLE):       return Bytecodes::_f2d;
 179 
 180   case SRC_DEST(T_DOUBLE, T_INT):         return Bytecodes::_d2i;
 181   case SRC_DEST(T_DOUBLE, T_LONG):        return Bytecodes::_d2l;
 182   case SRC_DEST(T_DOUBLE, T_FLOAT):       return Bytecodes::_d2f;
 183   }
 184 #undef SRC_DEST
 185 
 186   // cannot do it in one step, or at all
 187   return Bytecodes::_illegal;
 188 }
 189 
 190 
 191 // -----------------------------------------------------------------------------
 192 // MethodHandleWalker::walk
 193 //
 194 MethodHandleWalker::ArgToken
 195 MethodHandleWalker::walk(TRAPS) {
 196   ArgToken empty = ArgToken();  // Empty return value.
 197 
 198   walk_incoming_state(CHECK_(empty));
 199 
 200   for (;;) {
 201     set_method_handle(chain().method_handle_oop());
 202 
 203     assert(_outgoing_argc == argument_count_slow(), "empty slots under control");
 204 
 205     if (chain().is_adapter()) {
 206       int conv_op = chain().adapter_conversion_op();
 207       int arg_slot = chain().adapter_arg_slot();
 208       SlotState* arg_state = slot_state(arg_slot);
 209       if (arg_state == NULL
 210           && conv_op > java_lang_invoke_AdapterMethodHandle::OP_RETYPE_RAW) {
 211         lose("bad argument index", CHECK_(empty));
 212       }
 213 
 214       bool retain_original_args = false;  // used by fold/collect logic
 215 
 216       // perform the adapter action
 217       switch (conv_op) {
 218       case java_lang_invoke_AdapterMethodHandle::OP_RETYPE_ONLY:
 219         // No changes to arguments; pass the bits through.
 220         break;
 221 
 222       case java_lang_invoke_AdapterMethodHandle::OP_RETYPE_RAW: {
 223         // To keep the verifier happy, emit bitwise ("raw") conversions as needed.
 224         // See MethodHandles::same_basic_type_for_arguments for allowed conversions.
 225         Handle incoming_mtype(THREAD, chain().method_type_oop());
 226         Handle outgoing_mtype;
 227         {
 228           oop outgoing_mh_oop = chain().vmtarget_oop();
 229           if (!java_lang_invoke_MethodHandle::is_instance(outgoing_mh_oop))
 230             lose("outgoing target not a MethodHandle", CHECK_(empty));
 231           outgoing_mtype = Handle(THREAD, java_lang_invoke_MethodHandle::type(outgoing_mh_oop));
 232         }
 233 
 234         int nptypes = java_lang_invoke_MethodType::ptype_count(outgoing_mtype());
 235         if (nptypes != java_lang_invoke_MethodType::ptype_count(incoming_mtype()))
 236           lose("incoming and outgoing parameter count do not agree", CHECK_(empty));
 237 
 238         // Argument types.
 239         for (int i = 0, slot = _outgoing.length() - 1; slot >= 0; slot--) {
 240           SlotState* arg_state = slot_state(slot);
 241           if (arg_state->_type == T_VOID)  continue;
 242 
 243           klassOop  src_klass = NULL;
 244           klassOop  dst_klass = NULL;
 245           BasicType src = java_lang_Class::as_BasicType(java_lang_invoke_MethodType::ptype(incoming_mtype(), i), &src_klass);
 246           BasicType dst = java_lang_Class::as_BasicType(java_lang_invoke_MethodType::ptype(outgoing_mtype(), i), &dst_klass);
 247           retype_raw_argument_type(src, dst, slot, CHECK_(empty));
 248           i++;  // We need to skip void slots at the top of the loop.
 249         }
 250 
 251         // Return type.
 252         {
 253           BasicType src = java_lang_Class::as_BasicType(java_lang_invoke_MethodType::rtype(incoming_mtype()));
 254           BasicType dst = java_lang_Class::as_BasicType(java_lang_invoke_MethodType::rtype(outgoing_mtype()));
 255           retype_raw_return_type(src, dst, CHECK_(empty));
 256         }
 257         break;
 258       }
 259 
 260       case java_lang_invoke_AdapterMethodHandle::OP_CHECK_CAST: {
 261         // checkcast the Nth outgoing argument in place
 262         klassOop dest_klass = NULL;
 263         BasicType dest = java_lang_Class::as_BasicType(chain().adapter_arg_oop(), &dest_klass);
 264         assert(dest == T_OBJECT, "");
 265         assert(dest == arg_state->_type, "");
 266         ArgToken arg = arg_state->_arg;
 267         ArgToken new_arg = make_conversion(T_OBJECT, dest_klass, Bytecodes::_checkcast, arg, CHECK_(empty));
 268         assert(!arg.has_index() || arg.index() == new_arg.index(), "should be the same index");
 269         debug_only(dest_klass = (klassOop)badOop);
 270         break;
 271       }
 272 
 273       case java_lang_invoke_AdapterMethodHandle::OP_PRIM_TO_PRIM: {
 274         // i2l, etc., on the Nth outgoing argument in place
 275         BasicType src = chain().adapter_conversion_src_type(),
 276                   dest = chain().adapter_conversion_dest_type();
 277         Bytecodes::Code bc = conversion_code(src, dest);
 278         ArgToken arg = arg_state->_arg;
 279         if (bc == Bytecodes::_nop) {
 280           break;
 281         } else if (bc != Bytecodes::_illegal) {
 282           arg = make_conversion(dest, NULL, bc, arg, CHECK_(empty));
 283         } else if (is_subword_type(dest)) {
 284           bc = conversion_code(src, T_INT);
 285           if (bc != Bytecodes::_illegal) {
 286             arg = make_conversion(dest, NULL, bc, arg, CHECK_(empty));
 287             bc = conversion_code(T_INT, dest);
 288             arg = make_conversion(dest, NULL, bc, arg, CHECK_(empty));
 289           }
 290         }
 291         if (bc == Bytecodes::_illegal) {
 292           lose("bad primitive conversion", CHECK_(empty));
 293         }
 294         change_argument(src, arg_slot, dest, arg);
 295         break;
 296       }
 297 
 298       case java_lang_invoke_AdapterMethodHandle::OP_REF_TO_PRIM: {
 299         // checkcast to wrapper type & call intValue, etc.
 300         BasicType dest = chain().adapter_conversion_dest_type();
 301         ArgToken arg = arg_state->_arg;
 302         arg = make_conversion(T_OBJECT, SystemDictionary::box_klass(dest),
 303                               Bytecodes::_checkcast, arg, CHECK_(empty));
 304         vmIntrinsics::ID unboxer = vmIntrinsics::for_unboxing(dest);
 305         if (unboxer == vmIntrinsics::_none) {
 306           lose("no unboxing method", CHECK_(empty));
 307         }
 308         ArgToken arglist[2];
 309         arglist[0] = arg;         // outgoing 'this'
 310         arglist[1] = ArgToken();  // sentinel
 311         arg = make_invoke(NULL, unboxer, Bytecodes::_invokevirtual, false, 1, &arglist[0], CHECK_(empty));
 312         change_argument(T_OBJECT, arg_slot, dest, arg);
 313         break;
 314       }
 315 
 316       case java_lang_invoke_AdapterMethodHandle::OP_PRIM_TO_REF: {
 317         // call wrapper type.valueOf
 318         BasicType src = chain().adapter_conversion_src_type();
 319         ArgToken arg = arg_state->_arg;
 320         vmIntrinsics::ID boxer = vmIntrinsics::for_boxing(src);
 321         if (boxer == vmIntrinsics::_none) {
 322           lose("no boxing method", CHECK_(empty));
 323         }
 324         ArgToken arglist[2];
 325         arglist[0] = arg;         // outgoing value
 326         arglist[1] = ArgToken();  // sentinel
 327         arg = make_invoke(NULL, boxer, Bytecodes::_invokestatic, false, 1, &arglist[0], CHECK_(empty));
 328         change_argument(src, arg_slot, T_OBJECT, arg);
 329         break;
 330       }
 331 
 332       case java_lang_invoke_AdapterMethodHandle::OP_SWAP_ARGS: {
 333         int dest_arg_slot = chain().adapter_conversion_vminfo();
 334         if (!slot_has_argument(dest_arg_slot)) {
 335           lose("bad swap index", CHECK_(empty));
 336         }
 337         // a simple swap between two arguments
 338         SlotState* dest_arg_state = slot_state(dest_arg_slot);
 339         SlotState temp = (*dest_arg_state);
 340         (*dest_arg_state) = (*arg_state);
 341         (*arg_state) = temp;
 342         break;
 343       }
 344 
 345       case java_lang_invoke_AdapterMethodHandle::OP_ROT_ARGS: {
 346         int dest_arg_slot = chain().adapter_conversion_vminfo();
 347         if (!slot_has_argument(dest_arg_slot) || arg_slot == dest_arg_slot) {
 348           lose("bad rotate index", CHECK_(empty));
 349         }
 350         SlotState* dest_arg_state = slot_state(dest_arg_slot);
 351         // Rotate the source argument (plus following N slots) into the
 352         // position occupied by the dest argument (plus following N slots).
 353         int rotate_count = type2size[dest_arg_state->_type];
 354         // (no other rotate counts are currently supported)
 355         if (arg_slot < dest_arg_slot) {
 356           for (int i = 0; i < rotate_count; i++) {
 357             SlotState temp = _outgoing.at(arg_slot);
 358             _outgoing.remove_at(arg_slot);
 359             _outgoing.insert_before(dest_arg_slot + rotate_count - 1, temp);
 360           }
 361         } else { // arg_slot > dest_arg_slot
 362           for (int i = 0; i < rotate_count; i++) {
 363             SlotState temp = _outgoing.at(arg_slot + rotate_count - 1);
 364             _outgoing.remove_at(arg_slot + rotate_count - 1);
 365             _outgoing.insert_before(dest_arg_slot, temp);
 366           }
 367         }
 368         break;
 369       }
 370 
 371       case java_lang_invoke_AdapterMethodHandle::OP_DUP_ARGS: {
 372         int dup_slots = chain().adapter_conversion_stack_pushes();
 373         if (dup_slots <= 0) {
 374           lose("bad dup count", CHECK_(empty));
 375         }
 376         for (int i = 0; i < dup_slots; i++) {
 377           SlotState* dup = slot_state(arg_slot + 2*i);
 378           if (dup == NULL)              break;  // safety net
 379           if (dup->_type != T_VOID)     _outgoing_argc += 1;
 380           _outgoing.insert_before(i, (*dup));
 381         }
 382         break;
 383       }
 384 
 385       case java_lang_invoke_AdapterMethodHandle::OP_DROP_ARGS: {
 386         int drop_slots = -chain().adapter_conversion_stack_pushes();
 387         if (drop_slots <= 0) {
 388           lose("bad drop count", CHECK_(empty));
 389         }
 390         for (int i = 0; i < drop_slots; i++) {
 391           SlotState* drop = slot_state(arg_slot);
 392           if (drop == NULL)             break;  // safety net
 393           if (drop->_type != T_VOID)    _outgoing_argc -= 1;
 394           _outgoing.remove_at(arg_slot);
 395         }
 396         break;
 397       }
 398 
 399       case java_lang_invoke_AdapterMethodHandle::OP_FOLD_ARGS:
 400         retain_original_args = true;   // and fall through:
 401       case java_lang_invoke_AdapterMethodHandle::OP_COLLECT_ARGS: {
 402         // call argument MH recursively
 403         //{static int x; if (!x++) print_method_handle(chain().method_handle_oop()); --x;}
 404         Handle recursive_mh(THREAD, chain().adapter_arg_oop());
 405         if (!java_lang_invoke_MethodHandle::is_instance(recursive_mh())) {
 406           lose("recursive target not a MethodHandle", CHECK_(empty));
 407         }
 408         Handle recursive_mtype(THREAD, java_lang_invoke_MethodHandle::type(recursive_mh()));
 409         int argc = java_lang_invoke_MethodType::ptype_count(recursive_mtype());
 410         int coll_slots = java_lang_invoke_MethodHandle::vmslots(recursive_mh());
 411         BasicType rtype = java_lang_Class::as_BasicType(java_lang_invoke_MethodType::rtype(recursive_mtype()));
 412         ArgToken* arglist = NEW_RESOURCE_ARRAY(ArgToken, 1 + argc + 1);  // 1+: mh, +1: sentinel
 413         arglist[0] = make_oop_constant(recursive_mh(), CHECK_(empty));
 414         if (arg_slot < 0 || coll_slots < 0 || arg_slot + coll_slots > _outgoing.length()) {
 415           lose("bad fold/collect arg slot", CHECK_(empty));
 416         }
 417         for (int i = 0, slot = arg_slot + coll_slots - 1; slot >= arg_slot; slot--) {
 418           SlotState* arg_state = slot_state(slot);
 419           BasicType  arg_type  = arg_state->_type;
 420           if (arg_type == T_VOID)  continue;
 421           ArgToken arg = _outgoing.at(slot)._arg;
 422           if (i >= argc) { lose("bad fold/collect arg", CHECK_(empty)); }
 423           arglist[1+i] = arg;
 424           if (!retain_original_args)
 425             change_argument(arg_type, slot, T_VOID, ArgToken(tt_void));
 426           i++;
 427         }
 428         arglist[1+argc] = ArgToken();  // sentinel
 429         oop invoker = java_lang_invoke_MethodTypeForm::vmlayout(
 430                           java_lang_invoke_MethodType::form(recursive_mtype()) );
 431         if (invoker == NULL || !invoker->is_method()) {
 432           lose("bad vmlayout slot", CHECK_(empty));
 433         }
 434         // FIXME: consider inlining the invokee at the bytecode level
 435         ArgToken ret = make_invoke(methodOop(invoker), vmIntrinsics::_none,
 436                                    Bytecodes::_invokevirtual, false, 1+argc, &arglist[0], CHECK_(empty));
 437         DEBUG_ONLY(invoker = NULL);
 438         if (rtype == T_OBJECT) {
 439           klassOop rklass = java_lang_Class::as_klassOop( java_lang_invoke_MethodType::rtype(recursive_mtype()) );
 440           if (rklass != SystemDictionary::Object_klass() &&
 441               !Klass::cast(rklass)->is_interface()) {
 442             // preserve type safety
 443             ret = make_conversion(T_OBJECT, rklass, Bytecodes::_checkcast, ret, CHECK_(empty));
 444           }
 445         }
 446         if (rtype != T_VOID) {
 447           int ret_slot = arg_slot + (retain_original_args ? coll_slots : 0);
 448           change_argument(T_VOID, ret_slot, rtype, ret);
 449         }
 450         break;
 451       }
 452 
 453       case java_lang_invoke_AdapterMethodHandle::OP_SPREAD_ARGS: {
 454         klassOop array_klass_oop = NULL;
 455         BasicType array_type = java_lang_Class::as_BasicType(chain().adapter_arg_oop(),
 456                                                              &array_klass_oop);
 457         assert(array_type == T_OBJECT, "");
 458         assert(Klass::cast(array_klass_oop)->oop_is_array(), "");
 459         arrayKlassHandle array_klass(THREAD, array_klass_oop);
 460         debug_only(array_klass_oop = (klassOop)badOop);
 461 
 462         klassOop element_klass_oop = NULL;
 463         BasicType element_type = java_lang_Class::as_BasicType(array_klass->component_mirror(),
 464                                                                &element_klass_oop);
 465         KlassHandle element_klass(THREAD, element_klass_oop);
 466         debug_only(element_klass_oop = (klassOop)badOop);
 467 
 468         // Fetch the argument, which we will cast to the required array type.
 469         assert(arg_state->_type == T_OBJECT, "");
 470         ArgToken array_arg = arg_state->_arg;
 471         array_arg = make_conversion(T_OBJECT, array_klass(), Bytecodes::_checkcast, array_arg, CHECK_(empty));
 472         change_argument(T_OBJECT, arg_slot, T_VOID, ArgToken(tt_void));
 473 
 474         // Check the required length.
 475         int spread_slots = 1 + chain().adapter_conversion_stack_pushes();
 476         int spread_length = spread_slots;
 477         if (type2size[element_type] == 2) {
 478           if (spread_slots % 2 != 0)  spread_slots = -1;  // force error
 479           spread_length = spread_slots / 2;
 480         }
 481         if (spread_slots < 0) {
 482           lose("bad spread length", CHECK_(empty));
 483         }
 484 
 485         jvalue   length_jvalue;  length_jvalue.i = spread_length;
 486         ArgToken length_arg = make_prim_constant(T_INT, &length_jvalue, CHECK_(empty));
 487         // Call a built-in method known to the JVM to validate the length.
 488         ArgToken arglist[3];
 489         arglist[0] = array_arg;   // value to check
 490         arglist[1] = length_arg;  // length to check
 491         arglist[2] = ArgToken();  // sentinel
 492         make_invoke(NULL, vmIntrinsics::_checkSpreadArgument,
 493                     Bytecodes::_invokestatic, false, 2, &arglist[0], CHECK_(empty));
 494 
 495         // Spread out the array elements.
 496         Bytecodes::Code aload_op = Bytecodes::_nop;
 497         switch (element_type) {
 498         case T_INT:       aload_op = Bytecodes::_iaload; break;
 499         case T_LONG:      aload_op = Bytecodes::_laload; break;
 500         case T_FLOAT:     aload_op = Bytecodes::_faload; break;
 501         case T_DOUBLE:    aload_op = Bytecodes::_daload; break;
 502         case T_OBJECT:    aload_op = Bytecodes::_aaload; break;
 503         case T_BOOLEAN:   // fall through:
 504         case T_BYTE:      aload_op = Bytecodes::_baload; break;
 505         case T_CHAR:      aload_op = Bytecodes::_caload; break;
 506         case T_SHORT:     aload_op = Bytecodes::_saload; break;
 507         default:          lose("primitive array NYI", CHECK_(empty));
 508         }
 509         int ap = arg_slot;
 510         for (int i = 0; i < spread_length; i++) {
 511           jvalue   offset_jvalue;  offset_jvalue.i = i;
 512           ArgToken offset_arg = make_prim_constant(T_INT, &offset_jvalue, CHECK_(empty));
 513           ArgToken element_arg = make_fetch(element_type, element_klass(), aload_op, array_arg, offset_arg, CHECK_(empty));
 514           change_argument(T_VOID, ap, element_type, element_arg);
 515           ap += type2size[element_type];
 516         }
 517         break;
 518       }
 519 
 520       default:
 521         lose("bad adapter conversion", CHECK_(empty));
 522         break;
 523       }
 524     }
 525 
 526     if (chain().is_bound()) {
 527       // push a new argument
 528       BasicType arg_type  = chain().bound_arg_type();
 529       jint      arg_slot  = chain().bound_arg_slot();
 530       oop       arg_oop   = chain().bound_arg_oop();
 531       ArgToken  arg;
 532       if (arg_type == T_OBJECT) {
 533         arg = make_oop_constant(arg_oop, CHECK_(empty));
 534       } else {
 535         jvalue arg_value;
 536         BasicType bt = java_lang_boxing_object::get_value(arg_oop, &arg_value);
 537         if (bt == arg_type) {
 538           arg = make_prim_constant(arg_type, &arg_value, CHECK_(empty));
 539         } else {
 540           lose("bad bound value", CHECK_(empty));
 541         }
 542       }
 543       DEBUG_ONLY(arg_oop = badOop);
 544       change_argument(T_VOID, arg_slot, arg_type, arg);
 545     }
 546 
 547     // this test must come after the body of the loop
 548     if (!chain().is_last()) {
 549       chain().next(CHECK_(empty));
 550     } else {
 551       break;
 552     }
 553   }
 554 
 555   // finish the sequence with a tail-call to the ultimate target
 556   // parameters are passed in logical order (recv 1st), not slot order
 557   ArgToken* arglist = NEW_RESOURCE_ARRAY(ArgToken, _outgoing.length() + 1);
 558   int ap = 0;
 559   for (int i = _outgoing.length() - 1; i >= 0; i--) {
 560     SlotState* arg_state = slot_state(i);
 561     if (arg_state->_type == T_VOID)  continue;
 562     arglist[ap++] = _outgoing.at(i)._arg;
 563   }
 564   assert(ap == _outgoing_argc, "");
 565   arglist[ap] = ArgToken();  // add a sentinel, for the sake of asserts
 566   return make_invoke(chain().last_method_oop(),
 567                      vmIntrinsics::_none,
 568                      chain().last_invoke_code(), true,
 569                      ap, arglist, THREAD);
 570 }
 571 
 572 
 573 // -----------------------------------------------------------------------------
 574 // MethodHandleWalker::walk_incoming_state
 575 //
 576 void MethodHandleWalker::walk_incoming_state(TRAPS) {
 577   Handle mtype(THREAD, chain().method_type_oop());
 578   int nptypes = java_lang_invoke_MethodType::ptype_count(mtype());
 579   _outgoing_argc = nptypes;
 580   int argp = nptypes - 1;
 581   if (argp >= 0) {
 582     _outgoing.at_grow(argp, make_state(T_VOID, ArgToken(tt_void))); // presize
 583   }
 584   for (int i = 0; i < nptypes; i++) {
 585     klassOop  arg_type_klass = NULL;
 586     BasicType arg_type = java_lang_Class::as_BasicType(java_lang_invoke_MethodType::ptype(mtype(), i), &arg_type_klass);
 587     int index = new_local_index(arg_type);
 588     ArgToken arg = make_parameter(arg_type, arg_type_klass, index, CHECK);
 589     DEBUG_ONLY(arg_type_klass = (klassOop) NULL);
 590     _outgoing.at_put(argp, make_state(arg_type, arg));
 591     if (type2size[arg_type] == 2) {
 592       // add the extra slot, so we can model the JVM stack
 593       _outgoing.insert_before(argp+1, make_state(T_VOID, ArgToken(tt_void)));
 594     }
 595     --argp;
 596   }
 597   // call make_parameter at the end of the list for the return type
 598   klassOop  ret_type_klass = NULL;
 599   BasicType ret_type = java_lang_Class::as_BasicType(java_lang_invoke_MethodType::rtype(mtype()), &ret_type_klass);
 600   ArgToken  ret = make_parameter(ret_type, ret_type_klass, -1, CHECK);
 601   // ignore ret; client can catch it if needed
 602 }
 603 
 604 
 605 // -----------------------------------------------------------------------------
 606 // MethodHandleWalker::change_argument
 607 //
 608 // This is messy because some kinds of arguments are paired with
 609 // companion slots containing an empty value.
 610 void MethodHandleWalker::change_argument(BasicType old_type, int slot, BasicType new_type,
 611                                          const ArgToken& new_arg) {
 612   int old_size = type2size[old_type];
 613   int new_size = type2size[new_type];
 614   if (old_size == new_size) {
 615     // simple case first
 616     _outgoing.at_put(slot, make_state(new_type, new_arg));
 617   } else if (old_size > new_size) {
 618     for (int i = old_size - 1; i >= new_size; i--) {
 619       assert((i != 0) == (_outgoing.at(slot + i)._type == T_VOID), "");
 620       _outgoing.remove_at(slot + i);
 621     }
 622     if (new_size > 0)
 623       _outgoing.at_put(slot, make_state(new_type, new_arg));
 624     else
 625       _outgoing_argc -= 1;      // deleted a real argument
 626   } else {
 627     for (int i = old_size; i < new_size; i++) {
 628       _outgoing.insert_before(slot + i, make_state(T_VOID, ArgToken(tt_void)));
 629     }
 630     _outgoing.at_put(slot, make_state(new_type, new_arg));
 631     if (old_size == 0)
 632       _outgoing_argc += 1;      // inserted a real argument
 633   }
 634 }
 635 
 636 
 637 #ifdef ASSERT
 638 int MethodHandleWalker::argument_count_slow() {
 639   int args_seen = 0;
 640   for (int i = _outgoing.length() - 1; i >= 0; i--) {
 641     if (_outgoing.at(i)._type != T_VOID) {
 642       ++args_seen;
 643     }
 644   }
 645   return args_seen;
 646 }
 647 #endif
 648 
 649 
 650 // -----------------------------------------------------------------------------
 651 // MethodHandleWalker::retype_raw_conversion
 652 //
 653 // Do the raw retype conversions for OP_RETYPE_RAW.
 654 void MethodHandleWalker::retype_raw_conversion(BasicType src, BasicType dst, bool for_return, int slot, TRAPS) {
 655   if (src != dst) {
 656     if (MethodHandles::same_basic_type_for_returns(src, dst, /*raw*/ true)) {
 657       if (MethodHandles::is_float_fixed_reinterpretation_cast(src, dst)) {
 658         if (for_return)  Untested("MHW return raw conversion");  // still untested
 659         vmIntrinsics::ID iid = vmIntrinsics::for_raw_conversion(src, dst);
 660         if (iid == vmIntrinsics::_none) {
 661           lose("no raw conversion method", CHECK);
 662         }
 663         ArgToken arglist[2];
 664         if (!for_return) {
 665           // argument type conversion
 666           ArgToken arg = _outgoing.at(slot)._arg;
 667           assert(arg.token_type() >= tt_symbolic || src == arg.basic_type(), "sanity");
 668           arglist[0] = arg;         // outgoing 'this'
 669           arglist[1] = ArgToken();  // sentinel
 670           arg = make_invoke(NULL, iid, Bytecodes::_invokestatic, false, 1, &arglist[0], CHECK);
 671           change_argument(src, slot, dst, arg);
 672         } else {
 673           // return type conversion
 674           klassOop arg_klass = NULL;
 675           arglist[0] = make_parameter(src, arg_klass, -1, CHECK);  // return value
 676           arglist[1] = ArgToken();                                 // sentinel
 677           (void) make_invoke(NULL, iid, Bytecodes::_invokestatic, false, 1, &arglist[0], CHECK);
 678         }
 679       } else {
 680         // Nothing to do.
 681       }
 682     } else if (src == T_OBJECT && is_java_primitive(dst)) {
 683       // ref-to-prim: discard ref, push zero
 684       lose("requested ref-to-prim conversion not expected", CHECK);
 685     } else {
 686       lose("requested raw conversion not allowed", CHECK);
 687     }
 688   }
 689 }
 690 
 691 
 692 // -----------------------------------------------------------------------------
 693 // MethodHandleCompiler
 694 
 695 MethodHandleCompiler::MethodHandleCompiler(Handle root, Symbol* name, Symbol* signature, int invoke_count, bool is_invokedynamic, TRAPS)
 696   : MethodHandleWalker(root, is_invokedynamic, THREAD),
 697     _invoke_count(invoke_count),
 698     _thread(THREAD),
 699     _bytecode(THREAD, 50),
 700     _constants(THREAD, 10),
 701     _cur_stack(0),
 702     _max_stack(0),
 703     _rtype(T_ILLEGAL)
 704 {
 705 
 706   // Element zero is always the null constant.
 707   (void) _constants.append(NULL);
 708 
 709   // Set name and signature index.
 710   _name_index      = cpool_symbol_put(name);
 711   _signature_index = cpool_symbol_put(signature);
 712 
 713   // Get return type klass.
 714   Handle first_mtype(THREAD, chain().method_type_oop());
 715   // _rklass is NULL for primitives.
 716   _rtype = java_lang_Class::as_BasicType(java_lang_invoke_MethodType::rtype(first_mtype()), &_rklass);
 717   if (_rtype == T_ARRAY)  _rtype = T_OBJECT;
 718 
 719   ArgumentSizeComputer args(signature);
 720   int params = args.size() + 1;  // Incoming arguments plus receiver.
 721   _num_params = for_invokedynamic() ? params - 1 : params;  // XXX Check if callee is static?
 722 }
 723 
 724 
 725 // -----------------------------------------------------------------------------
 726 // MethodHandleCompiler::compile
 727 //
 728 // Compile this MethodHandle into a bytecode adapter and return a
 729 // methodOop.
 730 methodHandle MethodHandleCompiler::compile(TRAPS) {
 731   assert(_thread == THREAD, "must be same thread");
 732   methodHandle nullHandle;
 733   (void) walk(CHECK_(nullHandle));
 734   return get_method_oop(CHECK_(nullHandle));
 735 }
 736 
 737 
 738 void MethodHandleCompiler::emit_bc(Bytecodes::Code op, int index, int args_size) {
 739   Bytecodes::check(op);  // Are we legal?
 740 
 741   switch (op) {
 742   // b
 743   case Bytecodes::_aconst_null:
 744   case Bytecodes::_iconst_m1:
 745   case Bytecodes::_iconst_0:
 746   case Bytecodes::_iconst_1:
 747   case Bytecodes::_iconst_2:
 748   case Bytecodes::_iconst_3:
 749   case Bytecodes::_iconst_4:
 750   case Bytecodes::_iconst_5:
 751   case Bytecodes::_lconst_0:
 752   case Bytecodes::_lconst_1:
 753   case Bytecodes::_fconst_0:
 754   case Bytecodes::_fconst_1:
 755   case Bytecodes::_fconst_2:
 756   case Bytecodes::_dconst_0:
 757   case Bytecodes::_dconst_1:
 758   case Bytecodes::_iload_0:
 759   case Bytecodes::_iload_1:
 760   case Bytecodes::_iload_2:
 761   case Bytecodes::_iload_3:
 762   case Bytecodes::_lload_0:
 763   case Bytecodes::_lload_1:
 764   case Bytecodes::_lload_2:
 765   case Bytecodes::_lload_3:
 766   case Bytecodes::_fload_0:
 767   case Bytecodes::_fload_1:
 768   case Bytecodes::_fload_2:
 769   case Bytecodes::_fload_3:
 770   case Bytecodes::_dload_0:
 771   case Bytecodes::_dload_1:
 772   case Bytecodes::_dload_2:
 773   case Bytecodes::_dload_3:
 774   case Bytecodes::_aload_0:
 775   case Bytecodes::_aload_1:
 776   case Bytecodes::_aload_2:
 777   case Bytecodes::_aload_3:
 778   case Bytecodes::_istore_0:
 779   case Bytecodes::_istore_1:
 780   case Bytecodes::_istore_2:
 781   case Bytecodes::_istore_3:
 782   case Bytecodes::_lstore_0:
 783   case Bytecodes::_lstore_1:
 784   case Bytecodes::_lstore_2:
 785   case Bytecodes::_lstore_3:
 786   case Bytecodes::_fstore_0:
 787   case Bytecodes::_fstore_1:
 788   case Bytecodes::_fstore_2:
 789   case Bytecodes::_fstore_3:
 790   case Bytecodes::_dstore_0:
 791   case Bytecodes::_dstore_1:
 792   case Bytecodes::_dstore_2:
 793   case Bytecodes::_dstore_3:
 794   case Bytecodes::_astore_0:
 795   case Bytecodes::_astore_1:
 796   case Bytecodes::_astore_2:
 797   case Bytecodes::_astore_3:
 798   case Bytecodes::_iand:
 799   case Bytecodes::_i2l:
 800   case Bytecodes::_i2f:
 801   case Bytecodes::_i2d:
 802   case Bytecodes::_i2b:
 803   case Bytecodes::_i2c:
 804   case Bytecodes::_i2s:
 805   case Bytecodes::_l2i:
 806   case Bytecodes::_l2f:
 807   case Bytecodes::_l2d:
 808   case Bytecodes::_f2i:
 809   case Bytecodes::_f2l:
 810   case Bytecodes::_f2d:
 811   case Bytecodes::_d2i:
 812   case Bytecodes::_d2l:
 813   case Bytecodes::_d2f:
 814   case Bytecodes::_iaload:
 815   case Bytecodes::_laload:
 816   case Bytecodes::_faload:
 817   case Bytecodes::_daload:
 818   case Bytecodes::_aaload:
 819   case Bytecodes::_baload:
 820   case Bytecodes::_caload:
 821   case Bytecodes::_saload:
 822   case Bytecodes::_ireturn:
 823   case Bytecodes::_lreturn:
 824   case Bytecodes::_freturn:
 825   case Bytecodes::_dreturn:
 826   case Bytecodes::_areturn:
 827   case Bytecodes::_return:
 828     assert(Bytecodes::format_bits(op, false) == Bytecodes::_fmt_b, "wrong bytecode format");
 829     _bytecode.push(op);
 830     break;
 831 
 832   // bi
 833   case Bytecodes::_ldc:
 834     assert(Bytecodes::format_bits(op, false) == (Bytecodes::_fmt_b|Bytecodes::_fmt_has_k), "wrong bytecode format");
 835     if (index == (index & 0xff)) {
 836       _bytecode.push(op);
 837       _bytecode.push(index);
 838     } else {
 839       _bytecode.push(Bytecodes::_ldc_w);
 840       _bytecode.push(index >> 8);
 841       _bytecode.push(index);
 842     }
 843     break;
 844 
 845   case Bytecodes::_iload:
 846   case Bytecodes::_lload:
 847   case Bytecodes::_fload:
 848   case Bytecodes::_dload:
 849   case Bytecodes::_aload:
 850   case Bytecodes::_istore:
 851   case Bytecodes::_lstore:
 852   case Bytecodes::_fstore:
 853   case Bytecodes::_dstore:
 854   case Bytecodes::_astore:
 855     assert(Bytecodes::format_bits(op, false) == Bytecodes::_fmt_bi, "wrong bytecode format");
 856     if (index == (index & 0xff)) {
 857       _bytecode.push(op);
 858       _bytecode.push(index);
 859     } else {
 860       // doesn't fit in a u2
 861       _bytecode.push(Bytecodes::_wide);
 862       _bytecode.push(op);
 863       _bytecode.push(index >> 8);
 864       _bytecode.push(index);
 865     }
 866     break;
 867 
 868   // bkk
 869   case Bytecodes::_ldc_w:
 870   case Bytecodes::_ldc2_w:
 871   case Bytecodes::_checkcast:
 872     assert(Bytecodes::format_bits(op, false) == Bytecodes::_fmt_bkk, "wrong bytecode format");
 873     assert((unsigned short) index == index, "index does not fit in 16-bit");
 874     _bytecode.push(op);
 875     _bytecode.push(index >> 8);
 876     _bytecode.push(index);
 877     break;
 878 
 879   // bJJ
 880   case Bytecodes::_invokestatic:
 881   case Bytecodes::_invokespecial:
 882   case Bytecodes::_invokevirtual:
 883     assert(Bytecodes::format_bits(op, false) == Bytecodes::_fmt_bJJ, "wrong bytecode format");
 884     assert((unsigned short) index == index, "index does not fit in 16-bit");
 885     _bytecode.push(op);
 886     _bytecode.push(index >> 8);
 887     _bytecode.push(index);
 888     break;
 889 
 890   case Bytecodes::_invokeinterface:
 891     assert(Bytecodes::format_bits(op, false) == Bytecodes::_fmt_bJJ, "wrong bytecode format");
 892     assert((unsigned short) index == index, "index does not fit in 16-bit");
 893     assert(args_size > 0, "valid args_size");
 894     _bytecode.push(op);
 895     _bytecode.push(index >> 8);
 896     _bytecode.push(index);
 897     _bytecode.push(args_size);
 898     _bytecode.push(0);
 899     break;
 900 
 901   default:
 902     ShouldNotReachHere();
 903   }
 904 }
 905 
 906 
 907 void MethodHandleCompiler::emit_load(BasicType bt, int index) {
 908   if (index <= 3) {
 909     switch (bt) {
 910     case T_BOOLEAN: case T_BYTE: case T_CHAR: case T_SHORT:
 911     case T_INT:    emit_bc(Bytecodes::cast(Bytecodes::_iload_0 + index)); break;
 912     case T_LONG:   emit_bc(Bytecodes::cast(Bytecodes::_lload_0 + index)); break;
 913     case T_FLOAT:  emit_bc(Bytecodes::cast(Bytecodes::_fload_0 + index)); break;
 914     case T_DOUBLE: emit_bc(Bytecodes::cast(Bytecodes::_dload_0 + index)); break;
 915     case T_OBJECT: emit_bc(Bytecodes::cast(Bytecodes::_aload_0 + index)); break;
 916     default:
 917       ShouldNotReachHere();
 918     }
 919   }
 920   else {
 921     switch (bt) {
 922     case T_BOOLEAN: case T_BYTE: case T_CHAR: case T_SHORT:
 923     case T_INT:    emit_bc(Bytecodes::_iload, index); break;
 924     case T_LONG:   emit_bc(Bytecodes::_lload, index); break;
 925     case T_FLOAT:  emit_bc(Bytecodes::_fload, index); break;
 926     case T_DOUBLE: emit_bc(Bytecodes::_dload, index); break;
 927     case T_OBJECT: emit_bc(Bytecodes::_aload, index); break;
 928     default:
 929       ShouldNotReachHere();
 930     }
 931   }
 932   stack_push(bt);
 933 }
 934 
 935 void MethodHandleCompiler::emit_store(BasicType bt, int index) {
 936   if (index <= 3) {
 937     switch (bt) {
 938     case T_BOOLEAN: case T_BYTE: case T_CHAR: case T_SHORT:
 939     case T_INT:    emit_bc(Bytecodes::cast(Bytecodes::_istore_0 + index)); break;
 940     case T_LONG:   emit_bc(Bytecodes::cast(Bytecodes::_lstore_0 + index)); break;
 941     case T_FLOAT:  emit_bc(Bytecodes::cast(Bytecodes::_fstore_0 + index)); break;
 942     case T_DOUBLE: emit_bc(Bytecodes::cast(Bytecodes::_dstore_0 + index)); break;
 943     case T_OBJECT: emit_bc(Bytecodes::cast(Bytecodes::_astore_0 + index)); break;
 944     default:
 945       ShouldNotReachHere();
 946     }
 947   }
 948   else {
 949     switch (bt) {
 950     case T_BOOLEAN: case T_BYTE: case T_CHAR: case T_SHORT:
 951     case T_INT:    emit_bc(Bytecodes::_istore, index); break;
 952     case T_LONG:   emit_bc(Bytecodes::_lstore, index); break;
 953     case T_FLOAT:  emit_bc(Bytecodes::_fstore, index); break;
 954     case T_DOUBLE: emit_bc(Bytecodes::_dstore, index); break;
 955     case T_OBJECT: emit_bc(Bytecodes::_astore, index); break;
 956     default:
 957       ShouldNotReachHere();
 958     }
 959   }
 960   stack_pop(bt);
 961 }
 962 
 963 
 964 void MethodHandleCompiler::emit_load_constant(ArgToken arg) {
 965   BasicType bt = arg.basic_type();
 966   switch (bt) {
 967   case T_INT: {
 968     jint value = arg.get_jint();
 969     if (-1 <= value && value <= 5)
 970       emit_bc(Bytecodes::cast(Bytecodes::_iconst_0 + value));
 971     else
 972       emit_bc(Bytecodes::_ldc, cpool_int_put(value));
 973     break;
 974   }
 975   case T_LONG: {
 976     jlong value = arg.get_jlong();
 977     if (0 <= value && value <= 1)
 978       emit_bc(Bytecodes::cast(Bytecodes::_lconst_0 + (int) value));
 979     else
 980       emit_bc(Bytecodes::_ldc2_w, cpool_long_put(value));
 981     break;
 982   }
 983   case T_FLOAT: {
 984     jfloat value  = arg.get_jfloat();
 985     if (value == 0.0 || value == 1.0 || value == 2.0)
 986       emit_bc(Bytecodes::cast(Bytecodes::_fconst_0 + (int) value));
 987     else
 988       emit_bc(Bytecodes::_ldc, cpool_float_put(value));
 989     break;
 990   }
 991   case T_DOUBLE: {
 992     jdouble value = arg.get_jdouble();
 993     if (value == 0.0 || value == 1.0)
 994       emit_bc(Bytecodes::cast(Bytecodes::_dconst_0 + (int) value));
 995     else
 996       emit_bc(Bytecodes::_ldc2_w, cpool_double_put(value));
 997     break;
 998   }
 999   case T_OBJECT: {
1000     Handle value = arg.object();
1001     if (value.is_null())
1002       emit_bc(Bytecodes::_aconst_null);
1003     else
1004       emit_bc(Bytecodes::_ldc, cpool_object_put(value));
1005     break;
1006   }
1007   default:
1008     ShouldNotReachHere();
1009   }
1010   stack_push(bt);
1011 }
1012 
1013 
1014 MethodHandleWalker::ArgToken
1015 MethodHandleCompiler::make_conversion(BasicType type, klassOop tk, Bytecodes::Code op,
1016                                       const ArgToken& src, TRAPS) {
1017 
1018   BasicType srctype = src.basic_type();
1019   TokenType tt = src.token_type();
1020   int index = -1;
1021 
1022   switch (op) {
1023   case Bytecodes::_i2l:
1024   case Bytecodes::_i2f:
1025   case Bytecodes::_i2d:
1026   case Bytecodes::_i2b:
1027   case Bytecodes::_i2c:
1028   case Bytecodes::_i2s:
1029 
1030   case Bytecodes::_l2i:
1031   case Bytecodes::_l2f:
1032   case Bytecodes::_l2d:
1033 
1034   case Bytecodes::_f2i:
1035   case Bytecodes::_f2l:
1036   case Bytecodes::_f2d:
1037 
1038   case Bytecodes::_d2i:
1039   case Bytecodes::_d2l:
1040   case Bytecodes::_d2f:
1041     if (tt == tt_constant) {
1042       emit_load_constant(src);
1043     } else {
1044       emit_load(srctype, src.index());
1045     }
1046     stack_pop(srctype);  // pop the src type
1047     emit_bc(op);
1048     stack_push(type);    // push the dest value
1049     if (tt != tt_constant)
1050       index = src.index();
1051     if (srctype != type || index == -1)
1052       index = new_local_index(type);
1053     emit_store(type, index);
1054     break;
1055 
1056   case Bytecodes::_checkcast:
1057     if (tt == tt_constant) {
1058       emit_load_constant(src);
1059     } else {
1060       emit_load(srctype, src.index());
1061       index = src.index();
1062     }
1063     emit_bc(op, cpool_klass_put(tk));
1064     if (index == -1)
1065       index = new_local_index(type);
1066     emit_store(srctype, index);
1067     break;
1068 
1069   default:
1070     if (op == Bytecodes::_illegal)
1071       lose("no such primitive conversion", THREAD);
1072     else
1073       lose("bad primitive conversion op", THREAD);
1074     return make_prim_constant(type, &zero_jvalue, THREAD);
1075   }
1076 
1077   return make_parameter(type, tk, index, THREAD);
1078 }
1079 
1080 
1081 // -----------------------------------------------------------------------------
1082 // MethodHandleCompiler
1083 //
1084 
1085 // Values used by the compiler.
1086 jvalue MethodHandleCompiler::zero_jvalue = { 0 };
1087 jvalue MethodHandleCompiler::one_jvalue  = { 1 };
1088 
1089 // Emit bytecodes for the given invoke instruction.
1090 MethodHandleWalker::ArgToken
1091 MethodHandleCompiler::make_invoke(methodOop m, vmIntrinsics::ID iid,
1092                                   Bytecodes::Code op, bool tailcall,
1093                                   int argc, MethodHandleWalker::ArgToken* argv,
1094                                   TRAPS) {
1095   ArgToken zero;
1096   if (m == NULL) {
1097     // Get the intrinsic methodOop.
1098     m = vmIntrinsics::method_for(iid);
1099     if (m == NULL) {
1100       lose(vmIntrinsics::name_at(iid), CHECK_(zero));
1101     }
1102   }
1103 
1104   klassOop klass     = m->method_holder();
1105   Symbol*  name      = m->name();
1106   Symbol*  signature = m->signature();
1107 
1108   // Count the number of arguments, not the size
1109   ArgumentCount asc(signature);
1110   assert(argc == asc.size() + ((op == Bytecodes::_invokestatic || op == Bytecodes::_invokedynamic) ? 0 : 1),
1111          "argc mismatch");
1112 
1113   if (tailcall) {
1114     // Actually, in order to make these methods more recognizable,
1115     // let's put them in holder class MethodHandle.  That way stack
1116     // walkers and compiler heuristics can recognize them.
1117     _target_klass = SystemDictionary::MethodHandle_klass();
1118   }
1119 
1120   // Inline the method.
1121   InvocationCounter* ic = m->invocation_counter();
1122   ic->set_carry_flag();
1123 
1124   for (int i = 0; i < argc; i++) {
1125     ArgToken arg = argv[i];
1126     TokenType tt = arg.token_type();
1127     BasicType bt = arg.basic_type();
1128 
1129     switch (tt) {
1130     case tt_parameter:
1131     case tt_temporary:
1132       emit_load(bt, arg.index());
1133       break;
1134     case tt_constant:
1135       emit_load_constant(arg);
1136       break;
1137     case tt_illegal:
1138       // Sentinel.
1139       assert(i == (argc - 1), "sentinel must be last entry");
1140       break;
1141     case tt_void:
1142     default:
1143       ShouldNotReachHere();
1144     }
1145   }
1146 
1147   // Populate constant pool.
1148   int name_index          = cpool_symbol_put(name);
1149   int signature_index     = cpool_symbol_put(signature);
1150   int name_and_type_index = cpool_name_and_type_put(name_index, signature_index);
1151   int klass_index         = cpool_klass_put(klass);
1152   int methodref_index     = cpool_methodref_put(klass_index, name_and_type_index);
1153 
1154   // Generate invoke.
1155   switch (op) {
1156   case Bytecodes::_invokestatic:
1157   case Bytecodes::_invokespecial:
1158   case Bytecodes::_invokevirtual:
1159     emit_bc(op, methodref_index);
1160     break;
1161 
1162   case Bytecodes::_invokeinterface: {
1163     ArgumentSizeComputer asc(signature);
1164     emit_bc(op, methodref_index, asc.size() + 1);
1165     break;
1166   }
1167 
1168   default:
1169     ShouldNotReachHere();
1170   }
1171 
1172   // If tailcall, we have walked all the way to a direct method handle.
1173   // Otherwise, make a recursive call to some helper routine.
1174   BasicType rbt = m->result_type();
1175   if (rbt == T_ARRAY)  rbt = T_OBJECT;
1176   stack_push(rbt);  // The return value is already pushed onto the stack.
1177   ArgToken ret;
1178   if (tailcall) {
1179     if (rbt != _rtype) {
1180       if (rbt == T_VOID) {
1181         // push a zero of the right sort
1182         if (_rtype == T_OBJECT) {
1183           zero = make_oop_constant(NULL, CHECK_(zero));
1184         } else {
1185           zero = make_prim_constant(_rtype, &zero_jvalue, CHECK_(zero));
1186         }
1187         emit_load_constant(zero);
1188       } else if (_rtype == T_VOID) {
1189         // We'll emit a _return with something on the stack.
1190         // It's OK to ignore what's on the stack.
1191       } else if (rbt == T_INT && is_subword_type(_rtype)) {
1192         // Convert value to match return type.
1193         switch (_rtype) {
1194         case T_BOOLEAN: {
1195           // boolean is treated as a one-bit unsigned integer.
1196           // Cf. API documentation: java/lang/invoke/MethodHandles.html#explicitCastArguments
1197           ArgToken one = make_prim_constant(T_INT, &one_jvalue, CHECK_(zero));
1198           emit_load_constant(one);
1199           emit_bc(Bytecodes::_iand);
1200           break;
1201         }
1202         case T_BYTE:    emit_bc(Bytecodes::_i2b); break;
1203         case T_CHAR:    emit_bc(Bytecodes::_i2c); break;
1204         case T_SHORT:   emit_bc(Bytecodes::_i2s); break;
1205         default: ShouldNotReachHere();
1206         }
1207       } else if (is_subword_type(rbt) && (is_subword_type(_rtype) || (_rtype == T_INT))) {
1208         // The subword type was returned as an int and will be passed
1209         // on as an int.
1210       } else {
1211         lose("unknown conversion", CHECK_(zero));
1212       }
1213     }
1214     switch (_rtype) {
1215     case T_BOOLEAN: case T_BYTE: case T_CHAR: case T_SHORT:
1216     case T_INT:    emit_bc(Bytecodes::_ireturn); break;
1217     case T_LONG:   emit_bc(Bytecodes::_lreturn); break;
1218     case T_FLOAT:  emit_bc(Bytecodes::_freturn); break;
1219     case T_DOUBLE: emit_bc(Bytecodes::_dreturn); break;
1220     case T_VOID:   emit_bc(Bytecodes::_return);  break;
1221     case T_OBJECT:
1222       if (_rklass.not_null() && _rklass() != SystemDictionary::Object_klass())
1223         emit_bc(Bytecodes::_checkcast, cpool_klass_put(_rklass()));
1224       emit_bc(Bytecodes::_areturn);
1225       break;
1226     default: ShouldNotReachHere();
1227     }
1228     ret = ArgToken();  // Dummy return value.
1229   }
1230   else {
1231     int index = new_local_index(rbt);
1232     switch (rbt) {
1233     case T_BOOLEAN: case T_BYTE: case T_CHAR:  case T_SHORT:
1234     case T_INT:     case T_LONG: case T_FLOAT: case T_DOUBLE:
1235     case T_OBJECT:
1236       emit_store(rbt, index);
1237       ret = ArgToken(tt_temporary, rbt, index);
1238       break;
1239     case T_VOID:
1240       ret = ArgToken(tt_void);
1241       break;
1242     default:
1243       ShouldNotReachHere();
1244     }
1245   }
1246 
1247   return ret;
1248 }
1249 
1250 MethodHandleWalker::ArgToken
1251 MethodHandleCompiler::make_fetch(BasicType type, klassOop tk, Bytecodes::Code op,
1252                                  const MethodHandleWalker::ArgToken& base,
1253                                  const MethodHandleWalker::ArgToken& offset,
1254                                  TRAPS) {
1255   switch (base.token_type()) {
1256     case tt_parameter:
1257     case tt_temporary:
1258       emit_load(base.basic_type(), base.index());
1259       break;
1260     case tt_constant:
1261       emit_load_constant(base);
1262       break;
1263     default:
1264       ShouldNotReachHere();
1265   }
1266   switch (offset.token_type()) {
1267     case tt_parameter:
1268     case tt_temporary:
1269       emit_load(offset.basic_type(), offset.index());
1270       break;
1271     case tt_constant:
1272       emit_load_constant(offset);
1273       break;
1274     default:
1275       ShouldNotReachHere();
1276   }
1277   emit_bc(op);
1278   int index = new_local_index(type);
1279   emit_store(type, index);
1280   return ArgToken(tt_temporary, type, index);
1281 }
1282 
1283 
1284 int MethodHandleCompiler::cpool_primitive_put(BasicType bt, jvalue* con) {
1285   jvalue con_copy;
1286   assert(bt < T_OBJECT, "");
1287   if (type2aelembytes(bt) < jintSize) {
1288     // widen to int
1289     con_copy = (*con);
1290     con = &con_copy;
1291     switch (bt) {
1292     case T_BOOLEAN: con->i = (con->z ? 1 : 0); break;
1293     case T_BYTE:    con->i = con->b;           break;
1294     case T_CHAR:    con->i = con->c;           break;
1295     case T_SHORT:   con->i = con->s;           break;
1296     default: ShouldNotReachHere();
1297     }
1298     bt = T_INT;
1299   }
1300 
1301 //   for (int i = 1, imax = _constants.length(); i < imax; i++) {
1302 //     ConstantValue* con = _constants.at(i);
1303 //     if (con != NULL && con->is_primitive() && con->_type == bt) {
1304 //       bool match = false;
1305 //       switch (type2size[bt]) {
1306 //       case 1:  if (pcon->_value.i == con->i)  match = true;  break;
1307 //       case 2:  if (pcon->_value.j == con->j)  match = true;  break;
1308 //       }
1309 //       if (match)
1310 //         return i;
1311 //     }
1312 //   }
1313   ConstantValue* cv = new ConstantValue(bt, *con);
1314   int index = _constants.append(cv);
1315 
1316   // long and double entries take 2 slots, we add another empty entry.
1317   if (type2size[bt] == 2)
1318     (void) _constants.append(NULL);
1319 
1320   return index;
1321 }
1322 
1323 
1324 constantPoolHandle MethodHandleCompiler::get_constant_pool(TRAPS) const {
1325   constantPoolHandle nullHandle;
1326   constantPoolOop cpool_oop = oopFactory::new_constantPool(_constants.length(),
1327                                                            oopDesc::IsSafeConc,
1328                                                            CHECK_(nullHandle));
1329   constantPoolHandle cpool(THREAD, cpool_oop);
1330 
1331   // Fill the real constant pool skipping the zero element.
1332   for (int i = 1; i < _constants.length(); i++) {
1333     ConstantValue* cv = _constants.at(i);
1334     switch (cv->tag()) {
1335     case JVM_CONSTANT_Utf8:        cpool->symbol_at_put(       i, cv->symbol()                         ); break;
1336     case JVM_CONSTANT_Integer:     cpool->int_at_put(          i, cv->get_jint()                       ); break;
1337     case JVM_CONSTANT_Float:       cpool->float_at_put(        i, cv->get_jfloat()                     ); break;
1338     case JVM_CONSTANT_Long:        cpool->long_at_put(         i, cv->get_jlong()                      ); break;
1339     case JVM_CONSTANT_Double:      cpool->double_at_put(       i, cv->get_jdouble()                    ); break;
1340     case JVM_CONSTANT_Class:       cpool->klass_at_put(        i, cv->klass_oop()                      ); break;
1341     case JVM_CONSTANT_Methodref:   cpool->method_at_put(       i, cv->first_index(), cv->second_index()); break;
1342     case JVM_CONSTANT_NameAndType: cpool->name_and_type_at_put(i, cv->first_index(), cv->second_index()); break;
1343     case JVM_CONSTANT_Object:      cpool->object_at_put(       i, cv->object_oop()                     ); break;
1344     default: ShouldNotReachHere();
1345     }
1346 
1347     switch (cv->tag()) {
1348     case JVM_CONSTANT_Long:
1349     case JVM_CONSTANT_Double:
1350       i++;  // Skip empty entry.
1351       assert(_constants.at(i) == NULL, "empty entry");
1352       break;
1353     }
1354   }
1355 
1356   // Set the constant pool holder to the target method's class.
1357   cpool->set_pool_holder(_target_klass());
1358 
1359   return cpool;
1360 }
1361 
1362 
1363 methodHandle MethodHandleCompiler::get_method_oop(TRAPS) const {
1364   methodHandle empty;
1365   // Create a method that holds the generated bytecode.  invokedynamic
1366   // has no receiver, normal MH calls do.
1367   int flags_bits;
1368   if (for_invokedynamic())
1369     flags_bits = (/*JVM_MH_INVOKE_BITS |*/ JVM_ACC_PUBLIC | JVM_ACC_FINAL | JVM_ACC_SYNTHETIC | JVM_ACC_STATIC);
1370   else
1371     flags_bits = (/*JVM_MH_INVOKE_BITS |*/ JVM_ACC_PUBLIC | JVM_ACC_FINAL | JVM_ACC_SYNTHETIC);
1372 
1373   // Create a new method
1374   methodHandle m;
1375   {
1376     methodOop m_oop = oopFactory::new_method(bytecode_length(),
1377                                              accessFlags_from(flags_bits),
1378                                              0, 0, 0, oopDesc::IsSafeConc, CHECK_(empty));
1379     m = methodHandle(THREAD, m_oop);
1380   }
1381 
1382   constantPoolHandle cpool = get_constant_pool(CHECK_(empty));
1383   m->set_constants(cpool());
1384 
1385   m->set_name_index(_name_index);
1386   m->set_signature_index(_signature_index);
1387 
1388   m->set_code((address) bytecode());
1389 
1390   m->set_max_stack(_max_stack);
1391   m->set_max_locals(max_locals());
1392   m->set_size_of_parameters(_num_params);
1393 
1394   typeArrayHandle exception_handlers(THREAD, Universe::the_empty_int_array());
1395   m->set_exception_table(exception_handlers());
1396 
1397   // Rewrite the method and set up the constant pool cache.
1398   objArrayOop m_array = oopFactory::new_system_objArray(1, CHECK_(empty));
1399   objArrayHandle methods(THREAD, m_array);
1400   methods->obj_at_put(0, m());
1401   Rewriter::rewrite(_target_klass(), cpool, methods, CHECK_(empty));  // Use fake class.
1402 
1403   // Set the invocation counter's count to the invoke count of the
1404   // original call site.
1405   InvocationCounter* ic = m->invocation_counter();
1406   ic->set(InvocationCounter::wait_for_compile, _invoke_count);
1407 
1408   // Create a new MDO
1409   {
1410     methodDataOop mdo = oopFactory::new_methodData(m, CHECK_(empty));
1411     assert(m->method_data() == NULL, "there should not be an MDO yet");
1412     m->set_method_data(mdo);
1413 
1414     // Iterate over all profile data and set the count of the counter
1415     // data entries to the original call site counter.
1416     for (ProfileData* profile_data = mdo->first_data();
1417          mdo->is_valid(profile_data);
1418          profile_data = mdo->next_data(profile_data)) {
1419       if (profile_data->is_CounterData()) {
1420         CounterData* counter_data = profile_data->as_CounterData();
1421         counter_data->set_count(_invoke_count);
1422       }
1423     }
1424   }
1425 
1426 #ifndef PRODUCT
1427   if (TraceMethodHandles) {
1428     m->print();
1429     m->print_codes();
1430   }
1431 #endif //PRODUCT
1432 
1433   assert(m->is_method_handle_adapter(), "must be recognized as an adapter");
1434   return m;
1435 }
1436 
1437 
1438 #ifndef PRODUCT
1439 
1440 // MH printer for debugging.
1441 
1442 class MethodHandlePrinter : public MethodHandleWalker {
1443 private:
1444   outputStream* _out;
1445   bool          _verbose;
1446   int           _temp_num;
1447   int           _param_state;
1448   stringStream  _strbuf;
1449   const char* strbuf() {
1450     const char* s = _strbuf.as_string();
1451     _strbuf.reset();
1452     return s;
1453   }
1454   ArgToken token(const char* str) {
1455     return ArgToken(str);
1456   }
1457   const char* string(ArgToken token) {
1458     return token.str();
1459   }
1460   void start_params() {
1461     _param_state <<= 1;
1462     _out->print("(");
1463   }
1464   void end_params() {
1465     if (_verbose)  _out->print("\n");
1466     _out->print(") => {");
1467     _param_state >>= 1;
1468   }
1469   void put_type_name(BasicType type, klassOop tk, outputStream* s) {
1470     const char* kname = NULL;
1471     if (tk != NULL)
1472       kname = Klass::cast(tk)->external_name();
1473     s->print("%s", (kname != NULL) ? kname : type2name(type));
1474   }
1475   ArgToken maybe_make_temp(const char* statement_op, BasicType type, const char* temp_name) {
1476     const char* value = strbuf();
1477     if (!_verbose)  return token(value);
1478     // make an explicit binding for each separate value
1479     _strbuf.print("%s%d", temp_name, ++_temp_num);
1480     const char* temp = strbuf();
1481     _out->print("\n  %s %s %s = %s;", statement_op, type2name(type), temp, value);
1482     return token(temp);
1483   }
1484 
1485 public:
1486   MethodHandlePrinter(Handle root, bool verbose, outputStream* out, TRAPS)
1487     : MethodHandleWalker(root, false, THREAD),
1488       _out(out),
1489       _verbose(verbose),
1490       _param_state(0),
1491       _temp_num(0)
1492   {
1493     start_params();
1494   }
1495   virtual ArgToken make_parameter(BasicType type, klassOop tk, int argnum, TRAPS) {
1496     if (argnum < 0) {
1497       end_params();
1498       return token("return");
1499     }
1500     if ((_param_state & 1) == 0) {
1501       _param_state |= 1;
1502       _out->print(_verbose ? "\n  " : "");
1503     } else {
1504       _out->print(_verbose ? ",\n  " : ", ");
1505     }
1506     if (argnum >= _temp_num)
1507       _temp_num = argnum;
1508     // generate an argument name
1509     _strbuf.print("a%d", argnum);
1510     const char* arg = strbuf();
1511     put_type_name(type, tk, _out);
1512     _out->print(" %s", arg);
1513     return token(arg);
1514   }
1515   virtual ArgToken make_oop_constant(oop con, TRAPS) {
1516     if (con == NULL)
1517       _strbuf.print("null");
1518     else
1519       con->print_value_on(&_strbuf);
1520     if (_strbuf.size() == 0) {  // yuck
1521       _strbuf.print("(a ");
1522       put_type_name(T_OBJECT, con->klass(), &_strbuf);
1523       _strbuf.print(")");
1524     }
1525     return maybe_make_temp("constant", T_OBJECT, "k");
1526   }
1527   virtual ArgToken make_prim_constant(BasicType type, jvalue* con, TRAPS) {
1528     java_lang_boxing_object::print(type, con, &_strbuf);
1529     return maybe_make_temp("constant", type, "k");
1530   }
1531   void print_bytecode_name(Bytecodes::Code op) {
1532     if (Bytecodes::is_defined(op))
1533       _strbuf.print("%s", Bytecodes::name(op));
1534     else
1535       _strbuf.print("bytecode_%d", (int) op);
1536   }
1537   virtual ArgToken make_conversion(BasicType type, klassOop tk, Bytecodes::Code op, const ArgToken& src, TRAPS) {
1538     print_bytecode_name(op);
1539     _strbuf.print("(%s", string(src));
1540     if (tk != NULL) {
1541       _strbuf.print(", ");
1542       put_type_name(type, tk, &_strbuf);
1543     }
1544     _strbuf.print(")");
1545     return maybe_make_temp("convert", type, "v");
1546   }
1547   virtual ArgToken make_fetch(BasicType type, klassOop tk, Bytecodes::Code op, const ArgToken& base, const ArgToken& offset, TRAPS) {
1548     _strbuf.print("%s(%s, %s", Bytecodes::name(op), string(base), string(offset));
1549     if (tk != NULL) {
1550       _strbuf.print(", ");
1551       put_type_name(type, tk, &_strbuf);
1552     }
1553     _strbuf.print(")");
1554     return maybe_make_temp("fetch", type, "x");
1555   }
1556   virtual ArgToken make_invoke(methodOop m, vmIntrinsics::ID iid,
1557                                Bytecodes::Code op, bool tailcall,
1558                                int argc, ArgToken* argv, TRAPS) {
1559     Symbol* name;
1560     Symbol* sig;
1561     if (m != NULL) {
1562       name = m->name();
1563       sig  = m->signature();
1564     } else {
1565       name = vmSymbols::symbol_at(vmIntrinsics::name_for(iid));
1566       sig  = vmSymbols::symbol_at(vmIntrinsics::signature_for(iid));
1567     }
1568     _strbuf.print("%s %s%s(", Bytecodes::name(op), name->as_C_string(), sig->as_C_string());
1569     for (int i = 0; i < argc; i++) {
1570       _strbuf.print("%s%s", (i > 0 ? ", " : ""), string(argv[i]));
1571     }
1572     _strbuf.print(")");
1573     if (!tailcall) {
1574       BasicType rt = char2type(sig->byte_at(sig->utf8_length()-1));
1575       if (rt == T_ILLEGAL)  rt = T_OBJECT;  // ';' at the end of '(...)L...;'
1576       return maybe_make_temp("invoke", rt, "x");
1577     } else {
1578       const char* ret = strbuf();
1579       _out->print(_verbose ? "\n  return " : " ");
1580       _out->print("%s", ret);
1581       _out->print(_verbose ? "\n}\n" : " }");
1582     }
1583     return ArgToken();
1584   }
1585 
1586   virtual void set_method_handle(oop mh) {
1587     if (WizardMode && Verbose) {
1588       tty->print("\n--- next target: ");
1589       mh->print();
1590     }
1591   }
1592 
1593   static void print(Handle root, bool verbose, outputStream* out, TRAPS) {
1594     ResourceMark rm;
1595     MethodHandlePrinter printer(root, verbose, out, CHECK);
1596     printer.walk(CHECK);
1597     out->print("\n");
1598   }
1599   static void print(Handle root, bool verbose = Verbose, outputStream* out = tty) {
1600     EXCEPTION_MARK;
1601     ResourceMark rm;
1602     MethodHandlePrinter printer(root, verbose, out, THREAD);
1603     if (!HAS_PENDING_EXCEPTION)
1604       printer.walk(THREAD);
1605     if (HAS_PENDING_EXCEPTION) {
1606       oop ex = PENDING_EXCEPTION;
1607       CLEAR_PENDING_EXCEPTION;
1608       out->print(" *** ");
1609       if (printer.lose_message() != NULL)  out->print("%s ", printer.lose_message());
1610       out->print("}");
1611     }
1612     out->print("\n");
1613   }
1614 };
1615 
1616 extern "C"
1617 void print_method_handle(oop mh) {
1618   if (!mh->is_oop()) {
1619     tty->print_cr("*** not a method handle: "PTR_FORMAT, (intptr_t)mh);
1620   } else if (java_lang_invoke_MethodHandle::is_instance(mh)) {
1621     MethodHandlePrinter::print(mh);
1622   } else {
1623     tty->print("*** not a method handle: ");
1624     mh->print();
1625   }
1626 }
1627 
1628 #endif // PRODUCT