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