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