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