1/*
2 * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2014, Red Hat Inc. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 *
24 */
25
26#include "precompiled.hpp"
27#include "asm/macroAssembler.hpp"
28#include "classfile/javaClasses.inline.hpp"
29#include "interpreter/interpreter.hpp"
30#include "interpreter/interpreterRuntime.hpp"
31#include "memory/allocation.inline.hpp"
32#include "prims/methodHandles.hpp"
33
34#define __ _masm->
35
36#ifdef PRODUCT
37#define BLOCK_COMMENT(str) /* nothing */
38#else
39#define BLOCK_COMMENT(str) __ block_comment(str)
40#endif
41
42#define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
43
44void MethodHandles::load_klass_from_Class(MacroAssembler* _masm, Register klass_reg) {
45  if (VerifyMethodHandles)
46    verify_klass(_masm, klass_reg, SystemDictionary::WK_KLASS_ENUM_NAME(java_lang_Class),
47                 "MH argument is a Class");
48  __ ldr(klass_reg, Address(klass_reg, java_lang_Class::klass_offset_in_bytes()));
49}
50
51#ifdef ASSERT
52static int check_nonzero(const char* xname, int x) {
53  assert(x != 0, "%s should be nonzero", xname);
54  return x;
55}
56#define NONZERO(x) check_nonzero(#x, x)
57#else //ASSERT
58#define NONZERO(x) (x)
59#endif //PRODUCT
60
61#ifdef ASSERT
62void MethodHandles::verify_klass(MacroAssembler* _masm,
63                                 Register obj, SystemDictionary::WKID klass_id,
64                                 const char* error_message) {
65  InstanceKlass** klass_addr = SystemDictionary::well_known_klass_addr(klass_id);
66  KlassHandle klass = SystemDictionary::well_known_klass(klass_id);
67  Register temp = rscratch2;
68  Register temp2 = rscratch1; // used by MacroAssembler::cmpptr
69  Label L_ok, L_bad;
70  BLOCK_COMMENT("verify_klass {");
71  __ verify_oop(obj);
72  __ cbz(obj, L_bad);
73  __ push(RegSet::of(temp, temp2), sp);
74  __ load_klass(temp, obj);
75  __ cmpptr(temp, ExternalAddress((address) klass_addr));
76  __ br(Assembler::EQ, L_ok);
77  intptr_t super_check_offset = klass->super_check_offset();
78  __ ldr(temp, Address(temp, super_check_offset));
79  __ cmpptr(temp, ExternalAddress((address) klass_addr));
80  __ br(Assembler::EQ, L_ok);
81  __ pop(RegSet::of(temp, temp2), sp);
82  __ bind(L_bad);
83  __ stop(error_message);
84  __ BIND(L_ok);
85  __ pop(RegSet::of(temp, temp2), sp);
86  BLOCK_COMMENT("} verify_klass");
87}
88
89void MethodHandles::verify_ref_kind(MacroAssembler* _masm, int ref_kind, Register member_reg, Register temp) {  }
90
91#endif //ASSERT
92
93void MethodHandles::jump_from_method_handle(MacroAssembler* _masm, Register method, Register temp,
94                                            bool for_compiler_entry) {
95  assert(method == rmethod, "interpreter calling convention");
96  Label L_no_such_method;
97  __ cbz(rmethod, L_no_such_method);
98  __ verify_method_ptr(method);
99
100  if (!for_compiler_entry && JvmtiExport::can_post_interpreter_events()) {
101    Label run_compiled_code;
102    // JVMTI events, such as single-stepping, are implemented partly by avoiding running
103    // compiled code in threads for which the event is enabled.  Check here for
104    // interp_only_mode if these events CAN be enabled.
105
106    __ ldrb(rscratch1, Address(rthread, JavaThread::interp_only_mode_offset()));
107    __ cbnz(rscratch1, run_compiled_code);
108    __ ldr(rscratch1, Address(method, Method::interpreter_entry_offset()));
109    __ br(rscratch1);
110    __ BIND(run_compiled_code);
111  }
112
113  const ByteSize entry_offset = for_compiler_entry ? Method::from_compiled_offset() :
114                                                     Method::from_interpreted_offset();
115  __ ldr(rscratch1,Address(method, entry_offset));
116  __ br(rscratch1);
117  __ bind(L_no_such_method);
118  __ far_jump(RuntimeAddress(StubRoutines::throw_AbstractMethodError_entry()));
119}
120
121void MethodHandles::jump_to_lambda_form(MacroAssembler* _masm,
122                                        Register recv, Register method_temp,
123                                        Register temp2,
124                                        bool for_compiler_entry) {
125  BLOCK_COMMENT("jump_to_lambda_form {");
126  // This is the initial entry point of a lazy method handle.
127  // After type checking, it picks up the invoker from the LambdaForm.
128  assert_different_registers(recv, method_temp, temp2);
129  assert(recv != noreg, "required register");
130  assert(method_temp == rmethod, "required register for loading method");
131
132  //NOT_PRODUCT({ FlagSetting fs(TraceMethodHandles, true); trace_method_handle(_masm, "LZMH"); });
133
134  // Load the invoker, as MH -> MH.form -> LF.vmentry
135  __ verify_oop(recv);
136  __ load_heap_oop(method_temp, Address(recv, NONZERO(java_lang_invoke_MethodHandle::form_offset_in_bytes())));
137  __ verify_oop(method_temp);
138  __ load_heap_oop(method_temp, Address(method_temp, NONZERO(java_lang_invoke_LambdaForm::vmentry_offset_in_bytes())));
139  __ verify_oop(method_temp);
140  // the following assumes that a Method* is normally compressed in the vmtarget field:
141  __ ldr(method_temp, Address(method_temp, NONZERO(java_lang_invoke_MemberName::vmtarget_offset_in_bytes())));
142
143  if (VerifyMethodHandles && !for_compiler_entry) {
144    // make sure recv is already on stack
145    __ ldr(temp2, Address(method_temp, Method::const_offset()));
146    __ load_sized_value(temp2,
147                        Address(temp2, ConstMethod::size_of_parameters_offset()),
148                        sizeof(u2), /*is_signed*/ false);
149    // assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
150    Label L;
151    __ ldr(rscratch1, __ argument_address(temp2, -1));
152    __ cmp(recv, rscratch1);
153    __ br(Assembler::EQ, L);
154    __ ldr(r0, __ argument_address(temp2, -1));
155    __ hlt(0);
156    __ BIND(L);
157  }
158
159  jump_from_method_handle(_masm, method_temp, temp2, for_compiler_entry);
160  BLOCK_COMMENT("} jump_to_lambda_form");
161}
162
163// Code generation
164address MethodHandles::generate_method_handle_interpreter_entry(MacroAssembler* _masm,
165                                                                vmIntrinsics::ID iid) {
166  const bool not_for_compiler_entry = false;  // this is the interpreter entry
167  assert(is_signature_polymorphic(iid), "expected invoke iid");
168  if (iid == vmIntrinsics::_invokeGeneric ||
169      iid == vmIntrinsics::_compiledLambdaForm) {
170    // Perhaps surprisingly, the symbolic references visible to Java are not directly used.
171    // They are linked to Java-generated adapters via MethodHandleNatives.linkMethod.
172    // They all allow an appendix argument.
173    __ hlt(0);           // empty stubs make SG sick
174    return NULL;
175  }
176
177  // r13: sender SP (must preserve; see prepare_to_jump_from_interpreted)
178  // rmethod: Method*
179  // r3: argument locator (parameter slot count, added to rsp)
180  // r1: used as temp to hold mh or receiver
181  // r0, r11: garbage temps, blown away
182  Register argp   = r3;   // argument list ptr, live on error paths
183  Register temp   = r0;
184  Register mh     = r1;   // MH receiver; dies quickly and is recycled
185
186  // here's where control starts out:
187  __ align(CodeEntryAlignment);
188  address entry_point = __ pc();
189
190  if (VerifyMethodHandles) {
191    assert(Method::intrinsic_id_size_in_bytes() == 2, "assuming Method::_intrinsic_id is u2");
192
193    Label L;
194    BLOCK_COMMENT("verify_intrinsic_id {");
195    __ ldrh(rscratch1, Address(rmethod, Method::intrinsic_id_offset_in_bytes()));
196    __ cmp(rscratch1, (int) iid);
197    __ br(Assembler::EQ, L);
198    if (iid == vmIntrinsics::_linkToVirtual ||
199        iid == vmIntrinsics::_linkToSpecial) {
200      // could do this for all kinds, but would explode assembly code size
201      trace_method_handle(_masm, "bad Method*::intrinsic_id");
202    }
203    __ hlt(0);
204    __ bind(L);
205    BLOCK_COMMENT("} verify_intrinsic_id");
206  }
207
208  // First task:  Find out how big the argument list is.
209  Address r3_first_arg_addr;
210  int ref_kind = signature_polymorphic_intrinsic_ref_kind(iid);
211  assert(ref_kind != 0 || iid == vmIntrinsics::_invokeBasic, "must be _invokeBasic or a linkTo intrinsic");
212  if (ref_kind == 0 || MethodHandles::ref_kind_has_receiver(ref_kind)) {
213    __ ldr(argp, Address(rmethod, Method::const_offset()));
214    __ load_sized_value(argp,
215                        Address(argp, ConstMethod::size_of_parameters_offset()),
216                        sizeof(u2), /*is_signed*/ false);
217    // assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
218    r3_first_arg_addr = __ argument_address(argp, -1);
219  } else {
220    DEBUG_ONLY(argp = noreg);
221  }
222
223  if (!is_signature_polymorphic_static(iid)) {
224    __ ldr(mh, r3_first_arg_addr);
225    DEBUG_ONLY(argp = noreg);
226  }
227
228  // r3_first_arg_addr is live!
229
230  trace_method_handle_interpreter_entry(_masm, iid);
231  if (iid == vmIntrinsics::_invokeBasic) {
232    generate_method_handle_dispatch(_masm, iid, mh, noreg, not_for_compiler_entry);
233
234  } else {
235    // Adjust argument list by popping the trailing MemberName argument.
236    Register recv = noreg;
237    if (MethodHandles::ref_kind_has_receiver(ref_kind)) {
238      // Load the receiver (not the MH; the actual MemberName's receiver) up from the interpreter stack.
239      __ ldr(recv = r2, r3_first_arg_addr);
240    }
241    DEBUG_ONLY(argp = noreg);
242    Register rmember = rmethod;  // MemberName ptr; incoming method ptr is dead now
243    __ pop(rmember);             // extract last argument
244    generate_method_handle_dispatch(_masm, iid, recv, rmember, not_for_compiler_entry);
245  }
246
247  return entry_point;
248}
249
250
251void MethodHandles::generate_method_handle_dispatch(MacroAssembler* _masm,
252                                                    vmIntrinsics::ID iid,
253                                                    Register receiver_reg,
254                                                    Register member_reg,
255                                                    bool for_compiler_entry) {
256  assert(is_signature_polymorphic(iid), "expected invoke iid");
257  // temps used in this code are not used in *either* compiled or interpreted calling sequences
258  Register temp1 = r10;
259  Register temp2 = r11;
260  Register temp3 = r14;  // r13 is live by this point: it contains the sender SP
261  if (for_compiler_entry) {
262    assert(receiver_reg == (iid == vmIntrinsics::_linkToStatic ? noreg : j_rarg0), "only valid assignment");
263    assert_different_registers(temp1,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7);
264    assert_different_registers(temp2,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7);
265    assert_different_registers(temp3,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7);
266  }
267
268  assert_different_registers(temp1, temp2, temp3, receiver_reg);
269  assert_different_registers(temp1, temp2, temp3, member_reg);
270
271  if (iid == vmIntrinsics::_invokeBasic) {
272    // indirect through MH.form.vmentry.vmtarget
273    jump_to_lambda_form(_masm, receiver_reg, rmethod, temp1, for_compiler_entry);
274
275  } else {
276    // The method is a member invoker used by direct method handles.
277    if (VerifyMethodHandles) {
278      // make sure the trailing argument really is a MemberName (caller responsibility)
279      verify_klass(_masm, member_reg, SystemDictionary::WK_KLASS_ENUM_NAME(java_lang_invoke_MemberName),
280                   "MemberName required for invokeVirtual etc.");
281    }
282
283    Address member_clazz(    member_reg, NONZERO(java_lang_invoke_MemberName::clazz_offset_in_bytes()));
284    Address member_vmindex(  member_reg, NONZERO(java_lang_invoke_MemberName::vmindex_offset_in_bytes()));
285    Address member_vmtarget( member_reg, NONZERO(java_lang_invoke_MemberName::vmtarget_offset_in_bytes()));
286
287    Register temp1_recv_klass = temp1;
288    if (iid != vmIntrinsics::_linkToStatic) {
289      __ verify_oop(receiver_reg);
290      if (iid == vmIntrinsics::_linkToSpecial) {
291        // Don't actually load the klass; just null-check the receiver.
292        __ null_check(receiver_reg);
293      } else {
294        // load receiver klass itself
295        __ null_check(receiver_reg, oopDesc::klass_offset_in_bytes());
296        __ load_klass(temp1_recv_klass, receiver_reg);
297        __ verify_klass_ptr(temp1_recv_klass);
298      }
299      BLOCK_COMMENT("check_receiver {");
300      // The receiver for the MemberName must be in receiver_reg.
301      // Check the receiver against the MemberName.clazz
302      if (VerifyMethodHandles && iid == vmIntrinsics::_linkToSpecial) {
303        // Did not load it above...
304        __ load_klass(temp1_recv_klass, receiver_reg);
305        __ verify_klass_ptr(temp1_recv_klass);
306      }
307      if (VerifyMethodHandles && iid != vmIntrinsics::_linkToInterface) {
308        Label L_ok;
309        Register temp2_defc = temp2;
310        __ load_heap_oop(temp2_defc, member_clazz);
311        load_klass_from_Class(_masm, temp2_defc);
312        __ verify_klass_ptr(temp2_defc);
313        __ check_klass_subtype(temp1_recv_klass, temp2_defc, temp3, L_ok);
314        // If we get here, the type check failed!
315        __ hlt(0);
316        // __ STOP("receiver class disagrees with MemberName.clazz");
317        __ bind(L_ok);
318      }
319      BLOCK_COMMENT("} check_receiver");
320    }
321    if (iid == vmIntrinsics::_linkToSpecial ||
322        iid == vmIntrinsics::_linkToStatic) {
323      DEBUG_ONLY(temp1_recv_klass = noreg);  // these guys didn't load the recv_klass
324    }
325
326    // Live registers at this point:
327    //  member_reg - MemberName that was the trailing argument
328    //  temp1_recv_klass - klass of stacked receiver, if needed
329    //  r13 - interpreter linkage (if interpreted)  ??? FIXME
330    //  r1 ... r0 - compiler arguments (if compiled)
331
332    Label L_incompatible_class_change_error;
333    switch (iid) {
334    case vmIntrinsics::_linkToSpecial:
335      if (VerifyMethodHandles) {
336        verify_ref_kind(_masm, JVM_REF_invokeSpecial, member_reg, temp3);
337      }
338      __ ldr(rmethod, member_vmtarget);
339      break;
340
341    case vmIntrinsics::_linkToStatic:
342      if (VerifyMethodHandles) {
343        verify_ref_kind(_masm, JVM_REF_invokeStatic, member_reg, temp3);
344      }
345      __ ldr(rmethod, member_vmtarget);
346      break;
347
348    case vmIntrinsics::_linkToVirtual:
349    {
350      // same as TemplateTable::invokevirtual,
351      // minus the CP setup and profiling:
352
353      if (VerifyMethodHandles) {
354        verify_ref_kind(_masm, JVM_REF_invokeVirtual, member_reg, temp3);
355      }
356
357      // pick out the vtable index from the MemberName, and then we can discard it:
358      Register temp2_index = temp2;
359      __ ldr(temp2_index, member_vmindex);
360
361      if (VerifyMethodHandles) {
362        Label L_index_ok;
363        __ cmpw(temp2_index, 0U);
364        __ br(Assembler::GE, L_index_ok);
365        __ hlt(0);
366        __ BIND(L_index_ok);
367      }
368
369      // Note:  The verifier invariants allow us to ignore MemberName.clazz and vmtarget
370      // at this point.  And VerifyMethodHandles has already checked clazz, if needed.
371
372      // get target Method* & entry point
373      __ lookup_virtual_method(temp1_recv_klass, temp2_index, rmethod);
374      break;
375    }
376
377    case vmIntrinsics::_linkToInterface:
378    {
379      // same as TemplateTable::invokeinterface
380      // (minus the CP setup and profiling, with different argument motion)
381      if (VerifyMethodHandles) {
382        verify_ref_kind(_masm, JVM_REF_invokeInterface, member_reg, temp3);
383      }
384
385      Register temp3_intf = temp3;
386      __ load_heap_oop(temp3_intf, member_clazz);
387      load_klass_from_Class(_masm, temp3_intf);
388      __ verify_klass_ptr(temp3_intf);
389
390      Register rindex = rmethod;
391      __ ldr(rindex, member_vmindex);
392      if (VerifyMethodHandles) {
393        Label L;
394        __ cmpw(rindex, 0U);
395        __ br(Assembler::GE, L);
396        __ hlt(0);
397        __ bind(L);
398      }
399
400      // given intf, index, and recv klass, dispatch to the implementation method
401      __ lookup_interface_method(temp1_recv_klass, temp3_intf,
402                                 // note: next two args must be the same:
403                                 rindex, rmethod,
404                                 temp2,
405                                 L_incompatible_class_change_error);
406      break;
407    }
408
409    default:
410      fatal("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid));
411      break;
412    }
413
414    // live at this point:  rmethod, r13 (if interpreted)
415
416    // After figuring out which concrete method to call, jump into it.
417    // Note that this works in the interpreter with no data motion.
418    // But the compiled version will require that r2_recv be shifted out.
419    __ verify_method_ptr(rmethod);
420    jump_from_method_handle(_masm, rmethod, temp1, for_compiler_entry);
421    if (iid == vmIntrinsics::_linkToInterface) {
422      __ bind(L_incompatible_class_change_error);
423      __ far_jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
424    }
425  }
426}
427
428#ifndef PRODUCT
429void trace_method_handle_stub(const char* adaptername,
430                              oop mh,
431                              intptr_t* saved_regs,
432                              intptr_t* entry_sp) {  }
433
434// The stub wraps the arguments in a struct on the stack to avoid
435// dealing with the different calling conventions for passing 6
436// arguments.
437struct MethodHandleStubArguments {
438  const char* adaptername;
439  oopDesc* mh;
440  intptr_t* saved_regs;
441  intptr_t* entry_sp;
442};
443void trace_method_handle_stub_wrapper(MethodHandleStubArguments* args) {  }
444
445void MethodHandles::trace_method_handle(MacroAssembler* _masm, const char* adaptername) {  }
446#endif //PRODUCT
447