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