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