src/share/vm/prims/methodHandleWalk.cpp

Fri, 03 Jun 2011 22:31:43 -0700

author
never
date
Fri, 03 Jun 2011 22:31:43 -0700
changeset 2950
cba7b5c2d53f
parent 2937
5ac411b3b8fc
child 2954
f8c9417e3571
permissions
-rw-r--r--

7045514: SPARC assembly code for JSR 292 ricochet frames
Reviewed-by: kvn, jrose

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

mercurial