1 /*
  2  * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "asm/macroAssembler.hpp"
 26 #include "classfile/vmClasses.hpp"
 27 #include "compiler/disassembler.hpp"
 28 #include "classfile/javaClasses.inline.hpp"
 29 #include "interpreter/interpreter.hpp"
 30 #include "interpreter/interpreterRuntime.hpp"
 31 #include "jvm.h"
 32 #include "logging/log.hpp"
 33 #include "logging/logStream.hpp"
 34 #include "memory/allocation.inline.hpp"
 35 #include "memory/resourceArea.hpp"
 36 #include "prims/jvmtiExport.hpp"
 37 #include "prims/methodHandles.hpp"
 38 #include "runtime/flags/flagSetting.hpp"
 39 #include "runtime/frame.inline.hpp"
 40 #include "runtime/stubRoutines.hpp"
 41 #include "utilities/formatBuffer.hpp"
 42 #include "utilities/preserveException.hpp"
 43 
 44 #define __ Disassembler::hook<MacroAssembler>(__FILE__, __LINE__, _masm)->
 45 
 46 #ifdef PRODUCT
 47 #define BLOCK_COMMENT(str) /* nothing */
 48 #define STOP(error) stop(error)
 49 #else
 50 #define BLOCK_COMMENT(str) __ block_comment(str)
 51 #define STOP(error) block_comment(error); __ stop(error)
 52 #endif
 53 
 54 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
 55 
 56 void MethodHandles::load_klass_from_Class(MacroAssembler* _masm, Register klass_reg) {
 57   if (VerifyMethodHandles)
 58     verify_klass(_masm, klass_reg, VM_CLASS_ID(java_lang_Class),
 59                  "MH argument is a Class");
 60   __ movptr(klass_reg, Address(klass_reg, java_lang_Class::klass_offset()));
 61 }
 62 
 63 #ifdef ASSERT
 64 static int check_nonzero(const char* xname, int x) {
 65   assert(x != 0, "%s should be nonzero", xname);
 66   return x;
 67 }
 68 #define NONZERO(x) check_nonzero(#x, x)
 69 #else //ASSERT
 70 #define NONZERO(x) (x)
 71 #endif //ASSERT
 72 
 73 #ifdef ASSERT
 74 void MethodHandles::verify_klass(MacroAssembler* _masm,
 75                                  Register obj, vmClassID klass_id,
 76                                  const char* error_message) {
 77   InstanceKlass** klass_addr = vmClasses::klass_addr_at(klass_id);
 78   Klass* klass = vmClasses::klass_at(klass_id);
 79   Register temp = rdi;
 80   Label L_ok, L_bad;
 81   BLOCK_COMMENT("verify_klass {");
 82   __ verify_oop(obj);
 83   __ testptr(obj, obj);
 84   __ jcc(Assembler::zero, L_bad);
 85 #define PUSH { __ push(temp); __ push(rscratch1);               }
 86 #define POP  {                __ pop(rscratch1);  __ pop(temp); }
 87   PUSH;
 88   __ load_klass(temp, obj, rscratch1);
 89   __ cmpptr(temp, ExternalAddress((address) klass_addr), rscratch1);
 90   __ jcc(Assembler::equal, L_ok);
 91   intptr_t super_check_offset = klass->super_check_offset();
 92   __ movptr(temp, Address(temp, super_check_offset));
 93   __ cmpptr(temp, ExternalAddress((address) klass_addr), rscratch1);
 94   __ jcc(Assembler::equal, L_ok);
 95   POP;
 96   __ bind(L_bad);
 97   __ STOP(error_message);
 98   __ BIND(L_ok);
 99   POP;
100   BLOCK_COMMENT("} verify_klass");
101 #undef POP
102 #undef PUSH
103 }
104 
105 void MethodHandles::verify_ref_kind(MacroAssembler* _masm, int ref_kind, Register member_reg, Register temp) {
106   Label L;
107   BLOCK_COMMENT("verify_ref_kind {");
108   __ movl(temp, Address(member_reg, NONZERO(java_lang_invoke_MemberName::flags_offset())));
109   __ shrl(temp, java_lang_invoke_MemberName::MN_REFERENCE_KIND_SHIFT);
110   __ andl(temp, java_lang_invoke_MemberName::MN_REFERENCE_KIND_MASK);
111   __ cmpl(temp, ref_kind);
112   __ jcc(Assembler::equal, L);
113   { char* buf = NEW_C_HEAP_ARRAY(char, 100, mtInternal);
114     jio_snprintf(buf, 100, "verify_ref_kind expected %x", ref_kind);
115     if (ref_kind == JVM_REF_invokeVirtual ||
116         ref_kind == JVM_REF_invokeSpecial)
117       // could do this for all ref_kinds, but would explode assembly code size
118       trace_method_handle(_masm, buf);
119     __ STOP(buf);
120   }
121   BLOCK_COMMENT("} verify_ref_kind");
122   __ bind(L);
123 }
124 
125 void MethodHandles::verify_method(MacroAssembler* _masm, Register method, Register temp, vmIntrinsics::ID iid) {
126   BLOCK_COMMENT("verify_method {");
127   __ verify_method_ptr(method);
128   if (VerifyMethodHandles) {
129     Label L_ok;
130     assert_different_registers(method, temp);
131 
132     const Register method_holder = temp;
133     __ load_method_holder(method_holder, method);
134     __ push(method_holder); // keep holder around for diagnostic purposes
135 
136     switch (iid) {
137       case vmIntrinsicID::_invokeBasic:
138         // Require compiled LambdaForm class to be fully initialized.
139         __ cmpb(Address(method_holder, InstanceKlass::init_state_offset()), InstanceKlass::fully_initialized);
140         __ jccb(Assembler::equal, L_ok);
141         break;
142 
143       case vmIntrinsicID::_linkToStatic:
144         __ clinit_barrier(method_holder, &L_ok);
145         break;
146 
147       case vmIntrinsicID::_linkToVirtual:
148       case vmIntrinsicID::_linkToSpecial:
149       case vmIntrinsicID::_linkToInterface:
150         // Class initialization check is too strong here. Just ensure that initialization has been initiated.
151         __ cmpb(Address(method_holder, InstanceKlass::init_state_offset()), InstanceKlass::being_initialized);
152         __ jcc(Assembler::greaterEqual, L_ok);
153 
154         // init_state check failed, but it may be an abstract interface method
155         __ load_unsigned_short(temp, Address(method, Method::access_flags_offset()));
156         __ testl(temp, JVM_ACC_ABSTRACT);
157         __ jccb(Assembler::notZero, L_ok);
158         break;
159 
160       default:
161         fatal("unexpected intrinsic %d: %s", vmIntrinsics::as_int(iid), vmIntrinsics::name_at(iid));
162     }
163 
164     // clinit check failed for a concrete method
165     __ STOP("Method holder klass is not initialized");
166 
167     __ BIND(L_ok);
168     __ pop(method_holder); // restore stack layout
169   }
170   BLOCK_COMMENT("} verify_method");
171 }
172 #endif // ASSERT
173 
174 void MethodHandles::jump_from_method_handle(MacroAssembler* _masm, Register method, Register temp,
175                                             bool for_compiler_entry, vmIntrinsics::ID iid) {
176   assert(method == rbx, "interpreter calling convention");
177 
178    Label L_no_such_method;
179    __ testptr(rbx, rbx);
180    __ jcc(Assembler::zero, L_no_such_method);
181 
182   verify_method(_masm, method, temp, iid);
183 
184   if (!for_compiler_entry && JvmtiExport::can_post_interpreter_events()) {
185     Label run_compiled_code;
186     // JVMTI events, such as single-stepping, are implemented partly by avoiding running
187     // compiled code in threads for which the event is enabled.  Check here for
188     // interp_only_mode if these events CAN be enabled.
189     // interp_only is an int, on little endian it is sufficient to test the byte only
190     // Is a cmpl faster?
191     __ cmpb(Address(r15_thread, JavaThread::interp_only_mode_offset()), 0);
192     __ jccb(Assembler::zero, run_compiled_code);
193     __ jmp(Address(method, Method::interpreter_entry_offset()));
194     __ BIND(run_compiled_code);
195   }
196 
197   // The following jump might pass an inline type argument that was erased to Object as oop to a
198   // callee that expects inline type arguments to be passed as fields. We need to call the compiled
199   // value entry (_code->inline_entry_point() or _adapter->c2i_inline_entry()) which will take care
200   // of translating between the calling conventions.
201   const ByteSize entry_offset = for_compiler_entry ? Method::from_compiled_inline_offset() :
202                                                      Method::from_interpreted_offset();
203   __ jmp(Address(method, entry_offset));
204 
205   __ bind(L_no_such_method);
206   __ jump(RuntimeAddress(SharedRuntime::throw_AbstractMethodError_entry()));
207 }
208 
209 void MethodHandles::jump_to_lambda_form(MacroAssembler* _masm,
210                                         Register recv, Register method_temp,
211                                         Register temp2,
212                                         bool for_compiler_entry) {
213   BLOCK_COMMENT("jump_to_lambda_form {");
214   // This is the initial entry point of a lazy method handle.
215   // After type checking, it picks up the invoker from the LambdaForm.
216   assert_different_registers(recv, method_temp, temp2);
217   assert(recv != noreg, "required register");
218   assert(method_temp == rbx, "required register for loading method");
219 
220   // Load the invoker, as MH -> MH.form -> LF.vmentry
221   __ verify_oop(recv);
222   __ load_heap_oop(method_temp, Address(recv, NONZERO(java_lang_invoke_MethodHandle::form_offset())), temp2);
223   __ verify_oop(method_temp);
224   __ load_heap_oop(method_temp, Address(method_temp, NONZERO(java_lang_invoke_LambdaForm::vmentry_offset())), temp2);
225   __ verify_oop(method_temp);
226   __ load_heap_oop(method_temp, Address(method_temp, NONZERO(java_lang_invoke_MemberName::method_offset())), temp2);
227   __ verify_oop(method_temp);
228   __ access_load_at(T_ADDRESS, IN_HEAP, method_temp,
229                     Address(method_temp, NONZERO(java_lang_invoke_ResolvedMethodName::vmtarget_offset())),
230                     noreg);
231 
232   if (VerifyMethodHandles && !for_compiler_entry) {
233     // make sure recv is already on stack
234     __ movptr(temp2, Address(method_temp, Method::const_offset()));
235     __ load_sized_value(temp2,
236                         Address(temp2, ConstMethod::size_of_parameters_offset()),
237                         sizeof(u2), /*is_signed*/ false);
238     // assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
239     Label L;
240     __ cmpoop(recv, __ argument_address(temp2, -1));
241     __ jcc(Assembler::equal, L);
242     __ movptr(rax, __ argument_address(temp2, -1));
243     __ STOP("receiver not on stack");
244     __ BIND(L);
245   }
246 
247   jump_from_method_handle(_masm, method_temp, temp2, for_compiler_entry, vmIntrinsics::_invokeBasic);
248   BLOCK_COMMENT("} jump_to_lambda_form");
249 }
250 
251 void MethodHandles::jump_to_native_invoker(MacroAssembler* _masm, Register nep_reg, Register temp_target) {
252   BLOCK_COMMENT("jump_to_native_invoker {");
253   assert_different_registers(nep_reg, temp_target);
254   assert(nep_reg != noreg, "required register");
255 
256   // Load the invoker, as NEP -> .invoker
257   __ verify_oop(nep_reg);
258   __ access_load_at(T_ADDRESS, IN_HEAP, temp_target,
259                     Address(nep_reg, NONZERO(jdk_internal_foreign_abi_NativeEntryPoint::downcall_stub_address_offset_in_bytes())),
260                     noreg);
261 
262   __ jmp(temp_target);
263   BLOCK_COMMENT("} jump_to_native_invoker");
264 }
265 
266 
267 // Code generation
268 address MethodHandles::generate_method_handle_interpreter_entry(MacroAssembler* _masm,
269                                                                 vmIntrinsics::ID iid) {
270   const bool not_for_compiler_entry = false;  // this is the interpreter entry
271   assert(is_signature_polymorphic(iid), "expected invoke iid");
272   if (iid == vmIntrinsics::_invokeGeneric ||
273       iid == vmIntrinsics::_compiledLambdaForm) {
274     // Perhaps surprisingly, the symbolic references visible to Java are not directly used.
275     // They are linked to Java-generated adapters via MethodHandleNatives.linkMethod.
276     // They all allow an appendix argument.
277     __ hlt();           // empty stubs make SG sick
278     return nullptr;
279   }
280 
281   // No need in interpreter entry for linkToNative for now.
282   // Interpreter calls compiled entry through i2c.
283   if (iid == vmIntrinsics::_linkToNative) {
284     __ hlt();
285     return nullptr;
286   }
287 
288   // rsi/r13: sender SP (must preserve; see prepare_to_jump_from_interpreted)
289   // rbx: Method*
290   // rdx: argument locator (parameter slot count, added to rsp)
291   // rcx: used as temp to hold mh or receiver
292   // rax, rdi: garbage temps, blown away
293   Register rdx_argp   = rdx;   // argument list ptr, live on error paths
294   Register rax_temp   = rax;
295   Register rcx_mh     = rcx;   // MH receiver; dies quickly and is recycled
296   Register rbx_method = rbx;   // eventual target of this invocation
297 
298   // here's where control starts out:
299   __ align(CodeEntryAlignment);
300   address entry_point = __ pc();
301 
302   if (VerifyMethodHandles) {
303     assert(Method::intrinsic_id_size_in_bytes() == 2, "assuming Method::_intrinsic_id is u2");
304 
305     Label L;
306     BLOCK_COMMENT("verify_intrinsic_id {");
307     __ cmpw(Address(rbx_method, Method::intrinsic_id_offset()), (int) iid);
308     __ jcc(Assembler::equal, L);
309     if (iid == vmIntrinsics::_linkToVirtual ||
310         iid == vmIntrinsics::_linkToSpecial) {
311       // could do this for all kinds, but would explode assembly code size
312       trace_method_handle(_masm, "bad Method*::intrinsic_id");
313     }
314     __ STOP("bad Method*::intrinsic_id");
315     __ bind(L);
316     BLOCK_COMMENT("} verify_intrinsic_id");
317   }
318 
319   // First task:  Find out how big the argument list is.
320   Address rdx_first_arg_addr;
321   int ref_kind = signature_polymorphic_intrinsic_ref_kind(iid);
322   assert(ref_kind != 0 || iid == vmIntrinsics::_invokeBasic, "must be _invokeBasic or a linkTo intrinsic");
323   if (ref_kind == 0 || MethodHandles::ref_kind_has_receiver(ref_kind)) {
324     __ movptr(rdx_argp, Address(rbx_method, Method::const_offset()));
325     __ load_sized_value(rdx_argp,
326                         Address(rdx_argp, ConstMethod::size_of_parameters_offset()),
327                         sizeof(u2), /*is_signed*/ false);
328     // assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
329     rdx_first_arg_addr = __ argument_address(rdx_argp, -1);
330   } else {
331     DEBUG_ONLY(rdx_argp = noreg);
332   }
333 
334   if (!is_signature_polymorphic_static(iid)) {
335     __ movptr(rcx_mh, rdx_first_arg_addr);
336     DEBUG_ONLY(rdx_argp = noreg);
337   }
338 
339   // rdx_first_arg_addr is live!
340 
341   trace_method_handle_interpreter_entry(_masm, iid);
342 
343   if (iid == vmIntrinsics::_invokeBasic) {
344     generate_method_handle_dispatch(_masm, iid, rcx_mh, noreg, not_for_compiler_entry);
345 
346   } else {
347     // Adjust argument list by popping the trailing MemberName argument.
348     Register rcx_recv = noreg;
349     if (MethodHandles::ref_kind_has_receiver(ref_kind)) {
350       // Load the receiver (not the MH; the actual MemberName's receiver) up from the interpreter stack.
351       __ movptr(rcx_recv = rcx, rdx_first_arg_addr);
352     }
353     DEBUG_ONLY(rdx_argp = noreg);
354     Register rbx_member = rbx_method;  // MemberName ptr; incoming method ptr is dead now
355     __ pop(rax_temp);           // return address
356     __ pop(rbx_member);         // extract last argument
357     __ push(rax_temp);          // re-push return address
358     generate_method_handle_dispatch(_masm, iid, rcx_recv, rbx_member, not_for_compiler_entry);
359   }
360 
361   return entry_point;
362 }
363 
364 void MethodHandles::generate_method_handle_dispatch(MacroAssembler* _masm,
365                                                     vmIntrinsics::ID iid,
366                                                     Register receiver_reg,
367                                                     Register member_reg,
368                                                     bool for_compiler_entry) {
369   assert(is_signature_polymorphic(iid), "expected invoke iid");
370   Register rbx_method = rbx;   // eventual target of this invocation
371   // temps used in this code are not used in *either* compiled or interpreted calling sequences
372   Register temp1 = rscratch1;
373   Register temp2 = rscratch2;
374   Register temp3 = rax;
375   if (for_compiler_entry) {
376     assert(receiver_reg == (iid == vmIntrinsics::_linkToStatic || iid == vmIntrinsics::_linkToNative ? noreg : j_rarg0), "only valid assignment");
377     assert_different_registers(temp1,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5);
378     assert_different_registers(temp2,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5);
379     assert_different_registers(temp3,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5);
380   } else {
381     assert_different_registers(temp1, temp2, temp3, saved_last_sp_register());  // don't trash lastSP
382   }
383   assert_different_registers(temp1, temp2, temp3, receiver_reg);
384   assert_different_registers(temp1, temp2, temp3, member_reg);
385 
386   if (iid == vmIntrinsics::_invokeBasic) {
387     // indirect through MH.form.vmentry.vmtarget
388     jump_to_lambda_form(_masm, receiver_reg, rbx_method, temp1, for_compiler_entry);
389   } else if (iid == vmIntrinsics::_linkToNative) {
390     assert(for_compiler_entry, "only compiler entry is supported");
391     jump_to_native_invoker(_masm, member_reg, temp1);
392   } else {
393     // The method is a member invoker used by direct method handles.
394     if (VerifyMethodHandles) {
395       // make sure the trailing argument really is a MemberName (caller responsibility)
396       verify_klass(_masm, member_reg, VM_CLASS_ID(java_lang_invoke_MemberName),
397                    "MemberName required for invokeVirtual etc.");
398     }
399 
400     Address member_clazz(    member_reg, NONZERO(java_lang_invoke_MemberName::clazz_offset()));
401     Address member_vmindex(  member_reg, NONZERO(java_lang_invoke_MemberName::vmindex_offset()));
402     Address member_vmtarget( member_reg, NONZERO(java_lang_invoke_MemberName::method_offset()));
403     Address vmtarget_method( rbx_method, NONZERO(java_lang_invoke_ResolvedMethodName::vmtarget_offset()));
404 
405     Register temp1_recv_klass = temp1;
406     if (iid != vmIntrinsics::_linkToStatic) {
407       __ verify_oop(receiver_reg);
408       if (iid == vmIntrinsics::_linkToSpecial) {
409         // Don't actually load the klass; just null-check the receiver.
410         __ null_check(receiver_reg);
411       } else {
412         // load receiver klass itself
413         __ load_klass(temp1_recv_klass, receiver_reg, temp2);
414         __ verify_klass_ptr(temp1_recv_klass);
415       }
416       BLOCK_COMMENT("check_receiver {");
417       // The receiver for the MemberName must be in receiver_reg.
418       // Check the receiver against the MemberName.clazz
419       if (VerifyMethodHandles && iid == vmIntrinsics::_linkToSpecial) {
420         // Did not load it above...
421         __ load_klass(temp1_recv_klass, receiver_reg, temp2);
422         __ verify_klass_ptr(temp1_recv_klass);
423       }
424       if (VerifyMethodHandles && iid != vmIntrinsics::_linkToInterface) {
425         Label L_ok;
426         Register temp2_defc = temp2;
427         __ load_heap_oop(temp2_defc, member_clazz, temp3);
428         load_klass_from_Class(_masm, temp2_defc);
429         __ verify_klass_ptr(temp2_defc);
430         __ check_klass_subtype(temp1_recv_klass, temp2_defc, temp3, L_ok);
431         // If we get here, the type check failed!
432         __ STOP("receiver class disagrees with MemberName.clazz");
433         __ bind(L_ok);
434       }
435       BLOCK_COMMENT("} check_receiver");
436     }
437     if (iid == vmIntrinsics::_linkToSpecial ||
438         iid == vmIntrinsics::_linkToStatic) {
439       DEBUG_ONLY(temp1_recv_klass = noreg);  // these guys didn't load the recv_klass
440     }
441 
442     // Live registers at this point:
443     //  member_reg - MemberName that was the trailing argument
444     //  temp1_recv_klass - klass of stacked receiver, if needed
445     //  rsi/r13 - interpreter linkage (if interpreted)
446     //  rcx, rdx, rsi, rdi, r8 - compiler arguments (if compiled)
447 
448     Label L_incompatible_class_change_error;
449     switch (iid) {
450     case vmIntrinsics::_linkToSpecial:
451       if (VerifyMethodHandles) {
452         verify_ref_kind(_masm, JVM_REF_invokeSpecial, member_reg, temp3);
453       }
454       __ load_heap_oop(rbx_method, member_vmtarget);
455       __ access_load_at(T_ADDRESS, IN_HEAP, rbx_method, vmtarget_method, noreg);
456       break;
457 
458     case vmIntrinsics::_linkToStatic:
459       if (VerifyMethodHandles) {
460         verify_ref_kind(_masm, JVM_REF_invokeStatic, member_reg, temp3);
461       }
462       __ load_heap_oop(rbx_method, member_vmtarget);
463       __ access_load_at(T_ADDRESS, IN_HEAP, rbx_method, vmtarget_method, noreg);
464       break;
465 
466     case vmIntrinsics::_linkToVirtual:
467     {
468       // same as TemplateTable::invokevirtual,
469       // minus the CP setup and profiling:
470 
471       if (VerifyMethodHandles) {
472         verify_ref_kind(_masm, JVM_REF_invokeVirtual, member_reg, temp3);
473       }
474 
475       // pick out the vtable index from the MemberName, and then we can discard it:
476       Register temp2_index = temp2;
477       __ access_load_at(T_ADDRESS, IN_HEAP, temp2_index, member_vmindex, noreg);
478 
479       if (VerifyMethodHandles) {
480         Label L_index_ok;
481         __ cmpl(temp2_index, 0);
482         __ jcc(Assembler::greaterEqual, L_index_ok);
483         __ STOP("no virtual index");
484         __ BIND(L_index_ok);
485       }
486 
487       // Note:  The verifier invariants allow us to ignore MemberName.clazz and vmtarget
488       // at this point.  And VerifyMethodHandles has already checked clazz, if needed.
489 
490       // get target Method* & entry point
491       __ lookup_virtual_method(temp1_recv_klass, temp2_index, rbx_method);
492       break;
493     }
494 
495     case vmIntrinsics::_linkToInterface:
496     {
497       // same as TemplateTable::invokeinterface
498       // (minus the CP setup and profiling, with different argument motion)
499       if (VerifyMethodHandles) {
500         verify_ref_kind(_masm, JVM_REF_invokeInterface, member_reg, temp3);
501       }
502 
503       Register temp3_intf = temp3;
504       __ load_heap_oop(temp3_intf, member_clazz);
505       load_klass_from_Class(_masm, temp3_intf);
506       __ verify_klass_ptr(temp3_intf);
507 
508       Register rbx_index = rbx_method;
509       __ access_load_at(T_ADDRESS, IN_HEAP, rbx_index, member_vmindex, noreg);
510       if (VerifyMethodHandles) {
511         Label L;
512         __ cmpl(rbx_index, 0);
513         __ jcc(Assembler::greaterEqual, L);
514         __ STOP("invalid vtable index for MH.invokeInterface");
515         __ bind(L);
516       }
517 
518       // given intf, index, and recv klass, dispatch to the implementation method
519       __ lookup_interface_method(temp1_recv_klass, temp3_intf,
520                                  // note: next two args must be the same:
521                                  rbx_index, rbx_method,
522                                  temp2,
523                                  L_incompatible_class_change_error);
524       break;
525     }
526 
527     default:
528       fatal("unexpected intrinsic %d: %s", vmIntrinsics::as_int(iid), vmIntrinsics::name_at(iid));
529       break;
530     }
531 
532     // Live at this point:
533     //   rbx_method
534     //   rsi/r13 (if interpreted)
535 
536     // After figuring out which concrete method to call, jump into it.
537     // Note that this works in the interpreter with no data motion.
538     // But the compiled version will require that rcx_recv be shifted out.
539     jump_from_method_handle(_masm, rbx_method, temp1, for_compiler_entry, iid);
540 
541     if (iid == vmIntrinsics::_linkToInterface) {
542       __ bind(L_incompatible_class_change_error);
543       __ jump(RuntimeAddress(SharedRuntime::throw_IncompatibleClassChangeError_entry()));
544     }
545   }
546 }
547 
548 #ifndef PRODUCT
549 void trace_method_handle_stub(const char* adaptername,
550                               oopDesc* mh,
551                               intptr_t* saved_regs,
552                               intptr_t* entry_sp) {
553   // called as a leaf from native code: do not block the JVM!
554   bool has_mh = (strstr(adaptername, "/static") == nullptr &&
555                  strstr(adaptername, "linkTo") == nullptr);    // static linkers don't have MH
556   const char* mh_reg_name = has_mh ? "rcx_mh" : "rcx";
557   log_info(methodhandles)("MH %s %s=" PTR_FORMAT " sp=" PTR_FORMAT, adaptername, mh_reg_name, p2i(mh), p2i(entry_sp));
558 
559   LogTarget(Trace, methodhandles) lt;
560   if (lt.is_enabled()) {
561     ResourceMark rm;
562     LogStream ls(lt);
563     ls.print_cr("Registers:");
564     const int saved_regs_count = Register::number_of_registers;
565     for (int i = 0; i < saved_regs_count; i++) {
566       Register r = as_Register(i);
567       // The registers are stored in reverse order on the stack (by pusha).
568 #ifdef AMD64
569       int num_regs = UseAPX ? 32 : 16;
570       assert(Register::available_gp_registers() == num_regs, "sanity");
571       if (r == rsp) {
572         // rsp is actually not stored by pusha(), compute the old rsp from saved_regs (rsp after pusha): saved_regs + 16 = old rsp
573         ls.print("%3s=" PTR_FORMAT, r->name(), (intptr_t)(&saved_regs[num_regs]));
574       } else {
575         ls.print("%3s=" PTR_FORMAT, r->name(), saved_regs[((saved_regs_count - 1) - i)]);
576       }
577 #else
578       ls.print("%3s=" PTR_FORMAT, r->name(), saved_regs[((saved_regs_count - 1) - i)]);
579 #endif
580       if ((i + 1) % 4 == 0) {
581         ls.cr();
582       } else {
583         ls.print(", ");
584       }
585     }
586     ls.cr();
587 
588     // Note: We want to allow trace_method_handle from any call site.
589     // While trace_method_handle creates a frame, it may be entered
590     // without a PC on the stack top (e.g. not just after a call).
591     // Walking that frame could lead to failures due to that invalid PC.
592     // => carefully detect that frame when doing the stack walking
593 
594     {
595       // dumping last frame with frame::describe
596 
597       JavaThread* p = JavaThread::active();
598 
599       // may not be needed by safer and unexpensive here
600       PreserveExceptionMark pem(Thread::current());
601       FrameValues values;
602 
603       frame cur_frame = os::current_frame();
604 
605       if (cur_frame.fp() != nullptr) { // not walkable
606 
607         // Robust search of trace_calling_frame (independent of inlining).
608         // Assumes saved_regs comes from a pusha in the trace_calling_frame.
609         //
610         // We have to start the search from cur_frame, because trace_calling_frame may be it.
611         // It is guaranteed that trace_calling_frame is different from the top frame.
612         // But os::current_frame() does NOT return the top frame: it returns the next frame under it (caller's frame).
613         // (Due to inlining and tail call optimizations, caller's frame doesn't necessarily correspond to the immediate
614         // caller in the source code.)
615         assert(cur_frame.sp() < saved_regs, "registers not saved on stack ?");
616         frame trace_calling_frame = cur_frame;
617         while (trace_calling_frame.fp() < saved_regs) {
618           assert(trace_calling_frame.cb() == nullptr, "not a C frame");
619           trace_calling_frame = os::get_sender_for_C_frame(&trace_calling_frame);
620         }
621         assert(trace_calling_frame.sp() < saved_regs, "wrong frame");
622 
623         // safely create a frame and call frame::describe
624         intptr_t *dump_sp = trace_calling_frame.sender_sp();
625         intptr_t *dump_fp = trace_calling_frame.link();
626 
627         if (has_mh) {
628           // The previous definition of walkable may have to be refined
629           // if new call sites cause the next frame constructor to start
630           // failing. Alternatively, frame constructors could be
631           // modified to support the current or future non walkable
632           // frames (but this is more intrusive and is not considered as
633           // part of this RFE, which will instead use a simpler output).
634           frame dump_frame = frame(dump_sp, dump_fp);
635           dump_frame.describe(values, 1);
636         } else {
637           // Stack may not be walkable (invalid PC above FP):
638           // Add descriptions without building a Java frame to avoid issues
639           values.describe(-1, dump_fp, "fp for #1 <not parsed, cannot trust pc>");
640           values.describe(-1, dump_sp, "sp for #1");
641         }
642       }
643       values.describe(-1, entry_sp, "raw top of stack");
644 
645       ls.print_cr("Stack layout:");
646       values.print_on(p, &ls);
647     }
648     if (has_mh && oopDesc::is_oop(mh)) {
649       mh->print_on(&ls);
650       if (java_lang_invoke_MethodHandle::is_instance(mh)) {
651         java_lang_invoke_MethodHandle::form(mh)->print_on(&ls);
652       }
653     }
654   }
655 }
656 
657 // The stub wraps the arguments in a struct on the stack to avoid
658 // dealing with the different calling conventions for passing 6
659 // arguments.
660 struct MethodHandleStubArguments {
661   const char* adaptername;
662   oopDesc* mh;
663   intptr_t* saved_regs;
664   intptr_t* entry_sp;
665 };
666 void trace_method_handle_stub_wrapper(MethodHandleStubArguments* args) {
667   trace_method_handle_stub(args->adaptername,
668                            args->mh,
669                            args->saved_regs,
670                            args->entry_sp);
671 }
672 
673 void MethodHandles::trace_method_handle(MacroAssembler* _masm, const char* adaptername) {
674   if (!log_is_enabled(Info, methodhandles))  return;
675   BLOCK_COMMENT(err_msg("trace_method_handle %s {", adaptername));
676   __ enter();
677   __ andptr(rsp, -16); // align stack if needed for FPU state
678   __ pusha();
679   __ mov(rbx, rsp); // for retrieving saved_regs
680   // Note: saved_regs must be in the entered frame for the
681   // robust stack walking implemented in trace_method_handle_stub.
682 
683   // save FP result, valid at some call sites (adapter_opt_return_float, ...)
684   __ decrement(rsp, 2 * wordSize);
685   __ movdbl(Address(rsp, 0), xmm0);
686 
687   // Incoming state:
688   // rcx: method handle
689   //
690   // To avoid calling convention issues, build a record on the stack
691   // and pass the pointer to that instead.
692   __ push(rbp);               // entry_sp (with extra align space)
693   __ push(rbx);               // pusha saved_regs
694   __ push(rcx);               // mh
695   __ push(rcx);               // slot for adaptername
696   __ movptr(Address(rsp, 0), (intptr_t) adaptername, rscratch1);
697   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, trace_method_handle_stub_wrapper), rsp);
698   __ increment(rsp, sizeof(MethodHandleStubArguments));
699 
700   __ movdbl(xmm0, Address(rsp, 0));
701   __ increment(rsp, 2 * wordSize);
702 
703   __ popa();
704   __ leave();
705   BLOCK_COMMENT("} trace_method_handle");
706 }
707 #endif //PRODUCT