methodHandles_x86.cpp 103.7 KB
Newer Older
1
/*
2
 * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
22 23 24
 *
 */

25 26
#include "precompiled.hpp"
#include "interpreter/interpreter.hpp"
27
#include "interpreter/interpreterRuntime.hpp"
28 29
#include "memory/allocation.inline.hpp"
#include "prims/methodHandles.hpp"
30 31 32

#define __ _masm->

33 34 35 36 37 38 39 40
#ifdef PRODUCT
#define BLOCK_COMMENT(str) /* nothing */
#else
#define BLOCK_COMMENT(str) __ block_comment(str)
#endif

#define BIND(label) bind(label); BLOCK_COMMENT(#label ":")

41 42 43 44 45
// Workaround for C++ overloading nastiness on '0' for RegisterOrConstant.
static RegisterOrConstant constant(int value) {
  return RegisterOrConstant(value);
}

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
address MethodHandleEntry::start_compiled_entry(MacroAssembler* _masm,
                                                address interpreted_entry) {
  // Just before the actual machine code entry point, allocate space
  // for a MethodHandleEntry::Data record, so that we can manage everything
  // from one base pointer.
  __ align(wordSize);
  address target = __ pc() + sizeof(Data);
  while (__ pc() < target) {
    __ nop();
    __ align(wordSize);
  }

  MethodHandleEntry* me = (MethodHandleEntry*) __ pc();
  me->set_end_address(__ pc());         // set a temporary end_address
  me->set_from_interpreted_entry(interpreted_entry);
  me->set_type_checking_entry(NULL);

  return (address) me;
}

MethodHandleEntry* MethodHandleEntry::finish_compiled_entry(MacroAssembler* _masm,
                                                address start_addr) {
  MethodHandleEntry* me = (MethodHandleEntry*) start_addr;
  assert(me->end_address() == start_addr, "valid ME");

  // Fill in the real end_address:
  __ align(wordSize);
  me->set_end_address(__ pc());

  return me;
}

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
// stack walking support

frame MethodHandles::ricochet_frame_sender(const frame& fr, RegisterMap *map) {
  RicochetFrame* f = RicochetFrame::from_frame(fr);
  if (map->update_map())
    frame::update_map_with_saved_link(map, &f->_sender_link);
  return frame(f->extended_sender_sp(), f->exact_sender_sp(), f->sender_link(), f->sender_pc());
}

void MethodHandles::ricochet_frame_oops_do(const frame& fr, OopClosure* blk, const RegisterMap* reg_map) {
  RicochetFrame* f = RicochetFrame::from_frame(fr);

  // pick up the argument type descriptor:
  Thread* thread = Thread::current();
  Handle cookie(thread, f->compute_saved_args_layout(true, true));

  // process fixed part
  blk->do_oop((oop*)f->saved_target_addr());
  blk->do_oop((oop*)f->saved_args_layout_addr());

  // process variable arguments:
  if (cookie.is_null())  return;  // no arguments to describe

  // the cookie is actually the invokeExact method for my target
  // his argument signature is what I'm interested in
  assert(cookie->is_method(), "");
  methodHandle invoker(thread, methodOop(cookie()));
  assert(invoker->name() == vmSymbols::invokeExact_name(), "must be this kind of method");
  assert(!invoker->is_static(), "must have MH argument");
  int slot_count = invoker->size_of_parameters();
  assert(slot_count >= 1, "must include 'this'");
  intptr_t* base = f->saved_args_base();
  intptr_t* retval = NULL;
  if (f->has_return_value_slot())
    retval = f->return_value_slot_addr();
  int slot_num = slot_count;
  intptr_t* loc = &base[slot_num -= 1];
  //blk->do_oop((oop*) loc);   // original target, which is irrelevant
  int arg_num = 0;
  for (SignatureStream ss(invoker->signature()); !ss.is_done(); ss.next()) {
    if (ss.at_return_type())  continue;
    BasicType ptype = ss.type();
    if (ptype == T_ARRAY)  ptype = T_OBJECT; // fold all refs to T_OBJECT
    assert(ptype >= T_BOOLEAN && ptype <= T_OBJECT, "not array or void");
    loc = &base[slot_num -= type2size[ptype]];
    bool is_oop = (ptype == T_OBJECT && loc != retval);
    if (is_oop)  blk->do_oop((oop*)loc);
    arg_num += 1;
  }
  assert(slot_num == 0, "must have processed all the arguments");
}

oop MethodHandles::RicochetFrame::compute_saved_args_layout(bool read_cache, bool write_cache) {
  oop cookie = NULL;
  if (read_cache) {
    cookie = saved_args_layout();
    if (cookie != NULL)  return cookie;
  }
  oop target = saved_target();
  oop mtype  = java_lang_invoke_MethodHandle::type(target);
  oop mtform = java_lang_invoke_MethodType::form(mtype);
  cookie = java_lang_invoke_MethodTypeForm::vmlayout(mtform);
  if (write_cache)  {
    (*saved_args_layout_addr()) = cookie;
  }
  return cookie;
}

void MethodHandles::RicochetFrame::generate_ricochet_blob(MacroAssembler* _masm,
                                                          // output params:
                                                          int* bounce_offset,
149 150
                                                          int* exception_offset,
                                                          int* frame_size_in_words) {
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
  (*frame_size_in_words) = RicochetFrame::frame_size_in_bytes() / wordSize;

  address start = __ pc();

#ifdef ASSERT
  __ hlt(); __ hlt(); __ hlt();
  // here's a hint of something special:
  __ push(MAGIC_NUMBER_1);
  __ push(MAGIC_NUMBER_2);
#endif //ASSERT
  __ hlt();  // not reached

  // A return PC has just been popped from the stack.
  // Return values are in registers.
  // The ebp points into the RicochetFrame, which contains
  // a cleanup continuation we must return to.

  (*bounce_offset) = __ pc() - start;
  BLOCK_COMMENT("ricochet_blob.bounce");

  if (VerifyMethodHandles)  RicochetFrame::verify_clean(_masm);
172
  trace_method_handle(_masm, "return/ricochet_blob.bounce");
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

  __ jmp(frame_address(continuation_offset_in_bytes()));
  __ hlt();
  DEBUG_ONLY(__ push(MAGIC_NUMBER_2));

  (*exception_offset) = __ pc() - start;
  BLOCK_COMMENT("ricochet_blob.exception");

  // compare this to Interpreter::rethrow_exception_entry, which is parallel code
  // for example, see TemplateInterpreterGenerator::generate_throw_exception
  // Live registers in:
  //   rax: exception
  //   rdx: return address/pc that threw exception (ignored, always equal to bounce addr)
  __ verify_oop(rax);

  // no need to empty_FPU_stack or reinit_heapbase, since caller frame will do the same if needed

  // Take down the frame.

  // Cf. InterpreterMacroAssembler::remove_activation.
  leave_ricochet_frame(_masm, /*rcx_recv=*/ noreg,
                       saved_last_sp_register(),
                       /*sender_pc_reg=*/ rdx);

  // In between activations - previous activation type unknown yet
  // compute continuation point - the continuation point expects the
  // following registers set up:
  //
  // rax: exception
  // rdx: return address/pc that threw exception
  // rsp: expression stack of caller
  // rbp: ebp of caller
  __ push(rax);                                  // save exception
  __ push(rdx);                                  // save return address
  Register thread_reg = LP64_ONLY(r15_thread) NOT_LP64(rdi);
  NOT_LP64(__ get_thread(thread_reg));
  __ call_VM_leaf(CAST_FROM_FN_PTR(address,
                                   SharedRuntime::exception_handler_for_return_address),
                  thread_reg, rdx);
  __ mov(rbx, rax);                              // save exception handler
  __ pop(rdx);                                   // restore return address
  __ pop(rax);                                   // restore exception
  __ jmp(rbx);                                   // jump to exception
                                                 // handler of caller
}

void MethodHandles::RicochetFrame::enter_ricochet_frame(MacroAssembler* _masm,
                                                        Register rcx_recv,
                                                        Register rax_argv,
                                                        address return_handler,
                                                        Register rbx_temp) {
  const Register saved_last_sp = saved_last_sp_register();
  Address rcx_mh_vmtarget(    rcx_recv, java_lang_invoke_MethodHandle::vmtarget_offset_in_bytes() );
  Address rcx_amh_conversion( rcx_recv, java_lang_invoke_AdapterMethodHandle::conversion_offset_in_bytes() );

  // Push the RicochetFrame a word at a time.
  // This creates something similar to an interpreter frame.
  // Cf. TemplateInterpreterGenerator::generate_fixed_frame.
  BLOCK_COMMENT("push RicochetFrame {");
  DEBUG_ONLY(int rfo = (int) sizeof(RicochetFrame));
  assert((rfo -= wordSize) == RicochetFrame::sender_pc_offset_in_bytes(), "");
#define RF_FIELD(push_value, name)                                      \
  { push_value;                                                         \
    assert((rfo -= wordSize) == RicochetFrame::name##_offset_in_bytes(), ""); }
  RF_FIELD(__ push(rbp),                   sender_link);
  RF_FIELD(__ push(saved_last_sp),         exact_sender_sp);  // rsi/r13
  RF_FIELD(__ pushptr(rcx_amh_conversion), conversion);
  RF_FIELD(__ push(rax_argv),              saved_args_base);   // can be updated if args are shifted
  RF_FIELD(__ push((int32_t) NULL_WORD),   saved_args_layout); // cache for GC layout cookie
  if (UseCompressedOops) {
    __ load_heap_oop(rbx_temp, rcx_mh_vmtarget);
    RF_FIELD(__ push(rbx_temp),            saved_target);
  } else {
    RF_FIELD(__ pushptr(rcx_mh_vmtarget),  saved_target);
  }
  __ lea(rbx_temp, ExternalAddress(return_handler));
  RF_FIELD(__ push(rbx_temp),              continuation);
#undef RF_FIELD
  assert(rfo == 0, "fully initialized the RicochetFrame");
  // compute new frame pointer:
  __ lea(rbp, Address(rsp, RicochetFrame::sender_link_offset_in_bytes()));
  // Push guard word #1 in debug mode.
  DEBUG_ONLY(__ push((int32_t) RicochetFrame::MAGIC_NUMBER_1));
  // For debugging, leave behind an indication of which stub built this frame.
  DEBUG_ONLY({ Label L; __ call(L, relocInfo::none); __ bind(L); });
  BLOCK_COMMENT("} RicochetFrame");
}

void MethodHandles::RicochetFrame::leave_ricochet_frame(MacroAssembler* _masm,
                                                        Register rcx_recv,
                                                        Register new_sp_reg,
                                                        Register sender_pc_reg) {
  assert_different_registers(rcx_recv, new_sp_reg, sender_pc_reg);
  const Register saved_last_sp = saved_last_sp_register();
  // Take down the frame.
  // Cf. InterpreterMacroAssembler::remove_activation.
  BLOCK_COMMENT("end_ricochet_frame {");
  // TO DO: If (exact_sender_sp - extended_sender_sp) > THRESH, compact the frame down.
  // This will keep stack in bounds even with unlimited tailcalls, each with an adapter.
  if (rcx_recv->is_valid())
    __ movptr(rcx_recv,    RicochetFrame::frame_address(RicochetFrame::saved_target_offset_in_bytes()));
  __ movptr(sender_pc_reg, RicochetFrame::frame_address(RicochetFrame::sender_pc_offset_in_bytes()));
  __ movptr(saved_last_sp, RicochetFrame::frame_address(RicochetFrame::exact_sender_sp_offset_in_bytes()));
  __ movptr(rbp,           RicochetFrame::frame_address(RicochetFrame::sender_link_offset_in_bytes()));
  __ mov(rsp, new_sp_reg);
  BLOCK_COMMENT("} end_ricochet_frame");
}

// Emit code to verify that RBP is pointing at a valid ricochet frame.
282
#ifndef PRODUCT
283 284 285 286 287 288
enum {
  ARG_LIMIT = 255, SLOP = 4,
  // use this parameter for checking for garbage stack movements:
  UNREASONABLE_STACK_MOVE = (ARG_LIMIT + SLOP)
  // the slop defends against false alarms due to fencepost errors
};
289
#endif
290

291
#ifdef ASSERT
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
void MethodHandles::RicochetFrame::verify_clean(MacroAssembler* _masm) {
  // The stack should look like this:
  //    ... keep1 | dest=42 | keep2 | RF | magic | handler | magic | recursive args |
  // Check various invariants.
  verify_offsets();

  Register rdi_temp = rdi;
  Register rcx_temp = rcx;
  { __ push(rdi_temp); __ push(rcx_temp); }
#define UNPUSH_TEMPS \
  { __ pop(rcx_temp);  __ pop(rdi_temp); }

  Address magic_number_1_addr  = RicochetFrame::frame_address(RicochetFrame::magic_number_1_offset_in_bytes());
  Address magic_number_2_addr  = RicochetFrame::frame_address(RicochetFrame::magic_number_2_offset_in_bytes());
  Address continuation_addr    = RicochetFrame::frame_address(RicochetFrame::continuation_offset_in_bytes());
  Address conversion_addr      = RicochetFrame::frame_address(RicochetFrame::conversion_offset_in_bytes());
  Address saved_args_base_addr = RicochetFrame::frame_address(RicochetFrame::saved_args_base_offset_in_bytes());

  Label L_bad, L_ok;
  BLOCK_COMMENT("verify_clean {");
  // Magic numbers must check out:
  __ cmpptr(magic_number_1_addr, (int32_t) MAGIC_NUMBER_1);
  __ jcc(Assembler::notEqual, L_bad);
  __ cmpptr(magic_number_2_addr, (int32_t) MAGIC_NUMBER_2);
  __ jcc(Assembler::notEqual, L_bad);

  // Arguments pointer must look reasonable:
  __ movptr(rcx_temp, saved_args_base_addr);
  __ cmpptr(rcx_temp, rbp);
  __ jcc(Assembler::below, L_bad);
  __ subptr(rcx_temp, UNREASONABLE_STACK_MOVE * Interpreter::stackElementSize);
  __ cmpptr(rcx_temp, rbp);
  __ jcc(Assembler::above, L_bad);

  load_conversion_dest_type(_masm, rdi_temp, conversion_addr);
  __ cmpl(rdi_temp, T_VOID);
  __ jcc(Assembler::equal, L_ok);
  __ movptr(rcx_temp, saved_args_base_addr);
  load_conversion_vminfo(_masm, rdi_temp, conversion_addr);
  __ cmpptr(Address(rcx_temp, rdi_temp, Interpreter::stackElementScale()),
            (int32_t) RETURN_VALUE_PLACEHOLDER);
  __ jcc(Assembler::equal, L_ok);
  __ BIND(L_bad);
  UNPUSH_TEMPS;
  __ stop("damaged ricochet frame");
  __ BIND(L_ok);
  UNPUSH_TEMPS;
  BLOCK_COMMENT("} verify_clean");

#undef UNPUSH_TEMPS

}
#endif //ASSERT

void MethodHandles::load_klass_from_Class(MacroAssembler* _masm, Register klass_reg) {
  if (VerifyMethodHandles)
    verify_klass(_masm, klass_reg, SystemDictionaryHandles::Class_klass(),
                 "AMH argument is a Class");
  __ load_heap_oop(klass_reg, Address(klass_reg, java_lang_Class::klass_offset_in_bytes()));
}

void MethodHandles::load_conversion_vminfo(MacroAssembler* _masm, Register reg, Address conversion_field_addr) {
  int bits   = BitsPerByte;
  int offset = (CONV_VMINFO_SHIFT / bits);
  int shift  = (CONV_VMINFO_SHIFT % bits);
  __ load_unsigned_byte(reg, conversion_field_addr.plus_disp(offset));
  assert(CONV_VMINFO_MASK == right_n_bits(bits - shift), "else change type of previous load");
  assert(shift == 0, "no shift needed");
}

void MethodHandles::load_conversion_dest_type(MacroAssembler* _masm, Register reg, Address conversion_field_addr) {
  int bits   = BitsPerByte;
  int offset = (CONV_DEST_TYPE_SHIFT / bits);
  int shift  = (CONV_DEST_TYPE_SHIFT % bits);
  __ load_unsigned_byte(reg, conversion_field_addr.plus_disp(offset));
  assert(CONV_TYPE_MASK == right_n_bits(bits - shift), "else change type of previous load");
  __ shrl(reg, shift);
  DEBUG_ONLY(int conv_type_bits = (int) exact_log2(CONV_TYPE_MASK+1));
  assert((shift + conv_type_bits) == bits, "left justified in byte");
}

void MethodHandles::load_stack_move(MacroAssembler* _masm,
                                    Register rdi_stack_move,
                                    Register rcx_amh,
                                    bool might_be_negative) {
377
  BLOCK_COMMENT("load_stack_move {");
378 379 380 381 382 383 384 385 386
  Address rcx_amh_conversion(rcx_amh, java_lang_invoke_AdapterMethodHandle::conversion_offset_in_bytes());
  __ movl(rdi_stack_move, rcx_amh_conversion);
  __ sarl(rdi_stack_move, CONV_STACK_MOVE_SHIFT);
#ifdef _LP64
  if (might_be_negative) {
    // clean high bits of stack motion register (was loaded as an int)
    __ movslq(rdi_stack_move, rdi_stack_move);
  }
#endif //_LP64
387
#ifdef ASSERT
388 389 390 391 392 393 394 395 396 397 398
  if (VerifyMethodHandles) {
    Label L_ok, L_bad;
    int32_t stack_move_limit = 0x4000;  // extra-large
    __ cmpptr(rdi_stack_move, stack_move_limit);
    __ jcc(Assembler::greaterEqual, L_bad);
    __ cmpptr(rdi_stack_move, -stack_move_limit);
    __ jcc(Assembler::greater, L_ok);
    __ bind(L_bad);
    __ stop("load_stack_move of garbage value");
    __ BIND(L_ok);
  }
399
#endif
400
  BLOCK_COMMENT("} load_stack_move");
401 402
}

403
#ifdef ASSERT
404 405 406 407 408 409 410 411 412 413 414 415 416
void MethodHandles::RicochetFrame::verify_offsets() {
  // Check compatibility of this struct with the more generally used offsets of class frame:
  int ebp_off = sender_link_offset_in_bytes();  // offset from struct base to local rbp value
  assert(ebp_off + wordSize*frame::interpreter_frame_method_offset      == saved_args_base_offset_in_bytes(), "");
  assert(ebp_off + wordSize*frame::interpreter_frame_last_sp_offset     == conversion_offset_in_bytes(), "");
  assert(ebp_off + wordSize*frame::interpreter_frame_sender_sp_offset   == exact_sender_sp_offset_in_bytes(), "");
  // These last two have to be exact:
  assert(ebp_off + wordSize*frame::link_offset                          == sender_link_offset_in_bytes(), "");
  assert(ebp_off + wordSize*frame::return_addr_offset                   == sender_pc_offset_in_bytes(), "");
}

void MethodHandles::RicochetFrame::verify() const {
  verify_offsets();
417 418
  assert(magic_number_1() == MAGIC_NUMBER_1, err_msg(PTR_FORMAT " == " PTR_FORMAT, magic_number_1(), MAGIC_NUMBER_1));
  assert(magic_number_2() == MAGIC_NUMBER_2, err_msg(PTR_FORMAT " == " PTR_FORMAT, magic_number_2(), MAGIC_NUMBER_2));
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
  if (!Universe::heap()->is_gc_active()) {
    if (saved_args_layout() != NULL) {
      assert(saved_args_layout()->is_method(), "must be valid oop");
    }
    if (saved_target() != NULL) {
      assert(java_lang_invoke_MethodHandle::is_instance(saved_target()), "checking frame value");
    }
  }
  int conv_op = adapter_conversion_op(conversion());
  assert(conv_op == java_lang_invoke_AdapterMethodHandle::OP_COLLECT_ARGS ||
         conv_op == java_lang_invoke_AdapterMethodHandle::OP_FOLD_ARGS ||
         conv_op == java_lang_invoke_AdapterMethodHandle::OP_PRIM_TO_REF,
         "must be a sane conversion");
  if (has_return_value_slot()) {
    assert(*return_value_slot_addr() == RETURN_VALUE_PLACEHOLDER, "");
  }
}
#endif //PRODUCT

438
#ifdef ASSERT
439 440 441
void MethodHandles::verify_argslot(MacroAssembler* _masm,
                                   Register argslot_reg,
                                   const char* error_message) {
442 443
  // Verify that argslot lies within (rsp, rbp].
  Label L_ok, L_bad;
444
  BLOCK_COMMENT("verify_argslot {");
T
twisti 已提交
445
  __ cmpptr(argslot_reg, rbp);
446
  __ jccb(Assembler::above, L_bad);
T
twisti 已提交
447
  __ cmpptr(rsp, argslot_reg);
448
  __ jccb(Assembler::below, L_ok);
449 450
  __ bind(L_bad);
  __ stop(error_message);
451
  __ BIND(L_ok);
452
  BLOCK_COMMENT("} verify_argslot");
453 454
}

455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
void MethodHandles::verify_argslots(MacroAssembler* _masm,
                                    RegisterOrConstant arg_slots,
                                    Register arg_slot_base_reg,
                                    bool negate_argslots,
                                    const char* error_message) {
  // Verify that [argslot..argslot+size) lies within (rsp, rbp).
  Label L_ok, L_bad;
  Register rdi_temp = rdi;
  BLOCK_COMMENT("verify_argslots {");
  __ push(rdi_temp);
  if (negate_argslots) {
    if (arg_slots.is_constant()) {
      arg_slots = -1 * arg_slots.as_constant();
    } else {
      __ movptr(rdi_temp, arg_slots);
      __ negptr(rdi_temp);
      arg_slots = rdi_temp;
    }
  }
  __ lea(rdi_temp, Address(arg_slot_base_reg, arg_slots, Interpreter::stackElementScale()));
  __ cmpptr(rdi_temp, rbp);
  __ pop(rdi_temp);
  __ jcc(Assembler::above, L_bad);
  __ cmpptr(rsp, arg_slot_base_reg);
  __ jcc(Assembler::below, L_ok);
  __ bind(L_bad);
  __ stop(error_message);
  __ BIND(L_ok);
  BLOCK_COMMENT("} verify_argslots");
}

// Make sure that arg_slots has the same sign as the given direction.
// If (and only if) arg_slots is a assembly-time constant, also allow it to be zero.
void MethodHandles::verify_stack_move(MacroAssembler* _masm,
                                      RegisterOrConstant arg_slots, int direction) {
  bool allow_zero = arg_slots.is_constant();
  if (direction == 0) { direction = +1; allow_zero = true; }
  assert(stack_move_unit() == -1, "else add extra checks here");
  if (arg_slots.is_register()) {
    Label L_ok, L_bad;
    BLOCK_COMMENT("verify_stack_move {");
    // testl(arg_slots.as_register(), -stack_move_unit() - 1);  // no need
    // jcc(Assembler::notZero, L_bad);
    __ cmpptr(arg_slots.as_register(), (int32_t) NULL_WORD);
    if (direction > 0) {
      __ jcc(allow_zero ? Assembler::less : Assembler::lessEqual, L_bad);
      __ cmpptr(arg_slots.as_register(), (int32_t) UNREASONABLE_STACK_MOVE);
      __ jcc(Assembler::less, L_ok);
    } else {
      __ jcc(allow_zero ? Assembler::greater : Assembler::greaterEqual, L_bad);
      __ cmpptr(arg_slots.as_register(), (int32_t) -UNREASONABLE_STACK_MOVE);
      __ jcc(Assembler::greater, L_ok);
    }
    __ bind(L_bad);
    if (direction > 0)
      __ stop("assert arg_slots > 0");
    else
      __ stop("assert arg_slots < 0");
    __ BIND(L_ok);
    BLOCK_COMMENT("} verify_stack_move");
  } else {
    intptr_t size = arg_slots.as_constant();
    if (direction < 0)  size = -size;
    assert(size >= 0, "correct direction of constant move");
    assert(size < UNREASONABLE_STACK_MOVE, "reasonable size of constant move");
  }
}

void MethodHandles::verify_klass(MacroAssembler* _masm,
                                 Register obj, KlassHandle klass,
                                 const char* error_message) {
  oop* klass_addr = klass.raw_value();
  assert(klass_addr >= SystemDictionaryHandles::Object_klass().raw_value() &&
         klass_addr <= SystemDictionaryHandles::Long_klass().raw_value(),
         "must be one of the SystemDictionaryHandles");
  Register temp = rdi;
  Label L_ok, L_bad;
  BLOCK_COMMENT("verify_klass {");
  __ verify_oop(obj);
  __ testptr(obj, obj);
  __ jcc(Assembler::zero, L_bad);
  __ push(temp);
  __ load_klass(temp, obj);
  __ cmpptr(temp, ExternalAddress((address) klass_addr));
  __ jcc(Assembler::equal, L_ok);
  intptr_t super_check_offset = klass->super_check_offset();
  __ movptr(temp, Address(temp, super_check_offset));
  __ cmpptr(temp, ExternalAddress((address) klass_addr));
  __ jcc(Assembler::equal, L_ok);
  __ pop(temp);
  __ bind(L_bad);
  __ stop(error_message);
  __ BIND(L_ok);
  __ pop(temp);
  BLOCK_COMMENT("} verify_klass");
}
#endif //ASSERT
552

553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
void MethodHandles::jump_from_method_handle(MacroAssembler* _masm, Register method, Register temp) {
  if (JvmtiExport::can_post_interpreter_events()) {
    Label run_compiled_code;
    // JVMTI events, such as single-stepping, are implemented partly by avoiding running
    // compiled code in threads for which the event is enabled.  Check here for
    // interp_only_mode if these events CAN be enabled.
#ifdef _LP64
    Register rthread = r15_thread;
#else
    Register rthread = temp;
    __ get_thread(rthread);
#endif
    // interp_only is an int, on little endian it is sufficient to test the byte only
    // Is a cmpl faster?
    __ cmpb(Address(rthread, JavaThread::interp_only_mode_offset()), 0);
    __ jccb(Assembler::zero, run_compiled_code);
    __ jmp(Address(method, methodOopDesc::interpreter_entry_offset()));
    __ bind(run_compiled_code);
  }
  __ jmp(Address(method, methodOopDesc::from_interpreted_offset()));
}

575 576 577 578 579
// Code generation
address MethodHandles::generate_method_handle_interpreter_entry(MacroAssembler* _masm) {
  // rbx: methodOop
  // rcx: receiver method handle (must load from sp[MethodTypeForm.vmslots])
  // rsi/r13: sender SP (must preserve; see prepare_to_jump_from_interpreted)
580
  // rdx, rdi: garbage temp, blown away
581 582 583 584 585

  Register rbx_method = rbx;
  Register rcx_recv   = rcx;
  Register rax_mtype  = rax;
  Register rdx_temp   = rdx;
586
  Register rdi_temp   = rdi;
587 588 589 590

  // emit WrongMethodType path first, to enable jccb back-branch from main path
  Label wrong_method_type;
  __ bind(wrong_method_type);
591
  Label invoke_generic_slow_path, invoke_exact_error_path;
592 593 594
  assert(methodOopDesc::intrinsic_id_size_in_bytes() == sizeof(u1), "");;
  __ cmpb(Address(rbx_method, methodOopDesc::intrinsic_id_offset_in_bytes()), (int) vmIntrinsics::_invokeExact);
  __ jcc(Assembler::notEqual, invoke_generic_slow_path);
595
  __ jmp(invoke_exact_error_path);
596 597 598 599 600 601

  // here's where control starts out:
  __ align(CodeEntryAlignment);
  address entry_point = __ pc();

  // fetch the MethodType from the method handle into rax (the 'check' register)
602 603 604
  // FIXME: Interpreter should transmit pre-popped stack pointer, to locate base of arg list.
  // This would simplify several touchy bits of code.
  // See 6984712: JSR 292 method handle calls need a clean argument base pointer
605 606 607 608 609 610 611 612 613
  {
    Register tem = rbx_method;
    for (jint* pchase = methodOopDesc::method_type_offsets_chain(); (*pchase) != -1; pchase++) {
      __ movptr(rax_mtype, Address(tem, *pchase));
      tem = rax_mtype;          // in case there is another indirection
    }
  }

  // given the MethodType, find out where the MH argument is buried
614
  __ load_heap_oop(rdx_temp, Address(rax_mtype, __ delayed_value(java_lang_invoke_MethodType::form_offset_in_bytes, rdi_temp)));
615
  Register rdx_vmslots = rdx_temp;
616
  __ movl(rdx_vmslots, Address(rdx_temp, __ delayed_value(java_lang_invoke_MethodTypeForm::vmslots_offset_in_bytes, rdi_temp)));
617 618
  Address mh_receiver_slot_addr = __ argument_address(rdx_vmslots);
  __ movptr(rcx_recv, mh_receiver_slot_addr);
619

620 621 622
  trace_method_handle(_masm, "invokeExact");

  __ check_method_handle_type(rax_mtype, rcx_recv, rdi_temp, wrong_method_type);
623 624 625 626

  // Nobody uses the MH receiver slot after this.  Make sure.
  DEBUG_ONLY(__ movptr(mh_receiver_slot_addr, (int32_t)0x999999));

627 628
  __ jump_to_method_handle_entry(rcx_recv, rdi_temp);

629 630
  // error path for invokeExact (only)
  __ bind(invoke_exact_error_path);
631 632 633 634 635
  // ensure that the top of stack is properly aligned.
  __ mov(rdi, rsp);
  __ andptr(rsp, -StackAlignmentInBytes); // Align the stack for the ABI
  __ pushptr(Address(rdi, 0));  // Pick up the return address

636 637
  // Stub wants expected type in rax and the actual type in rcx
  __ jump(ExternalAddress(StubRoutines::throw_WrongMethodTypeException_entry()));
638

639 640 641
  // for invokeGeneric (only), apply argument and result conversions on the fly
  __ bind(invoke_generic_slow_path);
#ifdef ASSERT
642 643
  if (VerifyMethodHandles) {
    Label L;
644 645 646 647 648 649 650 651 652 653 654
    __ cmpb(Address(rbx_method, methodOopDesc::intrinsic_id_offset_in_bytes()), (int) vmIntrinsics::_invokeGeneric);
    __ jcc(Assembler::equal, L);
    __ stop("bad methodOop::intrinsic_id");
    __ bind(L);
  }
#endif //ASSERT
  Register rbx_temp = rbx_method;  // don't need it now

  // make room on the stack for another pointer:
  Register rcx_argslot = rcx_recv;
  __ lea(rcx_argslot, __ argument_address(rdx_vmslots, 1));
655
  insert_arg_slots(_masm, 2 * stack_move_unit(),
656 657 658 659
                   rcx_argslot, rbx_temp, rdx_temp);

  // load up an adapter from the calling type (Java weaves this)
  Register rdx_adapter = rdx_temp;
660 661 662
  __ load_heap_oop(rdx_temp,    Address(rax_mtype, __ delayed_value(java_lang_invoke_MethodType::form_offset_in_bytes,               rdi_temp)));
  __ load_heap_oop(rdx_adapter, Address(rdx_temp,  __ delayed_value(java_lang_invoke_MethodTypeForm::genericInvoker_offset_in_bytes, rdi_temp)));
  __ verify_oop(rdx_adapter);
663 664 665 666 667 668 669 670 671 672
  __ movptr(Address(rcx_argslot, 1 * Interpreter::stackElementSize), rdx_adapter);
  // As a trusted first argument, pass the type being called, so the adapter knows
  // the actual types of the arguments and return values.
  // (Generic invokers are shared among form-families of method-type.)
  __ movptr(Address(rcx_argslot, 0 * Interpreter::stackElementSize), rax_mtype);
  // FIXME: assert that rdx_adapter is of the right method-type.
  __ mov(rcx, rdx_adapter);
  trace_method_handle(_masm, "invokeGeneric");
  __ jump_to_method_handle_entry(rcx, rdi_temp);

673 674 675 676
  return entry_point;
}

// Helper to insert argument slots into the stack.
677 678 679
// arg_slots must be a multiple of stack_move_unit() and < 0
// rax_argslot is decremented to point to the new (shifted) location of the argslot
// But, rdx_temp ends up holding the original value of rax_argslot.
680 681 682
void MethodHandles::insert_arg_slots(MacroAssembler* _masm,
                                     RegisterOrConstant arg_slots,
                                     Register rax_argslot,
683 684 685 686
                                     Register rbx_temp, Register rdx_temp) {
  // allow constant zero
  if (arg_slots.is_constant() && arg_slots.as_constant() == 0)
    return;
687 688
  assert_different_registers(rax_argslot, rbx_temp, rdx_temp,
                             (!arg_slots.is_register() ? rsp : arg_slots.as_register()));
689 690 691 692
  if (VerifyMethodHandles)
    verify_argslot(_masm, rax_argslot, "insertion point must fall within current frame");
  if (VerifyMethodHandles)
    verify_stack_move(_masm, arg_slots, -1);
693 694 695 696 697 698 699 700 701

  // Make space on the stack for the inserted argument(s).
  // Then pull down everything shallower than rax_argslot.
  // The stacked return address gets pulled down with everything else.
  // That is, copy [rsp, argslot) downward by -size words.  In pseudo-code:
  //   rsp -= size;
  //   for (rdx = rsp + size; rdx < argslot; rdx++)
  //     rdx[-size] = rdx[0]
  //   argslot -= size;
702
  BLOCK_COMMENT("insert_arg_slots {");
703
  __ mov(rdx_temp, rsp);                        // source pointer for copy
704
  __ lea(rsp, Address(rsp, arg_slots, Interpreter::stackElementScale()));
705 706
  {
    Label loop;
707
    __ BIND(loop);
708 709
    // pull one word down each time through the loop
    __ movptr(rbx_temp, Address(rdx_temp, 0));
710
    __ movptr(Address(rdx_temp, arg_slots, Interpreter::stackElementScale()), rbx_temp);
711 712
    __ addptr(rdx_temp, wordSize);
    __ cmpptr(rdx_temp, rax_argslot);
713
    __ jcc(Assembler::below, loop);
714 715 716
  }

  // Now move the argslot down, to point to the opened-up space.
717
  __ lea(rax_argslot, Address(rax_argslot, arg_slots, Interpreter::stackElementScale()));
718
  BLOCK_COMMENT("} insert_arg_slots");
719 720 721
}

// Helper to remove argument slots from the stack.
722
// arg_slots must be a multiple of stack_move_unit() and > 0
723
void MethodHandles::remove_arg_slots(MacroAssembler* _masm,
724 725 726 727 728 729
                                     RegisterOrConstant arg_slots,
                                     Register rax_argslot,
                                     Register rbx_temp, Register rdx_temp) {
  // allow constant zero
  if (arg_slots.is_constant() && arg_slots.as_constant() == 0)
    return;
730 731
  assert_different_registers(rax_argslot, rbx_temp, rdx_temp,
                             (!arg_slots.is_register() ? rsp : arg_slots.as_register()));
732 733 734 735 736
  if (VerifyMethodHandles)
    verify_argslots(_masm, arg_slots, rax_argslot, false,
                    "deleted argument(s) must fall within current frame");
  if (VerifyMethodHandles)
    verify_stack_move(_masm, arg_slots, +1);
737

738
  BLOCK_COMMENT("remove_arg_slots {");
739 740 741 742 743 744 745 746 747 748 749
  // Pull up everything shallower than rax_argslot.
  // Then remove the excess space on the stack.
  // The stacked return address gets pulled up with everything else.
  // That is, copy [rsp, argslot) upward by size words.  In pseudo-code:
  //   for (rdx = argslot-1; rdx >= rsp; --rdx)
  //     rdx[size] = rdx[0]
  //   argslot += size;
  //   rsp += size;
  __ lea(rdx_temp, Address(rax_argslot, -wordSize)); // source pointer for copy
  {
    Label loop;
750
    __ BIND(loop);
751 752
    // pull one word up each time through the loop
    __ movptr(rbx_temp, Address(rdx_temp, 0));
753
    __ movptr(Address(rdx_temp, arg_slots, Interpreter::stackElementScale()), rbx_temp);
754 755
    __ addptr(rdx_temp, -wordSize);
    __ cmpptr(rdx_temp, rsp);
756
    __ jcc(Assembler::aboveEqual, loop);
757 758 759
  }

  // Now move the argslot up, to point to the just-copied block.
760
  __ lea(rsp, Address(rsp, arg_slots, Interpreter::stackElementScale()));
761
  // And adjust the argslot address to point at the deletion point.
762
  __ lea(rax_argslot, Address(rax_argslot, arg_slots, Interpreter::stackElementScale()));
763
  BLOCK_COMMENT("} remove_arg_slots");
764 765
}

766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
// Helper to copy argument slots to the top of the stack.
// The sequence starts with rax_argslot and is counted by slot_count
// slot_count must be a multiple of stack_move_unit() and >= 0
// This function blows the temps but does not change rax_argslot.
void MethodHandles::push_arg_slots(MacroAssembler* _masm,
                                   Register rax_argslot,
                                   RegisterOrConstant slot_count,
                                   int skip_words_count,
                                   Register rbx_temp, Register rdx_temp) {
  assert_different_registers(rax_argslot, rbx_temp, rdx_temp,
                             (!slot_count.is_register() ? rbp : slot_count.as_register()),
                             rsp);
  assert(Interpreter::stackElementSize == wordSize, "else change this code");

  if (VerifyMethodHandles)
    verify_stack_move(_masm, slot_count, 0);

  // allow constant zero
  if (slot_count.is_constant() && slot_count.as_constant() == 0)
    return;

  BLOCK_COMMENT("push_arg_slots {");

  Register rbx_top = rbx_temp;

  // There is at most 1 word to carry down with the TOS.
  switch (skip_words_count) {
  case 1: __ pop(rdx_temp); break;
  case 0:                   break;
  default: ShouldNotReachHere();
  }

  if (slot_count.is_constant()) {
    for (int i = slot_count.as_constant() - 1; i >= 0; i--) {
      __ pushptr(Address(rax_argslot, i * wordSize));
    }
  } else {
    Label L_plural, L_loop, L_break;
    // Emit code to dynamically check for the common cases, zero and one slot.
    __ cmpl(slot_count.as_register(), (int32_t) 1);
    __ jccb(Assembler::greater, L_plural);
    __ jccb(Assembler::less, L_break);
    __ pushptr(Address(rax_argslot, 0));
    __ jmpb(L_break);
    __ BIND(L_plural);

    // Loop for 2 or more:
    //   rbx = &rax[slot_count]
    //   while (rbx > rax)  *(--rsp) = *(--rbx)
    __ lea(rbx_top, Address(rax_argslot, slot_count, Address::times_ptr));
    __ BIND(L_loop);
    __ subptr(rbx_top, wordSize);
    __ pushptr(Address(rbx_top, 0));
    __ cmpptr(rbx_top, rax_argslot);
    __ jcc(Assembler::above, L_loop);
    __ bind(L_break);
  }
  switch (skip_words_count) {
  case 1: __ push(rdx_temp); break;
  case 0:                    break;
  default: ShouldNotReachHere();
  }
  BLOCK_COMMENT("} push_arg_slots");
}

// in-place movement; no change to rsp
// blows rax_temp, rdx_temp
void MethodHandles::move_arg_slots_up(MacroAssembler* _masm,
                                      Register rbx_bottom,  // invariant
                                      Address  top_addr,     // can use rax_temp
                                      RegisterOrConstant positive_distance_in_slots,
                                      Register rax_temp, Register rdx_temp) {
  BLOCK_COMMENT("move_arg_slots_up {");
  assert_different_registers(rbx_bottom,
                             rax_temp, rdx_temp,
                             positive_distance_in_slots.register_or_noreg());
  Label L_loop, L_break;
  Register rax_top = rax_temp;
  if (!top_addr.is_same_address(Address(rax_top, 0)))
    __ lea(rax_top, top_addr);
  // Detect empty (or broken) loop:
#ifdef ASSERT
  if (VerifyMethodHandles) {
    // Verify that &bottom < &top (non-empty interval)
    Label L_ok, L_bad;
    if (positive_distance_in_slots.is_register()) {
      __ cmpptr(positive_distance_in_slots.as_register(), (int32_t) 0);
      __ jcc(Assembler::lessEqual, L_bad);
    }
    __ cmpptr(rbx_bottom, rax_top);
    __ jcc(Assembler::below, L_ok);
    __ bind(L_bad);
    __ stop("valid bounds (copy up)");
    __ BIND(L_ok);
  }
#endif
  __ cmpptr(rbx_bottom, rax_top);
  __ jccb(Assembler::aboveEqual, L_break);
  // work rax down to rbx, copying contiguous data upwards
  // In pseudo-code:
  //   [rbx, rax) = &[bottom, top)
  //   while (--rax >= rbx) *(rax + distance) = *(rax + 0), rax--;
  __ BIND(L_loop);
  __ subptr(rax_top, wordSize);
  __ movptr(rdx_temp, Address(rax_top, 0));
  __ movptr(          Address(rax_top, positive_distance_in_slots, Address::times_ptr), rdx_temp);
  __ cmpptr(rax_top, rbx_bottom);
  __ jcc(Assembler::above, L_loop);
  assert(Interpreter::stackElementSize == wordSize, "else change loop");
  __ bind(L_break);
  BLOCK_COMMENT("} move_arg_slots_up");
}

// in-place movement; no change to rsp
// blows rax_temp, rdx_temp
void MethodHandles::move_arg_slots_down(MacroAssembler* _masm,
                                        Address  bottom_addr,  // can use rax_temp
                                        Register rbx_top,      // invariant
                                        RegisterOrConstant negative_distance_in_slots,
                                        Register rax_temp, Register rdx_temp) {
  BLOCK_COMMENT("move_arg_slots_down {");
  assert_different_registers(rbx_top,
                             negative_distance_in_slots.register_or_noreg(),
                             rax_temp, rdx_temp);
  Label L_loop, L_break;
  Register rax_bottom = rax_temp;
  if (!bottom_addr.is_same_address(Address(rax_bottom, 0)))
    __ lea(rax_bottom, bottom_addr);
  // Detect empty (or broken) loop:
#ifdef ASSERT
  assert(!negative_distance_in_slots.is_constant() || negative_distance_in_slots.as_constant() < 0, "");
  if (VerifyMethodHandles) {
    // Verify that &bottom < &top (non-empty interval)
    Label L_ok, L_bad;
    if (negative_distance_in_slots.is_register()) {
      __ cmpptr(negative_distance_in_slots.as_register(), (int32_t) 0);
      __ jcc(Assembler::greaterEqual, L_bad);
    }
    __ cmpptr(rax_bottom, rbx_top);
    __ jcc(Assembler::below, L_ok);
    __ bind(L_bad);
    __ stop("valid bounds (copy down)");
    __ BIND(L_ok);
  }
#endif
  __ cmpptr(rax_bottom, rbx_top);
  __ jccb(Assembler::aboveEqual, L_break);
  // work rax up to rbx, copying contiguous data downwards
  // In pseudo-code:
  //   [rax, rbx) = &[bottom, top)
  //   while (rax < rbx) *(rax - distance) = *(rax + 0), rax++;
  __ BIND(L_loop);
  __ movptr(rdx_temp, Address(rax_bottom, 0));
  __ movptr(          Address(rax_bottom, negative_distance_in_slots, Address::times_ptr), rdx_temp);
  __ addptr(rax_bottom, wordSize);
  __ cmpptr(rax_bottom, rbx_top);
  __ jcc(Assembler::below, L_loop);
  assert(Interpreter::stackElementSize == wordSize, "else change loop");
  __ bind(L_break);
  BLOCK_COMMENT("} move_arg_slots_down");
}

// Copy from a field or array element to a stacked argument slot.
// is_element (ignored) says whether caller is loading an array element instead of an instance field.
void MethodHandles::move_typed_arg(MacroAssembler* _masm,
                                   BasicType type, bool is_element,
                                   Address slot_dest, Address value_src,
                                   Register rbx_temp, Register rdx_temp) {
  BLOCK_COMMENT(!is_element ? "move_typed_arg {" : "move_typed_arg { (array element)");
  if (type == T_OBJECT || type == T_ARRAY) {
    __ load_heap_oop(rbx_temp, value_src);
    __ movptr(slot_dest, rbx_temp);
  } else if (type != T_VOID) {
    int  arg_size      = type2aelembytes(type);
    bool arg_is_signed = is_signed_subword_type(type);
    int  slot_size     = (arg_size > wordSize) ? arg_size : wordSize;
    __ load_sized_value(  rdx_temp,  value_src, arg_size, arg_is_signed, rbx_temp);
    __ store_sized_value( slot_dest, rdx_temp,  slot_size,               rbx_temp);
  }
  BLOCK_COMMENT("} move_typed_arg");
}

void MethodHandles::move_return_value(MacroAssembler* _masm, BasicType type,
                                      Address return_slot) {
  BLOCK_COMMENT("move_return_value {");
  // Old versions of the JVM must clean the FPU stack after every return.
#ifndef _LP64
#ifdef COMPILER2
  // The FPU stack is clean if UseSSE >= 2 but must be cleaned in other cases
  if ((type == T_FLOAT && UseSSE < 1) || (type == T_DOUBLE && UseSSE < 2)) {
    for (int i = 1; i < 8; i++) {
        __ ffree(i);
    }
  } else if (UseSSE < 2) {
    __ empty_FPU_stack();
  }
#endif //COMPILER2
#endif //!_LP64

  // Look at the type and pull the value out of the corresponding register.
  if (type == T_VOID) {
    // nothing to do
  } else if (type == T_OBJECT) {
    __ movptr(return_slot, rax);
  } else if (type == T_INT || is_subword_type(type)) {
    // write the whole word, even if only 32 bits is significant
    __ movptr(return_slot, rax);
  } else if (type == T_LONG) {
    // store the value by parts
    // Note: We assume longs are continguous (if misaligned) on the interpreter stack.
    __ store_sized_value(return_slot, rax, BytesPerLong, rdx);
  } else if (NOT_LP64((type == T_FLOAT  && UseSSE < 1) ||
                      (type == T_DOUBLE && UseSSE < 2) ||)
             false) {
    // Use old x86 FPU registers:
    if (type == T_FLOAT)
      __ fstp_s(return_slot);
    else
      __ fstp_d(return_slot);
  } else if (type == T_FLOAT) {
    __ movflt(return_slot, xmm0);
  } else if (type == T_DOUBLE) {
    __ movdbl(return_slot, xmm0);
  } else {
    ShouldNotReachHere();
  }
  BLOCK_COMMENT("} move_return_value");
}

995
#ifndef PRODUCT
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
#define DESCRIBE_RICOCHET_OFFSET(rf, name) \
  values.describe(frame_no, (intptr_t *) (((uintptr_t)rf) + MethodHandles::RicochetFrame::name##_offset_in_bytes()), #name)

void MethodHandles::RicochetFrame::describe(const frame* fr, FrameValues& values, int frame_no)  {
    address bp = (address) fr->fp();
    RicochetFrame* rf = (RicochetFrame*)(bp - sender_link_offset_in_bytes());

    // ricochet slots
    DESCRIBE_RICOCHET_OFFSET(rf, exact_sender_sp);
    DESCRIBE_RICOCHET_OFFSET(rf, conversion);
    DESCRIBE_RICOCHET_OFFSET(rf, saved_args_base);
    DESCRIBE_RICOCHET_OFFSET(rf, saved_args_layout);
    DESCRIBE_RICOCHET_OFFSET(rf, saved_target);
    DESCRIBE_RICOCHET_OFFSET(rf, continuation);

    // relevant ricochet targets (in caller frame)
    values.describe(-1, rf->saved_args_base(),  err_msg("*saved_args_base for #%d", frame_no));
}
#endif // ASSERT
1015

1016
#ifndef PRODUCT
1017
extern "C" void print_method_handle(oop mh);
1018
void trace_method_handle_stub(const char* adaptername,
1019
                              oop mh,
1020 1021 1022 1023
                              intptr_t* saved_regs,
                              intptr_t* entry_sp,
                              intptr_t* saved_sp,
                              intptr_t* saved_bp) {
1024
  // called as a leaf from native code: do not block the JVM!
1025
  bool has_mh = (strstr(adaptername, "return/") == NULL);  // return adapters don't have rcx_mh
1026

1027
  intptr_t* last_sp = (intptr_t*) saved_bp[frame::interpreter_frame_last_sp_offset];
1028 1029 1030
  intptr_t* base_sp = last_sp;
  typedef MethodHandles::RicochetFrame RicochetFrame;
  RicochetFrame* rfp = (RicochetFrame*)((address)saved_bp - RicochetFrame::sender_link_offset_in_bytes());
1031
  if (Universe::heap()->is_in((address) rfp->saved_args_base())) {
1032 1033 1034 1035 1036 1037 1038 1039 1040
    // Probably an interpreter frame.
    base_sp = (intptr_t*) saved_bp[frame::interpreter_frame_monitor_block_top_offset];
  }
  intptr_t    mh_reg = (intptr_t)mh;
  const char* mh_reg_name = "rcx_mh";
  if (!has_mh)  mh_reg_name = "rcx";
  tty->print_cr("MH %s %s="PTR_FORMAT" sp=("PTR_FORMAT"+"INTX_FORMAT") stack_size="INTX_FORMAT" bp="PTR_FORMAT,
                adaptername, mh_reg_name, mh_reg,
                (intptr_t)entry_sp, (intptr_t)(saved_sp - entry_sp), (intptr_t)(base_sp - last_sp), (intptr_t)saved_bp);
1041
  if (Verbose) {
1042 1043 1044 1045 1046 1047 1048 1049 1050
    tty->print(" reg dump: ");
    int saved_regs_count = (entry_sp-1) - saved_regs;
    // 32 bit: rdi rsi rbp rsp; rbx rdx rcx (*) rax
    int i;
    for (i = 0; i <= saved_regs_count; i++) {
      if (i > 0 && i % 4 == 0 && i != saved_regs_count) {
        tty->cr();
        tty->print("   + dump: ");
      }
1051
      tty->print(" %d: "PTR_FORMAT, i, saved_regs[i]);
1052 1053
    }
    tty->cr();
1054 1055
    if (last_sp != saved_sp && last_sp != NULL)
      tty->print_cr("*** last_sp="PTR_FORMAT, (intptr_t)last_sp);
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113

    {
     // dumping last frame with frame::describe

      JavaThread* p = JavaThread::active();

      ResourceMark rm;
      PRESERVE_EXCEPTION_MARK; // may not be needed by safer and unexpensive here
      FrameValues values;

      // Note: We want to allow trace_method_handle from any call site.
      // While trace_method_handle creates a frame, it may be entered
      // without a PC on the stack top (e.g. not just after a call).
      // Walking that frame could lead to failures due to that invalid PC.
      // => carefully detect that frame when doing the stack walking

      // Current C frame
      frame cur_frame = os::current_frame();

      // Robust search of trace_calling_frame (independant of inlining).
      // Assumes saved_regs comes from a pusha in the trace_calling_frame.
      assert(cur_frame.sp() < saved_regs, "registers not saved on stack ?");
      frame trace_calling_frame = os::get_sender_for_C_frame(&cur_frame);
      while (trace_calling_frame.fp() < saved_regs) {
        trace_calling_frame = os::get_sender_for_C_frame(&trace_calling_frame);
      }

      // safely create a frame and call frame::describe
      intptr_t *dump_sp = trace_calling_frame.sender_sp();
      intptr_t *dump_fp = trace_calling_frame.link();

      bool walkable = has_mh; // whether the traced frame shoud be walkable

      if (walkable) {
        // The previous definition of walkable may have to be refined
        // if new call sites cause the next frame constructor to start
        // failing. Alternatively, frame constructors could be
        // modified to support the current or future non walkable
        // frames (but this is more intrusive and is not considered as
        // part of this RFE, which will instead use a simpler output).
        frame dump_frame = frame(dump_sp, dump_fp);
        dump_frame.describe(values, 1);
      } else {
        // Stack may not be walkable (invalid PC above FP):
        // Add descriptions without building a Java frame to avoid issues
        values.describe(-1, dump_fp, "fp for #1 <not parsed, cannot trust pc>");
        values.describe(-1, dump_sp, "sp for #1");
      }

      // mark saved_sp if seems valid
      if (has_mh) {
        if ((saved_sp >= dump_sp - UNREASONABLE_STACK_MOVE) && (saved_sp < dump_fp)) {
          values.describe(-1, saved_sp, "*saved_sp");
        }
      }

      tty->print_cr("  stack layout:");
      values.print(p);
1114
    }
1115 1116
    if (has_mh)
      print_method_handle(mh);
1117 1118
  }
}
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139

// The stub wraps the arguments in a struct on the stack to avoid
// dealing with the different calling conventions for passing 6
// arguments.
struct MethodHandleStubArguments {
  const char* adaptername;
  oopDesc* mh;
  intptr_t* saved_regs;
  intptr_t* entry_sp;
  intptr_t* saved_sp;
  intptr_t* saved_bp;
};
void trace_method_handle_stub_wrapper(MethodHandleStubArguments* args) {
  trace_method_handle_stub(args->adaptername,
                           args->mh,
                           args->saved_regs,
                           args->entry_sp,
                           args->saved_sp,
                           args->saved_bp);
}

1140 1141 1142
void MethodHandles::trace_method_handle(MacroAssembler* _masm, const char* adaptername) {
  if (!TraceMethodHandles)  return;
  BLOCK_COMMENT("trace_method_handle {");
1143
  __ enter();
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
  __ andptr(rsp, -16); // align stack if needed for FPU state
  __ pusha();
  __ mov(rbx, rsp); // for retreiving saved_regs
  // Note: saved_regs must be in the entered frame for the
  // robust stack walking implemented in trace_method_handle_stub.

  // save FP result, valid at some call sites (adapter_opt_return_float, ...)
  __ increment(rsp, -2 * wordSize);
  if  (UseSSE >= 2) {
    __ movdbl(Address(rsp, 0), xmm0);
  } else if (UseSSE == 1) {
    __ movflt(Address(rsp, 0), xmm0);
  } else {
    __ fst_d(Address(rsp, 0));
  }

1160
  // incoming state:
1161
  // rcx: method handle
1162 1163
  // r13 or rsi: saved sp
  // To avoid calling convention issues, build a record on the stack and pass the pointer to that instead.
1164
  // Note: fix the increment below if pushing more arguments
1165
  __ push(rbp);               // saved_bp
1166 1167
  __ push(saved_last_sp_register()); // saved_sp
  __ push(rbp);               // entry_sp (with extra align space)
1168 1169
  __ push(rbx);               // pusha saved_regs
  __ push(rcx);               // mh
1170
  __ push(rcx);               // slot for adaptername
1171 1172
  __ movptr(Address(rsp, 0), (intptr_t) adaptername);
  __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, trace_method_handle_stub_wrapper), rsp);
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
  __ increment(rsp, 6 * wordSize); // MethodHandleStubArguments

  if  (UseSSE >= 2) {
    __ movdbl(xmm0, Address(rsp, 0));
  } else if (UseSSE == 1) {
    __ movflt(xmm0, Address(rsp, 0));
  } else {
    __ fld_d(Address(rsp, 0));
  }
  __ increment(rsp, 2 * wordSize);

1184
  __ popa();
1185
  __ leave();
1186
  BLOCK_COMMENT("} trace_method_handle");
1187 1188 1189
}
#endif //PRODUCT

1190 1191
// which conversion op types are implemented here?
int MethodHandles::adapter_conversion_ops_supported_mask() {
1192 1193 1194 1195 1196
  return ((1<<java_lang_invoke_AdapterMethodHandle::OP_RETYPE_ONLY)
         |(1<<java_lang_invoke_AdapterMethodHandle::OP_RETYPE_RAW)
         |(1<<java_lang_invoke_AdapterMethodHandle::OP_CHECK_CAST)
         |(1<<java_lang_invoke_AdapterMethodHandle::OP_PRIM_TO_PRIM)
         |(1<<java_lang_invoke_AdapterMethodHandle::OP_REF_TO_PRIM)
1197
          //OP_PRIM_TO_REF is below...
1198 1199 1200 1201
         |(1<<java_lang_invoke_AdapterMethodHandle::OP_SWAP_ARGS)
         |(1<<java_lang_invoke_AdapterMethodHandle::OP_ROT_ARGS)
         |(1<<java_lang_invoke_AdapterMethodHandle::OP_DUP_ARGS)
         |(1<<java_lang_invoke_AdapterMethodHandle::OP_DROP_ARGS)
1202 1203
          //OP_COLLECT_ARGS is below...
         |(1<<java_lang_invoke_AdapterMethodHandle::OP_SPREAD_ARGS)
1204
         |(
1205 1206 1207 1208 1209
           java_lang_invoke_MethodTypeForm::vmlayout_offset_in_bytes() <= 0 ? 0 :
           ((1<<java_lang_invoke_AdapterMethodHandle::OP_PRIM_TO_REF)
           |(1<<java_lang_invoke_AdapterMethodHandle::OP_COLLECT_ARGS)
           |(1<<java_lang_invoke_AdapterMethodHandle::OP_FOLD_ARGS)
            ))
1210 1211 1212
         );
}

1213 1214 1215
//------------------------------------------------------------------------------
// MethodHandles::generate_method_handle_stub
//
1216 1217
// Generate an "entry" field for a method handle.
// This determines how the method handle will respond to calls.
1218
void MethodHandles::generate_method_handle_stub(MacroAssembler* _masm, MethodHandles::EntryKind ek) {
1219 1220
  MethodHandles::EntryKind ek_orig = ek_original_kind(ek);

1221 1222 1223 1224 1225 1226 1227 1228
  // Here is the register state during an interpreted call,
  // as set up by generate_method_handle_interpreter_entry():
  // - rbx: garbage temp (was MethodHandle.invoke methodOop, unused)
  // - rcx: receiver method handle
  // - rax: method handle type (only used by the check_mtype entry point)
  // - rsi/r13: sender SP (must preserve; see prepare_to_jump_from_interpreted)
  // - rdx: garbage temp, can blow away

1229 1230 1231 1232
  const Register rcx_recv    = rcx;
  const Register rax_argslot = rax;
  const Register rbx_temp    = rbx;
  const Register rdx_temp    = rdx;
1233
  const Register rdi_temp    = rdi;
1234

1235 1236
  // This guy is set up by prepare_to_jump_from_interpreted (from interpreted calls)
  // and gen_c2i_adapter (from compiled calls):
1237
  const Register saved_last_sp = saved_last_sp_register();
1238 1239 1240 1241 1242 1243 1244

  // Argument registers for _raise_exception.
  // 32-bit: Pass first two oop/int args in registers ECX and EDX.
  const Register rarg0_code     = LP64_ONLY(j_rarg0) NOT_LP64(rcx);
  const Register rarg1_actual   = LP64_ONLY(j_rarg1) NOT_LP64(rdx);
  const Register rarg2_required = LP64_ONLY(j_rarg2) NOT_LP64(rdi);
  assert_different_registers(rarg0_code, rarg1_actual, rarg2_required, saved_last_sp);
1245

1246
  guarantee(java_lang_invoke_MethodHandle::vmentry_offset_in_bytes() != 0, "must have offsets");
1247 1248

  // some handy addresses
1249 1250
  Address rcx_mh_vmtarget(    rcx_recv, java_lang_invoke_MethodHandle::vmtarget_offset_in_bytes() );
  Address rcx_dmh_vmindex(    rcx_recv, java_lang_invoke_DirectMethodHandle::vmindex_offset_in_bytes() );
1251

1252 1253
  Address rcx_bmh_vmargslot(  rcx_recv, java_lang_invoke_BoundMethodHandle::vmargslot_offset_in_bytes() );
  Address rcx_bmh_argument(   rcx_recv, java_lang_invoke_BoundMethodHandle::argument_offset_in_bytes() );
1254

1255 1256 1257
  Address rcx_amh_vmargslot(  rcx_recv, java_lang_invoke_AdapterMethodHandle::vmargslot_offset_in_bytes() );
  Address rcx_amh_argument(   rcx_recv, java_lang_invoke_AdapterMethodHandle::argument_offset_in_bytes() );
  Address rcx_amh_conversion( rcx_recv, java_lang_invoke_AdapterMethodHandle::conversion_offset_in_bytes() );
1258 1259
  Address vmarg;                // __ argument_address(vmargslot)

1260
  const int java_mirror_offset = in_bytes(Klass::java_mirror_offset());
1261

1262 1263 1264 1265 1266
  if (have_entry(ek)) {
    __ nop();                   // empty stubs make SG sick
    return;
  }

1267 1268 1269 1270 1271 1272 1273
#ifdef ASSERT
  __ push((int32_t) 0xEEEEEEEE);
  __ push((int32_t) (intptr_t) entry_name(ek));
  LP64_ONLY(__ push((int32_t) high((intptr_t) entry_name(ek))));
  __ push((int32_t) 0x33333333);
#endif //ASSERT

1274 1275
  address interp_entry = __ pc();

1276 1277
  trace_method_handle(_masm, entry_name(ek));

1278
  BLOCK_COMMENT(err_msg("Entry %s {", entry_name(ek)));
1279 1280

  switch ((int) ek) {
1281
  case _raise_exception:
1282
    {
1283
      // Not a real MH entry, but rather shared code for raising an
1284 1285
      // exception.  Since we use the compiled entry, arguments are
      // expected in compiler argument registers.
1286
      assert(raise_exception_method(), "must be set");
1287
      assert(raise_exception_method()->from_compiled_entry(), "method must be linked");
1288

1289 1290
      const Register rax_pc = rax;
      __ pop(rax_pc);  // caller PC
1291
      __ mov(rsp, saved_last_sp);  // cut the stack back to where the caller started
1292

1293 1294
      Register rbx_method = rbx_temp;
      __ movptr(rbx_method, ExternalAddress((address) &_raise_exception_method));
1295 1296

      const int jobject_oop_offset = 0;
1297
      __ movptr(rbx_method, Address(rbx_method, jobject_oop_offset));  // dereference the jobject
1298

1299
      __ movptr(saved_last_sp, rsp);
1300 1301 1302
      __ subptr(rsp, 3 * wordSize);
      __ push(rax_pc);         // restore caller PC

1303
      __ movl  (__ argument_address(constant(2)), rarg0_code);
1304 1305 1306
      __ movptr(__ argument_address(constant(1)), rarg1_actual);
      __ movptr(__ argument_address(constant(0)), rarg2_required);
      jump_from_method_handle(_masm, rbx_method, rax);
1307 1308 1309 1310 1311 1312 1313
    }
    break;

  case _invokestatic_mh:
  case _invokespecial_mh:
    {
      Register rbx_method = rbx_temp;
1314
      __ load_heap_oop(rbx_method, rcx_mh_vmtarget); // target is a methodOop
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
      __ verify_oop(rbx_method);
      // same as TemplateTable::invokestatic or invokespecial,
      // minus the CP setup and profiling:
      if (ek == _invokespecial_mh) {
        // Must load & check the first argument before entering the target method.
        __ load_method_handle_vmslots(rax_argslot, rcx_recv, rdx_temp);
        __ movptr(rcx_recv, __ argument_address(rax_argslot, -1));
        __ null_check(rcx_recv);
        __ verify_oop(rcx_recv);
      }
1325
      jump_from_method_handle(_masm, rbx_method, rax);
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
    }
    break;

  case _invokevirtual_mh:
    {
      // same as TemplateTable::invokevirtual,
      // minus the CP setup and profiling:

      // pick out the vtable index and receiver offset from the MH,
      // and then we can discard it:
      __ load_method_handle_vmslots(rax_argslot, rcx_recv, rdx_temp);
      Register rbx_index = rbx_temp;
      __ movl(rbx_index, rcx_dmh_vmindex);
      // Note:  The verifier allows us to ignore rcx_mh_vmtarget.
      __ movptr(rcx_recv, __ argument_address(rax_argslot, -1));
      __ null_check(rcx_recv, oopDesc::klass_offset_in_bytes());

      // get receiver klass
      Register rax_klass = rax_argslot;
      __ load_klass(rax_klass, rcx_recv);
      __ verify_oop(rax_klass);

      // get target methodOop & entry point
      const int base = instanceKlass::vtable_start_offset() * wordSize;
      assert(vtableEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
      Address vtable_entry_addr(rax_klass,
                                rbx_index, Address::times_ptr,
                                base + vtableEntry::method_offset_in_bytes());
      Register rbx_method = rbx_temp;
1355
      __ movptr(rbx_method, vtable_entry_addr);
1356 1357

      __ verify_oop(rbx_method);
1358
      jump_from_method_handle(_masm, rbx_method, rax);
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
    }
    break;

  case _invokeinterface_mh:
    {
      // same as TemplateTable::invokeinterface,
      // minus the CP setup and profiling:

      // pick out the interface and itable index from the MH.
      __ load_method_handle_vmslots(rax_argslot, rcx_recv, rdx_temp);
      Register rdx_intf  = rdx_temp;
      Register rbx_index = rbx_temp;
1371 1372
      __ load_heap_oop(rdx_intf, rcx_mh_vmtarget);
      __ movl(rbx_index, rcx_dmh_vmindex);
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
      __ movptr(rcx_recv, __ argument_address(rax_argslot, -1));
      __ null_check(rcx_recv, oopDesc::klass_offset_in_bytes());

      // get receiver klass
      Register rax_klass = rax_argslot;
      __ load_klass(rax_klass, rcx_recv);
      __ verify_oop(rax_klass);

      Register rbx_method = rbx_index;

      // get interface klass
      Label no_such_interface;
      __ verify_oop(rdx_intf);
      __ lookup_interface_method(rax_klass, rdx_intf,
                                 // note: next two args must be the same:
                                 rbx_index, rbx_method,
1389
                                 rdi_temp,
1390 1391 1392
                                 no_such_interface);

      __ verify_oop(rbx_method);
1393
      jump_from_method_handle(_masm, rbx_method, rax);
1394 1395 1396 1397 1398
      __ hlt();

      __ bind(no_such_interface);
      // Throw an exception.
      // For historical reasons, it will be IncompatibleClassChangeError.
1399 1400 1401 1402 1403
      __ mov(rbx_temp, rcx_recv);  // rarg2_required might be RCX
      assert_different_registers(rarg2_required, rbx_temp);
      __ movptr(rarg2_required, Address(rdx_intf, java_mirror_offset));  // required interface
      __ mov(   rarg1_actual,   rbx_temp);                               // bad receiver
      __ movl(  rarg0_code,     (int) Bytecodes::_invokeinterface);      // who is complaining?
1404
      __ jump(ExternalAddress(from_interpreted_entry(_raise_exception)));
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
    }
    break;

  case _bound_ref_mh:
  case _bound_int_mh:
  case _bound_long_mh:
  case _bound_ref_direct_mh:
  case _bound_int_direct_mh:
  case _bound_long_direct_mh:
    {
1415
      const bool direct_to_method = (ek >= _bound_ref_direct_mh);
1416 1417
      BasicType arg_type  = ek_bound_mh_arg_type(ek);
      int       arg_slots = type2size[arg_type];
1418 1419 1420 1421

      // make room for the new argument:
      __ movl(rax_argslot, rcx_bmh_vmargslot);
      __ lea(rax_argslot, __ argument_address(rax_argslot));
1422

1423
      insert_arg_slots(_masm, arg_slots * stack_move_unit(), rax_argslot, rbx_temp, rdx_temp);
1424 1425

      // store bound argument into the new stack slot:
1426
      __ load_heap_oop(rbx_temp, rcx_bmh_argument);
1427 1428 1429
      if (arg_type == T_OBJECT) {
        __ movptr(Address(rax_argslot, 0), rbx_temp);
      } else {
1430
        Address prim_value_addr(rbx_temp, java_lang_boxing_object::value_offset_in_bytes(arg_type));
1431 1432 1433 1434
        move_typed_arg(_masm, arg_type, false,
                       Address(rax_argslot, 0),
                       prim_value_addr,
                       rbx_temp, rdx_temp);
1435 1436 1437 1438
      }

      if (direct_to_method) {
        Register rbx_method = rbx_temp;
1439
        __ load_heap_oop(rbx_method, rcx_mh_vmtarget);
1440
        __ verify_oop(rbx_method);
1441
        jump_from_method_handle(_masm, rbx_method, rax);
1442
      } else {
1443
        __ load_heap_oop(rcx_recv, rcx_mh_vmtarget);
1444 1445 1446 1447 1448 1449
        __ verify_oop(rcx_recv);
        __ jump_to_method_handle_entry(rcx_recv, rdx_temp);
      }
    }
    break;

1450 1451 1452 1453 1454 1455 1456
  case _adapter_opt_profiling:
    if (java_lang_invoke_CountingMethodHandle::vmcount_offset_in_bytes() != 0) {
      Address rcx_mh_vmcount(rcx_recv, java_lang_invoke_CountingMethodHandle::vmcount_offset_in_bytes());
      __ incrementl(rcx_mh_vmcount);
    }
    // fall through

1457
  case _adapter_retype_only:
1458
  case _adapter_retype_raw:
1459
    // immediately jump to the next MH layer:
1460
    __ load_heap_oop(rcx_recv, rcx_mh_vmtarget);
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
    __ verify_oop(rcx_recv);
    __ jump_to_method_handle_entry(rcx_recv, rdx_temp);
    // This is OK when all parameter types widen.
    // It is also OK when a return type narrows.
    break;

  case _adapter_check_cast:
    {
      // temps:
      Register rbx_klass = rbx_temp; // interesting AMH data

      // check a reference argument before jumping to the next layer of MH:
      __ movl(rax_argslot, rcx_amh_vmargslot);
      vmarg = __ argument_address(rax_argslot);

      // What class are we casting to?
1477
      __ load_heap_oop(rbx_klass, rcx_amh_argument); // this is a Class object!
1478
      load_klass_from_Class(_masm, rbx_klass);
1479 1480 1481

      Label done;
      __ movptr(rdx_temp, vmarg);
1482
      __ testptr(rdx_temp, rdx_temp);
1483
      __ jcc(Assembler::zero, done);         // no cast if null
1484 1485 1486 1487 1488
      __ load_klass(rdx_temp, rdx_temp);

      // live at this point:
      // - rbx_klass:  klass required by the target method
      // - rdx_temp:   argument klass to test
1489
      // - rcx_recv:   adapter method handle
1490 1491 1492 1493 1494
      __ check_klass_subtype(rdx_temp, rbx_klass, rax_argslot, done);

      // If we get here, the type check failed!
      // Call the wrong_method_type stub, passing the failing argument type in rax.
      Register rax_mtype = rax_argslot;
1495 1496 1497
      __ movl(rax_argslot, rcx_amh_vmargslot);  // reload argslot field
      __ movptr(rdx_temp, vmarg);

1498 1499 1500 1501
      assert_different_registers(rarg2_required, rdx_temp);
      __ load_heap_oop(rarg2_required, rcx_amh_argument);             // required class
      __ mov(          rarg1_actual,   rdx_temp);                     // bad object
      __ movl(         rarg0_code,     (int) Bytecodes::_checkcast);  // who is complaining?
1502
      __ jump(ExternalAddress(from_interpreted_entry(_raise_exception)));
1503 1504

      __ bind(done);
1505
      // get the new MH:
1506
      __ load_heap_oop(rcx_recv, rcx_mh_vmtarget);
1507 1508 1509 1510 1511 1512
      __ jump_to_method_handle_entry(rcx_recv, rdx_temp);
    }
    break;

  case _adapter_prim_to_prim:
  case _adapter_ref_to_prim:
1513
  case _adapter_prim_to_ref:
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
    // handled completely by optimized cases
    __ stop("init_AdapterMethodHandle should not issue this");
    break;

  case _adapter_opt_i2i:        // optimized subcase of adapt_prim_to_prim
//case _adapter_opt_f2i:        // optimized subcase of adapt_prim_to_prim
  case _adapter_opt_l2i:        // optimized subcase of adapt_prim_to_prim
  case _adapter_opt_unboxi:     // optimized subcase of adapt_ref_to_prim
    {
      // perform an in-place conversion to int or an int subword
      __ movl(rax_argslot, rcx_amh_vmargslot);
      vmarg = __ argument_address(rax_argslot);

      switch (ek) {
      case _adapter_opt_i2i:
        __ movl(rdx_temp, vmarg);
        break;
      case _adapter_opt_l2i:
        {
          // just delete the extra slot; on a little-endian machine we keep the first
          __ lea(rax_argslot, __ argument_address(rax_argslot, 1));
          remove_arg_slots(_masm, -stack_move_unit(),
                           rax_argslot, rbx_temp, rdx_temp);
1537
          vmarg = Address(rax_argslot, -Interpreter::stackElementSize);
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
          __ movl(rdx_temp, vmarg);
        }
        break;
      case _adapter_opt_unboxi:
        {
          // Load the value up from the heap.
          __ movptr(rdx_temp, vmarg);
          int value_offset = java_lang_boxing_object::value_offset_in_bytes(T_INT);
#ifdef ASSERT
          for (int bt = T_BOOLEAN; bt < T_INT; bt++) {
            if (is_subword_type(BasicType(bt)))
              assert(value_offset == java_lang_boxing_object::value_offset_in_bytes(BasicType(bt)), "");
          }
#endif
          __ null_check(rdx_temp, value_offset);
          __ movl(rdx_temp, Address(rdx_temp, value_offset));
          // We load this as a word.  Because we are little-endian,
          // the low bits will be correct, but the high bits may need cleaning.
          // The vminfo will guide us to clean those bits.
        }
        break;
      default:
T
twisti 已提交
1560
        ShouldNotReachHere();
1561 1562
      }

T
twisti 已提交
1563
      // Do the requested conversion and store the value.
1564
      Register rbx_vminfo = rbx_temp;
1565
      load_conversion_vminfo(_masm, rbx_vminfo, rcx_amh_conversion);
1566 1567

      // get the new MH:
1568
      __ load_heap_oop(rcx_recv, rcx_mh_vmtarget);
1569 1570 1571
      // (now we are done with the old MH)

      // original 32-bit vmdata word must be of this form:
1572 1573
      //    | MBZ:6 | signBitCount:8 | srcDstTypes:8 | conversionOp:8 |
      __ xchgptr(rcx, rbx_vminfo);                // free rcx for shifts
1574 1575 1576
      __ shll(rdx_temp /*, rcx*/);
      Label zero_extend, done;
      __ testl(rcx, CONV_VMINFO_SIGN_FLAG);
1577
      __ jccb(Assembler::zero, zero_extend);
1578 1579 1580

      // this path is taken for int->byte, int->short
      __ sarl(rdx_temp /*, rcx*/);
1581
      __ jmpb(done);
1582 1583 1584 1585 1586 1587

      __ bind(zero_extend);
      // this is taken for int->char
      __ shrl(rdx_temp /*, rcx*/);

      __ bind(done);
T
twisti 已提交
1588
      __ movl(vmarg, rdx_temp);  // Store the value.
1589
      __ xchgptr(rcx, rbx_vminfo);                // restore rcx_recv
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602

      __ jump_to_method_handle_entry(rcx_recv, rdx_temp);
    }
    break;

  case _adapter_opt_i2l:        // optimized subcase of adapt_prim_to_prim
  case _adapter_opt_unboxl:     // optimized subcase of adapt_ref_to_prim
    {
      // perform an in-place int-to-long or ref-to-long conversion
      __ movl(rax_argslot, rcx_amh_vmargslot);

      // on a little-endian machine we keep the first slot and add another after
      __ lea(rax_argslot, __ argument_address(rax_argslot, 1));
1603
      insert_arg_slots(_masm, stack_move_unit(),
1604
                       rax_argslot, rbx_temp, rdx_temp);
1605 1606
      Address vmarg1(rax_argslot, -Interpreter::stackElementSize);
      Address vmarg2 = vmarg1.plus_disp(Interpreter::stackElementSize);
1607 1608 1609 1610

      switch (ek) {
      case _adapter_opt_i2l:
        {
1611 1612 1613 1614
#ifdef _LP64
          __ movslq(rdx_temp, vmarg1);  // Load sign-extended
          __ movq(vmarg1, rdx_temp);    // Store into first slot
#else
1615
          __ movl(rdx_temp, vmarg1);
1616
          __ sarl(rdx_temp, BitsPerInt - 1);  // __ extend_sign()
1617
          __ movl(vmarg2, rdx_temp); // store second word
1618
#endif
1619 1620 1621 1622 1623 1624 1625 1626 1627
        }
        break;
      case _adapter_opt_unboxl:
        {
          // Load the value up from the heap.
          __ movptr(rdx_temp, vmarg1);
          int value_offset = java_lang_boxing_object::value_offset_in_bytes(T_LONG);
          assert(value_offset == java_lang_boxing_object::value_offset_in_bytes(T_DOUBLE), "");
          __ null_check(rdx_temp, value_offset);
1628 1629 1630 1631
#ifdef _LP64
          __ movq(rbx_temp, Address(rdx_temp, value_offset));
          __ movq(vmarg1, rbx_temp);
#else
1632 1633 1634 1635
          __ movl(rbx_temp, Address(rdx_temp, value_offset + 0*BytesPerInt));
          __ movl(rdx_temp, Address(rdx_temp, value_offset + 1*BytesPerInt));
          __ movl(vmarg1, rbx_temp);
          __ movl(vmarg2, rdx_temp);
1636
#endif
1637 1638 1639
        }
        break;
      default:
T
twisti 已提交
1640
        ShouldNotReachHere();
1641 1642
      }

1643
      __ load_heap_oop(rcx_recv, rcx_mh_vmtarget);
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
      __ jump_to_method_handle_entry(rcx_recv, rdx_temp);
    }
    break;

  case _adapter_opt_f2d:        // optimized subcase of adapt_prim_to_prim
  case _adapter_opt_d2f:        // optimized subcase of adapt_prim_to_prim
    {
      // perform an in-place floating primitive conversion
      __ movl(rax_argslot, rcx_amh_vmargslot);
      __ lea(rax_argslot, __ argument_address(rax_argslot, 1));
      if (ek == _adapter_opt_f2d) {
1655
        insert_arg_slots(_masm, stack_move_unit(),
1656 1657
                         rax_argslot, rbx_temp, rdx_temp);
      }
1658
      Address vmarg(rax_argslot, -Interpreter::stackElementSize);
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672

#ifdef _LP64
      if (ek == _adapter_opt_f2d) {
        __ movflt(xmm0, vmarg);
        __ cvtss2sd(xmm0, xmm0);
        __ movdbl(vmarg, xmm0);
      } else {
        __ movdbl(xmm0, vmarg);
        __ cvtsd2ss(xmm0, xmm0);
        __ movflt(vmarg, xmm0);
      }
#else //_LP64
      if (ek == _adapter_opt_f2d) {
        __ fld_s(vmarg);        // load float to ST0
1673
        __ fstp_d(vmarg);       // store double
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
      } else {
        __ fld_d(vmarg);        // load double to ST0
        __ fstp_s(vmarg);       // store single
      }
#endif //_LP64

      if (ek == _adapter_opt_d2f) {
        remove_arg_slots(_masm, -stack_move_unit(),
                         rax_argslot, rbx_temp, rdx_temp);
      }

1685
      __ load_heap_oop(rcx_recv, rcx_mh_vmtarget);
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
      __ jump_to_method_handle_entry(rcx_recv, rdx_temp);
    }
    break;

  case _adapter_swap_args:
  case _adapter_rot_args:
    // handled completely by optimized cases
    __ stop("init_AdapterMethodHandle should not issue this");
    break;

  case _adapter_opt_swap_1:
  case _adapter_opt_swap_2:
  case _adapter_opt_rot_1_up:
  case _adapter_opt_rot_1_down:
  case _adapter_opt_rot_2_up:
  case _adapter_opt_rot_2_down:
    {
1703 1704
      int swap_slots = ek_adapter_opt_swap_slots(ek);
      int rotate     = ek_adapter_opt_swap_mode(ek);
1705 1706 1707 1708 1709 1710 1711

      // 'argslot' is the position of the first argument to swap
      __ movl(rax_argslot, rcx_amh_vmargslot);
      __ lea(rax_argslot, __ argument_address(rax_argslot));

      // 'vminfo' is the second
      Register rbx_destslot = rbx_temp;
1712
      load_conversion_vminfo(_masm, rbx_destslot, rcx_amh_conversion);
1713
      __ lea(rbx_destslot, __ argument_address(rbx_destslot));
1714 1715
      if (VerifyMethodHandles)
        verify_argslot(_masm, rbx_destslot, "swap point must fall within current frame");
1716

1717
      assert(Interpreter::stackElementSize == wordSize, "else rethink use of wordSize here");
1718
      if (!rotate) {
1719 1720 1721 1722 1723 1724
        // simple swap
        for (int i = 0; i < swap_slots; i++) {
          __ movptr(rdi_temp, Address(rax_argslot,  i * wordSize));
          __ movptr(rdx_temp, Address(rbx_destslot, i * wordSize));
          __ movptr(Address(rax_argslot,  i * wordSize), rdx_temp);
          __ movptr(Address(rbx_destslot, i * wordSize), rdi_temp);
1725 1726
        }
      } else {
1727 1728 1729 1730 1731 1732 1733
        // A rotate is actually pair of moves, with an "odd slot" (or pair)
        // changing place with a series of other slots.
        // First, push the "odd slot", which is going to get overwritten
        for (int i = swap_slots - 1; i >= 0; i--) {
          // handle one with rdi_temp instead of a push:
          if (i == 0)  __ movptr(rdi_temp, Address(rax_argslot, i * wordSize));
          else         __ pushptr(         Address(rax_argslot, i * wordSize));
1734 1735
        }
        if (rotate > 0) {
1736 1737 1738 1739 1740
          // Here is rotate > 0:
          // (low mem)                                          (high mem)
          //     | dest:     more_slots...     | arg: odd_slot :arg+1 |
          // =>
          //     | dest: odd_slot | dest+1: more_slots...      :arg+1 |
1741 1742 1743 1744 1745
          // work argslot down to destslot, copying contiguous data upwards
          // pseudo-code:
          //   rax = src_addr - swap_bytes
          //   rbx = dest_addr
          //   while (rax >= rbx) *(rax + swap_bytes) = *(rax + 0), rax--;
1746 1747 1748 1749 1750
          move_arg_slots_up(_masm,
                            rbx_destslot,
                            Address(rax_argslot, 0),
                            swap_slots,
                            rax_argslot, rdx_temp);
1751
        } else {
1752 1753 1754 1755 1756
          // Here is the other direction, rotate < 0:
          // (low mem)                                          (high mem)
          //     | arg: odd_slot | arg+1: more_slots...       :dest+1 |
          // =>
          //     | arg:    more_slots...     | dest: odd_slot :dest+1 |
1757 1758 1759 1760 1761
          // work argslot up to destslot, copying contiguous data downwards
          // pseudo-code:
          //   rax = src_addr + swap_bytes
          //   rbx = dest_addr
          //   while (rax <= rbx) *(rax - swap_bytes) = *(rax + 0), rax++;
1762 1763 1764 1765
          // dest_slot denotes an exclusive upper limit
          int limit_bias = OP_ROT_ARGS_DOWN_LIMIT_BIAS;
          if (limit_bias != 0)
            __ addptr(rbx_destslot, - limit_bias * wordSize);
1766 1767 1768 1769 1770
          move_arg_slots_down(_masm,
                              Address(rax_argslot, swap_slots * wordSize),
                              rbx_destslot,
                              -swap_slots,
                              rax_argslot, rdx_temp);
1771
          __ subptr(rbx_destslot, swap_slots * wordSize);
1772 1773
        }
        // pop the original first chunk into the destination slot, now free
1774 1775 1776
        for (int i = 0; i < swap_slots; i++) {
          if (i == 0)  __ movptr(Address(rbx_destslot, i * wordSize), rdi_temp);
          else         __ popptr(Address(rbx_destslot, i * wordSize));
1777 1778 1779
        }
      }

1780
      __ load_heap_oop(rcx_recv, rcx_mh_vmtarget);
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
      __ jump_to_method_handle_entry(rcx_recv, rdx_temp);
    }
    break;

  case _adapter_dup_args:
    {
      // 'argslot' is the position of the first argument to duplicate
      __ movl(rax_argslot, rcx_amh_vmargslot);
      __ lea(rax_argslot, __ argument_address(rax_argslot));

      // 'stack_move' is negative number of words to duplicate
1792 1793 1794 1795 1796 1797
      Register rdi_stack_move = rdi_temp;
      load_stack_move(_masm, rdi_stack_move, rcx_recv, true);

      if (VerifyMethodHandles) {
        verify_argslots(_masm, rdi_stack_move, rax_argslot, true,
                        "copied argument(s) must fall within current frame");
1798 1799
      }

1800 1801 1802 1803 1804 1805 1806 1807
      // insert location is always the bottom of the argument list:
      Address insert_location = __ argument_address(constant(0));
      int pre_arg_words = insert_location.disp() / wordSize;   // return PC is pushed
      assert(insert_location.base() == rsp, "");

      __ negl(rdi_stack_move);
      push_arg_slots(_masm, rax_argslot, rdi_stack_move,
                     pre_arg_words, rbx_temp, rdx_temp);
1808

1809
      __ load_heap_oop(rcx_recv, rcx_mh_vmtarget);
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
      __ jump_to_method_handle_entry(rcx_recv, rdx_temp);
    }
    break;

  case _adapter_drop_args:
    {
      // 'argslot' is the position of the first argument to nuke
      __ movl(rax_argslot, rcx_amh_vmargslot);
      __ lea(rax_argslot, __ argument_address(rax_argslot));

      // (must do previous push after argslot address is taken)

      // 'stack_move' is number of words to drop
1823 1824
      Register rdi_stack_move = rdi_temp;
      load_stack_move(_masm, rdi_stack_move, rcx_recv, false);
1825 1826 1827
      remove_arg_slots(_masm, rdi_stack_move,
                       rax_argslot, rbx_temp, rdx_temp);

1828
      __ load_heap_oop(rcx_recv, rcx_mh_vmtarget);
1829 1830 1831 1832 1833
      __ jump_to_method_handle_entry(rcx_recv, rdx_temp);
    }
    break;

  case _adapter_collect_args:
1834
  case _adapter_fold_args:
1835 1836 1837 1838 1839
  case _adapter_spread_args:
    // handled completely by optimized cases
    __ stop("init_AdapterMethodHandle should not issue this");
    break;

1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060
  case _adapter_opt_collect_ref:
  case _adapter_opt_collect_int:
  case _adapter_opt_collect_long:
  case _adapter_opt_collect_float:
  case _adapter_opt_collect_double:
  case _adapter_opt_collect_void:
  case _adapter_opt_collect_0_ref:
  case _adapter_opt_collect_1_ref:
  case _adapter_opt_collect_2_ref:
  case _adapter_opt_collect_3_ref:
  case _adapter_opt_collect_4_ref:
  case _adapter_opt_collect_5_ref:
  case _adapter_opt_filter_S0_ref:
  case _adapter_opt_filter_S1_ref:
  case _adapter_opt_filter_S2_ref:
  case _adapter_opt_filter_S3_ref:
  case _adapter_opt_filter_S4_ref:
  case _adapter_opt_filter_S5_ref:
  case _adapter_opt_collect_2_S0_ref:
  case _adapter_opt_collect_2_S1_ref:
  case _adapter_opt_collect_2_S2_ref:
  case _adapter_opt_collect_2_S3_ref:
  case _adapter_opt_collect_2_S4_ref:
  case _adapter_opt_collect_2_S5_ref:
  case _adapter_opt_fold_ref:
  case _adapter_opt_fold_int:
  case _adapter_opt_fold_long:
  case _adapter_opt_fold_float:
  case _adapter_opt_fold_double:
  case _adapter_opt_fold_void:
  case _adapter_opt_fold_1_ref:
  case _adapter_opt_fold_2_ref:
  case _adapter_opt_fold_3_ref:
  case _adapter_opt_fold_4_ref:
  case _adapter_opt_fold_5_ref:
    {
      // Given a fresh incoming stack frame, build a new ricochet frame.
      // On entry, TOS points at a return PC, and RBP is the callers frame ptr.
      // RSI/R13 has the caller's exact stack pointer, which we must also preserve.
      // RCX contains an AdapterMethodHandle of the indicated kind.

      // Relevant AMH fields:
      // amh.vmargslot:
      //   points to the trailing edge of the arguments
      //   to filter, collect, or fold.  For a boxing operation,
      //   it points just after the single primitive value.
      // amh.argument:
      //   recursively called MH, on |collect| arguments
      // amh.vmtarget:
      //   final destination MH, on return value, etc.
      // amh.conversion.dest:
      //   tells what is the type of the return value
      //   (not needed here, since dest is also derived from ek)
      // amh.conversion.vminfo:
      //   points to the trailing edge of the return value
      //   when the vmtarget is to be called; this is
      //   equal to vmargslot + (retained ? |collect| : 0)

      // Pass 0 or more argument slots to the recursive target.
      int collect_count_constant = ek_adapter_opt_collect_count(ek);

      // The collected arguments are copied from the saved argument list:
      int collect_slot_constant = ek_adapter_opt_collect_slot(ek);

      assert(ek_orig == _adapter_collect_args ||
             ek_orig == _adapter_fold_args, "");
      bool retain_original_args = (ek_orig == _adapter_fold_args);

      // The return value is replaced (or inserted) at the 'vminfo' argslot.
      // Sometimes we can compute this statically.
      int dest_slot_constant = -1;
      if (!retain_original_args)
        dest_slot_constant = collect_slot_constant;
      else if (collect_slot_constant >= 0 && collect_count_constant >= 0)
        // We are preserving all the arguments, and the return value is prepended,
        // so the return slot is to the left (above) the |collect| sequence.
        dest_slot_constant = collect_slot_constant + collect_count_constant;

      // Replace all those slots by the result of the recursive call.
      // The result type can be one of ref, int, long, float, double, void.
      // In the case of void, nothing is pushed on the stack after return.
      BasicType dest = ek_adapter_opt_collect_type(ek);
      assert(dest == type2wfield[dest], "dest is a stack slot type");
      int dest_count = type2size[dest];
      assert(dest_count == 1 || dest_count == 2 || (dest_count == 0 && dest == T_VOID), "dest has a size");

      // Choose a return continuation.
      EntryKind ek_ret = _adapter_opt_return_any;
      if (dest != T_CONFLICT && OptimizeMethodHandles) {
        switch (dest) {
        case T_INT    : ek_ret = _adapter_opt_return_int;     break;
        case T_LONG   : ek_ret = _adapter_opt_return_long;    break;
        case T_FLOAT  : ek_ret = _adapter_opt_return_float;   break;
        case T_DOUBLE : ek_ret = _adapter_opt_return_double;  break;
        case T_OBJECT : ek_ret = _adapter_opt_return_ref;     break;
        case T_VOID   : ek_ret = _adapter_opt_return_void;    break;
        default       : ShouldNotReachHere();
        }
        if (dest == T_OBJECT && dest_slot_constant >= 0) {
          EntryKind ek_try = EntryKind(_adapter_opt_return_S0_ref + dest_slot_constant);
          if (ek_try <= _adapter_opt_return_LAST &&
              ek_adapter_opt_return_slot(ek_try) == dest_slot_constant) {
            ek_ret = ek_try;
          }
        }
        assert(ek_adapter_opt_return_type(ek_ret) == dest, "");
      }

      // Already pushed:  ... keep1 | collect | keep2 | sender_pc |
      // push(sender_pc);

      // Compute argument base:
      Register rax_argv = rax_argslot;
      __ lea(rax_argv, __ argument_address(constant(0)));

      // Push a few extra argument words, if we need them to store the return value.
      {
        int extra_slots = 0;
        if (retain_original_args) {
          extra_slots = dest_count;
        } else if (collect_count_constant == -1) {
          extra_slots = dest_count;  // collect_count might be zero; be generous
        } else if (dest_count > collect_count_constant) {
          extra_slots = (dest_count - collect_count_constant);
        } else {
          // else we know we have enough dead space in |collect| to repurpose for return values
        }
        DEBUG_ONLY(extra_slots += 1);
        if (extra_slots > 0) {
          __ pop(rbx_temp);   // return value
          __ subptr(rsp, (extra_slots * Interpreter::stackElementSize));
          // Push guard word #2 in debug mode.
          DEBUG_ONLY(__ movptr(Address(rsp, 0), (int32_t) RicochetFrame::MAGIC_NUMBER_2));
          __ push(rbx_temp);
        }
      }

      RicochetFrame::enter_ricochet_frame(_masm, rcx_recv, rax_argv,
                                          entry(ek_ret)->from_interpreted_entry(), rbx_temp);

      // Now pushed:  ... keep1 | collect | keep2 | RF |
      // some handy frame slots:
      Address exact_sender_sp_addr = RicochetFrame::frame_address(RicochetFrame::exact_sender_sp_offset_in_bytes());
      Address conversion_addr      = RicochetFrame::frame_address(RicochetFrame::conversion_offset_in_bytes());
      Address saved_args_base_addr = RicochetFrame::frame_address(RicochetFrame::saved_args_base_offset_in_bytes());

#ifdef ASSERT
      if (VerifyMethodHandles && dest != T_CONFLICT) {
        BLOCK_COMMENT("verify AMH.conv.dest");
        load_conversion_dest_type(_masm, rbx_temp, conversion_addr);
        Label L_dest_ok;
        __ cmpl(rbx_temp, (int) dest);
        __ jcc(Assembler::equal, L_dest_ok);
        if (dest == T_INT) {
          for (int bt = T_BOOLEAN; bt < T_INT; bt++) {
            if (is_subword_type(BasicType(bt))) {
              __ cmpl(rbx_temp, (int) bt);
              __ jcc(Assembler::equal, L_dest_ok);
            }
          }
        }
        __ stop("bad dest in AMH.conv");
        __ BIND(L_dest_ok);
      }
#endif //ASSERT

      // Find out where the original copy of the recursive argument sequence begins.
      Register rax_coll = rax_argv;
      {
        RegisterOrConstant collect_slot = collect_slot_constant;
        if (collect_slot_constant == -1) {
          __ movl(rdi_temp, rcx_amh_vmargslot);
          collect_slot = rdi_temp;
        }
        if (collect_slot_constant != 0)
          __ lea(rax_coll, Address(rax_argv, collect_slot, Interpreter::stackElementScale()));
        // rax_coll now points at the trailing edge of |collect| and leading edge of |keep2|
      }

      // Replace the old AMH with the recursive MH.  (No going back now.)
      // In the case of a boxing call, the recursive call is to a 'boxer' method,
      // such as Integer.valueOf or Long.valueOf.  In the case of a filter
      // or collect call, it will take one or more arguments, transform them,
      // and return some result, to store back into argument_base[vminfo].
      __ load_heap_oop(rcx_recv, rcx_amh_argument);
      if (VerifyMethodHandles)  verify_method_handle(_masm, rcx_recv);

      // Push a space for the recursively called MH first:
      __ push((int32_t)NULL_WORD);

      // Calculate |collect|, the number of arguments we are collecting.
      Register rdi_collect_count = rdi_temp;
      RegisterOrConstant collect_count;
      if (collect_count_constant >= 0) {
        collect_count = collect_count_constant;
      } else {
        __ load_method_handle_vmslots(rdi_collect_count, rcx_recv, rdx_temp);
        collect_count = rdi_collect_count;
      }
#ifdef ASSERT
      if (VerifyMethodHandles && collect_count_constant >= 0) {
        __ load_method_handle_vmslots(rbx_temp, rcx_recv, rdx_temp);
        Label L_count_ok;
        __ cmpl(rbx_temp, collect_count_constant);
        __ jcc(Assembler::equal, L_count_ok);
        __ stop("bad vminfo in AMH.conv");
        __ BIND(L_count_ok);
      }
#endif //ASSERT

      // copy |collect| slots directly to TOS:
      push_arg_slots(_masm, rax_coll, collect_count, 0, rbx_temp, rdx_temp);
      // Now pushed:  ... keep1 | collect | keep2 | RF... | collect |
      // rax_coll still points at the trailing edge of |collect| and leading edge of |keep2|

      // If necessary, adjust the saved arguments to make room for the eventual return value.
      // Normal adjustment:  ... keep1 | +dest+ | -collect- | keep2 | RF... | collect |
      // If retaining args:  ... keep1 | +dest+ |  collect  | keep2 | RF... | collect |
      // In the non-retaining case, this might move keep2 either up or down.
      // We don't have to copy the whole | RF... collect | complex,
      // but we must adjust RF.saved_args_base.
2061
      // Also, from now on, we will forget about the original copy of |collect|.
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
      // If we are retaining it, we will treat it as part of |keep2|.
      // For clarity we will define |keep3| = |collect|keep2| or |keep2|.

      BLOCK_COMMENT("adjust trailing arguments {");
      // Compare the sizes of |+dest+| and |-collect-|, which are opposed opening and closing movements.
      int                open_count  = dest_count;
      RegisterOrConstant close_count = collect_count_constant;
      Register rdi_close_count = rdi_collect_count;
      if (retain_original_args) {
        close_count = constant(0);
      } else if (collect_count_constant == -1) {
        close_count = rdi_collect_count;
      }

      // How many slots need moving?  This is simply dest_slot (0 => no |keep3|).
      RegisterOrConstant keep3_count;
      Register rsi_keep3_count = rsi;  // can repair from RF.exact_sender_sp
      if (dest_slot_constant >= 0) {
        keep3_count = dest_slot_constant;
      } else  {
        load_conversion_vminfo(_masm, rsi_keep3_count, conversion_addr);
        keep3_count = rsi_keep3_count;
      }
#ifdef ASSERT
      if (VerifyMethodHandles && dest_slot_constant >= 0) {
        load_conversion_vminfo(_masm, rbx_temp, conversion_addr);
        Label L_vminfo_ok;
        __ cmpl(rbx_temp, dest_slot_constant);
        __ jcc(Assembler::equal, L_vminfo_ok);
        __ stop("bad vminfo in AMH.conv");
        __ BIND(L_vminfo_ok);
      }
#endif //ASSERT

      // tasks remaining:
      bool move_keep3 = (!keep3_count.is_constant() || keep3_count.as_constant() != 0);
      bool stomp_dest = (NOT_DEBUG(dest == T_OBJECT) DEBUG_ONLY(dest_count != 0));
      bool fix_arg_base = (!close_count.is_constant() || open_count != close_count.as_constant());

      if (stomp_dest | fix_arg_base) {
        // we will probably need an updated rax_argv value
        if (collect_slot_constant >= 0) {
          // rax_coll already holds the leading edge of |keep2|, so tweak it
          assert(rax_coll == rax_argv, "elided a move");
          if (collect_slot_constant != 0)
            __ subptr(rax_argv, collect_slot_constant * Interpreter::stackElementSize);
        } else {
          // Just reload from RF.saved_args_base.
          __ movptr(rax_argv, saved_args_base_addr);
        }
      }

      // Old and new argument locations (based at slot 0).
      // Net shift (&new_argv - &old_argv) is (close_count - open_count).
      bool zero_open_count = (open_count == 0);  // remember this bit of info
      if (move_keep3 && fix_arg_base) {
2118
        // It will be easier to have everything in one register:
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
        if (close_count.is_register()) {
          // Deduct open_count from close_count register to get a clean +/- value.
          __ subptr(close_count.as_register(), open_count);
        } else {
          close_count = close_count.as_constant() - open_count;
        }
        open_count = 0;
      }
      Address old_argv(rax_argv, 0);
      Address new_argv(rax_argv, close_count,  Interpreter::stackElementScale(),
                                - open_count * Interpreter::stackElementSize);

      // First decide if any actual data are to be moved.
      // We can skip if (a) |keep3| is empty, or (b) the argument list size didn't change.
      // (As it happens, all movements involve an argument list size change.)

      // If there are variable parameters, use dynamic checks to skip around the whole mess.
      Label L_done;
      if (!keep3_count.is_constant()) {
        __ testl(keep3_count.as_register(), keep3_count.as_register());
        __ jcc(Assembler::zero, L_done);
      }
      if (!close_count.is_constant()) {
        __ cmpl(close_count.as_register(), open_count);
        __ jcc(Assembler::equal, L_done);
      }

      if (move_keep3 && fix_arg_base) {
        bool emit_move_down = false, emit_move_up = false, emit_guard = false;
        if (!close_count.is_constant()) {
          emit_move_down = emit_guard = !zero_open_count;
          emit_move_up   = true;
        } else if (open_count != close_count.as_constant()) {
          emit_move_down = (open_count > close_count.as_constant());
          emit_move_up   = !emit_move_down;
        }
        Label L_move_up;
        if (emit_guard) {
          __ cmpl(close_count.as_register(), open_count);
          __ jcc(Assembler::greater, L_move_up);
        }

        if (emit_move_down) {
          // Move arguments down if |+dest+| > |-collect-|
          // (This is rare, except when arguments are retained.)
          // This opens space for the return value.
          if (keep3_count.is_constant()) {
            for (int i = 0; i < keep3_count.as_constant(); i++) {
              __ movptr(rdx_temp, old_argv.plus_disp(i * Interpreter::stackElementSize));
              __ movptr(          new_argv.plus_disp(i * Interpreter::stackElementSize), rdx_temp);
            }
          } else {
            Register rbx_argv_top = rbx_temp;
            __ lea(rbx_argv_top, old_argv.plus_disp(keep3_count, Interpreter::stackElementScale()));
            move_arg_slots_down(_masm,
                                old_argv,     // beginning of old argv
                                rbx_argv_top, // end of old argv
                                close_count,  // distance to move down (must be negative)
                                rax_argv, rdx_temp);
            // Used argv as an iteration variable; reload from RF.saved_args_base.
            __ movptr(rax_argv, saved_args_base_addr);
          }
        }

        if (emit_guard) {
          __ jmp(L_done);  // assumes emit_move_up is true also
          __ BIND(L_move_up);
        }

        if (emit_move_up) {

          // Move arguments up if |+dest+| < |-collect-|
          // (This is usual, except when |keep3| is empty.)
          // This closes up the space occupied by the now-deleted collect values.
          if (keep3_count.is_constant()) {
            for (int i = keep3_count.as_constant() - 1; i >= 0; i--) {
              __ movptr(rdx_temp, old_argv.plus_disp(i * Interpreter::stackElementSize));
              __ movptr(          new_argv.plus_disp(i * Interpreter::stackElementSize), rdx_temp);
            }
          } else {
            Address argv_top = old_argv.plus_disp(keep3_count, Interpreter::stackElementScale());
            move_arg_slots_up(_masm,
                              rax_argv,     // beginning of old argv
                              argv_top,     // end of old argv
                              close_count,  // distance to move up (must be positive)
                              rbx_temp, rdx_temp);
          }
        }
      }
      __ BIND(L_done);

      if (fix_arg_base) {
        // adjust RF.saved_args_base by adding (close_count - open_count)
        if (!new_argv.is_same_address(Address(rax_argv, 0)))
          __ lea(rax_argv, new_argv);
        __ movptr(saved_args_base_addr, rax_argv);
      }

      if (stomp_dest) {
        // Stomp the return slot, so it doesn't hold garbage.
        // This isn't strictly necessary, but it may help detect bugs.
        int forty_two = RicochetFrame::RETURN_VALUE_PLACEHOLDER;
        __ movptr(Address(rax_argv, keep3_count, Address::times_ptr),
                  (int32_t) forty_two);
        // uses rsi_keep3_count
      }
      BLOCK_COMMENT("} adjust trailing arguments");

      BLOCK_COMMENT("do_recursive_call");
      __ mov(saved_last_sp, rsp);    // set rsi/r13 for callee
      __ pushptr(ExternalAddress(SharedRuntime::ricochet_blob()->bounce_addr()).addr());
      // The globally unique bounce address has two purposes:
      // 1. It helps the JVM recognize this frame (frame::is_ricochet_frame).
      // 2. When returned to, it cuts back the stack and redirects control flow
      //    to the return handler.
      // The return handler will further cut back the stack when it takes
      // down the RF.  Perhaps there is a way to streamline this further.

      // State during recursive call:
      // ... keep1 | dest | dest=42 | keep3 | RF... | collect | bounce_pc |
      __ jump_to_method_handle_entry(rcx_recv, rdx_temp);

      break;
    }

  case _adapter_opt_return_ref:
  case _adapter_opt_return_int:
  case _adapter_opt_return_long:
  case _adapter_opt_return_float:
  case _adapter_opt_return_double:
  case _adapter_opt_return_void:
  case _adapter_opt_return_S0_ref:
  case _adapter_opt_return_S1_ref:
  case _adapter_opt_return_S2_ref:
  case _adapter_opt_return_S3_ref:
  case _adapter_opt_return_S4_ref:
  case _adapter_opt_return_S5_ref:
    {
      BasicType dest_type_constant = ek_adapter_opt_return_type(ek);
      int       dest_slot_constant = ek_adapter_opt_return_slot(ek);

      if (VerifyMethodHandles)  RicochetFrame::verify_clean(_masm);

      if (dest_slot_constant == -1) {
        // The current stub is a general handler for this dest_type.
        // It can be called from _adapter_opt_return_any below.
        // Stash the address in a little table.
        assert((dest_type_constant & CONV_TYPE_MASK) == dest_type_constant, "oob");
        address return_handler = __ pc();
        _adapter_return_handlers[dest_type_constant] = return_handler;
        if (dest_type_constant == T_INT) {
          // do the subword types too
          for (int bt = T_BOOLEAN; bt < T_INT; bt++) {
            if (is_subword_type(BasicType(bt)) &&
                _adapter_return_handlers[bt] == NULL) {
              _adapter_return_handlers[bt] = return_handler;
            }
          }
        }
      }

      Register rbx_arg_base = rbx_temp;
      assert_different_registers(rax, rdx,  // possibly live return value registers
                                 rdi_temp, rbx_arg_base);

      Address conversion_addr      = RicochetFrame::frame_address(RicochetFrame::conversion_offset_in_bytes());
      Address saved_args_base_addr = RicochetFrame::frame_address(RicochetFrame::saved_args_base_offset_in_bytes());

      __ movptr(rbx_arg_base, saved_args_base_addr);
      RegisterOrConstant dest_slot = dest_slot_constant;
      if (dest_slot_constant == -1) {
        load_conversion_vminfo(_masm, rdi_temp, conversion_addr);
        dest_slot = rdi_temp;
      }
      // Store the result back into the argslot.
      // This code uses the interpreter calling sequence, in which the return value
      // is usually left in the TOS register, as defined by InterpreterMacroAssembler::pop.
      // There are certain irregularities with floating point values, which can be seen
      // in TemplateInterpreterGenerator::generate_return_entry_for.
      move_return_value(_masm, dest_type_constant, Address(rbx_arg_base, dest_slot, Interpreter::stackElementScale()));

      RicochetFrame::leave_ricochet_frame(_masm, rcx_recv, rbx_arg_base, rdx_temp);
      __ push(rdx_temp);  // repush the return PC

      // Load the final target and go.
      if (VerifyMethodHandles)  verify_method_handle(_masm, rcx_recv);
      __ jump_to_method_handle_entry(rcx_recv, rdx_temp);
      __ hlt(); // --------------------
      break;
    }

  case _adapter_opt_return_any:
    {
      if (VerifyMethodHandles)  RicochetFrame::verify_clean(_masm);
      Register rdi_conv = rdi_temp;
      assert_different_registers(rax, rdx,  // possibly live return value registers
                                 rdi_conv, rbx_temp);

      Address conversion_addr = RicochetFrame::frame_address(RicochetFrame::conversion_offset_in_bytes());
      load_conversion_dest_type(_masm, rdi_conv, conversion_addr);
      __ lea(rbx_temp, ExternalAddress((address) &_adapter_return_handlers[0]));
      __ movptr(rbx_temp, Address(rbx_temp, rdi_conv, Address::times_ptr));

#ifdef ASSERT
      { Label L_badconv;
        __ testptr(rbx_temp, rbx_temp);
        __ jccb(Assembler::zero, L_badconv);
        __ jmp(rbx_temp);
        __ bind(L_badconv);
        __ stop("bad method handle return");
      }
#else //ASSERT
      __ jmp(rbx_temp);
#endif //ASSERT
      break;
    }

2336
  case _adapter_opt_spread_0:
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
  case _adapter_opt_spread_1_ref:
  case _adapter_opt_spread_2_ref:
  case _adapter_opt_spread_3_ref:
  case _adapter_opt_spread_4_ref:
  case _adapter_opt_spread_5_ref:
  case _adapter_opt_spread_ref:
  case _adapter_opt_spread_byte:
  case _adapter_opt_spread_char:
  case _adapter_opt_spread_short:
  case _adapter_opt_spread_int:
  case _adapter_opt_spread_long:
  case _adapter_opt_spread_float:
  case _adapter_opt_spread_double:
2350 2351
    {
      // spread an array out into a group of arguments
2352 2353 2354 2355 2356 2357 2358 2359
      int length_constant = ek_adapter_opt_spread_count(ek);
      bool length_can_be_zero = (length_constant == 0);
      if (length_constant < 0) {
        // some adapters with variable length must handle the zero case
        if (!OptimizeMethodHandles ||
            ek_adapter_opt_spread_type(ek) != T_OBJECT)
          length_can_be_zero = true;
      }
2360 2361 2362 2363 2364

      // find the address of the array argument
      __ movl(rax_argslot, rcx_amh_vmargslot);
      __ lea(rax_argslot, __ argument_address(rax_argslot));

2365 2366 2367 2368 2369 2370
      // grab another temp
      Register rsi_temp = rsi;
      { if (rsi_temp == saved_last_sp)  __ push(saved_last_sp); }
      // (preceding push must be done after argslot address is taken!)
#define UNPUSH_RSI \
      { if (rsi_temp == saved_last_sp)  __ pop(saved_last_sp); }
2371 2372 2373 2374 2375

      // arx_argslot points both to the array and to the first output arg
      vmarg = Address(rax_argslot, 0);

      // Get the array value.
2376
      Register  rsi_array       = rsi_temp;
2377
      Register  rdx_array_klass = rdx_temp;
2378 2379 2380
      BasicType elem_type = ek_adapter_opt_spread_type(ek);
      int       elem_slots = type2size[elem_type];  // 1 or 2
      int       array_slots = 1;  // array is always a T_OBJECT
2381 2382 2383
      int       length_offset   = arrayOopDesc::length_offset_in_bytes();
      int       elem0_offset    = arrayOopDesc::base_offset_in_bytes(elem_type);
      __ movptr(rsi_array, vmarg);
2384 2385 2386 2387 2388 2389 2390 2391 2392 2393

      Label L_array_is_empty, L_insert_arg_space, L_copy_args, L_args_done;
      if (length_can_be_zero) {
        // handle the null pointer case, if zero is allowed
        Label L_skip;
        if (length_constant < 0) {
          load_conversion_vminfo(_masm, rbx_temp, rcx_amh_conversion);
          __ testl(rbx_temp, rbx_temp);
          __ jcc(Assembler::notZero, L_skip);
        }
2394
        __ testptr(rsi_array, rsi_array);
2395 2396
        __ jcc(Assembler::zero, L_array_is_empty);
        __ bind(L_skip);
2397 2398 2399 2400 2401 2402
      }
      __ null_check(rsi_array, oopDesc::klass_offset_in_bytes());
      __ load_klass(rdx_array_klass, rsi_array);

      // Check the array type.
      Register rbx_klass = rbx_temp;
2403
      __ load_heap_oop(rbx_klass, rcx_amh_argument); // this is a Class object!
2404
      load_klass_from_Class(_masm, rbx_klass);
2405 2406

      Label ok_array_klass, bad_array_klass, bad_array_length;
2407
      __ check_klass_subtype(rdx_array_klass, rbx_klass, rdi_temp, ok_array_klass);
2408 2409
      // If we get here, the type check failed!
      __ jmp(bad_array_klass);
2410
      __ BIND(ok_array_klass);
2411 2412 2413 2414 2415 2416

      // Check length.
      if (length_constant >= 0) {
        __ cmpl(Address(rsi_array, length_offset), length_constant);
      } else {
        Register rbx_vminfo = rbx_temp;
2417
        load_conversion_vminfo(_masm, rbx_vminfo, rcx_amh_conversion);
2418 2419 2420 2421 2422 2423 2424 2425 2426
        __ cmpl(rbx_vminfo, Address(rsi_array, length_offset));
      }
      __ jcc(Assembler::notEqual, bad_array_length);

      Register rdx_argslot_limit = rdx_temp;

      // Array length checks out.  Now insert any required stack slots.
      if (length_constant == -1) {
        // Form a pointer to the end of the affected region.
2427
        __ lea(rdx_argslot_limit, Address(rax_argslot, Interpreter::stackElementSize));
2428
        // 'stack_move' is negative number of words to insert
2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
        // This number already accounts for elem_slots.
        Register rdi_stack_move = rdi_temp;
        load_stack_move(_masm, rdi_stack_move, rcx_recv, true);
        __ cmpptr(rdi_stack_move, 0);
        assert(stack_move_unit() < 0, "else change this comparison");
        __ jcc(Assembler::less, L_insert_arg_space);
        __ jcc(Assembler::equal, L_copy_args);
        // single argument case, with no array movement
        __ BIND(L_array_is_empty);
        remove_arg_slots(_masm, -stack_move_unit() * array_slots,
                         rax_argslot, rbx_temp, rdx_temp);
        __ jmp(L_args_done);  // no spreading to do
        __ BIND(L_insert_arg_space);
        // come here in the usual case, stack_move < 0 (2 or more spread arguments)
2443
        Register rsi_temp = rsi_array;  // spill this
2444
        insert_arg_slots(_masm, rdi_stack_move,
2445
                         rax_argslot, rbx_temp, rsi_temp);
2446 2447 2448 2449 2450 2451
        // reload the array since rsi was killed
        // reload from rdx_argslot_limit since rax_argslot is now decremented
        __ movptr(rsi_array, Address(rdx_argslot_limit, -Interpreter::stackElementSize));
      } else if (length_constant >= 1) {
        int new_slots = (length_constant * elem_slots) - array_slots;
        insert_arg_slots(_masm, new_slots * stack_move_unit(),
2452 2453
                         rax_argslot, rbx_temp, rdx_temp);
      } else if (length_constant == 0) {
2454 2455
        __ BIND(L_array_is_empty);
        remove_arg_slots(_masm, -stack_move_unit() * array_slots,
2456
                         rax_argslot, rbx_temp, rdx_temp);
2457 2458
      } else {
        ShouldNotReachHere();
2459 2460 2461 2462 2463
      }

      // Copy from the array to the new slots.
      // Note: Stack change code preserves integrity of rax_argslot pointer.
      // So even after slot insertions, rax_argslot still points to first argument.
2464 2465 2466 2467
      // Beware:  Arguments that are shallow on the stack are deep in the array,
      // and vice versa.  So a downward-growing stack (the usual) has to be copied
      // elementwise in reverse order from the source array.
      __ BIND(L_copy_args);
2468 2469
      if (length_constant == -1) {
        // [rax_argslot, rdx_argslot_limit) is the area we are inserting into.
2470
        // Array element [0] goes at rdx_argslot_limit[-wordSize].
2471 2472
        Register rsi_source = rsi_array;
        __ lea(rsi_source, Address(rsi_array, elem0_offset));
2473
        Register rdx_fill_ptr = rdx_argslot_limit;
2474
        Label loop;
2475 2476 2477 2478 2479
        __ BIND(loop);
        __ addptr(rdx_fill_ptr, -Interpreter::stackElementSize * elem_slots);
        move_typed_arg(_masm, elem_type, true,
                       Address(rdx_fill_ptr, 0), Address(rsi_source, 0),
                       rbx_temp, rdi_temp);
2480
        __ addptr(rsi_source, type2aelembytes(elem_type));
2481
        __ cmpptr(rdx_fill_ptr, rax_argslot);
2482
        __ jcc(Assembler::above, loop);
2483 2484 2485 2486
      } else if (length_constant == 0) {
        // nothing to copy
      } else {
        int elem_offset = elem0_offset;
2487
        int slot_offset = length_constant * Interpreter::stackElementSize;
2488
        for (int index = 0; index < length_constant; index++) {
2489 2490 2491 2492
          slot_offset -= Interpreter::stackElementSize * elem_slots;  // fill backward
          move_typed_arg(_masm, elem_type, true,
                         Address(rax_argslot, slot_offset), Address(rsi_array, elem_offset),
                         rbx_temp, rdi_temp);
2493 2494 2495
          elem_offset += type2aelembytes(elem_type);
        }
      }
2496
      __ BIND(L_args_done);
2497 2498

      // Arguments are spread.  Move to next method handle.
2499
      UNPUSH_RSI;
2500
      __ load_heap_oop(rcx_recv, rcx_mh_vmtarget);
2501 2502 2503
      __ jump_to_method_handle_entry(rcx_recv, rdx_temp);

      __ bind(bad_array_klass);
2504
      UNPUSH_RSI;
2505
      assert(!vmarg.uses(rarg2_required), "must be different registers");
2506 2507 2508
      __ load_heap_oop( rarg2_required, Address(rdx_array_klass, java_mirror_offset));  // required type
      __ movptr(        rarg1_actual,   vmarg);                                         // bad array
      __ movl(          rarg0_code,     (int) Bytecodes::_aaload);                      // who is complaining?
2509
      __ jump(ExternalAddress(from_interpreted_entry(_raise_exception)));
2510 2511

      __ bind(bad_array_length);
2512
      UNPUSH_RSI;
2513
      assert(!vmarg.uses(rarg2_required), "must be different registers");
2514 2515 2516
      __ mov(    rarg2_required, rcx_recv);                       // AMH requiring a certain length
      __ movptr( rarg1_actual,   vmarg);                          // bad array
      __ movl(   rarg0_code,     (int) Bytecodes::_arraylength);  // who is complaining?
2517
      __ jump(ExternalAddress(from_interpreted_entry(_raise_exception)));
2518
#undef UNPUSH_RSI
2519

2520
      break;
2521 2522
    }

2523 2524 2525 2526
  default:
    // do not require all platforms to recognize all adapter types
    __ nop();
    return;
2527
  }
2528
  BLOCK_COMMENT(err_msg("} Entry %s", entry_name(ek)));
2529 2530 2531 2532 2533 2534 2535
  __ hlt();

  address me_cookie = MethodHandleEntry::start_compiled_entry(_masm, interp_entry);
  __ unimplemented(entry_name(ek)); // %%% FIXME: NYI

  init_entry(ek, MethodHandleEntry::finish_compiled_entry(_masm, me_cookie));
}