src/share/vm/prims/methodHandleWalk.cpp

Thu, 02 Jun 2011 21:01:48 -0700

author
coleenp
date
Thu, 02 Jun 2011 21:01:48 -0700
changeset 2947
96c891ebe56a
parent 2937
5ac411b3b8fc
parent 2945
d3b9f2be46ab
child 2956
cfcf2ba8f3eb
permissions
-rw-r--r--

Merge

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

mercurial