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