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