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