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