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