sharedRuntime.cpp revision 9721:9e1dc7ba8db3
1/*
2 * Copyright (c) 1997, 2015, 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 "precompiled.hpp"
26#include "classfile/stringTable.hpp"
27#include "classfile/systemDictionary.hpp"
28#include "classfile/vmSymbols.hpp"
29#include "code/codeCache.hpp"
30#include "code/compiledIC.hpp"
31#include "code/codeCacheExtensions.hpp"
32#include "code/scopeDesc.hpp"
33#include "code/vtableStubs.hpp"
34#include "compiler/abstractCompiler.hpp"
35#include "compiler/compileBroker.hpp"
36#include "compiler/disassembler.hpp"
37#include "gc/shared/gcLocker.inline.hpp"
38#include "interpreter/interpreter.hpp"
39#include "interpreter/interpreterRuntime.hpp"
40#include "logging/log.hpp"
41#include "memory/universe.inline.hpp"
42#include "oops/oop.inline.hpp"
43#include "prims/forte.hpp"
44#include "prims/jvmtiExport.hpp"
45#include "prims/jvmtiRedefineClassesTrace.hpp"
46#include "prims/methodHandles.hpp"
47#include "prims/nativeLookup.hpp"
48#include "runtime/arguments.hpp"
49#include "runtime/atomic.inline.hpp"
50#include "runtime/biasedLocking.hpp"
51#include "runtime/compilationPolicy.hpp"
52#include "runtime/handles.inline.hpp"
53#include "runtime/init.hpp"
54#include "runtime/interfaceSupport.hpp"
55#include "runtime/javaCalls.hpp"
56#include "runtime/sharedRuntime.hpp"
57#include "runtime/stubRoutines.hpp"
58#include "runtime/vframe.hpp"
59#include "runtime/vframeArray.hpp"
60#include "utilities/copy.hpp"
61#include "utilities/dtrace.hpp"
62#include "utilities/events.hpp"
63#include "utilities/hashtable.inline.hpp"
64#include "utilities/macros.hpp"
65#include "utilities/xmlstream.hpp"
66#ifdef COMPILER1
67#include "c1/c1_Runtime1.hpp"
68#endif
69
70// Shared stub locations
71RuntimeStub*        SharedRuntime::_wrong_method_blob;
72RuntimeStub*        SharedRuntime::_wrong_method_abstract_blob;
73RuntimeStub*        SharedRuntime::_ic_miss_blob;
74RuntimeStub*        SharedRuntime::_resolve_opt_virtual_call_blob;
75RuntimeStub*        SharedRuntime::_resolve_virtual_call_blob;
76RuntimeStub*        SharedRuntime::_resolve_static_call_blob;
77
78DeoptimizationBlob* SharedRuntime::_deopt_blob;
79SafepointBlob*      SharedRuntime::_polling_page_vectors_safepoint_handler_blob;
80SafepointBlob*      SharedRuntime::_polling_page_safepoint_handler_blob;
81SafepointBlob*      SharedRuntime::_polling_page_return_handler_blob;
82
83#ifdef COMPILER2
84UncommonTrapBlob*   SharedRuntime::_uncommon_trap_blob;
85#endif // COMPILER2
86
87
88//----------------------------generate_stubs-----------------------------------
89void SharedRuntime::generate_stubs() {
90  _wrong_method_blob                   = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method),          "wrong_method_stub");
91  _wrong_method_abstract_blob          = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_abstract), "wrong_method_abstract_stub");
92  _ic_miss_blob                        = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss),  "ic_miss_stub");
93  _resolve_opt_virtual_call_blob       = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C),   "resolve_opt_virtual_call");
94  _resolve_virtual_call_blob           = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C),       "resolve_virtual_call");
95  _resolve_static_call_blob            = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C),        "resolve_static_call");
96
97#if defined(COMPILER2) || INCLUDE_JVMCI
98  // Vectors are generated only by C2 and JVMCI.
99  bool support_wide = is_wide_vector(MaxVectorSize);
100  if (support_wide) {
101    _polling_page_vectors_safepoint_handler_blob = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_VECTOR_LOOP);
102  }
103#endif // COMPILER2 || INCLUDE_JVMCI
104  _polling_page_safepoint_handler_blob = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_LOOP);
105  _polling_page_return_handler_blob    = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_RETURN);
106
107  generate_deopt_blob();
108
109#ifdef COMPILER2
110  generate_uncommon_trap_blob();
111#endif // COMPILER2
112}
113
114#include <math.h>
115
116// Implementation of SharedRuntime
117
118#ifndef PRODUCT
119// For statistics
120int SharedRuntime::_ic_miss_ctr = 0;
121int SharedRuntime::_wrong_method_ctr = 0;
122int SharedRuntime::_resolve_static_ctr = 0;
123int SharedRuntime::_resolve_virtual_ctr = 0;
124int SharedRuntime::_resolve_opt_virtual_ctr = 0;
125int SharedRuntime::_implicit_null_throws = 0;
126int SharedRuntime::_implicit_div0_throws = 0;
127int SharedRuntime::_throw_null_ctr = 0;
128
129int SharedRuntime::_nof_normal_calls = 0;
130int SharedRuntime::_nof_optimized_calls = 0;
131int SharedRuntime::_nof_inlined_calls = 0;
132int SharedRuntime::_nof_megamorphic_calls = 0;
133int SharedRuntime::_nof_static_calls = 0;
134int SharedRuntime::_nof_inlined_static_calls = 0;
135int SharedRuntime::_nof_interface_calls = 0;
136int SharedRuntime::_nof_optimized_interface_calls = 0;
137int SharedRuntime::_nof_inlined_interface_calls = 0;
138int SharedRuntime::_nof_megamorphic_interface_calls = 0;
139int SharedRuntime::_nof_removable_exceptions = 0;
140
141int SharedRuntime::_new_instance_ctr=0;
142int SharedRuntime::_new_array_ctr=0;
143int SharedRuntime::_multi1_ctr=0;
144int SharedRuntime::_multi2_ctr=0;
145int SharedRuntime::_multi3_ctr=0;
146int SharedRuntime::_multi4_ctr=0;
147int SharedRuntime::_multi5_ctr=0;
148int SharedRuntime::_mon_enter_stub_ctr=0;
149int SharedRuntime::_mon_exit_stub_ctr=0;
150int SharedRuntime::_mon_enter_ctr=0;
151int SharedRuntime::_mon_exit_ctr=0;
152int SharedRuntime::_partial_subtype_ctr=0;
153int SharedRuntime::_jbyte_array_copy_ctr=0;
154int SharedRuntime::_jshort_array_copy_ctr=0;
155int SharedRuntime::_jint_array_copy_ctr=0;
156int SharedRuntime::_jlong_array_copy_ctr=0;
157int SharedRuntime::_oop_array_copy_ctr=0;
158int SharedRuntime::_checkcast_array_copy_ctr=0;
159int SharedRuntime::_unsafe_array_copy_ctr=0;
160int SharedRuntime::_generic_array_copy_ctr=0;
161int SharedRuntime::_slow_array_copy_ctr=0;
162int SharedRuntime::_find_handler_ctr=0;
163int SharedRuntime::_rethrow_ctr=0;
164
165int     SharedRuntime::_ICmiss_index                    = 0;
166int     SharedRuntime::_ICmiss_count[SharedRuntime::maxICmiss_count];
167address SharedRuntime::_ICmiss_at[SharedRuntime::maxICmiss_count];
168
169
170void SharedRuntime::trace_ic_miss(address at) {
171  for (int i = 0; i < _ICmiss_index; i++) {
172    if (_ICmiss_at[i] == at) {
173      _ICmiss_count[i]++;
174      return;
175    }
176  }
177  int index = _ICmiss_index++;
178  if (_ICmiss_index >= maxICmiss_count) _ICmiss_index = maxICmiss_count - 1;
179  _ICmiss_at[index] = at;
180  _ICmiss_count[index] = 1;
181}
182
183void SharedRuntime::print_ic_miss_histogram() {
184  if (ICMissHistogram) {
185    tty->print_cr("IC Miss Histogram:");
186    int tot_misses = 0;
187    for (int i = 0; i < _ICmiss_index; i++) {
188      tty->print_cr("  at: " INTPTR_FORMAT "  nof: %d", p2i(_ICmiss_at[i]), _ICmiss_count[i]);
189      tot_misses += _ICmiss_count[i];
190    }
191    tty->print_cr("Total IC misses: %7d", tot_misses);
192  }
193}
194#endif // PRODUCT
195
196#if INCLUDE_ALL_GCS
197
198// G1 write-barrier pre: executed before a pointer store.
199JRT_LEAF(void, SharedRuntime::g1_wb_pre(oopDesc* orig, JavaThread *thread))
200  if (orig == NULL) {
201    assert(false, "should be optimized out");
202    return;
203  }
204  assert(orig->is_oop(true /* ignore mark word */), "Error");
205  // store the original value that was in the field reference
206  thread->satb_mark_queue().enqueue(orig);
207JRT_END
208
209// G1 write-barrier post: executed after a pointer store.
210JRT_LEAF(void, SharedRuntime::g1_wb_post(void* card_addr, JavaThread* thread))
211  thread->dirty_card_queue().enqueue(card_addr);
212JRT_END
213
214#endif // INCLUDE_ALL_GCS
215
216
217JRT_LEAF(jlong, SharedRuntime::lmul(jlong y, jlong x))
218  return x * y;
219JRT_END
220
221
222JRT_LEAF(jlong, SharedRuntime::ldiv(jlong y, jlong x))
223  if (x == min_jlong && y == CONST64(-1)) {
224    return x;
225  } else {
226    return x / y;
227  }
228JRT_END
229
230
231JRT_LEAF(jlong, SharedRuntime::lrem(jlong y, jlong x))
232  if (x == min_jlong && y == CONST64(-1)) {
233    return 0;
234  } else {
235    return x % y;
236  }
237JRT_END
238
239
240const juint  float_sign_mask  = 0x7FFFFFFF;
241const juint  float_infinity   = 0x7F800000;
242const julong double_sign_mask = CONST64(0x7FFFFFFFFFFFFFFF);
243const julong double_infinity  = CONST64(0x7FF0000000000000);
244
245JRT_LEAF(jfloat, SharedRuntime::frem(jfloat  x, jfloat  y))
246#ifdef _WIN64
247  // 64-bit Windows on amd64 returns the wrong values for
248  // infinity operands.
249  union { jfloat f; juint i; } xbits, ybits;
250  xbits.f = x;
251  ybits.f = y;
252  // x Mod Infinity == x unless x is infinity
253  if (((xbits.i & float_sign_mask) != float_infinity) &&
254       ((ybits.i & float_sign_mask) == float_infinity) ) {
255    return x;
256  }
257  return ((jfloat)fmod_winx64((double)x, (double)y));
258#else
259  return ((jfloat)fmod((double)x,(double)y));
260#endif
261JRT_END
262
263
264JRT_LEAF(jdouble, SharedRuntime::drem(jdouble x, jdouble y))
265#ifdef _WIN64
266  union { jdouble d; julong l; } xbits, ybits;
267  xbits.d = x;
268  ybits.d = y;
269  // x Mod Infinity == x unless x is infinity
270  if (((xbits.l & double_sign_mask) != double_infinity) &&
271       ((ybits.l & double_sign_mask) == double_infinity) ) {
272    return x;
273  }
274  return ((jdouble)fmod_winx64((double)x, (double)y));
275#else
276  return ((jdouble)fmod((double)x,(double)y));
277#endif
278JRT_END
279
280#ifdef __SOFTFP__
281JRT_LEAF(jfloat, SharedRuntime::fadd(jfloat x, jfloat y))
282  return x + y;
283JRT_END
284
285JRT_LEAF(jfloat, SharedRuntime::fsub(jfloat x, jfloat y))
286  return x - y;
287JRT_END
288
289JRT_LEAF(jfloat, SharedRuntime::fmul(jfloat x, jfloat y))
290  return x * y;
291JRT_END
292
293JRT_LEAF(jfloat, SharedRuntime::fdiv(jfloat x, jfloat y))
294  return x / y;
295JRT_END
296
297JRT_LEAF(jdouble, SharedRuntime::dadd(jdouble x, jdouble y))
298  return x + y;
299JRT_END
300
301JRT_LEAF(jdouble, SharedRuntime::dsub(jdouble x, jdouble y))
302  return x - y;
303JRT_END
304
305JRT_LEAF(jdouble, SharedRuntime::dmul(jdouble x, jdouble y))
306  return x * y;
307JRT_END
308
309JRT_LEAF(jdouble, SharedRuntime::ddiv(jdouble x, jdouble y))
310  return x / y;
311JRT_END
312
313JRT_LEAF(jfloat, SharedRuntime::i2f(jint x))
314  return (jfloat)x;
315JRT_END
316
317JRT_LEAF(jdouble, SharedRuntime::i2d(jint x))
318  return (jdouble)x;
319JRT_END
320
321JRT_LEAF(jdouble, SharedRuntime::f2d(jfloat x))
322  return (jdouble)x;
323JRT_END
324
325JRT_LEAF(int,  SharedRuntime::fcmpl(float x, float y))
326  return x>y ? 1 : (x==y ? 0 : -1);  /* x<y or is_nan*/
327JRT_END
328
329JRT_LEAF(int,  SharedRuntime::fcmpg(float x, float y))
330  return x<y ? -1 : (x==y ? 0 : 1);  /* x>y or is_nan */
331JRT_END
332
333JRT_LEAF(int,  SharedRuntime::dcmpl(double x, double y))
334  return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan */
335JRT_END
336
337JRT_LEAF(int,  SharedRuntime::dcmpg(double x, double y))
338  return x<y ? -1 : (x==y ? 0 : 1);  /* x>y or is_nan */
339JRT_END
340
341// Functions to return the opposite of the aeabi functions for nan.
342JRT_LEAF(int, SharedRuntime::unordered_fcmplt(float x, float y))
343  return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
344JRT_END
345
346JRT_LEAF(int, SharedRuntime::unordered_dcmplt(double x, double y))
347  return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
348JRT_END
349
350JRT_LEAF(int, SharedRuntime::unordered_fcmple(float x, float y))
351  return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
352JRT_END
353
354JRT_LEAF(int, SharedRuntime::unordered_dcmple(double x, double y))
355  return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
356JRT_END
357
358JRT_LEAF(int, SharedRuntime::unordered_fcmpge(float x, float y))
359  return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
360JRT_END
361
362JRT_LEAF(int, SharedRuntime::unordered_dcmpge(double x, double y))
363  return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
364JRT_END
365
366JRT_LEAF(int, SharedRuntime::unordered_fcmpgt(float x, float y))
367  return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
368JRT_END
369
370JRT_LEAF(int, SharedRuntime::unordered_dcmpgt(double x, double y))
371  return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
372JRT_END
373
374// Intrinsics make gcc generate code for these.
375float  SharedRuntime::fneg(float f)   {
376  return -f;
377}
378
379double SharedRuntime::dneg(double f)  {
380  return -f;
381}
382
383#endif // __SOFTFP__
384
385#if defined(__SOFTFP__) || defined(E500V2)
386// Intrinsics make gcc generate code for these.
387double SharedRuntime::dabs(double f)  {
388  return (f <= (double)0.0) ? (double)0.0 - f : f;
389}
390
391#endif
392
393#if defined(__SOFTFP__) || defined(PPC)
394double SharedRuntime::dsqrt(double f) {
395  return sqrt(f);
396}
397#endif
398
399JRT_LEAF(jint, SharedRuntime::f2i(jfloat  x))
400  if (g_isnan(x))
401    return 0;
402  if (x >= (jfloat) max_jint)
403    return max_jint;
404  if (x <= (jfloat) min_jint)
405    return min_jint;
406  return (jint) x;
407JRT_END
408
409
410JRT_LEAF(jlong, SharedRuntime::f2l(jfloat  x))
411  if (g_isnan(x))
412    return 0;
413  if (x >= (jfloat) max_jlong)
414    return max_jlong;
415  if (x <= (jfloat) min_jlong)
416    return min_jlong;
417  return (jlong) x;
418JRT_END
419
420
421JRT_LEAF(jint, SharedRuntime::d2i(jdouble x))
422  if (g_isnan(x))
423    return 0;
424  if (x >= (jdouble) max_jint)
425    return max_jint;
426  if (x <= (jdouble) min_jint)
427    return min_jint;
428  return (jint) x;
429JRT_END
430
431
432JRT_LEAF(jlong, SharedRuntime::d2l(jdouble x))
433  if (g_isnan(x))
434    return 0;
435  if (x >= (jdouble) max_jlong)
436    return max_jlong;
437  if (x <= (jdouble) min_jlong)
438    return min_jlong;
439  return (jlong) x;
440JRT_END
441
442
443JRT_LEAF(jfloat, SharedRuntime::d2f(jdouble x))
444  return (jfloat)x;
445JRT_END
446
447
448JRT_LEAF(jfloat, SharedRuntime::l2f(jlong x))
449  return (jfloat)x;
450JRT_END
451
452
453JRT_LEAF(jdouble, SharedRuntime::l2d(jlong x))
454  return (jdouble)x;
455JRT_END
456
457// Exception handling across interpreter/compiler boundaries
458//
459// exception_handler_for_return_address(...) returns the continuation address.
460// The continuation address is the entry point of the exception handler of the
461// previous frame depending on the return address.
462
463address SharedRuntime::raw_exception_handler_for_return_address(JavaThread* thread, address return_address) {
464  assert(frame::verify_return_pc(return_address), "must be a return address: " INTPTR_FORMAT, p2i(return_address));
465  assert(thread->frames_to_pop_failed_realloc() == 0 || Interpreter::contains(return_address), "missed frames to pop?");
466
467  // Reset method handle flag.
468  thread->set_is_method_handle_return(false);
469
470#if INCLUDE_JVMCI
471  // JVMCI's ExceptionHandlerStub expects the thread local exception PC to be clear
472  // and other exception handler continuations do not read it
473  thread->set_exception_pc(NULL);
474#endif
475
476  // The fastest case first
477  CodeBlob* blob = CodeCache::find_blob(return_address);
478  nmethod* nm = (blob != NULL) ? blob->as_nmethod_or_null() : NULL;
479  if (nm != NULL) {
480    // Set flag if return address is a method handle call site.
481    thread->set_is_method_handle_return(nm->is_method_handle_return(return_address));
482    // native nmethods don't have exception handlers
483    assert(!nm->is_native_method(), "no exception handler");
484    assert(nm->header_begin() != nm->exception_begin(), "no exception handler");
485    if (nm->is_deopt_pc(return_address)) {
486      // If we come here because of a stack overflow, the stack may be
487      // unguarded. Reguard the stack otherwise if we return to the
488      // deopt blob and the stack bang causes a stack overflow we
489      // crash.
490      bool guard_pages_enabled = thread->stack_yellow_zone_enabled();
491      if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
492      assert(guard_pages_enabled, "stack banging in deopt blob may cause crash");
493      return SharedRuntime::deopt_blob()->unpack_with_exception();
494    } else {
495      return nm->exception_begin();
496    }
497  }
498
499  // Entry code
500  if (StubRoutines::returns_to_call_stub(return_address)) {
501    return StubRoutines::catch_exception_entry();
502  }
503  // Interpreted code
504  if (Interpreter::contains(return_address)) {
505    return Interpreter::rethrow_exception_entry();
506  }
507
508  guarantee(blob == NULL || !blob->is_runtime_stub(), "caller should have skipped stub");
509  guarantee(!VtableStubs::contains(return_address), "NULL exceptions in vtables should have been handled already!");
510
511#ifndef PRODUCT
512  { ResourceMark rm;
513    tty->print_cr("No exception handler found for exception at " INTPTR_FORMAT " - potential problems:", p2i(return_address));
514    tty->print_cr("a) exception happened in (new?) code stubs/buffers that is not handled here");
515    tty->print_cr("b) other problem");
516  }
517#endif // PRODUCT
518
519  ShouldNotReachHere();
520  return NULL;
521}
522
523
524JRT_LEAF(address, SharedRuntime::exception_handler_for_return_address(JavaThread* thread, address return_address))
525  return raw_exception_handler_for_return_address(thread, return_address);
526JRT_END
527
528
529address SharedRuntime::get_poll_stub(address pc) {
530  address stub;
531  // Look up the code blob
532  CodeBlob *cb = CodeCache::find_blob(pc);
533
534  // Should be an nmethod
535  assert(cb && cb->is_nmethod(), "safepoint polling: pc must refer to an nmethod");
536
537  // Look up the relocation information
538  assert(((nmethod*)cb)->is_at_poll_or_poll_return(pc),
539    "safepoint polling: type must be poll");
540
541#ifdef ASSERT
542  if (!((NativeInstruction*)pc)->is_safepoint_poll()) {
543    tty->print_cr("bad pc: " PTR_FORMAT, p2i(pc));
544    Disassembler::decode(cb);
545    fatal("Only polling locations are used for safepoint");
546  }
547#endif
548
549  bool at_poll_return = ((nmethod*)cb)->is_at_poll_return(pc);
550  bool has_wide_vectors = ((nmethod*)cb)->has_wide_vectors();
551  if (at_poll_return) {
552    assert(SharedRuntime::polling_page_return_handler_blob() != NULL,
553           "polling page return stub not created yet");
554    stub = SharedRuntime::polling_page_return_handler_blob()->entry_point();
555  } else if (has_wide_vectors) {
556    assert(SharedRuntime::polling_page_vectors_safepoint_handler_blob() != NULL,
557           "polling page vectors safepoint stub not created yet");
558    stub = SharedRuntime::polling_page_vectors_safepoint_handler_blob()->entry_point();
559  } else {
560    assert(SharedRuntime::polling_page_safepoint_handler_blob() != NULL,
561           "polling page safepoint stub not created yet");
562    stub = SharedRuntime::polling_page_safepoint_handler_blob()->entry_point();
563  }
564  log_debug(safepoint)("... found polling page %s exception at pc = "
565                       INTPTR_FORMAT ", stub =" INTPTR_FORMAT,
566                       at_poll_return ? "return" : "loop",
567                       (intptr_t)pc, (intptr_t)stub);
568  return stub;
569}
570
571
572oop SharedRuntime::retrieve_receiver( Symbol* sig, frame caller ) {
573  assert(caller.is_interpreted_frame(), "");
574  int args_size = ArgumentSizeComputer(sig).size() + 1;
575  assert(args_size <= caller.interpreter_frame_expression_stack_size(), "receiver must be on interpreter stack");
576  oop result = cast_to_oop(*caller.interpreter_frame_tos_at(args_size - 1));
577  assert(Universe::heap()->is_in(result) && result->is_oop(), "receiver must be an oop");
578  return result;
579}
580
581
582void SharedRuntime::throw_and_post_jvmti_exception(JavaThread *thread, Handle h_exception) {
583  if (JvmtiExport::can_post_on_exceptions()) {
584    vframeStream vfst(thread, true);
585    methodHandle method = methodHandle(thread, vfst.method());
586    address bcp = method()->bcp_from(vfst.bci());
587    JvmtiExport::post_exception_throw(thread, method(), bcp, h_exception());
588  }
589  Exceptions::_throw(thread, __FILE__, __LINE__, h_exception);
590}
591
592void SharedRuntime::throw_and_post_jvmti_exception(JavaThread *thread, Symbol* name, const char *message) {
593  Handle h_exception = Exceptions::new_exception(thread, name, message);
594  throw_and_post_jvmti_exception(thread, h_exception);
595}
596
597// The interpreter code to call this tracing function is only
598// called/generated when TraceRedefineClasses has the right bits
599// set. Since obsolete methods are never compiled, we don't have
600// to modify the compilers to generate calls to this function.
601//
602JRT_LEAF(int, SharedRuntime::rc_trace_method_entry(
603    JavaThread* thread, Method* method))
604  assert(RC_TRACE_IN_RANGE(0x00001000, 0x00002000), "wrong call");
605
606  if (method->is_obsolete()) {
607    // We are calling an obsolete method, but this is not necessarily
608    // an error. Our method could have been redefined just after we
609    // fetched the Method* from the constant pool.
610
611    // RC_TRACE macro has an embedded ResourceMark
612    RC_TRACE_WITH_THREAD(0x00001000, thread,
613                         ("calling obsolete method '%s'",
614                          method->name_and_sig_as_C_string()));
615    if (RC_TRACE_ENABLED(0x00002000)) {
616      // this option is provided to debug calls to obsolete methods
617      guarantee(false, "faulting at call to an obsolete method.");
618    }
619  }
620  return 0;
621JRT_END
622
623// ret_pc points into caller; we are returning caller's exception handler
624// for given exception
625address SharedRuntime::compute_compiled_exc_handler(nmethod* nm, address ret_pc, Handle& exception,
626                                                    bool force_unwind, bool top_frame_only) {
627  assert(nm != NULL, "must exist");
628  ResourceMark rm;
629
630#if INCLUDE_JVMCI
631  if (nm->is_compiled_by_jvmci()) {
632    // lookup exception handler for this pc
633    int catch_pco = ret_pc - nm->code_begin();
634    ExceptionHandlerTable table(nm);
635    HandlerTableEntry *t = table.entry_for(catch_pco, -1, 0);
636    if (t != NULL) {
637      return nm->code_begin() + t->pco();
638    } else {
639      // there is no exception handler for this pc => deoptimize
640      nm->make_not_entrant();
641
642      // Use Deoptimization::deoptimize for all of its side-effects:
643      // revoking biases of monitors, gathering traps statistics, logging...
644      // it also patches the return pc but we do not care about that
645      // since we return a continuation to the deopt_blob below.
646      JavaThread* thread = JavaThread::current();
647      RegisterMap reg_map(thread, UseBiasedLocking);
648      frame runtime_frame = thread->last_frame();
649      frame caller_frame = runtime_frame.sender(&reg_map);
650      Deoptimization::deoptimize(thread, caller_frame, &reg_map, Deoptimization::Reason_not_compiled_exception_handler);
651
652      return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
653    }
654  }
655#endif // INCLUDE_JVMCI
656
657  ScopeDesc* sd = nm->scope_desc_at(ret_pc);
658  // determine handler bci, if any
659  EXCEPTION_MARK;
660
661  int handler_bci = -1;
662  int scope_depth = 0;
663  if (!force_unwind) {
664    int bci = sd->bci();
665    bool recursive_exception = false;
666    do {
667      bool skip_scope_increment = false;
668      // exception handler lookup
669      KlassHandle ek (THREAD, exception->klass());
670      methodHandle mh(THREAD, sd->method());
671      handler_bci = Method::fast_exception_handler_bci_for(mh, ek, bci, THREAD);
672      if (HAS_PENDING_EXCEPTION) {
673        recursive_exception = true;
674        // We threw an exception while trying to find the exception handler.
675        // Transfer the new exception to the exception handle which will
676        // be set into thread local storage, and do another lookup for an
677        // exception handler for this exception, this time starting at the
678        // BCI of the exception handler which caused the exception to be
679        // thrown (bugs 4307310 and 4546590). Set "exception" reference
680        // argument to ensure that the correct exception is thrown (4870175).
681        exception = Handle(THREAD, PENDING_EXCEPTION);
682        CLEAR_PENDING_EXCEPTION;
683        if (handler_bci >= 0) {
684          bci = handler_bci;
685          handler_bci = -1;
686          skip_scope_increment = true;
687        }
688      }
689      else {
690        recursive_exception = false;
691      }
692      if (!top_frame_only && handler_bci < 0 && !skip_scope_increment) {
693        sd = sd->sender();
694        if (sd != NULL) {
695          bci = sd->bci();
696        }
697        ++scope_depth;
698      }
699    } while (recursive_exception || (!top_frame_only && handler_bci < 0 && sd != NULL));
700  }
701
702  // found handling method => lookup exception handler
703  int catch_pco = ret_pc - nm->code_begin();
704
705  ExceptionHandlerTable table(nm);
706  HandlerTableEntry *t = table.entry_for(catch_pco, handler_bci, scope_depth);
707  if (t == NULL && (nm->is_compiled_by_c1() || handler_bci != -1)) {
708    // Allow abbreviated catch tables.  The idea is to allow a method
709    // to materialize its exceptions without committing to the exact
710    // routing of exceptions.  In particular this is needed for adding
711    // a synthetic handler to unlock monitors when inlining
712    // synchronized methods since the unlock path isn't represented in
713    // the bytecodes.
714    t = table.entry_for(catch_pco, -1, 0);
715  }
716
717#ifdef COMPILER1
718  if (t == NULL && nm->is_compiled_by_c1()) {
719    assert(nm->unwind_handler_begin() != NULL, "");
720    return nm->unwind_handler_begin();
721  }
722#endif
723
724  if (t == NULL) {
725    tty->print_cr("MISSING EXCEPTION HANDLER for pc " INTPTR_FORMAT " and handler bci %d", p2i(ret_pc), handler_bci);
726    tty->print_cr("   Exception:");
727    exception->print();
728    tty->cr();
729    tty->print_cr(" Compiled exception table :");
730    table.print();
731    nm->print_code();
732    guarantee(false, "missing exception handler");
733    return NULL;
734  }
735
736  return nm->code_begin() + t->pco();
737}
738
739JRT_ENTRY(void, SharedRuntime::throw_AbstractMethodError(JavaThread* thread))
740  // These errors occur only at call sites
741  throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_AbstractMethodError());
742JRT_END
743
744JRT_ENTRY(void, SharedRuntime::throw_IncompatibleClassChangeError(JavaThread* thread))
745  // These errors occur only at call sites
746  throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_IncompatibleClassChangeError(), "vtable stub");
747JRT_END
748
749JRT_ENTRY(void, SharedRuntime::throw_ArithmeticException(JavaThread* thread))
750  throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArithmeticException(), "/ by zero");
751JRT_END
752
753JRT_ENTRY(void, SharedRuntime::throw_NullPointerException(JavaThread* thread))
754  throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_NullPointerException());
755JRT_END
756
757JRT_ENTRY(void, SharedRuntime::throw_NullPointerException_at_call(JavaThread* thread))
758  // This entry point is effectively only used for NullPointerExceptions which occur at inline
759  // cache sites (when the callee activation is not yet set up) so we are at a call site
760  throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_NullPointerException());
761JRT_END
762
763JRT_ENTRY(void, SharedRuntime::throw_StackOverflowError(JavaThread* thread))
764  // We avoid using the normal exception construction in this case because
765  // it performs an upcall to Java, and we're already out of stack space.
766  Klass* k = SystemDictionary::StackOverflowError_klass();
767  oop exception_oop = InstanceKlass::cast(k)->allocate_instance(CHECK);
768  Handle exception (thread, exception_oop);
769  if (StackTraceInThrowable) {
770    java_lang_Throwable::fill_in_stack_trace(exception);
771  }
772  // Increment counter for hs_err file reporting
773  Atomic::inc(&Exceptions::_stack_overflow_errors);
774  throw_and_post_jvmti_exception(thread, exception);
775JRT_END
776
777#if INCLUDE_JVMCI
778address SharedRuntime::deoptimize_for_implicit_exception(JavaThread* thread, address pc, nmethod* nm, int deopt_reason) {
779  assert(deopt_reason > Deoptimization::Reason_none && deopt_reason < Deoptimization::Reason_LIMIT, "invalid deopt reason");
780  thread->set_jvmci_implicit_exception_pc(pc);
781  thread->set_pending_deoptimization(Deoptimization::make_trap_request((Deoptimization::DeoptReason)deopt_reason, Deoptimization::Action_reinterpret));
782  return (SharedRuntime::deopt_blob()->implicit_exception_uncommon_trap());
783}
784#endif // INCLUDE_JVMCI
785
786address SharedRuntime::continuation_for_implicit_exception(JavaThread* thread,
787                                                           address pc,
788                                                           SharedRuntime::ImplicitExceptionKind exception_kind)
789{
790  address target_pc = NULL;
791
792  if (Interpreter::contains(pc)) {
793#ifdef CC_INTERP
794    // C++ interpreter doesn't throw implicit exceptions
795    ShouldNotReachHere();
796#else
797    switch (exception_kind) {
798      case IMPLICIT_NULL:           return Interpreter::throw_NullPointerException_entry();
799      case IMPLICIT_DIVIDE_BY_ZERO: return Interpreter::throw_ArithmeticException_entry();
800      case STACK_OVERFLOW:          return Interpreter::throw_StackOverflowError_entry();
801      default:                      ShouldNotReachHere();
802    }
803#endif // !CC_INTERP
804  } else {
805    switch (exception_kind) {
806      case STACK_OVERFLOW: {
807        // Stack overflow only occurs upon frame setup; the callee is
808        // going to be unwound. Dispatch to a shared runtime stub
809        // which will cause the StackOverflowError to be fabricated
810        // and processed.
811        // Stack overflow should never occur during deoptimization:
812        // the compiled method bangs the stack by as much as the
813        // interpreter would need in case of a deoptimization. The
814        // deoptimization blob and uncommon trap blob bang the stack
815        // in a debug VM to verify the correctness of the compiled
816        // method stack banging.
817        assert(thread->deopt_mark() == NULL, "no stack overflow from deopt blob/uncommon trap");
818        Events::log_exception(thread, "StackOverflowError at " INTPTR_FORMAT, p2i(pc));
819        return StubRoutines::throw_StackOverflowError_entry();
820      }
821
822      case IMPLICIT_NULL: {
823        if (VtableStubs::contains(pc)) {
824          // We haven't yet entered the callee frame. Fabricate an
825          // exception and begin dispatching it in the caller. Since
826          // the caller was at a call site, it's safe to destroy all
827          // caller-saved registers, as these entry points do.
828          VtableStub* vt_stub = VtableStubs::stub_containing(pc);
829
830          // If vt_stub is NULL, then return NULL to signal handler to report the SEGV error.
831          if (vt_stub == NULL) return NULL;
832
833          if (vt_stub->is_abstract_method_error(pc)) {
834            assert(!vt_stub->is_vtable_stub(), "should never see AbstractMethodErrors from vtable-type VtableStubs");
835            Events::log_exception(thread, "AbstractMethodError at " INTPTR_FORMAT, p2i(pc));
836            return StubRoutines::throw_AbstractMethodError_entry();
837          } else {
838            Events::log_exception(thread, "NullPointerException at vtable entry " INTPTR_FORMAT, p2i(pc));
839            return StubRoutines::throw_NullPointerException_at_call_entry();
840          }
841        } else {
842          CodeBlob* cb = CodeCache::find_blob(pc);
843
844          // If code blob is NULL, then return NULL to signal handler to report the SEGV error.
845          if (cb == NULL) return NULL;
846
847          // Exception happened in CodeCache. Must be either:
848          // 1. Inline-cache check in C2I handler blob,
849          // 2. Inline-cache check in nmethod, or
850          // 3. Implicit null exception in nmethod
851
852          if (!cb->is_nmethod()) {
853            bool is_in_blob = cb->is_adapter_blob() || cb->is_method_handles_adapter_blob();
854            if (!is_in_blob) {
855              // Allow normal crash reporting to handle this
856              return NULL;
857            }
858            Events::log_exception(thread, "NullPointerException in code blob at " INTPTR_FORMAT, p2i(pc));
859            // There is no handler here, so we will simply unwind.
860            return StubRoutines::throw_NullPointerException_at_call_entry();
861          }
862
863          // Otherwise, it's an nmethod.  Consult its exception handlers.
864          nmethod* nm = (nmethod*)cb;
865          if (nm->inlinecache_check_contains(pc)) {
866            // exception happened inside inline-cache check code
867            // => the nmethod is not yet active (i.e., the frame
868            // is not set up yet) => use return address pushed by
869            // caller => don't push another return address
870            Events::log_exception(thread, "NullPointerException in IC check " INTPTR_FORMAT, p2i(pc));
871            return StubRoutines::throw_NullPointerException_at_call_entry();
872          }
873
874          if (nm->method()->is_method_handle_intrinsic()) {
875            // exception happened inside MH dispatch code, similar to a vtable stub
876            Events::log_exception(thread, "NullPointerException in MH adapter " INTPTR_FORMAT, p2i(pc));
877            return StubRoutines::throw_NullPointerException_at_call_entry();
878          }
879
880#ifndef PRODUCT
881          _implicit_null_throws++;
882#endif
883#if INCLUDE_JVMCI
884          if (nm->is_compiled_by_jvmci() && nm->pc_desc_at(pc) != NULL) {
885            // If there's no PcDesc then we'll die way down inside of
886            // deopt instead of just getting normal error reporting,
887            // so only go there if it will succeed.
888            return deoptimize_for_implicit_exception(thread, pc, nm, Deoptimization::Reason_null_check);
889          } else {
890#endif // INCLUDE_JVMCI
891          assert (nm->is_nmethod(), "Expect nmethod");
892          target_pc = nm->continuation_for_implicit_exception(pc);
893#if INCLUDE_JVMCI
894          }
895#endif // INCLUDE_JVMCI
896          // If there's an unexpected fault, target_pc might be NULL,
897          // in which case we want to fall through into the normal
898          // error handling code.
899        }
900
901        break; // fall through
902      }
903
904
905      case IMPLICIT_DIVIDE_BY_ZERO: {
906        nmethod* nm = CodeCache::find_nmethod(pc);
907        guarantee(nm != NULL, "must have containing compiled method for implicit division-by-zero exceptions");
908#ifndef PRODUCT
909        _implicit_div0_throws++;
910#endif
911#if INCLUDE_JVMCI
912        if (nm->is_compiled_by_jvmci() && nm->pc_desc_at(pc) != NULL) {
913          return deoptimize_for_implicit_exception(thread, pc, nm, Deoptimization::Reason_div0_check);
914        } else {
915#endif // INCLUDE_JVMCI
916        target_pc = nm->continuation_for_implicit_exception(pc);
917#if INCLUDE_JVMCI
918        }
919#endif // INCLUDE_JVMCI
920        // If there's an unexpected fault, target_pc might be NULL,
921        // in which case we want to fall through into the normal
922        // error handling code.
923        break; // fall through
924      }
925
926      default: ShouldNotReachHere();
927    }
928
929    assert(exception_kind == IMPLICIT_NULL || exception_kind == IMPLICIT_DIVIDE_BY_ZERO, "wrong implicit exception kind");
930
931    if (exception_kind == IMPLICIT_NULL) {
932#ifndef PRODUCT
933      // for AbortVMOnException flag
934      Exceptions::debug_check_abort("java.lang.NullPointerException");
935#endif //PRODUCT
936      Events::log_exception(thread, "Implicit null exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc));
937    } else {
938#ifndef PRODUCT
939      // for AbortVMOnException flag
940      Exceptions::debug_check_abort("java.lang.ArithmeticException");
941#endif //PRODUCT
942      Events::log_exception(thread, "Implicit division by zero exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc));
943    }
944    return target_pc;
945  }
946
947  ShouldNotReachHere();
948  return NULL;
949}
950
951
952/**
953 * Throws an java/lang/UnsatisfiedLinkError.  The address of this method is
954 * installed in the native function entry of all native Java methods before
955 * they get linked to their actual native methods.
956 *
957 * \note
958 * This method actually never gets called!  The reason is because
959 * the interpreter's native entries call NativeLookup::lookup() which
960 * throws the exception when the lookup fails.  The exception is then
961 * caught and forwarded on the return from NativeLookup::lookup() call
962 * before the call to the native function.  This might change in the future.
963 */
964JNI_ENTRY(void*, throw_unsatisfied_link_error(JNIEnv* env, ...))
965{
966  // We return a bad value here to make sure that the exception is
967  // forwarded before we look at the return value.
968  THROW_(vmSymbols::java_lang_UnsatisfiedLinkError(), (void*)badJNIHandle);
969}
970JNI_END
971
972address SharedRuntime::native_method_throw_unsatisfied_link_error_entry() {
973  return CAST_FROM_FN_PTR(address, &throw_unsatisfied_link_error);
974}
975
976
977#ifndef PRODUCT
978JRT_ENTRY(intptr_t, SharedRuntime::trace_bytecode(JavaThread* thread, intptr_t preserve_this_value, intptr_t tos, intptr_t tos2))
979  const frame f = thread->last_frame();
980  assert(f.is_interpreted_frame(), "must be an interpreted frame");
981#ifndef PRODUCT
982  methodHandle mh(THREAD, f.interpreter_frame_method());
983  BytecodeTracer::trace(mh, f.interpreter_frame_bcp(), tos, tos2);
984#endif // !PRODUCT
985  return preserve_this_value;
986JRT_END
987#endif // !PRODUCT
988
989JRT_ENTRY_NO_ASYNC(void, SharedRuntime::register_finalizer(JavaThread* thread, oopDesc* obj))
990  assert(obj->is_oop(), "must be a valid oop");
991#if INCLUDE_JVMCI
992  // This removes the requirement for JVMCI compilers to emit code
993  // performing a dynamic check that obj has a finalizer before
994  // calling this routine. There should be no performance impact
995  // for C1 since it emits a dynamic check. C2 and the interpreter
996  // uses other runtime routines for registering finalizers.
997  if (!obj->klass()->has_finalizer()) {
998    return;
999  }
1000#endif // INCLUDE_JVMCI
1001  assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise");
1002  InstanceKlass::register_finalizer(instanceOop(obj), CHECK);
1003JRT_END
1004
1005
1006jlong SharedRuntime::get_java_tid(Thread* thread) {
1007  if (thread != NULL) {
1008    if (thread->is_Java_thread()) {
1009      oop obj = ((JavaThread*)thread)->threadObj();
1010      return (obj == NULL) ? 0 : java_lang_Thread::thread_id(obj);
1011    }
1012  }
1013  return 0;
1014}
1015
1016/**
1017 * This function ought to be a void function, but cannot be because
1018 * it gets turned into a tail-call on sparc, which runs into dtrace bug
1019 * 6254741.  Once that is fixed we can remove the dummy return value.
1020 */
1021int SharedRuntime::dtrace_object_alloc(oopDesc* o, int size) {
1022  return dtrace_object_alloc_base(Thread::current(), o, size);
1023}
1024
1025int SharedRuntime::dtrace_object_alloc_base(Thread* thread, oopDesc* o, int size) {
1026  assert(DTraceAllocProbes, "wrong call");
1027  Klass* klass = o->klass();
1028  Symbol* name = klass->name();
1029  HOTSPOT_OBJECT_ALLOC(
1030                   get_java_tid(thread),
1031                   (char *) name->bytes(), name->utf8_length(), size * HeapWordSize);
1032  return 0;
1033}
1034
1035JRT_LEAF(int, SharedRuntime::dtrace_method_entry(
1036    JavaThread* thread, Method* method))
1037  assert(DTraceMethodProbes, "wrong call");
1038  Symbol* kname = method->klass_name();
1039  Symbol* name = method->name();
1040  Symbol* sig = method->signature();
1041  HOTSPOT_METHOD_ENTRY(
1042      get_java_tid(thread),
1043      (char *) kname->bytes(), kname->utf8_length(),
1044      (char *) name->bytes(), name->utf8_length(),
1045      (char *) sig->bytes(), sig->utf8_length());
1046  return 0;
1047JRT_END
1048
1049JRT_LEAF(int, SharedRuntime::dtrace_method_exit(
1050    JavaThread* thread, Method* method))
1051  assert(DTraceMethodProbes, "wrong call");
1052  Symbol* kname = method->klass_name();
1053  Symbol* name = method->name();
1054  Symbol* sig = method->signature();
1055  HOTSPOT_METHOD_RETURN(
1056      get_java_tid(thread),
1057      (char *) kname->bytes(), kname->utf8_length(),
1058      (char *) name->bytes(), name->utf8_length(),
1059      (char *) sig->bytes(), sig->utf8_length());
1060  return 0;
1061JRT_END
1062
1063
1064// Finds receiver, CallInfo (i.e. receiver method), and calling bytecode)
1065// for a call current in progress, i.e., arguments has been pushed on stack
1066// put callee has not been invoked yet.  Used by: resolve virtual/static,
1067// vtable updates, etc.  Caller frame must be compiled.
1068Handle SharedRuntime::find_callee_info(JavaThread* thread, Bytecodes::Code& bc, CallInfo& callinfo, TRAPS) {
1069  ResourceMark rm(THREAD);
1070
1071  // last java frame on stack (which includes native call frames)
1072  vframeStream vfst(thread, true);  // Do not skip and javaCalls
1073
1074  return find_callee_info_helper(thread, vfst, bc, callinfo, THREAD);
1075}
1076
1077
1078// Finds receiver, CallInfo (i.e. receiver method), and calling bytecode
1079// for a call current in progress, i.e., arguments has been pushed on stack
1080// but callee has not been invoked yet.  Caller frame must be compiled.
1081Handle SharedRuntime::find_callee_info_helper(JavaThread* thread,
1082                                              vframeStream& vfst,
1083                                              Bytecodes::Code& bc,
1084                                              CallInfo& callinfo, TRAPS) {
1085  Handle receiver;
1086  Handle nullHandle;  //create a handy null handle for exception returns
1087
1088  assert(!vfst.at_end(), "Java frame must exist");
1089
1090  // Find caller and bci from vframe
1091  methodHandle caller(THREAD, vfst.method());
1092  int          bci   = vfst.bci();
1093
1094  // Find bytecode
1095  Bytecode_invoke bytecode(caller, bci);
1096  bc = bytecode.invoke_code();
1097  int bytecode_index = bytecode.index();
1098
1099  // Find receiver for non-static call
1100  if (bc != Bytecodes::_invokestatic &&
1101      bc != Bytecodes::_invokedynamic &&
1102      bc != Bytecodes::_invokehandle) {
1103    // This register map must be update since we need to find the receiver for
1104    // compiled frames. The receiver might be in a register.
1105    RegisterMap reg_map2(thread);
1106    frame stubFrame   = thread->last_frame();
1107    // Caller-frame is a compiled frame
1108    frame callerFrame = stubFrame.sender(&reg_map2);
1109
1110    methodHandle callee = bytecode.static_target(CHECK_(nullHandle));
1111    if (callee.is_null()) {
1112      THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
1113    }
1114    // Retrieve from a compiled argument list
1115    receiver = Handle(THREAD, callerFrame.retrieve_receiver(&reg_map2));
1116
1117    if (receiver.is_null()) {
1118      THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);
1119    }
1120  }
1121
1122  // Resolve method. This is parameterized by bytecode.
1123  constantPoolHandle constants(THREAD, caller->constants());
1124  assert(receiver.is_null() || receiver->is_oop(), "wrong receiver");
1125  LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_(nullHandle));
1126
1127#ifdef ASSERT
1128  // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
1129  if (bc != Bytecodes::_invokestatic && bc != Bytecodes::_invokedynamic && bc != Bytecodes::_invokehandle) {
1130    assert(receiver.not_null(), "should have thrown exception");
1131    KlassHandle receiver_klass(THREAD, receiver->klass());
1132    Klass* rk = constants->klass_ref_at(bytecode_index, CHECK_(nullHandle));
1133                            // klass is already loaded
1134    KlassHandle static_receiver_klass(THREAD, rk);
1135    // Method handle invokes might have been optimized to a direct call
1136    // so don't check for the receiver class.
1137    // FIXME this weakens the assert too much
1138    methodHandle callee = callinfo.selected_method();
1139    assert(receiver_klass->is_subtype_of(static_receiver_klass()) ||
1140           callee->is_method_handle_intrinsic() ||
1141           callee->is_compiled_lambda_form(),
1142           "actual receiver must be subclass of static receiver klass");
1143    if (receiver_klass->is_instance_klass()) {
1144      if (InstanceKlass::cast(receiver_klass())->is_not_initialized()) {
1145        tty->print_cr("ERROR: Klass not yet initialized!!");
1146        receiver_klass()->print();
1147      }
1148      assert(!InstanceKlass::cast(receiver_klass())->is_not_initialized(), "receiver_klass must be initialized");
1149    }
1150  }
1151#endif
1152
1153  return receiver;
1154}
1155
1156methodHandle SharedRuntime::find_callee_method(JavaThread* thread, TRAPS) {
1157  ResourceMark rm(THREAD);
1158  // We need first to check if any Java activations (compiled, interpreted)
1159  // exist on the stack since last JavaCall.  If not, we need
1160  // to get the target method from the JavaCall wrapper.
1161  vframeStream vfst(thread, true);  // Do not skip any javaCalls
1162  methodHandle callee_method;
1163  if (vfst.at_end()) {
1164    // No Java frames were found on stack since we did the JavaCall.
1165    // Hence the stack can only contain an entry_frame.  We need to
1166    // find the target method from the stub frame.
1167    RegisterMap reg_map(thread, false);
1168    frame fr = thread->last_frame();
1169    assert(fr.is_runtime_frame(), "must be a runtimeStub");
1170    fr = fr.sender(&reg_map);
1171    assert(fr.is_entry_frame(), "must be");
1172    // fr is now pointing to the entry frame.
1173    callee_method = methodHandle(THREAD, fr.entry_frame_call_wrapper()->callee_method());
1174    assert(fr.entry_frame_call_wrapper()->receiver() == NULL || !callee_method->is_static(), "non-null receiver for static call??");
1175  } else {
1176    Bytecodes::Code bc;
1177    CallInfo callinfo;
1178    find_callee_info_helper(thread, vfst, bc, callinfo, CHECK_(methodHandle()));
1179    callee_method = callinfo.selected_method();
1180  }
1181  assert(callee_method()->is_method(), "must be");
1182  return callee_method;
1183}
1184
1185// Resolves a call.
1186methodHandle SharedRuntime::resolve_helper(JavaThread *thread,
1187                                           bool is_virtual,
1188                                           bool is_optimized, TRAPS) {
1189  methodHandle callee_method;
1190  callee_method = resolve_sub_helper(thread, is_virtual, is_optimized, THREAD);
1191  if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
1192    int retry_count = 0;
1193    while (!HAS_PENDING_EXCEPTION && callee_method->is_old() &&
1194           callee_method->method_holder() != SystemDictionary::Object_klass()) {
1195      // If has a pending exception then there is no need to re-try to
1196      // resolve this method.
1197      // If the method has been redefined, we need to try again.
1198      // Hack: we have no way to update the vtables of arrays, so don't
1199      // require that java.lang.Object has been updated.
1200
1201      // It is very unlikely that method is redefined more than 100 times
1202      // in the middle of resolve. If it is looping here more than 100 times
1203      // means then there could be a bug here.
1204      guarantee((retry_count++ < 100),
1205                "Could not resolve to latest version of redefined method");
1206      // method is redefined in the middle of resolve so re-try.
1207      callee_method = resolve_sub_helper(thread, is_virtual, is_optimized, THREAD);
1208    }
1209  }
1210  return callee_method;
1211}
1212
1213// Resolves a call.  The compilers generate code for calls that go here
1214// and are patched with the real destination of the call.
1215methodHandle SharedRuntime::resolve_sub_helper(JavaThread *thread,
1216                                           bool is_virtual,
1217                                           bool is_optimized, TRAPS) {
1218
1219  ResourceMark rm(thread);
1220  RegisterMap cbl_map(thread, false);
1221  frame caller_frame = thread->last_frame().sender(&cbl_map);
1222
1223  CodeBlob* caller_cb = caller_frame.cb();
1224  guarantee(caller_cb != NULL && caller_cb->is_nmethod(), "must be called from nmethod");
1225  nmethod* caller_nm = caller_cb->as_nmethod_or_null();
1226
1227  // make sure caller is not getting deoptimized
1228  // and removed before we are done with it.
1229  // CLEANUP - with lazy deopt shouldn't need this lock
1230  nmethodLocker caller_lock(caller_nm);
1231
1232  // determine call info & receiver
1233  // note: a) receiver is NULL for static calls
1234  //       b) an exception is thrown if receiver is NULL for non-static calls
1235  CallInfo call_info;
1236  Bytecodes::Code invoke_code = Bytecodes::_illegal;
1237  Handle receiver = find_callee_info(thread, invoke_code,
1238                                     call_info, CHECK_(methodHandle()));
1239  methodHandle callee_method = call_info.selected_method();
1240
1241  assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
1242         (!is_virtual && invoke_code == Bytecodes::_invokespecial) ||
1243         (!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
1244         (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
1245         ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
1246
1247  assert(caller_nm->is_alive(), "It should be alive");
1248
1249#ifndef PRODUCT
1250  // tracing/debugging/statistics
1251  int *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) :
1252                (is_virtual) ? (&_resolve_virtual_ctr) :
1253                               (&_resolve_static_ctr);
1254  Atomic::inc(addr);
1255
1256  if (TraceCallFixup) {
1257    ResourceMark rm(thread);
1258    tty->print("resolving %s%s (%s) call to",
1259      (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static",
1260      Bytecodes::name(invoke_code));
1261    callee_method->print_short_name(tty);
1262    tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT,
1263                  p2i(caller_frame.pc()), p2i(callee_method->code()));
1264  }
1265#endif
1266
1267  // JSR 292 key invariant:
1268  // If the resolved method is a MethodHandle invoke target, the call
1269  // site must be a MethodHandle call site, because the lambda form might tail-call
1270  // leaving the stack in a state unknown to either caller or callee
1271  // TODO detune for now but we might need it again
1272//  assert(!callee_method->is_compiled_lambda_form() ||
1273//         caller_nm->is_method_handle_return(caller_frame.pc()), "must be MH call site");
1274
1275  // Compute entry points. This might require generation of C2I converter
1276  // frames, so we cannot be holding any locks here. Furthermore, the
1277  // computation of the entry points is independent of patching the call.  We
1278  // always return the entry-point, but we only patch the stub if the call has
1279  // not been deoptimized.  Return values: For a virtual call this is an
1280  // (cached_oop, destination address) pair. For a static call/optimized
1281  // virtual this is just a destination address.
1282
1283  StaticCallInfo static_call_info;
1284  CompiledICInfo virtual_call_info;
1285
1286  // Make sure the callee nmethod does not get deoptimized and removed before
1287  // we are done patching the code.
1288  nmethod* callee_nm = callee_method->code();
1289  if (callee_nm != NULL && !callee_nm->is_in_use()) {
1290    // Patch call site to C2I adapter if callee nmethod is deoptimized or unloaded.
1291    callee_nm = NULL;
1292  }
1293  nmethodLocker nl_callee(callee_nm);
1294#ifdef ASSERT
1295  address dest_entry_point = callee_nm == NULL ? 0 : callee_nm->entry_point(); // used below
1296#endif
1297
1298  if (is_virtual) {
1299    assert(receiver.not_null() || invoke_code == Bytecodes::_invokehandle, "sanity check");
1300    bool static_bound = call_info.resolved_method()->can_be_statically_bound();
1301    KlassHandle h_klass(THREAD, invoke_code == Bytecodes::_invokehandle ? NULL : receiver->klass());
1302    CompiledIC::compute_monomorphic_entry(callee_method, h_klass,
1303                     is_optimized, static_bound, virtual_call_info,
1304                     CHECK_(methodHandle()));
1305  } else {
1306    // static call
1307    CompiledStaticCall::compute_entry(callee_method, static_call_info);
1308  }
1309
1310  // grab lock, check for deoptimization and potentially patch caller
1311  {
1312    MutexLocker ml_patch(CompiledIC_lock);
1313
1314    // Lock blocks for safepoint during which both nmethods can change state.
1315
1316    // Now that we are ready to patch if the Method* was redefined then
1317    // don't update call site and let the caller retry.
1318    // Don't update call site if callee nmethod was unloaded or deoptimized.
1319    // Don't update call site if callee nmethod was replaced by an other nmethod
1320    // which may happen when multiply alive nmethod (tiered compilation)
1321    // will be supported.
1322    if (!callee_method->is_old() &&
1323        (callee_nm == NULL || callee_nm->is_in_use() && (callee_method->code() == callee_nm))) {
1324#ifdef ASSERT
1325      // We must not try to patch to jump to an already unloaded method.
1326      if (dest_entry_point != 0) {
1327        CodeBlob* cb = CodeCache::find_blob(dest_entry_point);
1328        assert((cb != NULL) && cb->is_nmethod() && (((nmethod*)cb) == callee_nm),
1329               "should not call unloaded nmethod");
1330      }
1331#endif
1332      if (is_virtual) {
1333        CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1334        if (inline_cache->is_clean()) {
1335          inline_cache->set_to_monomorphic(virtual_call_info);
1336        }
1337      } else {
1338        CompiledStaticCall* ssc = compiledStaticCall_before(caller_frame.pc());
1339        if (ssc->is_clean()) ssc->set(static_call_info);
1340      }
1341    }
1342
1343  } // unlock CompiledIC_lock
1344
1345  return callee_method;
1346}
1347
1348
1349// Inline caches exist only in compiled code
1350JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* thread))
1351#ifdef ASSERT
1352  RegisterMap reg_map(thread, false);
1353  frame stub_frame = thread->last_frame();
1354  assert(stub_frame.is_runtime_frame(), "sanity check");
1355  frame caller_frame = stub_frame.sender(&reg_map);
1356  assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame(), "unexpected frame");
1357#endif /* ASSERT */
1358
1359  methodHandle callee_method;
1360  JRT_BLOCK
1361    callee_method = SharedRuntime::handle_ic_miss_helper(thread, CHECK_NULL);
1362    // Return Method* through TLS
1363    thread->set_vm_result_2(callee_method());
1364  JRT_BLOCK_END
1365  // return compiled code entry point after potential safepoints
1366  assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1367  return callee_method->verified_code_entry();
1368JRT_END
1369
1370
1371// Handle call site that has been made non-entrant
1372JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* thread))
1373  // 6243940 We might end up in here if the callee is deoptimized
1374  // as we race to call it.  We don't want to take a safepoint if
1375  // the caller was interpreted because the caller frame will look
1376  // interpreted to the stack walkers and arguments are now
1377  // "compiled" so it is much better to make this transition
1378  // invisible to the stack walking code. The i2c path will
1379  // place the callee method in the callee_target. It is stashed
1380  // there because if we try and find the callee by normal means a
1381  // safepoint is possible and have trouble gc'ing the compiled args.
1382  RegisterMap reg_map(thread, false);
1383  frame stub_frame = thread->last_frame();
1384  assert(stub_frame.is_runtime_frame(), "sanity check");
1385  frame caller_frame = stub_frame.sender(&reg_map);
1386
1387  if (caller_frame.is_interpreted_frame() ||
1388      caller_frame.is_entry_frame()) {
1389    Method* callee = thread->callee_target();
1390    guarantee(callee != NULL && callee->is_method(), "bad handshake");
1391    thread->set_vm_result_2(callee);
1392    thread->set_callee_target(NULL);
1393    return callee->get_c2i_entry();
1394  }
1395
1396  // Must be compiled to compiled path which is safe to stackwalk
1397  methodHandle callee_method;
1398  JRT_BLOCK
1399    // Force resolving of caller (if we called from compiled frame)
1400    callee_method = SharedRuntime::reresolve_call_site(thread, CHECK_NULL);
1401    thread->set_vm_result_2(callee_method());
1402  JRT_BLOCK_END
1403  // return compiled code entry point after potential safepoints
1404  assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1405  return callee_method->verified_code_entry();
1406JRT_END
1407
1408// Handle abstract method call
1409JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* thread))
1410  return StubRoutines::throw_AbstractMethodError_entry();
1411JRT_END
1412
1413
1414// resolve a static call and patch code
1415JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread *thread ))
1416  methodHandle callee_method;
1417  JRT_BLOCK
1418    callee_method = SharedRuntime::resolve_helper(thread, false, false, CHECK_NULL);
1419    thread->set_vm_result_2(callee_method());
1420  JRT_BLOCK_END
1421  // return compiled code entry point after potential safepoints
1422  assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1423  return callee_method->verified_code_entry();
1424JRT_END
1425
1426
1427// resolve virtual call and update inline cache to monomorphic
1428JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread *thread ))
1429  methodHandle callee_method;
1430  JRT_BLOCK
1431    callee_method = SharedRuntime::resolve_helper(thread, true, false, CHECK_NULL);
1432    thread->set_vm_result_2(callee_method());
1433  JRT_BLOCK_END
1434  // return compiled code entry point after potential safepoints
1435  assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1436  return callee_method->verified_code_entry();
1437JRT_END
1438
1439
1440// Resolve a virtual call that can be statically bound (e.g., always
1441// monomorphic, so it has no inline cache).  Patch code to resolved target.
1442JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread *thread))
1443  methodHandle callee_method;
1444  JRT_BLOCK
1445    callee_method = SharedRuntime::resolve_helper(thread, true, true, CHECK_NULL);
1446    thread->set_vm_result_2(callee_method());
1447  JRT_BLOCK_END
1448  // return compiled code entry point after potential safepoints
1449  assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1450  return callee_method->verified_code_entry();
1451JRT_END
1452
1453
1454methodHandle SharedRuntime::handle_ic_miss_helper(JavaThread *thread, TRAPS) {
1455  ResourceMark rm(thread);
1456  CallInfo call_info;
1457  Bytecodes::Code bc;
1458
1459  // receiver is NULL for static calls. An exception is thrown for NULL
1460  // receivers for non-static calls
1461  Handle receiver = find_callee_info(thread, bc, call_info,
1462                                     CHECK_(methodHandle()));
1463  // Compiler1 can produce virtual call sites that can actually be statically bound
1464  // If we fell thru to below we would think that the site was going megamorphic
1465  // when in fact the site can never miss. Worse because we'd think it was megamorphic
1466  // we'd try and do a vtable dispatch however methods that can be statically bound
1467  // don't have vtable entries (vtable_index < 0) and we'd blow up. So we force a
1468  // reresolution of the  call site (as if we did a handle_wrong_method and not an
1469  // plain ic_miss) and the site will be converted to an optimized virtual call site
1470  // never to miss again. I don't believe C2 will produce code like this but if it
1471  // did this would still be the correct thing to do for it too, hence no ifdef.
1472  //
1473  if (call_info.resolved_method()->can_be_statically_bound()) {
1474    methodHandle callee_method = SharedRuntime::reresolve_call_site(thread, CHECK_(methodHandle()));
1475    if (TraceCallFixup) {
1476      RegisterMap reg_map(thread, false);
1477      frame caller_frame = thread->last_frame().sender(&reg_map);
1478      ResourceMark rm(thread);
1479      tty->print("converting IC miss to reresolve (%s) call to", Bytecodes::name(bc));
1480      callee_method->print_short_name(tty);
1481      tty->print_cr(" from pc: " INTPTR_FORMAT, p2i(caller_frame.pc()));
1482      tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1483    }
1484    return callee_method;
1485  }
1486
1487  methodHandle callee_method = call_info.selected_method();
1488
1489  bool should_be_mono = false;
1490
1491#ifndef PRODUCT
1492  Atomic::inc(&_ic_miss_ctr);
1493
1494  // Statistics & Tracing
1495  if (TraceCallFixup) {
1496    ResourceMark rm(thread);
1497    tty->print("IC miss (%s) call to", Bytecodes::name(bc));
1498    callee_method->print_short_name(tty);
1499    tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1500  }
1501
1502  if (ICMissHistogram) {
1503    MutexLocker m(VMStatistic_lock);
1504    RegisterMap reg_map(thread, false);
1505    frame f = thread->last_frame().real_sender(&reg_map);// skip runtime stub
1506    // produce statistics under the lock
1507    trace_ic_miss(f.pc());
1508  }
1509#endif
1510
1511  // install an event collector so that when a vtable stub is created the
1512  // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
1513  // event can't be posted when the stub is created as locks are held
1514  // - instead the event will be deferred until the event collector goes
1515  // out of scope.
1516  JvmtiDynamicCodeEventCollector event_collector;
1517
1518  // Update inline cache to megamorphic. Skip update if we are called from interpreted.
1519  { MutexLocker ml_patch (CompiledIC_lock);
1520    RegisterMap reg_map(thread, false);
1521    frame caller_frame = thread->last_frame().sender(&reg_map);
1522    CodeBlob* cb = caller_frame.cb();
1523    if (cb->is_nmethod()) {
1524      CompiledIC* inline_cache = CompiledIC_before(((nmethod*)cb), caller_frame.pc());
1525      bool should_be_mono = false;
1526      if (inline_cache->is_optimized()) {
1527        if (TraceCallFixup) {
1528          ResourceMark rm(thread);
1529          tty->print("OPTIMIZED IC miss (%s) call to", Bytecodes::name(bc));
1530          callee_method->print_short_name(tty);
1531          tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1532        }
1533        should_be_mono = true;
1534      } else if (inline_cache->is_icholder_call()) {
1535        CompiledICHolder* ic_oop = inline_cache->cached_icholder();
1536        if (ic_oop != NULL) {
1537
1538          if (receiver()->klass() == ic_oop->holder_klass()) {
1539            // This isn't a real miss. We must have seen that compiled code
1540            // is now available and we want the call site converted to a
1541            // monomorphic compiled call site.
1542            // We can't assert for callee_method->code() != NULL because it
1543            // could have been deoptimized in the meantime
1544            if (TraceCallFixup) {
1545              ResourceMark rm(thread);
1546              tty->print("FALSE IC miss (%s) converting to compiled call to", Bytecodes::name(bc));
1547              callee_method->print_short_name(tty);
1548              tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1549            }
1550            should_be_mono = true;
1551          }
1552        }
1553      }
1554
1555      if (should_be_mono) {
1556
1557        // We have a path that was monomorphic but was going interpreted
1558        // and now we have (or had) a compiled entry. We correct the IC
1559        // by using a new icBuffer.
1560        CompiledICInfo info;
1561        KlassHandle receiver_klass(THREAD, receiver()->klass());
1562        inline_cache->compute_monomorphic_entry(callee_method,
1563                                                receiver_klass,
1564                                                inline_cache->is_optimized(),
1565                                                false,
1566                                                info, CHECK_(methodHandle()));
1567        inline_cache->set_to_monomorphic(info);
1568      } else if (!inline_cache->is_megamorphic() && !inline_cache->is_clean()) {
1569        // Potential change to megamorphic
1570        bool successful = inline_cache->set_to_megamorphic(&call_info, bc, CHECK_(methodHandle()));
1571        if (!successful) {
1572          inline_cache->set_to_clean();
1573        }
1574      } else {
1575        // Either clean or megamorphic
1576      }
1577    } else {
1578      fatal("Unimplemented");
1579    }
1580  } // Release CompiledIC_lock
1581
1582  return callee_method;
1583}
1584
1585//
1586// Resets a call-site in compiled code so it will get resolved again.
1587// This routines handles both virtual call sites, optimized virtual call
1588// sites, and static call sites. Typically used to change a call sites
1589// destination from compiled to interpreted.
1590//
1591methodHandle SharedRuntime::reresolve_call_site(JavaThread *thread, TRAPS) {
1592  ResourceMark rm(thread);
1593  RegisterMap reg_map(thread, false);
1594  frame stub_frame = thread->last_frame();
1595  assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
1596  frame caller = stub_frame.sender(&reg_map);
1597
1598  // Do nothing if the frame isn't a live compiled frame.
1599  // nmethod could be deoptimized by the time we get here
1600  // so no update to the caller is needed.
1601
1602  if (caller.is_compiled_frame() && !caller.is_deoptimized_frame()) {
1603
1604    address pc = caller.pc();
1605
1606    // Check for static or virtual call
1607    bool is_static_call = false;
1608    nmethod* caller_nm = CodeCache::find_nmethod(pc);
1609
1610    // Default call_addr is the location of the "basic" call.
1611    // Determine the address of the call we a reresolving. With
1612    // Inline Caches we will always find a recognizable call.
1613    // With Inline Caches disabled we may or may not find a
1614    // recognizable call. We will always find a call for static
1615    // calls and for optimized virtual calls. For vanilla virtual
1616    // calls it depends on the state of the UseInlineCaches switch.
1617    //
1618    // With Inline Caches disabled we can get here for a virtual call
1619    // for two reasons:
1620    //   1 - calling an abstract method. The vtable for abstract methods
1621    //       will run us thru handle_wrong_method and we will eventually
1622    //       end up in the interpreter to throw the ame.
1623    //   2 - a racing deoptimization. We could be doing a vanilla vtable
1624    //       call and between the time we fetch the entry address and
1625    //       we jump to it the target gets deoptimized. Similar to 1
1626    //       we will wind up in the interprter (thru a c2i with c2).
1627    //
1628    address call_addr = NULL;
1629    {
1630      // Get call instruction under lock because another thread may be
1631      // busy patching it.
1632      MutexLockerEx ml_patch(Patching_lock, Mutex::_no_safepoint_check_flag);
1633      // Location of call instruction
1634      if (NativeCall::is_call_before(pc)) {
1635        NativeCall *ncall = nativeCall_before(pc);
1636        call_addr = ncall->instruction_address();
1637      }
1638    }
1639    // Make sure nmethod doesn't get deoptimized and removed until
1640    // this is done with it.
1641    // CLEANUP - with lazy deopt shouldn't need this lock
1642    nmethodLocker nmlock(caller_nm);
1643
1644    if (call_addr != NULL) {
1645      RelocIterator iter(caller_nm, call_addr, call_addr+1);
1646      int ret = iter.next(); // Get item
1647      if (ret) {
1648        assert(iter.addr() == call_addr, "must find call");
1649        if (iter.type() == relocInfo::static_call_type) {
1650          is_static_call = true;
1651        } else {
1652          assert(iter.type() == relocInfo::virtual_call_type ||
1653                 iter.type() == relocInfo::opt_virtual_call_type
1654                , "unexpected relocInfo. type");
1655        }
1656      } else {
1657        assert(!UseInlineCaches, "relocation info. must exist for this address");
1658      }
1659
1660      // Cleaning the inline cache will force a new resolve. This is more robust
1661      // than directly setting it to the new destination, since resolving of calls
1662      // is always done through the same code path. (experience shows that it
1663      // leads to very hard to track down bugs, if an inline cache gets updated
1664      // to a wrong method). It should not be performance critical, since the
1665      // resolve is only done once.
1666
1667      MutexLocker ml(CompiledIC_lock);
1668      if (is_static_call) {
1669        CompiledStaticCall* ssc= compiledStaticCall_at(call_addr);
1670        ssc->set_to_clean();
1671      } else {
1672        // compiled, dispatched call (which used to call an interpreted method)
1673        CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
1674        inline_cache->set_to_clean();
1675      }
1676    }
1677
1678  }
1679
1680  methodHandle callee_method = find_callee_method(thread, CHECK_(methodHandle()));
1681
1682
1683#ifndef PRODUCT
1684  Atomic::inc(&_wrong_method_ctr);
1685
1686  if (TraceCallFixup) {
1687    ResourceMark rm(thread);
1688    tty->print("handle_wrong_method reresolving call to");
1689    callee_method->print_short_name(tty);
1690    tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1691  }
1692#endif
1693
1694  return callee_method;
1695}
1696
1697#ifdef ASSERT
1698void SharedRuntime::check_member_name_argument_is_last_argument(const methodHandle& method,
1699                                                                const BasicType* sig_bt,
1700                                                                const VMRegPair* regs) {
1701  ResourceMark rm;
1702  const int total_args_passed = method->size_of_parameters();
1703  const VMRegPair*    regs_with_member_name = regs;
1704        VMRegPair* regs_without_member_name = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed - 1);
1705
1706  const int member_arg_pos = total_args_passed - 1;
1707  assert(member_arg_pos >= 0 && member_arg_pos < total_args_passed, "oob");
1708  assert(sig_bt[member_arg_pos] == T_OBJECT, "dispatch argument must be an object");
1709
1710  const bool is_outgoing = method->is_method_handle_intrinsic();
1711  int comp_args_on_stack = java_calling_convention(sig_bt, regs_without_member_name, total_args_passed - 1, is_outgoing);
1712
1713  for (int i = 0; i < member_arg_pos; i++) {
1714    VMReg a =    regs_with_member_name[i].first();
1715    VMReg b = regs_without_member_name[i].first();
1716    assert(a->value() == b->value(), "register allocation mismatch: a=" INTX_FORMAT ", b=" INTX_FORMAT, a->value(), b->value());
1717  }
1718  assert(regs_with_member_name[member_arg_pos].first()->is_valid(), "bad member arg");
1719}
1720#endif
1721
1722// ---------------------------------------------------------------------------
1723// We are calling the interpreter via a c2i. Normally this would mean that
1724// we were called by a compiled method. However we could have lost a race
1725// where we went int -> i2c -> c2i and so the caller could in fact be
1726// interpreted. If the caller is compiled we attempt to patch the caller
1727// so he no longer calls into the interpreter.
1728IRT_LEAF(void, SharedRuntime::fixup_callers_callsite(Method* method, address caller_pc))
1729  Method* moop(method);
1730
1731  address entry_point = moop->from_compiled_entry();
1732
1733  // It's possible that deoptimization can occur at a call site which hasn't
1734  // been resolved yet, in which case this function will be called from
1735  // an nmethod that has been patched for deopt and we can ignore the
1736  // request for a fixup.
1737  // Also it is possible that we lost a race in that from_compiled_entry
1738  // is now back to the i2c in that case we don't need to patch and if
1739  // we did we'd leap into space because the callsite needs to use
1740  // "to interpreter" stub in order to load up the Method*. Don't
1741  // ask me how I know this...
1742
1743  CodeBlob* cb = CodeCache::find_blob(caller_pc);
1744  if (!cb->is_nmethod() || entry_point == moop->get_c2i_entry()) {
1745    return;
1746  }
1747
1748  // The check above makes sure this is a nmethod.
1749  nmethod* nm = cb->as_nmethod_or_null();
1750  assert(nm, "must be");
1751
1752  // Get the return PC for the passed caller PC.
1753  address return_pc = caller_pc + frame::pc_return_offset;
1754
1755  // There is a benign race here. We could be attempting to patch to a compiled
1756  // entry point at the same time the callee is being deoptimized. If that is
1757  // the case then entry_point may in fact point to a c2i and we'd patch the
1758  // call site with the same old data. clear_code will set code() to NULL
1759  // at the end of it. If we happen to see that NULL then we can skip trying
1760  // to patch. If we hit the window where the callee has a c2i in the
1761  // from_compiled_entry and the NULL isn't present yet then we lose the race
1762  // and patch the code with the same old data. Asi es la vida.
1763
1764  if (moop->code() == NULL) return;
1765
1766  if (nm->is_in_use()) {
1767
1768    // Expect to find a native call there (unless it was no-inline cache vtable dispatch)
1769    MutexLockerEx ml_patch(Patching_lock, Mutex::_no_safepoint_check_flag);
1770    if (NativeCall::is_call_before(return_pc)) {
1771      NativeCall *call = nativeCall_before(return_pc);
1772      //
1773      // bug 6281185. We might get here after resolving a call site to a vanilla
1774      // virtual call. Because the resolvee uses the verified entry it may then
1775      // see compiled code and attempt to patch the site by calling us. This would
1776      // then incorrectly convert the call site to optimized and its downhill from
1777      // there. If you're lucky you'll get the assert in the bugid, if not you've
1778      // just made a call site that could be megamorphic into a monomorphic site
1779      // for the rest of its life! Just another racing bug in the life of
1780      // fixup_callers_callsite ...
1781      //
1782      RelocIterator iter(nm, call->instruction_address(), call->next_instruction_address());
1783      iter.next();
1784      assert(iter.has_current(), "must have a reloc at java call site");
1785      relocInfo::relocType typ = iter.reloc()->type();
1786      if (typ != relocInfo::static_call_type &&
1787           typ != relocInfo::opt_virtual_call_type &&
1788           typ != relocInfo::static_stub_type) {
1789        return;
1790      }
1791      address destination = call->destination();
1792      if (destination != entry_point) {
1793        CodeBlob* callee = CodeCache::find_blob(destination);
1794        // callee == cb seems weird. It means calling interpreter thru stub.
1795        if (callee == cb || callee->is_adapter_blob()) {
1796          // static call or optimized virtual
1797          if (TraceCallFixup) {
1798            tty->print("fixup callsite           at " INTPTR_FORMAT " to compiled code for", p2i(caller_pc));
1799            moop->print_short_name(tty);
1800            tty->print_cr(" to " INTPTR_FORMAT, p2i(entry_point));
1801          }
1802          call->set_destination_mt_safe(entry_point);
1803        } else {
1804          if (TraceCallFixup) {
1805            tty->print("failed to fixup callsite at " INTPTR_FORMAT " to compiled code for", p2i(caller_pc));
1806            moop->print_short_name(tty);
1807            tty->print_cr(" to " INTPTR_FORMAT, p2i(entry_point));
1808          }
1809          // assert is too strong could also be resolve destinations.
1810          // assert(InlineCacheBuffer::contains(destination) || VtableStubs::contains(destination), "must be");
1811        }
1812      } else {
1813          if (TraceCallFixup) {
1814            tty->print("already patched callsite at " INTPTR_FORMAT " to compiled code for", p2i(caller_pc));
1815            moop->print_short_name(tty);
1816            tty->print_cr(" to " INTPTR_FORMAT, p2i(entry_point));
1817          }
1818      }
1819    }
1820  }
1821IRT_END
1822
1823
1824// same as JVM_Arraycopy, but called directly from compiled code
1825JRT_ENTRY(void, SharedRuntime::slow_arraycopy_C(oopDesc* src,  jint src_pos,
1826                                                oopDesc* dest, jint dest_pos,
1827                                                jint length,
1828                                                JavaThread* thread)) {
1829#ifndef PRODUCT
1830  _slow_array_copy_ctr++;
1831#endif
1832  // Check if we have null pointers
1833  if (src == NULL || dest == NULL) {
1834    THROW(vmSymbols::java_lang_NullPointerException());
1835  }
1836  // Do the copy.  The casts to arrayOop are necessary to the copy_array API,
1837  // even though the copy_array API also performs dynamic checks to ensure
1838  // that src and dest are truly arrays (and are conformable).
1839  // The copy_array mechanism is awkward and could be removed, but
1840  // the compilers don't call this function except as a last resort,
1841  // so it probably doesn't matter.
1842  src->klass()->copy_array((arrayOopDesc*)src, src_pos,
1843                                        (arrayOopDesc*)dest, dest_pos,
1844                                        length, thread);
1845}
1846JRT_END
1847
1848char* SharedRuntime::generate_class_cast_message(
1849    JavaThread* thread, const char* objName) {
1850
1851  // Get target class name from the checkcast instruction
1852  vframeStream vfst(thread, true);
1853  assert(!vfst.at_end(), "Java frame must exist");
1854  Bytecode_checkcast cc(vfst.method(), vfst.method()->bcp_from(vfst.bci()));
1855  Klass* targetKlass = vfst.method()->constants()->klass_at(
1856    cc.index(), thread);
1857  return generate_class_cast_message(objName, targetKlass->external_name());
1858}
1859
1860char* SharedRuntime::generate_class_cast_message(
1861    const char* objName, const char* targetKlassName, const char* desc) {
1862  size_t msglen = strlen(objName) + strlen(desc) + strlen(targetKlassName) + 1;
1863
1864  char* message = NEW_RESOURCE_ARRAY(char, msglen);
1865  if (NULL == message) {
1866    // Shouldn't happen, but don't cause even more problems if it does
1867    message = const_cast<char*>(objName);
1868  } else {
1869    jio_snprintf(message, msglen, "%s%s%s", objName, desc, targetKlassName);
1870  }
1871  return message;
1872}
1873
1874JRT_LEAF(void, SharedRuntime::reguard_yellow_pages())
1875  (void) JavaThread::current()->reguard_stack();
1876JRT_END
1877
1878
1879// Handles the uncommon case in locking, i.e., contention or an inflated lock.
1880JRT_BLOCK_ENTRY(void, SharedRuntime::complete_monitor_locking_C(oopDesc* _obj, BasicLock* lock, JavaThread* thread))
1881  // Disable ObjectSynchronizer::quick_enter() in default config
1882  // until JDK-8077392 is resolved.
1883  if ((SyncFlags & 256) != 0 && !SafepointSynchronize::is_synchronizing()) {
1884    // Only try quick_enter() if we're not trying to reach a safepoint
1885    // so that the calling thread reaches the safepoint more quickly.
1886    if (ObjectSynchronizer::quick_enter(_obj, thread, lock)) return;
1887  }
1888  // NO_ASYNC required because an async exception on the state transition destructor
1889  // would leave you with the lock held and it would never be released.
1890  // The normal monitorenter NullPointerException is thrown without acquiring a lock
1891  // and the model is that an exception implies the method failed.
1892  JRT_BLOCK_NO_ASYNC
1893  oop obj(_obj);
1894  if (PrintBiasedLockingStatistics) {
1895    Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
1896  }
1897  Handle h_obj(THREAD, obj);
1898  if (UseBiasedLocking) {
1899    // Retry fast entry if bias is revoked to avoid unnecessary inflation
1900    ObjectSynchronizer::fast_enter(h_obj, lock, true, CHECK);
1901  } else {
1902    ObjectSynchronizer::slow_enter(h_obj, lock, CHECK);
1903  }
1904  assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");
1905  JRT_BLOCK_END
1906JRT_END
1907
1908// Handles the uncommon cases of monitor unlocking in compiled code
1909JRT_LEAF(void, SharedRuntime::complete_monitor_unlocking_C(oopDesc* _obj, BasicLock* lock, JavaThread * THREAD))
1910   oop obj(_obj);
1911  assert(JavaThread::current() == THREAD, "invariant");
1912  // I'm not convinced we need the code contained by MIGHT_HAVE_PENDING anymore
1913  // testing was unable to ever fire the assert that guarded it so I have removed it.
1914  assert(!HAS_PENDING_EXCEPTION, "Do we need code below anymore?");
1915#undef MIGHT_HAVE_PENDING
1916#ifdef MIGHT_HAVE_PENDING
1917  // Save and restore any pending_exception around the exception mark.
1918  // While the slow_exit must not throw an exception, we could come into
1919  // this routine with one set.
1920  oop pending_excep = NULL;
1921  const char* pending_file;
1922  int pending_line;
1923  if (HAS_PENDING_EXCEPTION) {
1924    pending_excep = PENDING_EXCEPTION;
1925    pending_file  = THREAD->exception_file();
1926    pending_line  = THREAD->exception_line();
1927    CLEAR_PENDING_EXCEPTION;
1928  }
1929#endif /* MIGHT_HAVE_PENDING */
1930
1931  {
1932    // Exit must be non-blocking, and therefore no exceptions can be thrown.
1933    EXCEPTION_MARK;
1934    ObjectSynchronizer::slow_exit(obj, lock, THREAD);
1935  }
1936
1937#ifdef MIGHT_HAVE_PENDING
1938  if (pending_excep != NULL) {
1939    THREAD->set_pending_exception(pending_excep, pending_file, pending_line);
1940  }
1941#endif /* MIGHT_HAVE_PENDING */
1942JRT_END
1943
1944#ifndef PRODUCT
1945
1946void SharedRuntime::print_statistics() {
1947  ttyLocker ttyl;
1948  if (xtty != NULL)  xtty->head("statistics type='SharedRuntime'");
1949
1950  if (_throw_null_ctr) tty->print_cr("%5d implicit null throw", _throw_null_ctr);
1951
1952  SharedRuntime::print_ic_miss_histogram();
1953
1954  if (CountRemovableExceptions) {
1955    if (_nof_removable_exceptions > 0) {
1956      Unimplemented(); // this counter is not yet incremented
1957      tty->print_cr("Removable exceptions: %d", _nof_removable_exceptions);
1958    }
1959  }
1960
1961  // Dump the JRT_ENTRY counters
1962  if (_new_instance_ctr) tty->print_cr("%5d new instance requires GC", _new_instance_ctr);
1963  if (_new_array_ctr) tty->print_cr("%5d new array requires GC", _new_array_ctr);
1964  if (_multi1_ctr) tty->print_cr("%5d multianewarray 1 dim", _multi1_ctr);
1965  if (_multi2_ctr) tty->print_cr("%5d multianewarray 2 dim", _multi2_ctr);
1966  if (_multi3_ctr) tty->print_cr("%5d multianewarray 3 dim", _multi3_ctr);
1967  if (_multi4_ctr) tty->print_cr("%5d multianewarray 4 dim", _multi4_ctr);
1968  if (_multi5_ctr) tty->print_cr("%5d multianewarray 5 dim", _multi5_ctr);
1969
1970  tty->print_cr("%5d inline cache miss in compiled", _ic_miss_ctr);
1971  tty->print_cr("%5d wrong method", _wrong_method_ctr);
1972  tty->print_cr("%5d unresolved static call site", _resolve_static_ctr);
1973  tty->print_cr("%5d unresolved virtual call site", _resolve_virtual_ctr);
1974  tty->print_cr("%5d unresolved opt virtual call site", _resolve_opt_virtual_ctr);
1975
1976  if (_mon_enter_stub_ctr) tty->print_cr("%5d monitor enter stub", _mon_enter_stub_ctr);
1977  if (_mon_exit_stub_ctr) tty->print_cr("%5d monitor exit stub", _mon_exit_stub_ctr);
1978  if (_mon_enter_ctr) tty->print_cr("%5d monitor enter slow", _mon_enter_ctr);
1979  if (_mon_exit_ctr) tty->print_cr("%5d monitor exit slow", _mon_exit_ctr);
1980  if (_partial_subtype_ctr) tty->print_cr("%5d slow partial subtype", _partial_subtype_ctr);
1981  if (_jbyte_array_copy_ctr) tty->print_cr("%5d byte array copies", _jbyte_array_copy_ctr);
1982  if (_jshort_array_copy_ctr) tty->print_cr("%5d short array copies", _jshort_array_copy_ctr);
1983  if (_jint_array_copy_ctr) tty->print_cr("%5d int array copies", _jint_array_copy_ctr);
1984  if (_jlong_array_copy_ctr) tty->print_cr("%5d long array copies", _jlong_array_copy_ctr);
1985  if (_oop_array_copy_ctr) tty->print_cr("%5d oop array copies", _oop_array_copy_ctr);
1986  if (_checkcast_array_copy_ctr) tty->print_cr("%5d checkcast array copies", _checkcast_array_copy_ctr);
1987  if (_unsafe_array_copy_ctr) tty->print_cr("%5d unsafe array copies", _unsafe_array_copy_ctr);
1988  if (_generic_array_copy_ctr) tty->print_cr("%5d generic array copies", _generic_array_copy_ctr);
1989  if (_slow_array_copy_ctr) tty->print_cr("%5d slow array copies", _slow_array_copy_ctr);
1990  if (_find_handler_ctr) tty->print_cr("%5d find exception handler", _find_handler_ctr);
1991  if (_rethrow_ctr) tty->print_cr("%5d rethrow handler", _rethrow_ctr);
1992
1993  AdapterHandlerLibrary::print_statistics();
1994
1995  if (xtty != NULL)  xtty->tail("statistics");
1996}
1997
1998inline double percent(int x, int y) {
1999  return 100.0 * x / MAX2(y, 1);
2000}
2001
2002class MethodArityHistogram {
2003 public:
2004  enum { MAX_ARITY = 256 };
2005 private:
2006  static int _arity_histogram[MAX_ARITY];     // histogram of #args
2007  static int _size_histogram[MAX_ARITY];      // histogram of arg size in words
2008  static int _max_arity;                      // max. arity seen
2009  static int _max_size;                       // max. arg size seen
2010
2011  static void add_method_to_histogram(nmethod* nm) {
2012    Method* m = nm->method();
2013    ArgumentCount args(m->signature());
2014    int arity   = args.size() + (m->is_static() ? 0 : 1);
2015    int argsize = m->size_of_parameters();
2016    arity   = MIN2(arity, MAX_ARITY-1);
2017    argsize = MIN2(argsize, MAX_ARITY-1);
2018    int count = nm->method()->compiled_invocation_count();
2019    _arity_histogram[arity]  += count;
2020    _size_histogram[argsize] += count;
2021    _max_arity = MAX2(_max_arity, arity);
2022    _max_size  = MAX2(_max_size, argsize);
2023  }
2024
2025  void print_histogram_helper(int n, int* histo, const char* name) {
2026    const int N = MIN2(5, n);
2027    tty->print_cr("\nHistogram of call arity (incl. rcvr, calls to compiled methods only):");
2028    double sum = 0;
2029    double weighted_sum = 0;
2030    int i;
2031    for (i = 0; i <= n; i++) { sum += histo[i]; weighted_sum += i*histo[i]; }
2032    double rest = sum;
2033    double percent = sum / 100;
2034    for (i = 0; i <= N; i++) {
2035      rest -= histo[i];
2036      tty->print_cr("%4d: %7d (%5.1f%%)", i, histo[i], histo[i] / percent);
2037    }
2038    tty->print_cr("rest: %7d (%5.1f%%))", (int)rest, rest / percent);
2039    tty->print_cr("(avg. %s = %3.1f, max = %d)", name, weighted_sum / sum, n);
2040  }
2041
2042  void print_histogram() {
2043    tty->print_cr("\nHistogram of call arity (incl. rcvr, calls to compiled methods only):");
2044    print_histogram_helper(_max_arity, _arity_histogram, "arity");
2045    tty->print_cr("\nSame for parameter size (in words):");
2046    print_histogram_helper(_max_size, _size_histogram, "size");
2047    tty->cr();
2048  }
2049
2050 public:
2051  MethodArityHistogram() {
2052    MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2053    _max_arity = _max_size = 0;
2054    for (int i = 0; i < MAX_ARITY; i++) _arity_histogram[i] = _size_histogram[i] = 0;
2055    CodeCache::nmethods_do(add_method_to_histogram);
2056    print_histogram();
2057  }
2058};
2059
2060int MethodArityHistogram::_arity_histogram[MethodArityHistogram::MAX_ARITY];
2061int MethodArityHistogram::_size_histogram[MethodArityHistogram::MAX_ARITY];
2062int MethodArityHistogram::_max_arity;
2063int MethodArityHistogram::_max_size;
2064
2065void SharedRuntime::print_call_statistics(int comp_total) {
2066  tty->print_cr("Calls from compiled code:");
2067  int total  = _nof_normal_calls + _nof_interface_calls + _nof_static_calls;
2068  int mono_c = _nof_normal_calls - _nof_optimized_calls - _nof_megamorphic_calls;
2069  int mono_i = _nof_interface_calls - _nof_optimized_interface_calls - _nof_megamorphic_interface_calls;
2070  tty->print_cr("\t%9d   (%4.1f%%) total non-inlined   ", total, percent(total, total));
2071  tty->print_cr("\t%9d   (%4.1f%%) virtual calls       ", _nof_normal_calls, percent(_nof_normal_calls, total));
2072  tty->print_cr("\t  %9d  (%3.0f%%)   inlined          ", _nof_inlined_calls, percent(_nof_inlined_calls, _nof_normal_calls));
2073  tty->print_cr("\t  %9d  (%3.0f%%)   optimized        ", _nof_optimized_calls, percent(_nof_optimized_calls, _nof_normal_calls));
2074  tty->print_cr("\t  %9d  (%3.0f%%)   monomorphic      ", mono_c, percent(mono_c, _nof_normal_calls));
2075  tty->print_cr("\t  %9d  (%3.0f%%)   megamorphic      ", _nof_megamorphic_calls, percent(_nof_megamorphic_calls, _nof_normal_calls));
2076  tty->print_cr("\t%9d   (%4.1f%%) interface calls     ", _nof_interface_calls, percent(_nof_interface_calls, total));
2077  tty->print_cr("\t  %9d  (%3.0f%%)   inlined          ", _nof_inlined_interface_calls, percent(_nof_inlined_interface_calls, _nof_interface_calls));
2078  tty->print_cr("\t  %9d  (%3.0f%%)   optimized        ", _nof_optimized_interface_calls, percent(_nof_optimized_interface_calls, _nof_interface_calls));
2079  tty->print_cr("\t  %9d  (%3.0f%%)   monomorphic      ", mono_i, percent(mono_i, _nof_interface_calls));
2080  tty->print_cr("\t  %9d  (%3.0f%%)   megamorphic      ", _nof_megamorphic_interface_calls, percent(_nof_megamorphic_interface_calls, _nof_interface_calls));
2081  tty->print_cr("\t%9d   (%4.1f%%) static/special calls", _nof_static_calls, percent(_nof_static_calls, total));
2082  tty->print_cr("\t  %9d  (%3.0f%%)   inlined          ", _nof_inlined_static_calls, percent(_nof_inlined_static_calls, _nof_static_calls));
2083  tty->cr();
2084  tty->print_cr("Note 1: counter updates are not MT-safe.");
2085  tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;");
2086  tty->print_cr("        %% in nested categories are relative to their category");
2087  tty->print_cr("        (and thus add up to more than 100%% with inlining)");
2088  tty->cr();
2089
2090  MethodArityHistogram h;
2091}
2092#endif
2093
2094
2095// A simple wrapper class around the calling convention information
2096// that allows sharing of adapters for the same calling convention.
2097class AdapterFingerPrint : public CHeapObj<mtCode> {
2098 private:
2099  enum {
2100    _basic_type_bits = 4,
2101    _basic_type_mask = right_n_bits(_basic_type_bits),
2102    _basic_types_per_int = BitsPerInt / _basic_type_bits,
2103    _compact_int_count = 3
2104  };
2105  // TO DO:  Consider integrating this with a more global scheme for compressing signatures.
2106  // For now, 4 bits per components (plus T_VOID gaps after double/long) is not excessive.
2107
2108  union {
2109    int  _compact[_compact_int_count];
2110    int* _fingerprint;
2111  } _value;
2112  int _length; // A negative length indicates the fingerprint is in the compact form,
2113               // Otherwise _value._fingerprint is the array.
2114
2115  // Remap BasicTypes that are handled equivalently by the adapters.
2116  // These are correct for the current system but someday it might be
2117  // necessary to make this mapping platform dependent.
2118  static int adapter_encoding(BasicType in) {
2119    switch (in) {
2120      case T_BOOLEAN:
2121      case T_BYTE:
2122      case T_SHORT:
2123      case T_CHAR:
2124        // There are all promoted to T_INT in the calling convention
2125        return T_INT;
2126
2127      case T_OBJECT:
2128      case T_ARRAY:
2129        // In other words, we assume that any register good enough for
2130        // an int or long is good enough for a managed pointer.
2131#ifdef _LP64
2132        return T_LONG;
2133#else
2134        return T_INT;
2135#endif
2136
2137      case T_INT:
2138      case T_LONG:
2139      case T_FLOAT:
2140      case T_DOUBLE:
2141      case T_VOID:
2142        return in;
2143
2144      default:
2145        ShouldNotReachHere();
2146        return T_CONFLICT;
2147    }
2148  }
2149
2150 public:
2151  AdapterFingerPrint(int total_args_passed, BasicType* sig_bt) {
2152    // The fingerprint is based on the BasicType signature encoded
2153    // into an array of ints with eight entries per int.
2154    int* ptr;
2155    int len = (total_args_passed + (_basic_types_per_int-1)) / _basic_types_per_int;
2156    if (len <= _compact_int_count) {
2157      assert(_compact_int_count == 3, "else change next line");
2158      _value._compact[0] = _value._compact[1] = _value._compact[2] = 0;
2159      // Storing the signature encoded as signed chars hits about 98%
2160      // of the time.
2161      _length = -len;
2162      ptr = _value._compact;
2163    } else {
2164      _length = len;
2165      _value._fingerprint = NEW_C_HEAP_ARRAY(int, _length, mtCode);
2166      ptr = _value._fingerprint;
2167    }
2168
2169    // Now pack the BasicTypes with 8 per int
2170    int sig_index = 0;
2171    for (int index = 0; index < len; index++) {
2172      int value = 0;
2173      for (int byte = 0; byte < _basic_types_per_int; byte++) {
2174        int bt = ((sig_index < total_args_passed)
2175                  ? adapter_encoding(sig_bt[sig_index++])
2176                  : 0);
2177        assert((bt & _basic_type_mask) == bt, "must fit in 4 bits");
2178        value = (value << _basic_type_bits) | bt;
2179      }
2180      ptr[index] = value;
2181    }
2182  }
2183
2184  ~AdapterFingerPrint() {
2185    if (_length > 0) {
2186      FREE_C_HEAP_ARRAY(int, _value._fingerprint);
2187    }
2188  }
2189
2190  int value(int index) {
2191    if (_length < 0) {
2192      return _value._compact[index];
2193    }
2194    return _value._fingerprint[index];
2195  }
2196  int length() {
2197    if (_length < 0) return -_length;
2198    return _length;
2199  }
2200
2201  bool is_compact() {
2202    return _length <= 0;
2203  }
2204
2205  unsigned int compute_hash() {
2206    int hash = 0;
2207    for (int i = 0; i < length(); i++) {
2208      int v = value(i);
2209      hash = (hash << 8) ^ v ^ (hash >> 5);
2210    }
2211    return (unsigned int)hash;
2212  }
2213
2214  const char* as_string() {
2215    stringStream st;
2216    st.print("0x");
2217    for (int i = 0; i < length(); i++) {
2218      st.print("%08x", value(i));
2219    }
2220    return st.as_string();
2221  }
2222
2223  bool equals(AdapterFingerPrint* other) {
2224    if (other->_length != _length) {
2225      return false;
2226    }
2227    if (_length < 0) {
2228      assert(_compact_int_count == 3, "else change next line");
2229      return _value._compact[0] == other->_value._compact[0] &&
2230             _value._compact[1] == other->_value._compact[1] &&
2231             _value._compact[2] == other->_value._compact[2];
2232    } else {
2233      for (int i = 0; i < _length; i++) {
2234        if (_value._fingerprint[i] != other->_value._fingerprint[i]) {
2235          return false;
2236        }
2237      }
2238    }
2239    return true;
2240  }
2241};
2242
2243
2244// A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries
2245class AdapterHandlerTable : public BasicHashtable<mtCode> {
2246  friend class AdapterHandlerTableIterator;
2247
2248 private:
2249
2250#ifndef PRODUCT
2251  static int _lookups; // number of calls to lookup
2252  static int _buckets; // number of buckets checked
2253  static int _equals;  // number of buckets checked with matching hash
2254  static int _hits;    // number of successful lookups
2255  static int _compact; // number of equals calls with compact signature
2256#endif
2257
2258  AdapterHandlerEntry* bucket(int i) {
2259    return (AdapterHandlerEntry*)BasicHashtable<mtCode>::bucket(i);
2260  }
2261
2262 public:
2263  AdapterHandlerTable()
2264    : BasicHashtable<mtCode>(293, sizeof(AdapterHandlerEntry)) { }
2265
2266  // Create a new entry suitable for insertion in the table
2267  AdapterHandlerEntry* new_entry(AdapterFingerPrint* fingerprint, address i2c_entry, address c2i_entry, address c2i_unverified_entry) {
2268    AdapterHandlerEntry* entry = (AdapterHandlerEntry*)BasicHashtable<mtCode>::new_entry(fingerprint->compute_hash());
2269    entry->init(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
2270    return entry;
2271  }
2272
2273  // Insert an entry into the table
2274  void add(AdapterHandlerEntry* entry) {
2275    int index = hash_to_index(entry->hash());
2276    add_entry(index, entry);
2277  }
2278
2279  void free_entry(AdapterHandlerEntry* entry) {
2280    entry->deallocate();
2281    BasicHashtable<mtCode>::free_entry(entry);
2282  }
2283
2284  // Find a entry with the same fingerprint if it exists
2285  AdapterHandlerEntry* lookup(int total_args_passed, BasicType* sig_bt) {
2286    NOT_PRODUCT(_lookups++);
2287    AdapterFingerPrint fp(total_args_passed, sig_bt);
2288    unsigned int hash = fp.compute_hash();
2289    int index = hash_to_index(hash);
2290    for (AdapterHandlerEntry* e = bucket(index); e != NULL; e = e->next()) {
2291      NOT_PRODUCT(_buckets++);
2292      if (e->hash() == hash) {
2293        NOT_PRODUCT(_equals++);
2294        if (fp.equals(e->fingerprint())) {
2295#ifndef PRODUCT
2296          if (fp.is_compact()) _compact++;
2297          _hits++;
2298#endif
2299          return e;
2300        }
2301      }
2302    }
2303    return NULL;
2304  }
2305
2306#ifndef PRODUCT
2307  void print_statistics() {
2308    ResourceMark rm;
2309    int longest = 0;
2310    int empty = 0;
2311    int total = 0;
2312    int nonempty = 0;
2313    for (int index = 0; index < table_size(); index++) {
2314      int count = 0;
2315      for (AdapterHandlerEntry* e = bucket(index); e != NULL; e = e->next()) {
2316        count++;
2317      }
2318      if (count != 0) nonempty++;
2319      if (count == 0) empty++;
2320      if (count > longest) longest = count;
2321      total += count;
2322    }
2323    tty->print_cr("AdapterHandlerTable: empty %d longest %d total %d average %f",
2324                  empty, longest, total, total / (double)nonempty);
2325    tty->print_cr("AdapterHandlerTable: lookups %d buckets %d equals %d hits %d compact %d",
2326                  _lookups, _buckets, _equals, _hits, _compact);
2327  }
2328#endif
2329};
2330
2331
2332#ifndef PRODUCT
2333
2334int AdapterHandlerTable::_lookups;
2335int AdapterHandlerTable::_buckets;
2336int AdapterHandlerTable::_equals;
2337int AdapterHandlerTable::_hits;
2338int AdapterHandlerTable::_compact;
2339
2340#endif
2341
2342class AdapterHandlerTableIterator : public StackObj {
2343 private:
2344  AdapterHandlerTable* _table;
2345  int _index;
2346  AdapterHandlerEntry* _current;
2347
2348  void scan() {
2349    while (_index < _table->table_size()) {
2350      AdapterHandlerEntry* a = _table->bucket(_index);
2351      _index++;
2352      if (a != NULL) {
2353        _current = a;
2354        return;
2355      }
2356    }
2357  }
2358
2359 public:
2360  AdapterHandlerTableIterator(AdapterHandlerTable* table): _table(table), _index(0), _current(NULL) {
2361    scan();
2362  }
2363  bool has_next() {
2364    return _current != NULL;
2365  }
2366  AdapterHandlerEntry* next() {
2367    if (_current != NULL) {
2368      AdapterHandlerEntry* result = _current;
2369      _current = _current->next();
2370      if (_current == NULL) scan();
2371      return result;
2372    } else {
2373      return NULL;
2374    }
2375  }
2376};
2377
2378
2379// ---------------------------------------------------------------------------
2380// Implementation of AdapterHandlerLibrary
2381AdapterHandlerTable* AdapterHandlerLibrary::_adapters = NULL;
2382AdapterHandlerEntry* AdapterHandlerLibrary::_abstract_method_handler = NULL;
2383const int AdapterHandlerLibrary_size = 16*K;
2384BufferBlob* AdapterHandlerLibrary::_buffer = NULL;
2385
2386BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2387  // Should be called only when AdapterHandlerLibrary_lock is active.
2388  if (_buffer == NULL) // Initialize lazily
2389      _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2390  return _buffer;
2391}
2392
2393extern "C" void unexpected_adapter_call() {
2394  ShouldNotCallThis();
2395}
2396
2397void AdapterHandlerLibrary::initialize() {
2398  if (_adapters != NULL) return;
2399  _adapters = new AdapterHandlerTable();
2400
2401  if (!CodeCacheExtensions::skip_compiler_support()) {
2402    // Create a special handler for abstract methods.  Abstract methods
2403    // are never compiled so an i2c entry is somewhat meaningless, but
2404    // throw AbstractMethodError just in case.
2405    // Pass wrong_method_abstract for the c2i transitions to return
2406    // AbstractMethodError for invalid invocations.
2407    address wrong_method_abstract = SharedRuntime::get_handle_wrong_method_abstract_stub();
2408    _abstract_method_handler = AdapterHandlerLibrary::new_entry(new AdapterFingerPrint(0, NULL),
2409                                                                StubRoutines::throw_AbstractMethodError_entry(),
2410                                                                wrong_method_abstract, wrong_method_abstract);
2411  } else {
2412    // Adapters are not supposed to be used.
2413    // Generate a special one to cause an error if used (and store this
2414    // singleton in place of the useless _abstract_method_error adapter).
2415    address entry = (address) &unexpected_adapter_call;
2416    _abstract_method_handler = AdapterHandlerLibrary::new_entry(new AdapterFingerPrint(0, NULL),
2417                                                                entry,
2418                                                                entry,
2419                                                                entry);
2420
2421  }
2422}
2423
2424AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint,
2425                                                      address i2c_entry,
2426                                                      address c2i_entry,
2427                                                      address c2i_unverified_entry) {
2428  return _adapters->new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
2429}
2430
2431AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
2432  // Use customized signature handler.  Need to lock around updates to
2433  // the AdapterHandlerTable (it is not safe for concurrent readers
2434  // and a single writer: this could be fixed if it becomes a
2435  // problem).
2436
2437  ResourceMark rm;
2438
2439  NOT_PRODUCT(int insts_size);
2440  AdapterBlob* new_adapter = NULL;
2441  AdapterHandlerEntry* entry = NULL;
2442  AdapterFingerPrint* fingerprint = NULL;
2443  {
2444    MutexLocker mu(AdapterHandlerLibrary_lock);
2445    // make sure data structure is initialized
2446    initialize();
2447
2448    if (CodeCacheExtensions::skip_compiler_support()) {
2449      // adapters are useless and should not be used, including the
2450      // abstract_method_handler. However, some callers check that
2451      // an adapter was installed.
2452      // Return the singleton adapter, stored into _abstract_method_handler
2453      // and modified to cause an error if we ever call it.
2454      return _abstract_method_handler;
2455    }
2456
2457    if (method->is_abstract()) {
2458      return _abstract_method_handler;
2459    }
2460
2461    // Fill in the signature array, for the calling-convention call.
2462    int total_args_passed = method->size_of_parameters(); // All args on stack
2463
2464    BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
2465    VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
2466    int i = 0;
2467    if (!method->is_static())  // Pass in receiver first
2468      sig_bt[i++] = T_OBJECT;
2469    for (SignatureStream ss(method->signature()); !ss.at_return_type(); ss.next()) {
2470      sig_bt[i++] = ss.type();  // Collect remaining bits of signature
2471      if (ss.type() == T_LONG || ss.type() == T_DOUBLE)
2472        sig_bt[i++] = T_VOID;   // Longs & doubles take 2 Java slots
2473    }
2474    assert(i == total_args_passed, "");
2475
2476    // Lookup method signature's fingerprint
2477    entry = _adapters->lookup(total_args_passed, sig_bt);
2478
2479#ifdef ASSERT
2480    AdapterHandlerEntry* shared_entry = NULL;
2481    // Start adapter sharing verification only after the VM is booted.
2482    if (VerifyAdapterSharing && (entry != NULL)) {
2483      shared_entry = entry;
2484      entry = NULL;
2485    }
2486#endif
2487
2488    if (entry != NULL) {
2489      return entry;
2490    }
2491
2492    // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage
2493    int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed, false);
2494
2495    // Make a C heap allocated version of the fingerprint to store in the adapter
2496    fingerprint = new AdapterFingerPrint(total_args_passed, sig_bt);
2497
2498    // StubRoutines::code2() is initialized after this function can be called. As a result,
2499    // VerifyAdapterCalls and VerifyAdapterSharing can fail if we re-use code that generated
2500    // prior to StubRoutines::code2() being set. Checks refer to checks generated in an I2C
2501    // stub that ensure that an I2C stub is called from an interpreter frame.
2502    bool contains_all_checks = StubRoutines::code2() != NULL;
2503
2504    // Create I2C & C2I handlers
2505    BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
2506    if (buf != NULL) {
2507      CodeBuffer buffer(buf);
2508      short buffer_locs[20];
2509      buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
2510                                             sizeof(buffer_locs)/sizeof(relocInfo));
2511
2512      MacroAssembler _masm(&buffer);
2513      entry = SharedRuntime::generate_i2c2i_adapters(&_masm,
2514                                                     total_args_passed,
2515                                                     comp_args_on_stack,
2516                                                     sig_bt,
2517                                                     regs,
2518                                                     fingerprint);
2519#ifdef ASSERT
2520      if (VerifyAdapterSharing) {
2521        if (shared_entry != NULL) {
2522          assert(shared_entry->compare_code(buf->code_begin(), buffer.insts_size()), "code must match");
2523          // Release the one just created and return the original
2524          _adapters->free_entry(entry);
2525          return shared_entry;
2526        } else  {
2527          entry->save_code(buf->code_begin(), buffer.insts_size());
2528        }
2529      }
2530#endif
2531
2532      new_adapter = AdapterBlob::create(&buffer);
2533      NOT_PRODUCT(insts_size = buffer.insts_size());
2534    }
2535    if (new_adapter == NULL) {
2536      // CodeCache is full, disable compilation
2537      // Ought to log this but compile log is only per compile thread
2538      // and we're some non descript Java thread.
2539      return NULL; // Out of CodeCache space
2540    }
2541    entry->relocate(new_adapter->content_begin());
2542#ifndef PRODUCT
2543    // debugging suppport
2544    if (PrintAdapterHandlers || PrintStubCode) {
2545      ttyLocker ttyl;
2546      entry->print_adapter_on(tty);
2547      tty->print_cr("i2c argument handler #%d for: %s %s %s (%d bytes generated)",
2548                    _adapters->number_of_entries(), (method->is_static() ? "static" : "receiver"),
2549                    method->signature()->as_C_string(), fingerprint->as_string(), insts_size);
2550      tty->print_cr("c2i argument handler starts at %p", entry->get_c2i_entry());
2551      if (Verbose || PrintStubCode) {
2552        address first_pc = entry->base_address();
2553        if (first_pc != NULL) {
2554          Disassembler::decode(first_pc, first_pc + insts_size);
2555          tty->cr();
2556        }
2557      }
2558    }
2559#endif
2560    // Add the entry only if the entry contains all required checks (see sharedRuntime_xxx.cpp)
2561    // The checks are inserted only if -XX:+VerifyAdapterCalls is specified.
2562    if (contains_all_checks || !VerifyAdapterCalls) {
2563      _adapters->add(entry);
2564    }
2565  }
2566  // Outside of the lock
2567  if (new_adapter != NULL) {
2568    char blob_id[256];
2569    jio_snprintf(blob_id,
2570                 sizeof(blob_id),
2571                 "%s(%s)@" PTR_FORMAT,
2572                 new_adapter->name(),
2573                 fingerprint->as_string(),
2574                 new_adapter->content_begin());
2575    Forte::register_stub(blob_id, new_adapter->content_begin(), new_adapter->content_end());
2576
2577    if (JvmtiExport::should_post_dynamic_code_generated()) {
2578      JvmtiExport::post_dynamic_code_generated(blob_id, new_adapter->content_begin(), new_adapter->content_end());
2579    }
2580  }
2581  return entry;
2582}
2583
2584address AdapterHandlerEntry::base_address() {
2585  address base = _i2c_entry;
2586  if (base == NULL)  base = _c2i_entry;
2587  assert(base <= _c2i_entry || _c2i_entry == NULL, "");
2588  assert(base <= _c2i_unverified_entry || _c2i_unverified_entry == NULL, "");
2589  return base;
2590}
2591
2592void AdapterHandlerEntry::relocate(address new_base) {
2593  address old_base = base_address();
2594  assert(old_base != NULL, "");
2595  ptrdiff_t delta = new_base - old_base;
2596  if (_i2c_entry != NULL)
2597    _i2c_entry += delta;
2598  if (_c2i_entry != NULL)
2599    _c2i_entry += delta;
2600  if (_c2i_unverified_entry != NULL)
2601    _c2i_unverified_entry += delta;
2602  assert(base_address() == new_base, "");
2603}
2604
2605
2606void AdapterHandlerEntry::deallocate() {
2607  delete _fingerprint;
2608#ifdef ASSERT
2609  if (_saved_code) FREE_C_HEAP_ARRAY(unsigned char, _saved_code);
2610#endif
2611}
2612
2613
2614#ifdef ASSERT
2615// Capture the code before relocation so that it can be compared
2616// against other versions.  If the code is captured after relocation
2617// then relative instructions won't be equivalent.
2618void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) {
2619  _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
2620  _saved_code_length = length;
2621  memcpy(_saved_code, buffer, length);
2622}
2623
2624
2625bool AdapterHandlerEntry::compare_code(unsigned char* buffer, int length) {
2626  if (length != _saved_code_length) {
2627    return false;
2628  }
2629
2630  return (memcmp(buffer, _saved_code, length) == 0) ? true : false;
2631}
2632#endif
2633
2634
2635/**
2636 * Create a native wrapper for this native method.  The wrapper converts the
2637 * Java-compiled calling convention to the native convention, handles
2638 * arguments, and transitions to native.  On return from the native we transition
2639 * back to java blocking if a safepoint is in progress.
2640 */
2641void AdapterHandlerLibrary::create_native_wrapper(const methodHandle& method) {
2642  ResourceMark rm;
2643  nmethod* nm = NULL;
2644
2645  assert(method->is_native(), "must be native");
2646  assert(method->is_method_handle_intrinsic() ||
2647         method->has_native_function(), "must have something valid to call!");
2648
2649  {
2650    // Perform the work while holding the lock, but perform any printing outside the lock
2651    MutexLocker mu(AdapterHandlerLibrary_lock);
2652    // See if somebody beat us to it
2653    if (method->code() != NULL) {
2654      return;
2655    }
2656
2657    const int compile_id = CompileBroker::assign_compile_id(method, CompileBroker::standard_entry_bci);
2658    assert(compile_id > 0, "Must generate native wrapper");
2659
2660
2661    ResourceMark rm;
2662    BufferBlob*  buf = buffer_blob(); // the temporary code buffer in CodeCache
2663    if (buf != NULL) {
2664      CodeBuffer buffer(buf);
2665      double locs_buf[20];
2666      buffer.insts()->initialize_shared_locs((relocInfo*)locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
2667      MacroAssembler _masm(&buffer);
2668
2669      // Fill in the signature array, for the calling-convention call.
2670      const int total_args_passed = method->size_of_parameters();
2671
2672      BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
2673      VMRegPair*   regs = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
2674      int i=0;
2675      if (!method->is_static())  // Pass in receiver first
2676        sig_bt[i++] = T_OBJECT;
2677      SignatureStream ss(method->signature());
2678      for (; !ss.at_return_type(); ss.next()) {
2679        sig_bt[i++] = ss.type();  // Collect remaining bits of signature
2680        if (ss.type() == T_LONG || ss.type() == T_DOUBLE)
2681          sig_bt[i++] = T_VOID;   // Longs & doubles take 2 Java slots
2682      }
2683      assert(i == total_args_passed, "");
2684      BasicType ret_type = ss.type();
2685
2686      // Now get the compiled-Java layout as input (or output) arguments.
2687      // NOTE: Stubs for compiled entry points of method handle intrinsics
2688      // are just trampolines so the argument registers must be outgoing ones.
2689      const bool is_outgoing = method->is_method_handle_intrinsic();
2690      int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed, is_outgoing);
2691
2692      // Generate the compiled-to-native wrapper code
2693      nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type);
2694
2695      if (nm != NULL) {
2696        method->set_code(method, nm);
2697
2698        DirectiveSet* directive = DirectivesStack::getDefaultDirective(CompileBroker::compiler(CompLevel_simple));
2699        if (directive->PrintAssemblyOption) {
2700          Disassembler::decode(nm, tty);
2701        }
2702        DirectivesStack::release(directive);
2703      }
2704    }
2705  } // Unlock AdapterHandlerLibrary_lock
2706
2707
2708  // Install the generated code.
2709  if (nm != NULL) {
2710    if (PrintCompilation) {
2711      ttyLocker ttyl;
2712      CompileTask::print(tty, nm, method->is_static() ? "(static)" : "");
2713    }
2714    nm->post_compiled_method_load_event();
2715  }
2716}
2717
2718JRT_ENTRY_NO_ASYNC(void, SharedRuntime::block_for_jni_critical(JavaThread* thread))
2719  assert(thread == JavaThread::current(), "must be");
2720  // The code is about to enter a JNI lazy critical native method and
2721  // _needs_gc is true, so if this thread is already in a critical
2722  // section then just return, otherwise this thread should block
2723  // until needs_gc has been cleared.
2724  if (thread->in_critical()) {
2725    return;
2726  }
2727  // Lock and unlock a critical section to give the system a chance to block
2728  GC_locker::lock_critical(thread);
2729  GC_locker::unlock_critical(thread);
2730JRT_END
2731
2732// -------------------------------------------------------------------------
2733// Java-Java calling convention
2734// (what you use when Java calls Java)
2735
2736//------------------------------name_for_receiver----------------------------------
2737// For a given signature, return the VMReg for parameter 0.
2738VMReg SharedRuntime::name_for_receiver() {
2739  VMRegPair regs;
2740  BasicType sig_bt = T_OBJECT;
2741  (void) java_calling_convention(&sig_bt, &regs, 1, true);
2742  // Return argument 0 register.  In the LP64 build pointers
2743  // take 2 registers, but the VM wants only the 'main' name.
2744  return regs.first();
2745}
2746
2747VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, bool has_appendix, int* arg_size) {
2748  // This method is returning a data structure allocating as a
2749  // ResourceObject, so do not put any ResourceMarks in here.
2750  char *s = sig->as_C_string();
2751  int len = (int)strlen(s);
2752  s++; len--;                   // Skip opening paren
2753  char *t = s+len;
2754  while (*(--t) != ')');      // Find close paren
2755
2756  BasicType *sig_bt = NEW_RESOURCE_ARRAY(BasicType, 256);
2757  VMRegPair *regs = NEW_RESOURCE_ARRAY(VMRegPair, 256);
2758  int cnt = 0;
2759  if (has_receiver) {
2760    sig_bt[cnt++] = T_OBJECT; // Receiver is argument 0; not in signature
2761  }
2762
2763  while (s < t) {
2764    switch (*s++) {            // Switch on signature character
2765    case 'B': sig_bt[cnt++] = T_BYTE;    break;
2766    case 'C': sig_bt[cnt++] = T_CHAR;    break;
2767    case 'D': sig_bt[cnt++] = T_DOUBLE;  sig_bt[cnt++] = T_VOID; break;
2768    case 'F': sig_bt[cnt++] = T_FLOAT;   break;
2769    case 'I': sig_bt[cnt++] = T_INT;     break;
2770    case 'J': sig_bt[cnt++] = T_LONG;    sig_bt[cnt++] = T_VOID; break;
2771    case 'S': sig_bt[cnt++] = T_SHORT;   break;
2772    case 'Z': sig_bt[cnt++] = T_BOOLEAN; break;
2773    case 'V': sig_bt[cnt++] = T_VOID;    break;
2774    case 'L':                   // Oop
2775      while (*s++ != ';');   // Skip signature
2776      sig_bt[cnt++] = T_OBJECT;
2777      break;
2778    case '[': {                 // Array
2779      do {                      // Skip optional size
2780        while (*s >= '0' && *s <= '9') s++;
2781      } while (*s++ == '[');   // Nested arrays?
2782      // Skip element type
2783      if (s[-1] == 'L')
2784        while (*s++ != ';'); // Skip signature
2785      sig_bt[cnt++] = T_ARRAY;
2786      break;
2787    }
2788    default : ShouldNotReachHere();
2789    }
2790  }
2791
2792  if (has_appendix) {
2793    sig_bt[cnt++] = T_OBJECT;
2794  }
2795
2796  assert(cnt < 256, "grow table size");
2797
2798  int comp_args_on_stack;
2799  comp_args_on_stack = java_calling_convention(sig_bt, regs, cnt, true);
2800
2801  // the calling convention doesn't count out_preserve_stack_slots so
2802  // we must add that in to get "true" stack offsets.
2803
2804  if (comp_args_on_stack) {
2805    for (int i = 0; i < cnt; i++) {
2806      VMReg reg1 = regs[i].first();
2807      if (reg1->is_stack()) {
2808        // Yuck
2809        reg1 = reg1->bias(out_preserve_stack_slots());
2810      }
2811      VMReg reg2 = regs[i].second();
2812      if (reg2->is_stack()) {
2813        // Yuck
2814        reg2 = reg2->bias(out_preserve_stack_slots());
2815      }
2816      regs[i].set_pair(reg2, reg1);
2817    }
2818  }
2819
2820  // results
2821  *arg_size = cnt;
2822  return regs;
2823}
2824
2825// OSR Migration Code
2826//
2827// This code is used convert interpreter frames into compiled frames.  It is
2828// called from very start of a compiled OSR nmethod.  A temp array is
2829// allocated to hold the interesting bits of the interpreter frame.  All
2830// active locks are inflated to allow them to move.  The displaced headers and
2831// active interpreter locals are copied into the temp buffer.  Then we return
2832// back to the compiled code.  The compiled code then pops the current
2833// interpreter frame off the stack and pushes a new compiled frame.  Then it
2834// copies the interpreter locals and displaced headers where it wants.
2835// Finally it calls back to free the temp buffer.
2836//
2837// All of this is done NOT at any Safepoint, nor is any safepoint or GC allowed.
2838
2839JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *thread) )
2840
2841  //
2842  // This code is dependent on the memory layout of the interpreter local
2843  // array and the monitors. On all of our platforms the layout is identical
2844  // so this code is shared. If some platform lays the their arrays out
2845  // differently then this code could move to platform specific code or
2846  // the code here could be modified to copy items one at a time using
2847  // frame accessor methods and be platform independent.
2848
2849  frame fr = thread->last_frame();
2850  assert(fr.is_interpreted_frame(), "");
2851  assert(fr.interpreter_frame_expression_stack_size()==0, "only handle empty stacks");
2852
2853  // Figure out how many monitors are active.
2854  int active_monitor_count = 0;
2855  for (BasicObjectLock *kptr = fr.interpreter_frame_monitor_end();
2856       kptr < fr.interpreter_frame_monitor_begin();
2857       kptr = fr.next_monitor_in_interpreter_frame(kptr) ) {
2858    if (kptr->obj() != NULL) active_monitor_count++;
2859  }
2860
2861  // QQQ we could place number of active monitors in the array so that compiled code
2862  // could double check it.
2863
2864  Method* moop = fr.interpreter_frame_method();
2865  int max_locals = moop->max_locals();
2866  // Allocate temp buffer, 1 word per local & 2 per active monitor
2867  int buf_size_words = max_locals + active_monitor_count*2;
2868  intptr_t *buf = NEW_C_HEAP_ARRAY(intptr_t,buf_size_words, mtCode);
2869
2870  // Copy the locals.  Order is preserved so that loading of longs works.
2871  // Since there's no GC I can copy the oops blindly.
2872  assert(sizeof(HeapWord)==sizeof(intptr_t), "fix this code");
2873  Copy::disjoint_words((HeapWord*)fr.interpreter_frame_local_at(max_locals-1),
2874                       (HeapWord*)&buf[0],
2875                       max_locals);
2876
2877  // Inflate locks.  Copy the displaced headers.  Be careful, there can be holes.
2878  int i = max_locals;
2879  for (BasicObjectLock *kptr2 = fr.interpreter_frame_monitor_end();
2880       kptr2 < fr.interpreter_frame_monitor_begin();
2881       kptr2 = fr.next_monitor_in_interpreter_frame(kptr2) ) {
2882    if (kptr2->obj() != NULL) {         // Avoid 'holes' in the monitor array
2883      BasicLock *lock = kptr2->lock();
2884      // Inflate so the displaced header becomes position-independent
2885      if (lock->displaced_header()->is_unlocked())
2886        ObjectSynchronizer::inflate_helper(kptr2->obj());
2887      // Now the displaced header is free to move
2888      buf[i++] = (intptr_t)lock->displaced_header();
2889      buf[i++] = cast_from_oop<intptr_t>(kptr2->obj());
2890    }
2891  }
2892  assert(i - max_locals == active_monitor_count*2, "found the expected number of monitors");
2893
2894  return buf;
2895JRT_END
2896
2897JRT_LEAF(void, SharedRuntime::OSR_migration_end( intptr_t* buf) )
2898  FREE_C_HEAP_ARRAY(intptr_t, buf);
2899JRT_END
2900
2901bool AdapterHandlerLibrary::contains(const CodeBlob* b) {
2902  AdapterHandlerTableIterator iter(_adapters);
2903  while (iter.has_next()) {
2904    AdapterHandlerEntry* a = iter.next();
2905    if (b == CodeCache::find_blob(a->get_i2c_entry())) return true;
2906  }
2907  return false;
2908}
2909
2910void AdapterHandlerLibrary::print_handler_on(outputStream* st, const CodeBlob* b) {
2911  AdapterHandlerTableIterator iter(_adapters);
2912  while (iter.has_next()) {
2913    AdapterHandlerEntry* a = iter.next();
2914    if (b == CodeCache::find_blob(a->get_i2c_entry())) {
2915      st->print("Adapter for signature: ");
2916      a->print_adapter_on(tty);
2917      return;
2918    }
2919  }
2920  assert(false, "Should have found handler");
2921}
2922
2923void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
2924  st->print_cr("AHE@" INTPTR_FORMAT ": %s i2c: " INTPTR_FORMAT " c2i: " INTPTR_FORMAT " c2iUV: " INTPTR_FORMAT,
2925               p2i(this), fingerprint()->as_string(),
2926               p2i(get_i2c_entry()), p2i(get_c2i_entry()), p2i(get_c2i_unverified_entry()));
2927
2928}
2929
2930#ifndef PRODUCT
2931
2932void AdapterHandlerLibrary::print_statistics() {
2933  _adapters->print_statistics();
2934}
2935
2936#endif /* PRODUCT */
2937