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