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