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