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