1 /*
   2  * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "classfile/javaClasses.inline.hpp"
  26 #include "classfile/symbolTable.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmClasses.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "compiler/compilationPolicy.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/disassembler.hpp"
  34 #include "gc/shared/barrierSetNMethod.hpp"
  35 #include "gc/shared/collectedHeap.hpp"
  36 #include "interpreter/bytecodeTracer.hpp"
  37 #include "interpreter/interpreter.hpp"
  38 #include "interpreter/interpreterRuntime.hpp"
  39 #include "interpreter/linkResolver.hpp"
  40 #include "interpreter/templateTable.hpp"
  41 #include "jvm_io.h"
  42 #include "logging/log.hpp"
  43 #include "memory/oopFactory.hpp"
  44 #include "memory/resourceArea.hpp"
  45 #include "memory/universe.hpp"
  46 #include "oops/constantPool.inline.hpp"
  47 #include "oops/cpCache.inline.hpp"
  48 #include "oops/flatArrayKlass.hpp"
  49 #include "oops/flatArrayOop.inline.hpp"
  50 #include "oops/inlineKlass.inline.hpp"
  51 #include "oops/instanceKlass.inline.hpp"
  52 #include "oops/klass.inline.hpp"
  53 #include "oops/method.inline.hpp"
  54 #include "oops/methodData.hpp"
  55 #include "oops/objArrayKlass.hpp"
  56 #include "oops/objArrayOop.inline.hpp"
  57 #include "oops/oop.inline.hpp"
  58 #include "oops/symbol.hpp"
  59 #include "prims/jvmtiExport.hpp"
  60 #include "prims/methodHandles.hpp"
  61 #include "prims/nativeLookup.hpp"
  62 #include "runtime/atomicAccess.hpp"
  63 #include "runtime/continuation.hpp"
  64 #include "runtime/deoptimization.hpp"
  65 #include "runtime/fieldDescriptor.inline.hpp"
  66 #include "runtime/frame.inline.hpp"
  67 #include "runtime/handles.inline.hpp"
  68 #include "runtime/icache.hpp"
  69 #include "runtime/interfaceSupport.inline.hpp"
  70 #include "runtime/java.hpp"
  71 #include "runtime/javaCalls.hpp"
  72 #include "runtime/jfieldIDWorkaround.hpp"
  73 #include "runtime/osThread.hpp"
  74 #include "runtime/sharedRuntime.hpp"
  75 #include "runtime/stackWatermarkSet.hpp"
  76 #include "runtime/stubRoutines.hpp"
  77 #include "runtime/synchronizer.inline.hpp"
  78 #include "utilities/align.hpp"
  79 #include "utilities/checkedCast.hpp"
  80 #include "utilities/copy.hpp"
  81 #include "utilities/events.hpp"
  82 #include "utilities/globalDefinitions.hpp"
  83 #if INCLUDE_JFR
  84 #include "jfr/jfr.inline.hpp"
  85 #endif
  86 
  87 // Helper class to access current interpreter state
  88 class LastFrameAccessor : public StackObj {
  89   frame _last_frame;
  90 public:
  91   LastFrameAccessor(JavaThread* current) {
  92     assert(current == Thread::current(), "sanity");
  93     _last_frame = current->last_frame();
  94   }
  95   bool is_interpreted_frame() const              { return _last_frame.is_interpreted_frame(); }
  96   Method*   method() const                       { return _last_frame.interpreter_frame_method(); }
  97   address   bcp() const                          { return _last_frame.interpreter_frame_bcp(); }
  98   int       bci() const                          { return _last_frame.interpreter_frame_bci(); }
  99   address   mdp() const                          { return _last_frame.interpreter_frame_mdp(); }
 100 
 101   void      set_bcp(address bcp)                 { _last_frame.interpreter_frame_set_bcp(bcp); }
 102   void      set_mdp(address dp)                  { _last_frame.interpreter_frame_set_mdp(dp); }
 103 
 104   // pass method to avoid calling unsafe bcp_to_method (partial fix 4926272)
 105   Bytecodes::Code code() const                   { return Bytecodes::code_at(method(), bcp()); }
 106 
 107   Bytecode  bytecode() const                     { return Bytecode(method(), bcp()); }
 108   int get_index_u1(Bytecodes::Code bc) const     { return bytecode().get_index_u1(bc); }
 109   int get_index_u2(Bytecodes::Code bc) const     { return bytecode().get_index_u2(bc); }
 110   int get_index_u4(Bytecodes::Code bc) const     { return bytecode().get_index_u4(bc); }
 111   int number_of_dimensions() const               { return bcp()[3]; }
 112 
 113   oop callee_receiver(Symbol* signature) {
 114     return _last_frame.interpreter_callee_receiver(signature);
 115   }
 116   BasicObjectLock* monitor_begin() const {
 117     return _last_frame.interpreter_frame_monitor_begin();
 118   }
 119   BasicObjectLock* monitor_end() const {
 120     return _last_frame.interpreter_frame_monitor_end();
 121   }
 122   BasicObjectLock* next_monitor(BasicObjectLock* current) const {
 123     return _last_frame.next_monitor_in_interpreter_frame(current);
 124   }
 125 
 126   frame& get_frame()                             { return _last_frame; }
 127 };
 128 
 129 //------------------------------------------------------------------------------------------------------------------------
 130 // State accessors
 131 
 132 void InterpreterRuntime::set_bcp_and_mdp(address bcp, JavaThread* current) {
 133   LastFrameAccessor last_frame(current);
 134   last_frame.set_bcp(bcp);
 135   if (ProfileInterpreter) {
 136     // ProfileTraps uses MDOs independently of ProfileInterpreter.
 137     // That is why we must check both ProfileInterpreter and mdo != nullptr.
 138     MethodData* mdo = last_frame.method()->method_data();
 139     if (mdo != nullptr) {
 140       NEEDS_CLEANUP;
 141       last_frame.set_mdp(mdo->bci_to_dp(last_frame.bci()));
 142     }
 143   }
 144 }
 145 
 146 //------------------------------------------------------------------------------------------------------------------------
 147 // Constants
 148 
 149 
 150 JRT_ENTRY(void, InterpreterRuntime::ldc(JavaThread* current, bool wide))
 151   // access constant pool
 152   LastFrameAccessor last_frame(current);
 153   ConstantPool* pool = last_frame.method()->constants();
 154   int cp_index = wide ? last_frame.get_index_u2(Bytecodes::_ldc_w) : last_frame.get_index_u1(Bytecodes::_ldc);
 155   constantTag tag = pool->tag_at(cp_index);
 156 
 157   assert (tag.is_unresolved_klass() || tag.is_klass(), "wrong ldc call");
 158   Klass* klass = pool->klass_at(cp_index, CHECK);
 159   oop java_class = klass->java_mirror();
 160   current->set_vm_result_oop(java_class);
 161 JRT_END
 162 
 163 JRT_ENTRY(void, InterpreterRuntime::resolve_ldc(JavaThread* current, Bytecodes::Code bytecode)) {
 164   assert(bytecode == Bytecodes::_ldc ||
 165          bytecode == Bytecodes::_ldc_w ||
 166          bytecode == Bytecodes::_ldc2_w ||
 167          bytecode == Bytecodes::_fast_aldc ||
 168          bytecode == Bytecodes::_fast_aldc_w, "wrong bc");
 169   ResourceMark rm(current);
 170   const bool is_fast_aldc = (bytecode == Bytecodes::_fast_aldc ||
 171                              bytecode == Bytecodes::_fast_aldc_w);
 172   LastFrameAccessor last_frame(current);
 173   methodHandle m (current, last_frame.method());
 174   Bytecode_loadconstant ldc(m, last_frame.bci());
 175 
 176   // Double-check the size.  (Condy can have any type.)
 177   BasicType type = ldc.result_type();
 178   switch (type2size[type]) {
 179   case 2: guarantee(bytecode == Bytecodes::_ldc2_w, ""); break;
 180   case 1: guarantee(bytecode != Bytecodes::_ldc2_w, ""); break;
 181   default: ShouldNotReachHere();
 182   }
 183 
 184   // Resolve the constant.  This does not do unboxing.
 185   // But it does replace Universe::the_null_sentinel by null.
 186   oop result = ldc.resolve_constant(CHECK);
 187   assert(result != nullptr || is_fast_aldc, "null result only valid for fast_aldc");
 188 
 189 #ifdef ASSERT
 190   {
 191     // The bytecode wrappers aren't GC-safe so construct a new one
 192     Bytecode_loadconstant ldc2(m, last_frame.bci());
 193     int rindex = ldc2.cache_index();
 194     if (rindex < 0)
 195       rindex = m->constants()->cp_to_object_index(ldc2.pool_index());
 196     if (rindex >= 0) {
 197       oop coop = m->constants()->resolved_reference_at(rindex);
 198       oop roop = (result == nullptr ? Universe::the_null_sentinel() : result);
 199       assert(roop == coop, "expected result for assembly code");
 200     }
 201   }
 202 #endif
 203   current->set_vm_result_oop(result);
 204   if (!is_fast_aldc) {
 205     // Tell the interpreter how to unbox the primitive.
 206     guarantee(java_lang_boxing_object::is_instance(result, type), "");
 207     int offset = java_lang_boxing_object::value_offset(type);
 208     intptr_t flags = ((as_TosState(type) << ConstantPoolCache::tos_state_shift)
 209                       | (offset & ConstantPoolCache::field_index_mask));
 210     current->set_vm_result_metadata((Metadata*)flags);
 211   }
 212 }
 213 JRT_END
 214 
 215 
 216 //------------------------------------------------------------------------------------------------------------------------
 217 // Allocation
 218 
 219 JRT_ENTRY(void, InterpreterRuntime::_new(JavaThread* current, ConstantPool* pool, int index))
 220   Klass* k = pool->klass_at(index, CHECK);
 221   InstanceKlass* klass = InstanceKlass::cast(k);
 222 
 223   // Make sure we are not instantiating an abstract klass
 224   klass->check_valid_for_instantiation(true, CHECK);
 225 
 226   // Make sure klass is initialized
 227   klass->initialize(CHECK);
 228 
 229   oop obj = klass->allocate_instance(CHECK);
 230   current->set_vm_result_oop(obj);
 231 JRT_END
 232 
 233 JRT_ENTRY(void, InterpreterRuntime::read_flat_field(JavaThread* current, oopDesc* obj, ResolvedFieldEntry* entry))
 234   assert(oopDesc::is_oop(obj), "Sanity check");
 235   Handle obj_h(THREAD, obj);
 236 
 237   InstanceKlass* holder = InstanceKlass::cast(entry->field_holder());
 238   assert(entry->field_holder()->field_is_flat(entry->field_index()), "Sanity check");
 239 
 240   InlineLayoutInfo* layout_info = holder->inline_layout_info_adr(entry->field_index());
 241   InlineKlass* field_vklass = layout_info->klass();
 242 
 243 #ifdef ASSERT
 244   fieldDescriptor fd;
 245   bool found = holder->find_field_from_offset(entry->field_offset(), false, &fd);
 246   assert(found, "Field not found");
 247   assert(fd.is_flat(), "Field must be flat");
 248 #endif // ASSERT
 249 
 250   oop res = field_vklass->read_payload_from_addr(obj_h(), entry->field_offset(), layout_info->kind(), CHECK);
 251   current->set_vm_result_oop(res);
 252 JRT_END
 253 
 254 JRT_ENTRY(void, InterpreterRuntime::write_flat_field(JavaThread* current, oopDesc* obj, oopDesc* value, ResolvedFieldEntry* entry))
 255   assert(oopDesc::is_oop(obj), "Sanity check");
 256   Handle obj_h(THREAD, obj);
 257   assert(value == nullptr || oopDesc::is_oop(value), "Sanity check");
 258   Handle val_h(THREAD, value);
 259 
 260   InstanceKlass* holder = entry->field_holder();
 261   InlineLayoutInfo* li = holder->inline_layout_info_adr(entry->field_index());
 262   InlineKlass* vk = li->klass();
 263   vk->write_value_to_addr(val_h(), ((char*)(oopDesc*)obj_h()) + entry->field_offset(), li->kind(), true, CHECK);
 264 JRT_END
 265 
 266 JRT_ENTRY(void, InterpreterRuntime::newarray(JavaThread* current, BasicType type, jint size))
 267   oop obj = oopFactory::new_typeArray(type, size, CHECK);
 268   current->set_vm_result_oop(obj);
 269 JRT_END
 270 
 271 
 272 JRT_ENTRY(void, InterpreterRuntime::anewarray(JavaThread* current, ConstantPool* pool, int index, jint size))
 273   Klass*    klass = pool->klass_at(index, CHECK);
 274   arrayOop obj = oopFactory::new_objArray(klass, size, CHECK);
 275   current->set_vm_result_oop(obj);
 276 JRT_END
 277 
 278 JRT_ENTRY(void, InterpreterRuntime::flat_array_load(JavaThread* current, arrayOopDesc* array, int index))
 279   assert(array->is_flatArray(), "Must be");
 280   flatArrayOop farray = (flatArrayOop)array;
 281   oop res = farray->obj_at(index, CHECK);
 282   current->set_vm_result_oop(res);
 283 JRT_END
 284 
 285 JRT_ENTRY(void, InterpreterRuntime::flat_array_store(JavaThread* current, oopDesc* val, arrayOopDesc* array, int index))
 286   assert(array->is_flatArray(), "Must be");
 287   flatArrayOop farray = (flatArrayOop)array;
 288   farray->obj_at_put(index, val, CHECK);
 289 JRT_END
 290 
 291 JRT_ENTRY(void, InterpreterRuntime::multianewarray(JavaThread* current, jint* first_size_address))
 292   // We may want to pass in more arguments - could make this slightly faster
 293   LastFrameAccessor last_frame(current);
 294   ConstantPool* constants = last_frame.method()->constants();
 295   int i = last_frame.get_index_u2(Bytecodes::_multianewarray);
 296   Klass* klass = constants->klass_at(i, CHECK);
 297   int   nof_dims = last_frame.number_of_dimensions();
 298   assert(klass->is_klass(), "not a class");
 299   assert(nof_dims >= 1, "multianewarray rank must be nonzero");
 300 
 301   // We must create an array of jints to pass to multi_allocate.
 302   ResourceMark rm(current);
 303   const int small_dims = 10;
 304   jint dim_array[small_dims];
 305   jint *dims = &dim_array[0];
 306   if (nof_dims > small_dims) {
 307     dims = (jint*) NEW_RESOURCE_ARRAY(jint, nof_dims);
 308   }
 309   for (int index = 0; index < nof_dims; index++) {
 310     // offset from first_size_address is addressed as local[index]
 311     int n = Interpreter::local_offset_in_bytes(index)/jintSize;
 312     dims[index] = first_size_address[n];
 313   }
 314   oop obj = ArrayKlass::cast(klass)->multi_allocate(nof_dims, dims, CHECK);
 315   current->set_vm_result_oop(obj);
 316 JRT_END
 317 
 318 
 319 JRT_ENTRY(void, InterpreterRuntime::register_finalizer(JavaThread* current, oopDesc* obj))
 320   assert(oopDesc::is_oop(obj), "must be a valid oop");
 321   assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise");
 322   InstanceKlass::register_finalizer(instanceOop(obj), CHECK);
 323 JRT_END
 324 
 325 JRT_ENTRY(jboolean, InterpreterRuntime::is_substitutable(JavaThread* current, oopDesc* aobj, oopDesc* bobj))
 326   assert(oopDesc::is_oop(aobj) && oopDesc::is_oop(bobj), "must be valid oops");
 327 
 328   Handle ha(THREAD, aobj);
 329   Handle hb(THREAD, bobj);
 330   JavaValue result(T_BOOLEAN);
 331   JavaCallArguments args;
 332   args.push_oop(ha);
 333   args.push_oop(hb);
 334   methodHandle method(current, UseAltSubstitutabilityMethod ?  Universe::is_substitutableAlt_method() : Universe::is_substitutable_method());
 335   method->method_holder()->initialize(CHECK_false); // Ensure class ValueObjectMethods is initialized
 336   JavaCalls::call(&result, method, &args, THREAD);
 337   if (HAS_PENDING_EXCEPTION) {
 338     // Something really bad happened because isSubstitutable() should not throw exceptions
 339     // If it is an error, just let it propagate
 340     // If it is an exception, wrap it into an InternalError
 341     if (!PENDING_EXCEPTION->is_a(vmClasses::Error_klass())) {
 342       Handle e(THREAD, PENDING_EXCEPTION);
 343       CLEAR_PENDING_EXCEPTION;
 344       THROW_MSG_CAUSE_(vmSymbols::java_lang_InternalError(), "Internal error in substitutability test", e, false);
 345     }
 346   }
 347   return result.get_jboolean();
 348 JRT_END
 349 
 350 // Quicken instance-of and check-cast bytecodes
 351 JRT_ENTRY(void, InterpreterRuntime::quicken_io_cc(JavaThread* current))
 352   // Force resolving; quicken the bytecode
 353   LastFrameAccessor last_frame(current);
 354   int which = last_frame.get_index_u2(Bytecodes::_checkcast);
 355   ConstantPool* cpool = last_frame.method()->constants();
 356   // We'd expect to assert that we're only here to quicken bytecodes, but in a multithreaded
 357   // program we might have seen an unquick'd bytecode in the interpreter but have another
 358   // thread quicken the bytecode before we get here.
 359   // assert( cpool->tag_at(which).is_unresolved_klass(), "should only come here to quicken bytecodes" );
 360   Klass* klass = cpool->klass_at(which, CHECK);
 361   current->set_vm_result_metadata(klass);
 362 JRT_END
 363 
 364 
 365 //------------------------------------------------------------------------------------------------------------------------
 366 // Exceptions
 367 
 368 void InterpreterRuntime::note_trap_inner(JavaThread* current, int reason,
 369                                          const methodHandle& trap_method, int trap_bci) {
 370   if (trap_method.not_null()) {
 371     MethodData* trap_mdo = trap_method->method_data();
 372     if (trap_mdo == nullptr) {
 373       ExceptionMark em(current);
 374       JavaThread* THREAD = current; // For exception macros.
 375       Method::build_profiling_method_data(trap_method, THREAD);
 376       if (HAS_PENDING_EXCEPTION) {
 377         // Only metaspace OOM is expected. No Java code executed.
 378         assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())),
 379                "we expect only an OOM error here");
 380         CLEAR_PENDING_EXCEPTION;
 381       }
 382       trap_mdo = trap_method->method_data();
 383       // and fall through...
 384     }
 385     if (trap_mdo != nullptr) {
 386       // Update per-method count of trap events.  The interpreter
 387       // is updating the MDO to simulate the effect of compiler traps.
 388       Deoptimization::update_method_data_from_interpreter(trap_mdo, trap_bci, reason);
 389     }
 390   }
 391 }
 392 
 393 // Assume the compiler is (or will be) interested in this event.
 394 // If necessary, create an MDO to hold the information, and record it.
 395 void InterpreterRuntime::note_trap(JavaThread* current, int reason) {
 396   assert(ProfileTraps, "call me only if profiling");
 397   LastFrameAccessor last_frame(current);
 398   methodHandle trap_method(current, last_frame.method());
 399   int trap_bci = trap_method->bci_from(last_frame.bcp());
 400   note_trap_inner(current, reason, trap_method, trap_bci);
 401 }
 402 
 403 static Handle get_preinitialized_exception(Klass* k, TRAPS) {
 404   // get klass
 405   InstanceKlass* klass = InstanceKlass::cast(k);
 406   assert(klass->is_initialized(),
 407          "this klass should have been initialized during VM initialization");
 408   // create instance - do not call constructor since we may have no
 409   // (java) stack space left (should assert constructor is empty)
 410   Handle exception;
 411   oop exception_oop = klass->allocate_instance(CHECK_(exception));
 412   exception = Handle(THREAD, exception_oop);
 413   if (StackTraceInThrowable) {
 414     java_lang_Throwable::fill_in_stack_trace(exception);
 415   }
 416   return exception;
 417 }
 418 
 419 // Special handling for stack overflow: since we don't have any (java) stack
 420 // space left we use the pre-allocated & pre-initialized StackOverflowError
 421 // klass to create an stack overflow error instance.  We do not call its
 422 // constructor for the same reason (it is empty, anyway).
 423 JRT_ENTRY(void, InterpreterRuntime::throw_StackOverflowError(JavaThread* current))
 424   Handle exception = get_preinitialized_exception(
 425                                  vmClasses::StackOverflowError_klass(),
 426                                  CHECK);
 427   // Increment counter for hs_err file reporting
 428   AtomicAccess::inc(&Exceptions::_stack_overflow_errors);
 429   // Remove the ScopedValue bindings in case we got a StackOverflowError
 430   // while we were trying to manipulate ScopedValue bindings.
 431   current->clear_scopedValueBindings();
 432   THROW_HANDLE(exception);
 433 JRT_END
 434 
 435 JRT_ENTRY(void, InterpreterRuntime::throw_delayed_StackOverflowError(JavaThread* current))
 436   Handle exception = get_preinitialized_exception(
 437                                  vmClasses::StackOverflowError_klass(),
 438                                  CHECK);
 439   java_lang_Throwable::set_message(exception(),
 440           Universe::delayed_stack_overflow_error_message());
 441   // Increment counter for hs_err file reporting
 442   AtomicAccess::inc(&Exceptions::_stack_overflow_errors);
 443   // Remove the ScopedValue bindings in case we got a StackOverflowError
 444   // while we were trying to manipulate ScopedValue bindings.
 445   current->clear_scopedValueBindings();
 446   THROW_HANDLE(exception);
 447 JRT_END
 448 
 449 JRT_ENTRY(void, InterpreterRuntime::create_exception(JavaThread* current, char* name, char* message))
 450   // lookup exception klass
 451   TempNewSymbol s = SymbolTable::new_symbol(name);
 452   if (ProfileTraps) {
 453     if (s == vmSymbols::java_lang_ArithmeticException()) {
 454       note_trap(current, Deoptimization::Reason_div0_check);
 455     } else if (s == vmSymbols::java_lang_NullPointerException()) {
 456       note_trap(current, Deoptimization::Reason_null_check);
 457     }
 458   }
 459   // create exception
 460   Handle exception = Exceptions::new_exception(current, s, message);
 461   current->set_vm_result_oop(exception());
 462 JRT_END
 463 
 464 
 465 JRT_ENTRY(void, InterpreterRuntime::create_klass_exception(JavaThread* current, char* name, oopDesc* obj))
 466   // Produce the error message first because note_trap can safepoint
 467   ResourceMark rm(current);
 468   const char* klass_name = obj->klass()->external_name();
 469   // lookup exception klass
 470   TempNewSymbol s = SymbolTable::new_symbol(name);
 471   if (ProfileTraps) {
 472     if (s == vmSymbols::java_lang_ArrayStoreException()) {
 473       note_trap(current, Deoptimization::Reason_array_check);
 474     } else {
 475       note_trap(current, Deoptimization::Reason_class_check);
 476     }
 477   }
 478   // create exception, with klass name as detail message
 479   Handle exception = Exceptions::new_exception(current, s, klass_name);
 480   current->set_vm_result_oop(exception());
 481 JRT_END
 482 
 483 JRT_ENTRY(void, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException(JavaThread* current, arrayOopDesc* a, jint index))
 484   // Produce the error message first because note_trap can safepoint
 485   ResourceMark rm(current);
 486   stringStream ss;
 487   ss.print("Index %d out of bounds for length %d", index, a->length());
 488 
 489   if (ProfileTraps) {
 490     note_trap(current, Deoptimization::Reason_range_check);
 491   }
 492 
 493   THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), ss.as_string());
 494 JRT_END
 495 
 496 JRT_ENTRY(void, InterpreterRuntime::throw_ClassCastException(
 497   JavaThread* current, oopDesc* obj))
 498 
 499   // Produce the error message first because note_trap can safepoint
 500   ResourceMark rm(current);
 501   char* message = SharedRuntime::generate_class_cast_message(
 502     current, obj->klass());
 503 
 504   if (ProfileTraps) {
 505     note_trap(current, Deoptimization::Reason_class_check);
 506   }
 507 
 508   // create exception
 509   THROW_MSG(vmSymbols::java_lang_ClassCastException(), message);
 510 JRT_END
 511 
 512 // exception_handler_for_exception(...) returns the continuation address,
 513 // the exception oop (via TLS) and sets the bci/bcp for the continuation.
 514 // The exception oop is returned to make sure it is preserved over GC (it
 515 // is only on the stack if the exception was thrown explicitly via athrow).
 516 // During this operation, the expression stack contains the values for the
 517 // bci where the exception happened. If the exception was propagated back
 518 // from a call, the expression stack contains the values for the bci at the
 519 // invoke w/o arguments (i.e., as if one were inside the call).
 520 // Note that the implementation of this method assumes it's only called when an exception has actually occured
 521 JRT_ENTRY(address, InterpreterRuntime::exception_handler_for_exception(JavaThread* current, oopDesc* exception))
 522   // We get here after we have unwound from a callee throwing an exception
 523   // into the interpreter. Any deferred stack processing is notified of
 524   // the event via the StackWatermarkSet.
 525   StackWatermarkSet::after_unwind(current);
 526 
 527   LastFrameAccessor last_frame(current);
 528   Handle             h_exception(current, exception);
 529   methodHandle       h_method   (current, last_frame.method());
 530   constantPoolHandle h_constants(current, h_method->constants());
 531   bool               should_repeat;
 532   int                handler_bci;
 533   int                current_bci = last_frame.bci();
 534 
 535   if (current->frames_to_pop_failed_realloc() > 0) {
 536     // Allocation of scalar replaced object used in this frame
 537     // failed. Unconditionally pop the frame.
 538     current->dec_frames_to_pop_failed_realloc();
 539     current->set_vm_result_oop(h_exception());
 540     // If the method is synchronized we already unlocked the monitor
 541     // during deoptimization so the interpreter needs to skip it when
 542     // the frame is popped.
 543     current->set_do_not_unlock_if_synchronized(true);
 544     return Interpreter::remove_activation_entry();
 545   }
 546 
 547   // Need to do this check first since when _do_not_unlock_if_synchronized
 548   // is set, we don't want to trigger any classloading which may make calls
 549   // into java, or surprisingly find a matching exception handler for bci 0
 550   // since at this moment the method hasn't been "officially" entered yet.
 551   if (current->do_not_unlock_if_synchronized()) {
 552     ResourceMark rm;
 553     assert(current_bci == 0,  "bci isn't zero for do_not_unlock_if_synchronized");
 554     current->set_vm_result_oop(exception);
 555     return Interpreter::remove_activation_entry();
 556   }
 557 
 558   do {
 559     should_repeat = false;
 560 
 561     // assertions
 562     assert(h_exception.not_null(), "null exceptions should be handled by athrow");
 563     // Check that exception is a subclass of Throwable.
 564     assert(h_exception->is_a(vmClasses::Throwable_klass()),
 565            "Exception not subclass of Throwable");
 566 
 567     // tracing
 568     if (log_is_enabled(Info, exceptions)) {
 569       ResourceMark rm(current);
 570       stringStream tempst;
 571       tempst.print("interpreter method <%s>\n"
 572                    " at bci %d for thread " INTPTR_FORMAT " (%s)",
 573                    h_method->print_value_string(), current_bci, p2i(current), current->name());
 574       Exceptions::log_exception(h_exception, tempst.as_string());
 575     }
 576     if (log_is_enabled(Info, exceptions, stacktrace)) {
 577       Exceptions::log_exception_stacktrace(h_exception, h_method, current_bci);
 578     }
 579 
 580 // Don't go paging in something which won't be used.
 581 //     else if (extable->length() == 0) {
 582 //       // disabled for now - interpreter is not using shortcut yet
 583 //       // (shortcut is not to call runtime if we have no exception handlers)
 584 //       // warning("performance bug: should not call runtime if method has no exception handlers");
 585 //     }
 586     // for AbortVMOnException flag
 587     Exceptions::debug_check_abort(h_exception);
 588 
 589     // exception handler lookup
 590     Klass* klass = h_exception->klass();
 591     handler_bci = Method::fast_exception_handler_bci_for(h_method, klass, current_bci, THREAD);
 592     if (HAS_PENDING_EXCEPTION) {
 593       // We threw an exception while trying to find the exception handler.
 594       // Transfer the new exception to the exception handle which will
 595       // be set into thread local storage, and do another lookup for an
 596       // exception handler for this exception, this time starting at the
 597       // BCI of the exception handler which caused the exception to be
 598       // thrown (bug 4307310).
 599       h_exception = Handle(THREAD, PENDING_EXCEPTION);
 600       CLEAR_PENDING_EXCEPTION;
 601       if (handler_bci >= 0) {
 602         current_bci = handler_bci;
 603         should_repeat = true;
 604       }
 605     }
 606   } while (should_repeat == true);
 607 
 608 #if INCLUDE_JVMCI
 609   if (EnableJVMCI && h_method->method_data() != nullptr) {
 610     ResourceMark rm(current);
 611     MethodData* mdo = h_method->method_data();
 612 
 613     // Lock to read ProfileData, and ensure lock is not broken by a safepoint
 614     MutexLocker ml(mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
 615 
 616     ProfileData* pdata = mdo->allocate_bci_to_data(current_bci, nullptr);
 617     if (pdata != nullptr && pdata->is_BitData()) {
 618       BitData* bit_data = (BitData*) pdata;
 619       bit_data->set_exception_seen();
 620     }
 621   }
 622 #endif
 623 
 624   // notify JVMTI of an exception throw; JVMTI will detect if this is a first
 625   // time throw or a stack unwinding throw and accordingly notify the debugger
 626   if (JvmtiExport::can_post_on_exceptions()) {
 627     JvmtiExport::post_exception_throw(current, h_method(), last_frame.bcp(), h_exception());
 628   }
 629 
 630   address continuation = nullptr;
 631   address handler_pc = nullptr;
 632   if (handler_bci < 0 || !current->stack_overflow_state()->reguard_stack((address) &continuation)) {
 633     // Forward exception to callee (leaving bci/bcp untouched) because (a) no
 634     // handler in this method, or (b) after a stack overflow there is not yet
 635     // enough stack space available to reprotect the stack.
 636     continuation = Interpreter::remove_activation_entry();
 637 #if COMPILER2_OR_JVMCI
 638     // Count this for compilation purposes
 639     h_method->interpreter_throwout_increment(THREAD);
 640 #endif
 641   } else {
 642     // handler in this method => change bci/bcp to handler bci/bcp and continue there
 643     handler_pc = h_method->code_base() + handler_bci;
 644     h_method->set_exception_handler_entered(handler_bci); // profiling
 645 #ifndef ZERO
 646     set_bcp_and_mdp(handler_pc, current);
 647     continuation = Interpreter::dispatch_table(vtos)[*handler_pc];
 648 #else
 649     continuation = (address)(intptr_t) handler_bci;
 650 #endif
 651   }
 652 
 653   // notify debugger of an exception catch
 654   // (this is good for exceptions caught in native methods as well)
 655   if (JvmtiExport::can_post_on_exceptions()) {
 656     JvmtiExport::notice_unwind_due_to_exception(current, h_method(), handler_pc, h_exception(), (handler_pc != nullptr));
 657   }
 658 
 659   current->set_vm_result_oop(h_exception());
 660   return continuation;
 661 JRT_END
 662 
 663 
 664 JRT_ENTRY(void, InterpreterRuntime::throw_pending_exception(JavaThread* current))
 665   assert(current->has_pending_exception(), "must only be called if there's an exception pending");
 666   // nothing to do - eventually we should remove this code entirely (see comments @ call sites)
 667 JRT_END
 668 
 669 
 670 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodError(JavaThread* current))
 671   THROW(vmSymbols::java_lang_AbstractMethodError());
 672 JRT_END
 673 
 674 // This method is called from the "abstract_entry" of the interpreter.
 675 // At that point, the arguments have already been removed from the stack
 676 // and therefore we don't have the receiver object at our fingertips. (Though,
 677 // on some platforms the receiver still resides in a register...). Thus,
 678 // we have no choice but print an error message not containing the receiver
 679 // type.
 680 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorWithMethod(JavaThread* current,
 681                                                                         Method* missingMethod))
 682   ResourceMark rm(current);
 683   assert(missingMethod != nullptr, "sanity");
 684   methodHandle m(current, missingMethod);
 685   LinkResolver::throw_abstract_method_error(m, THREAD);
 686 JRT_END
 687 
 688 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorVerbose(JavaThread* current,
 689                                                                      Klass* recvKlass,
 690                                                                      Method* missingMethod))
 691   ResourceMark rm(current);
 692   methodHandle mh = methodHandle(current, missingMethod);
 693   LinkResolver::throw_abstract_method_error(mh, recvKlass, THREAD);
 694 JRT_END
 695 
 696 JRT_ENTRY(void, InterpreterRuntime::throw_InstantiationError(JavaThread* current))
 697   THROW(vmSymbols::java_lang_InstantiationError());
 698 JRT_END
 699 
 700 
 701 JRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeError(JavaThread* current))
 702   THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
 703 JRT_END
 704 
 705 JRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeErrorVerbose(JavaThread* current,
 706                                                                               Klass* recvKlass,
 707                                                                               Klass* interfaceKlass))
 708   ResourceMark rm(current);
 709   char buf[1000];
 710   buf[0] = '\0';
 711   jio_snprintf(buf, sizeof(buf),
 712                "Class %s does not implement the requested interface %s",
 713                recvKlass ? recvKlass->external_name() : "nullptr",
 714                interfaceKlass ? interfaceKlass->external_name() : "nullptr");
 715   THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), buf);
 716 JRT_END
 717 
 718 JRT_ENTRY(void, InterpreterRuntime::throw_NullPointerException(JavaThread* current))
 719   THROW(vmSymbols::java_lang_NullPointerException());
 720 JRT_END
 721 
 722 //------------------------------------------------------------------------------------------------------------------------
 723 // Fields
 724 //
 725 
 726 void InterpreterRuntime::resolve_get_put(JavaThread* current, Bytecodes::Code bytecode) {
 727   LastFrameAccessor last_frame(current);
 728   constantPoolHandle pool(current, last_frame.method()->constants());
 729   methodHandle m(current, last_frame.method());
 730 
 731   resolve_get_put(bytecode, last_frame.get_index_u2(bytecode), m, pool, true /*initialize_holder*/, current);
 732 }
 733 
 734 void InterpreterRuntime::resolve_get_put(Bytecodes::Code bytecode, int field_index,
 735                                          methodHandle& m,
 736                                          constantPoolHandle& pool,
 737                                          bool initialize_holder, TRAPS) {
 738   fieldDescriptor info;
 739   bool is_put    = (bytecode == Bytecodes::_putfield  || bytecode == Bytecodes::_nofast_putfield ||
 740                     bytecode == Bytecodes::_putstatic);
 741   bool is_static = (bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic);
 742 
 743   {
 744     JvmtiHideSingleStepping jhss(THREAD);
 745     LinkResolver::resolve_field_access(info, pool, field_index,
 746                                        m, bytecode, initialize_holder, CHECK);
 747   } // end JvmtiHideSingleStepping
 748 
 749   // check if link resolution caused cpCache to be updated
 750   if (pool->resolved_field_entry_at(field_index)->is_resolved(bytecode)) return;
 751 
 752   // compute auxiliary field attributes
 753   TosState state  = as_TosState(info.field_type());
 754 
 755   // Resolution of put instructions on final fields is delayed. That is required so that
 756   // exceptions are thrown at the correct place (when the instruction is actually invoked).
 757   // If we do not resolve an instruction in the current pass, leaving the put_code
 758   // set to zero will cause the next put instruction to the same field to reresolve.
 759 
 760   // Resolution of put instructions to final instance fields with invalid updates (i.e.,
 761   // to final instance fields with updates originating from a method different than <init>)
 762   // is inhibited. A putfield instruction targeting an instance final field must throw
 763   // an IllegalAccessError if the instruction is not in an instance
 764   // initializer method <init>. If resolution were not inhibited, a putfield
 765   // in an initializer method could be resolved in the initializer. Subsequent
 766   // putfield instructions to the same field would then use cached information.
 767   // As a result, those instructions would not pass through the VM. That is,
 768   // checks in resolve_field_access() would not be executed for those instructions
 769   // and the required IllegalAccessError would not be thrown.
 770   //
 771   // Also, we need to delay resolving getstatic and putstatic instructions until the
 772   // class is initialized.  This is required so that access to the static
 773   // field will call the initialization function every time until the class
 774   // is completely initialized ala. in 2.17.5 in JVM Specification.
 775   InstanceKlass* klass = info.field_holder();
 776   bool uninitialized_static = is_static && !klass->is_initialized();
 777   bool has_initialized_final_update = info.field_holder()->major_version() >= 53 &&
 778                                       info.has_initialized_final_update();
 779   bool strict_static_final = info.is_strict() && info.is_static() && info.is_final();
 780   assert(!(has_initialized_final_update && !info.access_flags().is_final()), "Fields with initialized final updates must be final");
 781 
 782   Bytecodes::Code get_code = (Bytecodes::Code)0;
 783   Bytecodes::Code put_code = (Bytecodes::Code)0;
 784   if (uninitialized_static && (info.is_strict_static_unset() || strict_static_final)) {
 785     // During <clinit>, closely track the state of strict statics.
 786     // 1. if we are reading an uninitialized strict static, throw
 787     // 2. if we are writing one, clear the "unset" flag
 788     //
 789     // Note: If we were handling an attempted write of a null to a
 790     // null-restricted strict static, we would NOT clear the "unset"
 791     // flag.
 792     assert(klass->is_being_initialized(), "else should have thrown");
 793     assert(klass->is_reentrant_initialization(THREAD),
 794       "<clinit> must be running in current thread");
 795     klass->notify_strict_static_access(info.index(), is_put, CHECK);
 796     assert(!info.is_strict_static_unset(), "after initialization, no unset flags");
 797   } else if (!uninitialized_static || VM_Version::supports_fast_class_init_checks()) {
 798     get_code = ((is_static) ? Bytecodes::_getstatic : Bytecodes::_getfield);
 799     if ((is_put && !has_initialized_final_update) || !info.access_flags().is_final()) {
 800       put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_putfield);
 801     }
 802   }
 803 
 804   ResolvedFieldEntry* entry = pool->resolved_field_entry_at(field_index);
 805   entry->set_flags(info.access_flags().is_final(), info.access_flags().is_volatile(),
 806                    info.is_flat(), info.is_null_free_inline_type(),
 807                    info.has_null_marker());
 808 
 809   entry->fill_in(info.field_holder(), info.offset(),
 810                  checked_cast<u2>(info.index()), checked_cast<u1>(state),
 811                  static_cast<u1>(get_code), static_cast<u1>(put_code));
 812 }
 813 
 814 
 815 //------------------------------------------------------------------------------------------------------------------------
 816 // Synchronization
 817 //
 818 // The interpreter's synchronization code is factored out so that it can
 819 // be shared by method invocation and synchronized blocks.
 820 //%note synchronization_3
 821 
 822 //%note monitor_1
 823 JRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* current, BasicObjectLock* elem))
 824 #ifdef ASSERT
 825   current->last_frame().interpreter_frame_verify_monitor(elem);
 826 #endif
 827   Handle h_obj(current, elem->obj());
 828   assert(Universe::heap()->is_in_or_null(h_obj()),
 829          "must be null or an object");
 830   ObjectSynchronizer::enter(h_obj, elem->lock(), current);
 831   assert(Universe::heap()->is_in_or_null(elem->obj()),
 832          "must be null or an object");
 833 #ifdef ASSERT
 834   if (!current->preempting()) current->last_frame().interpreter_frame_verify_monitor(elem);
 835 #endif
 836 JRT_END
 837 
 838 JRT_LEAF(void, InterpreterRuntime::monitorexit(BasicObjectLock* elem))
 839   oop obj = elem->obj();
 840   assert(Universe::heap()->is_in(obj), "must be an object");
 841   // The object could become unlocked through a JNI call, which we have no other checks for.
 842   // Give a fatal message if CheckJNICalls. Otherwise we ignore it.
 843   if (obj->is_unlocked()) {
 844     if (CheckJNICalls) {
 845       fatal("Object has been unlocked by JNI");
 846     }
 847     return;
 848   }
 849   ObjectSynchronizer::exit(obj, elem->lock(), JavaThread::current());
 850   // Free entry. If it is not cleared, the exception handling code will try to unlock the monitor
 851   // again at method exit or in the case of an exception.
 852   elem->set_obj(nullptr);
 853 JRT_END
 854 
 855 JRT_ENTRY(void, InterpreterRuntime::throw_illegal_monitor_state_exception(JavaThread* current))
 856   THROW(vmSymbols::java_lang_IllegalMonitorStateException());
 857 JRT_END
 858 
 859 JRT_ENTRY(void, InterpreterRuntime::new_illegal_monitor_state_exception(JavaThread* current))
 860   // Returns an illegal exception to install into the current thread. The
 861   // pending_exception flag is cleared so normal exception handling does not
 862   // trigger. Any current installed exception will be overwritten. This
 863   // method will be called during an exception unwind.
 864 
 865   assert(!HAS_PENDING_EXCEPTION, "no pending exception");
 866   Handle exception(current, current->vm_result_oop());
 867   assert(exception() != nullptr, "vm result should be set");
 868   current->set_vm_result_oop(nullptr); // clear vm result before continuing (may cause memory leaks and assert failures)
 869   exception = get_preinitialized_exception(vmClasses::IllegalMonitorStateException_klass(), CATCH);
 870   current->set_vm_result_oop(exception());
 871 JRT_END
 872 
 873 JRT_ENTRY(void, InterpreterRuntime::throw_identity_exception(JavaThread* current, oopDesc* obj))
 874   Klass* klass = cast_to_oop(obj)->klass();
 875   ResourceMark rm(THREAD);
 876   const char* desc = "Cannot synchronize on an instance of value class ";
 877   const char* className = klass->external_name();
 878   size_t msglen = strlen(desc) + strlen(className) + 1;
 879   char* message = NEW_RESOURCE_ARRAY(char, msglen);
 880   if (nullptr == message) {
 881     // Out of memory: can't create detailed error message
 882     THROW_MSG(vmSymbols::java_lang_IdentityException(), className);
 883   } else {
 884     jio_snprintf(message, msglen, "%s%s", desc, className);
 885     THROW_MSG(vmSymbols::java_lang_IdentityException(), message);
 886   }
 887 JRT_END
 888 
 889 //------------------------------------------------------------------------------------------------------------------------
 890 // Invokes
 891 
 892 JRT_ENTRY(Bytecodes::Code, InterpreterRuntime::get_original_bytecode_at(JavaThread* current, Method* method, address bcp))
 893   return method->orig_bytecode_at(method->bci_from(bcp));
 894 JRT_END
 895 
 896 JRT_ENTRY(void, InterpreterRuntime::set_original_bytecode_at(JavaThread* current, Method* method, address bcp, Bytecodes::Code new_code))
 897   method->set_orig_bytecode_at(method->bci_from(bcp), new_code);
 898 JRT_END
 899 
 900 JRT_ENTRY(void, InterpreterRuntime::_breakpoint(JavaThread* current, Method* method, address bcp))
 901   JvmtiExport::post_raw_breakpoint(current, method, bcp);
 902 JRT_END
 903 
 904 void InterpreterRuntime::resolve_invoke(JavaThread* current, Bytecodes::Code bytecode) {
 905   LastFrameAccessor last_frame(current);
 906   // extract receiver from the outgoing argument list if necessary
 907   Handle receiver(current, nullptr);
 908   if (bytecode == Bytecodes::_invokevirtual || bytecode == Bytecodes::_invokeinterface ||
 909       bytecode == Bytecodes::_invokespecial) {
 910     ResourceMark rm(current);
 911     methodHandle m (current, last_frame.method());
 912     Bytecode_invoke call(m, last_frame.bci());
 913     Symbol* signature = call.signature();
 914     receiver = Handle(current, last_frame.callee_receiver(signature));
 915 
 916     assert(Universe::heap()->is_in_or_null(receiver()),
 917            "sanity check");
 918     assert(receiver.is_null() ||
 919            !Universe::heap()->is_in(receiver->klass()),
 920            "sanity check");
 921   }
 922 
 923   // resolve method
 924   CallInfo info;
 925   constantPoolHandle pool(current, last_frame.method()->constants());
 926 
 927   methodHandle resolved_method;
 928 
 929   int method_index = last_frame.get_index_u2(bytecode);
 930   {
 931     JvmtiHideSingleStepping jhss(current);
 932     JavaThread* THREAD = current; // For exception macros.
 933     LinkResolver::resolve_invoke(info, receiver, pool,
 934                                  method_index, bytecode,
 935                                  THREAD);
 936 
 937     if (HAS_PENDING_EXCEPTION) {
 938       if (ProfileTraps && PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_NullPointerException()) {
 939         // Preserve the original exception across the call to note_trap()
 940         PreserveExceptionMark pm(current);
 941         // Recording the trap will help the compiler to potentially recognize this exception as "hot"
 942         note_trap(current, Deoptimization::Reason_null_check);
 943       }
 944       return;
 945     }
 946 
 947     resolved_method = methodHandle(current, info.resolved_method());
 948   } // end JvmtiHideSingleStepping
 949 
 950   update_invoke_cp_cache_entry(info, bytecode, resolved_method, pool, method_index);
 951 }
 952 
 953 void InterpreterRuntime::update_invoke_cp_cache_entry(CallInfo& info, Bytecodes::Code bytecode,
 954                                                       methodHandle& resolved_method,
 955                                                       constantPoolHandle& pool,
 956                                                       int method_index) {
 957   // Don't allow safepoints until the method is cached.
 958   NoSafepointVerifier nsv;
 959 
 960   // check if link resolution caused cpCache to be updated
 961   ConstantPoolCache* cache = pool->cache();
 962   if (cache->resolved_method_entry_at(method_index)->is_resolved(bytecode)) return;
 963 
 964 #ifdef ASSERT
 965   if (bytecode == Bytecodes::_invokeinterface) {
 966     if (resolved_method->method_holder() == vmClasses::Object_klass()) {
 967       // NOTE: THIS IS A FIX FOR A CORNER CASE in the JVM spec
 968       // (see also CallInfo::set_interface for details)
 969       assert(info.call_kind() == CallInfo::vtable_call ||
 970              info.call_kind() == CallInfo::direct_call, "");
 971       assert(resolved_method->is_final() || info.has_vtable_index(),
 972              "should have been set already");
 973     } else if (!resolved_method->has_itable_index()) {
 974       // Resolved something like CharSequence.toString.  Use vtable not itable.
 975       assert(info.call_kind() != CallInfo::itable_call, "");
 976     } else {
 977       // Setup itable entry
 978       assert(info.call_kind() == CallInfo::itable_call, "");
 979       int index = resolved_method->itable_index();
 980       assert(info.itable_index() == index, "");
 981     }
 982   } else if (bytecode == Bytecodes::_invokespecial) {
 983     assert(info.call_kind() == CallInfo::direct_call, "must be direct call");
 984   } else {
 985     assert(info.call_kind() == CallInfo::direct_call ||
 986            info.call_kind() == CallInfo::vtable_call, "");
 987   }
 988 #endif
 989   // Get sender and only set cpCache entry to resolved if it is not an
 990   // interface.  The receiver for invokespecial calls within interface
 991   // methods must be checked for every call.
 992   InstanceKlass* sender = pool->pool_holder();
 993 
 994   switch (info.call_kind()) {
 995   case CallInfo::direct_call:
 996     cache->set_direct_call(bytecode, method_index, resolved_method, sender->is_interface());
 997     break;
 998   case CallInfo::vtable_call:
 999     cache->set_vtable_call(bytecode, method_index, resolved_method, info.vtable_index());
1000     break;
1001   case CallInfo::itable_call:
1002     cache->set_itable_call(
1003       bytecode,
1004       method_index,
1005       info.resolved_klass(),
1006       resolved_method,
1007       info.itable_index());
1008     break;
1009   default:  ShouldNotReachHere();
1010   }
1011 }
1012 
1013 void InterpreterRuntime::cds_resolve_invoke(Bytecodes::Code bytecode, int method_index,
1014                                             constantPoolHandle& pool, TRAPS) {
1015   LinkInfo link_info(pool, method_index, bytecode, CHECK);
1016 
1017   if (!link_info.resolved_klass()->is_instance_klass() || InstanceKlass::cast(link_info.resolved_klass())->is_linked()) {
1018     CallInfo call_info;
1019     switch (bytecode) {
1020       case Bytecodes::_invokevirtual:   LinkResolver::cds_resolve_virtual_call  (call_info, link_info, CHECK); break;
1021       case Bytecodes::_invokeinterface: LinkResolver::cds_resolve_interface_call(call_info, link_info, CHECK); break;
1022       case Bytecodes::_invokestatic:    LinkResolver::cds_resolve_static_call   (call_info, link_info, CHECK); break;
1023       case Bytecodes::_invokespecial:   LinkResolver::cds_resolve_special_call  (call_info, link_info, CHECK); break;
1024 
1025       default: fatal("Unimplemented: %s", Bytecodes::name(bytecode));
1026     }
1027     methodHandle resolved_method(THREAD, call_info.resolved_method());
1028     guarantee(resolved_method->method_holder()->is_linked(), "");
1029     update_invoke_cp_cache_entry(call_info, bytecode, resolved_method, pool, method_index);
1030   } else {
1031     // FIXME: why a shared class is not linked yet?
1032     // Can't link it here since there are no guarantees it'll be prelinked on the next run.
1033     ResourceMark rm;
1034     InstanceKlass* resolved_iklass = InstanceKlass::cast(link_info.resolved_klass());
1035     log_info(aot, resolve)("Not resolved: class not linked: %s %s %s",
1036                            resolved_iklass->in_aot_cache() ? "in_aot_cache" : "",
1037                            resolved_iklass->init_state_name(),
1038                            resolved_iklass->external_name());
1039   }
1040 }
1041 
1042 // First time execution:  Resolve symbols, create a permanent MethodType object.
1043 void InterpreterRuntime::resolve_invokehandle(JavaThread* current) {
1044   const Bytecodes::Code bytecode = Bytecodes::_invokehandle;
1045   LastFrameAccessor last_frame(current);
1046 
1047   // resolve method
1048   CallInfo info;
1049   constantPoolHandle pool(current, last_frame.method()->constants());
1050   int method_index = last_frame.get_index_u2(bytecode);
1051   {
1052     JvmtiHideSingleStepping jhss(current);
1053     JavaThread* THREAD = current; // For exception macros.
1054     LinkResolver::resolve_invoke(info, Handle(), pool,
1055                                  method_index, bytecode,
1056                                  CHECK);
1057   } // end JvmtiHideSingleStepping
1058 
1059   pool->cache()->set_method_handle(method_index, info);
1060 }
1061 
1062 void InterpreterRuntime::cds_resolve_invokehandle(int raw_index,
1063                                                   constantPoolHandle& pool, TRAPS) {
1064   const Bytecodes::Code bytecode = Bytecodes::_invokehandle;
1065   CallInfo info;
1066   LinkResolver::resolve_invoke(info, Handle(), pool, raw_index, bytecode, CHECK);
1067 
1068   pool->cache()->set_method_handle(raw_index, info);
1069 }
1070 
1071 // First time execution:  Resolve symbols, create a permanent CallSite object.
1072 void InterpreterRuntime::resolve_invokedynamic(JavaThread* current) {
1073   LastFrameAccessor last_frame(current);
1074   const Bytecodes::Code bytecode = Bytecodes::_invokedynamic;
1075 
1076   // resolve method
1077   CallInfo info;
1078   constantPoolHandle pool(current, last_frame.method()->constants());
1079   int index = last_frame.get_index_u4(bytecode);
1080   {
1081     JvmtiHideSingleStepping jhss(current);
1082     JavaThread* THREAD = current; // For exception macros.
1083     LinkResolver::resolve_invoke(info, Handle(), pool,
1084                                  index, bytecode, CHECK);
1085   } // end JvmtiHideSingleStepping
1086 
1087   pool->cache()->set_dynamic_call(info, index);
1088 }
1089 
1090 void InterpreterRuntime::cds_resolve_invokedynamic(int raw_index,
1091                                                    constantPoolHandle& pool, TRAPS) {
1092   const Bytecodes::Code bytecode = Bytecodes::_invokedynamic;
1093   CallInfo info;
1094   LinkResolver::resolve_invoke(info, Handle(), pool, raw_index, bytecode, CHECK);
1095   pool->cache()->set_dynamic_call(info, raw_index);
1096 }
1097 
1098 // This function is the interface to the assembly code. It returns the resolved
1099 // cpCache entry.  This doesn't safepoint, but the helper routines safepoint.
1100 // This function will check for redefinition!
1101 JRT_ENTRY(void, InterpreterRuntime::resolve_from_cache(JavaThread* current, Bytecodes::Code bytecode)) {
1102   switch (bytecode) {
1103   case Bytecodes::_getstatic:
1104   case Bytecodes::_putstatic:
1105   case Bytecodes::_getfield:
1106   case Bytecodes::_putfield:
1107     resolve_get_put(current, bytecode);
1108     break;
1109   case Bytecodes::_invokevirtual:
1110   case Bytecodes::_invokespecial:
1111   case Bytecodes::_invokestatic:
1112   case Bytecodes::_invokeinterface:
1113     resolve_invoke(current, bytecode);
1114     break;
1115   case Bytecodes::_invokehandle:
1116     resolve_invokehandle(current);
1117     break;
1118   case Bytecodes::_invokedynamic:
1119     resolve_invokedynamic(current);
1120     break;
1121   default:
1122     fatal("unexpected bytecode: %s", Bytecodes::name(bytecode));
1123     break;
1124   }
1125 }
1126 JRT_END
1127 
1128 //------------------------------------------------------------------------------------------------------------------------
1129 // Miscellaneous
1130 
1131 
1132 nmethod* InterpreterRuntime::frequency_counter_overflow(JavaThread* current, address branch_bcp) {
1133   // Enable WXWrite: the function is called directly by interpreter.
1134   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
1135 
1136   // frequency_counter_overflow_inner can throw async exception.
1137   nmethod* nm = frequency_counter_overflow_inner(current, branch_bcp);
1138   assert(branch_bcp != nullptr || nm == nullptr, "always returns null for non OSR requests");
1139   if (branch_bcp != nullptr && nm != nullptr) {
1140     // This was a successful request for an OSR nmethod.  Because
1141     // frequency_counter_overflow_inner ends with a safepoint check,
1142     // nm could have been unloaded so look it up again.  It's unsafe
1143     // to examine nm directly since it might have been freed and used
1144     // for something else.
1145     LastFrameAccessor last_frame(current);
1146     Method* method =  last_frame.method();
1147     int bci = method->bci_from(last_frame.bcp());
1148     nm = method->lookup_osr_nmethod_for(bci, CompLevel_none, false);
1149     BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
1150     if (nm != nullptr) {
1151       // in case the transition passed a safepoint we need to barrier this again
1152       if (!bs_nm->nmethod_osr_entry_barrier(nm)) {
1153         nm = nullptr;
1154       }
1155     }
1156   }
1157   if (nm != nullptr && current->is_interp_only_mode()) {
1158     // Normally we never get an nm if is_interp_only_mode() is true, because
1159     // policy()->event has a check for this and won't compile the method when
1160     // true. However, it's possible for is_interp_only_mode() to become true
1161     // during the compilation. We don't want to return the nm in that case
1162     // because we want to continue to execute interpreted.
1163     nm = nullptr;
1164   }
1165 #ifndef PRODUCT
1166   if (TraceOnStackReplacement) {
1167     if (nm != nullptr) {
1168       tty->print("OSR entry @ pc: " INTPTR_FORMAT ": ", p2i(nm->osr_entry()));
1169       nm->print();
1170     }
1171   }
1172 #endif
1173   return nm;
1174 }
1175 
1176 JRT_ENTRY(nmethod*,
1177           InterpreterRuntime::frequency_counter_overflow_inner(JavaThread* current, address branch_bcp))
1178   // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
1179   // flag, in case this method triggers classloading which will call into Java.
1180   UnlockFlagSaver fs(current);
1181 
1182   LastFrameAccessor last_frame(current);
1183   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1184   methodHandle method(current, last_frame.method());
1185   const int branch_bci = branch_bcp != nullptr ? method->bci_from(branch_bcp) : InvocationEntryBci;
1186   const int bci = branch_bcp != nullptr ? method->bci_from(last_frame.bcp()) : InvocationEntryBci;
1187 
1188   nmethod* osr_nm = CompilationPolicy::event(method, method, branch_bci, bci, CompLevel_none, nullptr, CHECK_NULL);
1189 
1190   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
1191   if (osr_nm != nullptr) {
1192     if (!bs_nm->nmethod_osr_entry_barrier(osr_nm)) {
1193       osr_nm = nullptr;
1194     }
1195   }
1196   return osr_nm;
1197 JRT_END
1198 
1199 JRT_LEAF(jint, InterpreterRuntime::bcp_to_di(Method* method, address cur_bcp))
1200   assert(ProfileInterpreter, "must be profiling interpreter");
1201   int bci = method->bci_from(cur_bcp);
1202   MethodData* mdo = method->method_data();
1203   if (mdo == nullptr)  return 0;
1204   return mdo->bci_to_di(bci);
1205 JRT_END
1206 
1207 #ifdef ASSERT
1208 JRT_LEAF(void, InterpreterRuntime::verify_mdp(Method* method, address bcp, address mdp))
1209   assert(ProfileInterpreter, "must be profiling interpreter");
1210 
1211   MethodData* mdo = method->method_data();
1212   assert(mdo != nullptr, "must not be null");
1213 
1214   int bci = method->bci_from(bcp);
1215 
1216   address mdp2 = mdo->bci_to_dp(bci);
1217   if (mdp != mdp2) {
1218     ResourceMark rm;
1219     tty->print_cr("FAILED verify : actual mdp %p   expected mdp %p @ bci %d", mdp, mdp2, bci);
1220     int current_di = mdo->dp_to_di(mdp);
1221     int expected_di  = mdo->dp_to_di(mdp2);
1222     tty->print_cr("  actual di %d   expected di %d", current_di, expected_di);
1223     int expected_approx_bci = mdo->data_at(expected_di)->bci();
1224     int approx_bci = -1;
1225     if (current_di >= 0) {
1226       approx_bci = mdo->data_at(current_di)->bci();
1227     }
1228     tty->print_cr("  actual bci is %d  expected bci %d", approx_bci, expected_approx_bci);
1229     mdo->print_on(tty);
1230     method->print_codes();
1231   }
1232   assert(mdp == mdp2, "wrong mdp");
1233 JRT_END
1234 #endif // ASSERT
1235 
1236 JRT_ENTRY(void, InterpreterRuntime::update_mdp_for_ret(JavaThread* current, int return_bci))
1237   assert(ProfileInterpreter, "must be profiling interpreter");
1238   ResourceMark rm(current);
1239   LastFrameAccessor last_frame(current);
1240   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1241   MethodData* h_mdo = last_frame.method()->method_data();
1242 
1243   // Grab a lock to ensure atomic access to setting the return bci and
1244   // the displacement.  This can block and GC, invalidating all naked oops.
1245   MutexLocker ml(RetData_lock);
1246 
1247   // ProfileData is essentially a wrapper around a derived oop, so we
1248   // need to take the lock before making any ProfileData structures.
1249   ProfileData* data = h_mdo->data_at(h_mdo->dp_to_di(last_frame.mdp()));
1250   guarantee(data != nullptr, "profile data must be valid");
1251   RetData* rdata = data->as_RetData();
1252   address new_mdp = rdata->fixup_ret(return_bci, h_mdo);
1253   last_frame.set_mdp(new_mdp);
1254 JRT_END
1255 
1256 JRT_ENTRY(MethodCounters*, InterpreterRuntime::build_method_counters(JavaThread* current, Method* m))
1257   return Method::build_method_counters(current, m);
1258 JRT_END
1259 
1260 
1261 JRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* current))
1262   // We used to need an explicit preserve_arguments here for invoke bytecodes. However,
1263   // stack traversal automatically takes care of preserving arguments for invoke, so
1264   // this is no longer needed.
1265 
1266   // JRT_END does an implicit safepoint check, hence we are guaranteed to block
1267   // if this is called during a safepoint
1268 
1269   if (JvmtiExport::should_post_single_step()) {
1270     // This function is called by the interpreter when single stepping. Such single
1271     // stepping could unwind a frame. Then, it is important that we process any frames
1272     // that we might return into.
1273     StackWatermarkSet::before_unwind(current);
1274 
1275     // We are called during regular safepoints and when the VM is
1276     // single stepping. If any thread is marked for single stepping,
1277     // then we may have JVMTI work to do.
1278     LastFrameAccessor last_frame(current);
1279     JvmtiExport::at_single_stepping_point(current, last_frame.method(), last_frame.bcp());
1280   }
1281 JRT_END
1282 
1283 JRT_LEAF(void, InterpreterRuntime::at_unwind(JavaThread* current))
1284   assert(current == JavaThread::current(), "pre-condition");
1285   JFR_ONLY(Jfr::check_and_process_sample_request(current);)
1286   // This function is called by the interpreter when the return poll found a reason
1287   // to call the VM. The reason could be that we are returning into a not yet safe
1288   // to access frame. We handle that below.
1289   // Note that this path does not check for single stepping, because we do not want
1290   // to single step when unwinding frames for an exception being thrown. Instead,
1291   // such single stepping code will use the safepoint table, which will use the
1292   // InterpreterRuntime::at_safepoint callback.
1293   StackWatermarkSet::before_unwind(current);
1294 JRT_END
1295 
1296 JRT_ENTRY(void, InterpreterRuntime::post_field_access(JavaThread* current, oopDesc* obj,
1297                                                       ResolvedFieldEntry *entry))
1298 
1299   assert(entry->is_valid(), "Invalid ResolvedFieldEntry");
1300   // check the access_flags for the field in the klass
1301 
1302   InstanceKlass* ik = entry->field_holder();
1303   int index = entry->field_index();
1304   if (!ik->field_status(index).is_access_watched()) return;
1305 
1306   bool is_static = (obj == nullptr);
1307   bool is_flat = entry->is_flat();
1308   HandleMark hm(current);
1309 
1310   Handle h_obj;
1311   if (!is_static) {
1312     // non-static field accessors have an object, but we need a handle
1313     h_obj = Handle(current, obj);
1314   }
1315   InstanceKlass* field_holder = entry->field_holder(); // HERE
1316   jfieldID fid = jfieldIDWorkaround::to_jfieldID(field_holder, entry->field_offset(), is_static, is_flat);
1317   LastFrameAccessor last_frame(current);
1318   JvmtiExport::post_field_access(current, last_frame.method(), last_frame.bcp(), field_holder, h_obj, fid);
1319 JRT_END
1320 
1321 JRT_ENTRY(void, InterpreterRuntime::post_field_modification(JavaThread* current, oopDesc* obj,
1322                                                             ResolvedFieldEntry *entry, jvalue *value))
1323 
1324   assert(entry->is_valid(), "Invalid ResolvedFieldEntry");
1325   InstanceKlass* ik = entry->field_holder();
1326 
1327   // check the access_flags for the field in the klass
1328   int index = entry->field_index();
1329   // bail out if field modifications are not watched
1330   if (!ik->field_status(index).is_modification_watched()) return;
1331 
1332   char sig_type = '\0';
1333 
1334   switch((TosState)entry->tos_state()) {
1335     case btos: sig_type = JVM_SIGNATURE_BYTE;    break;
1336     case ztos: sig_type = JVM_SIGNATURE_BOOLEAN; break;
1337     case ctos: sig_type = JVM_SIGNATURE_CHAR;    break;
1338     case stos: sig_type = JVM_SIGNATURE_SHORT;   break;
1339     case itos: sig_type = JVM_SIGNATURE_INT;     break;
1340     case ftos: sig_type = JVM_SIGNATURE_FLOAT;   break;
1341     case atos: sig_type = JVM_SIGNATURE_CLASS;   break;
1342     case ltos: sig_type = JVM_SIGNATURE_LONG;    break;
1343     case dtos: sig_type = JVM_SIGNATURE_DOUBLE;  break;
1344     default:  ShouldNotReachHere(); return;
1345   }
1346 
1347   bool is_static = (obj == nullptr);
1348   bool is_flat = entry->is_flat();
1349 
1350   HandleMark hm(current);
1351   jfieldID fid = jfieldIDWorkaround::to_jfieldID(ik, entry->field_offset(), is_static, is_flat);
1352   jvalue fvalue;
1353 #ifdef _LP64
1354   fvalue = *value;
1355 #else
1356   // Long/double values are stored unaligned and also noncontiguously with
1357   // tagged stacks.  We can't just do a simple assignment even in the non-
1358   // J/D cases because a C++ compiler is allowed to assume that a jvalue is
1359   // 8-byte aligned, and interpreter stack slots are only 4-byte aligned.
1360   // We assume that the two halves of longs/doubles are stored in interpreter
1361   // stack slots in platform-endian order.
1362   jlong_accessor u;
1363   jint* newval = (jint*)value;
1364   u.words[0] = newval[0];
1365   u.words[1] = newval[Interpreter::stackElementWords]; // skip if tag
1366   fvalue.j = u.long_value;
1367 #endif // _LP64
1368 
1369   Handle h_obj;
1370   if (!is_static) {
1371     // non-static field accessors have an object, but we need a handle
1372     h_obj = Handle(current, obj);
1373   }
1374 
1375   LastFrameAccessor last_frame(current);
1376   JvmtiExport::post_raw_field_modification(current, last_frame.method(), last_frame.bcp(), ik, h_obj,
1377                                            fid, sig_type, &fvalue);
1378 JRT_END
1379 
1380 JRT_ENTRY(void, InterpreterRuntime::post_method_entry(JavaThread* current))
1381   LastFrameAccessor last_frame(current);
1382   JvmtiExport::post_method_entry(current, last_frame.method(), last_frame.get_frame());
1383 JRT_END
1384 
1385 
1386 // This is a JRT_BLOCK_ENTRY because we have to stash away the return oop
1387 // before transitioning to VM, and restore it after transitioning back
1388 // to Java. The return oop at the top-of-stack, is not walked by the GC.
1389 JRT_BLOCK_ENTRY(void, InterpreterRuntime::post_method_exit(JavaThread* current))
1390   LastFrameAccessor last_frame(current);
1391   JvmtiExport::post_method_exit(current, last_frame.method(), last_frame.get_frame());
1392 JRT_END
1393 
1394 JRT_LEAF(int, InterpreterRuntime::interpreter_contains(address pc))
1395 {
1396   return (Interpreter::contains(Continuation::get_top_return_pc_post_barrier(JavaThread::current(), pc)) ? 1 : 0);
1397 }
1398 JRT_END
1399 
1400 
1401 // Implementation of SignatureHandlerLibrary
1402 
1403 #ifndef SHARING_FAST_NATIVE_FINGERPRINTS
1404 // Dummy definition (else normalization method is defined in CPU
1405 // dependent code)
1406 uint64_t InterpreterRuntime::normalize_fast_native_fingerprint(uint64_t fingerprint) {
1407   return fingerprint;
1408 }
1409 #endif
1410 
1411 address SignatureHandlerLibrary::set_handler_blob() {
1412   BufferBlob* handler_blob = BufferBlob::create("native signature handlers", blob_size);
1413   if (handler_blob == nullptr) {
1414     return nullptr;
1415   }
1416   address handler = handler_blob->code_begin();
1417   _handler_blob = handler_blob;
1418   _handler = handler;
1419   return handler;
1420 }
1421 
1422 void SignatureHandlerLibrary::initialize() {
1423   if (_fingerprints != nullptr) {
1424     return;
1425   }
1426   if (set_handler_blob() == nullptr) {
1427     vm_exit_out_of_memory(blob_size, OOM_MALLOC_ERROR, "native signature handlers");
1428   }
1429 
1430   BufferBlob* bb = BufferBlob::create("Signature Handler Temp Buffer",
1431                                       SignatureHandlerLibrary::buffer_size);
1432   _buffer = bb->code_begin();
1433 
1434   _fingerprints = new (mtCode) GrowableArray<uint64_t>(32, mtCode);
1435   _handlers     = new (mtCode) GrowableArray<address>(32, mtCode);
1436 }
1437 
1438 address SignatureHandlerLibrary::set_handler(CodeBuffer* buffer) {
1439   address handler   = _handler;
1440   int     insts_size = buffer->pure_insts_size();
1441   if (handler + insts_size > _handler_blob->code_end()) {
1442     // get a new handler blob
1443     handler = set_handler_blob();
1444   }
1445   if (handler != nullptr) {
1446     memcpy(handler, buffer->insts_begin(), insts_size);
1447     pd_set_handler(handler);
1448     ICache::invalidate_range(handler, insts_size);
1449     _handler = handler + insts_size;
1450   }
1451   return handler;
1452 }
1453 
1454 void SignatureHandlerLibrary::add(const methodHandle& method) {
1455   if (method->signature_handler() == nullptr) {
1456     // use slow signature handler if we can't do better
1457     int handler_index = -1;
1458     // check if we can use customized (fast) signature handler
1459     if (UseFastSignatureHandlers && method->size_of_parameters() <= Fingerprinter::fp_max_size_of_parameters) {
1460       // use customized signature handler
1461       MutexLocker mu(SignatureHandlerLibrary_lock);
1462       // make sure data structure is initialized
1463       initialize();
1464       // lookup method signature's fingerprint
1465       uint64_t fingerprint = Fingerprinter(method).fingerprint();
1466       // allow CPU dependent code to optimize the fingerprints for the fast handler
1467       fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1468       handler_index = _fingerprints->find(fingerprint);
1469       // create handler if necessary
1470       if (handler_index < 0) {
1471         ResourceMark rm;
1472         ptrdiff_t align_offset = align_up(_buffer, CodeEntryAlignment) - (address)_buffer;
1473         CodeBuffer buffer((address)(_buffer + align_offset),
1474                           checked_cast<int>(SignatureHandlerLibrary::buffer_size - align_offset));
1475         InterpreterRuntime::SignatureHandlerGenerator(method, &buffer).generate(fingerprint);
1476         // copy into code heap
1477         address handler = set_handler(&buffer);
1478         if (handler == nullptr) {
1479           // use slow signature handler (without memorizing it in the fingerprints)
1480         } else {
1481           // debugging support
1482           if (PrintSignatureHandlers && (handler != Interpreter::slow_signature_handler())) {
1483             ttyLocker ttyl;
1484             tty->cr();
1485             tty->print_cr("argument handler #%d for: %s %s (fingerprint = " UINT64_FORMAT ", %d bytes generated)",
1486                           _handlers->length(),
1487                           (method->is_static() ? "static" : "receiver"),
1488                           method->name_and_sig_as_C_string(),
1489                           fingerprint,
1490                           buffer.insts_size());
1491             if (buffer.insts_size() > 0) {
1492               Disassembler::decode(handler, handler + buffer.insts_size(), tty
1493                                    NOT_PRODUCT(COMMA &buffer.asm_remarks()));
1494             }
1495 #ifndef PRODUCT
1496             address rh_begin = Interpreter::result_handler(method()->result_type());
1497             if (CodeCache::contains(rh_begin)) {
1498               // else it might be special platform dependent values
1499               tty->print_cr(" --- associated result handler ---");
1500               address rh_end = rh_begin;
1501               while (*(int*)rh_end != 0) {
1502                 rh_end += sizeof(int);
1503               }
1504               Disassembler::decode(rh_begin, rh_end);
1505             } else {
1506               tty->print_cr(" associated result handler: " PTR_FORMAT, p2i(rh_begin));
1507             }
1508 #endif
1509           }
1510           // add handler to library
1511           _fingerprints->append(fingerprint);
1512           _handlers->append(handler);
1513           // set handler index
1514           assert(_fingerprints->length() == _handlers->length(), "sanity check");
1515           handler_index = _fingerprints->length() - 1;
1516         }
1517       }
1518       // Set handler under SignatureHandlerLibrary_lock
1519       if (handler_index < 0) {
1520         // use generic signature handler
1521         method->set_signature_handler(Interpreter::slow_signature_handler());
1522       } else {
1523         // set handler
1524         method->set_signature_handler(_handlers->at(handler_index));
1525       }
1526     } else {
1527       DEBUG_ONLY(JavaThread::current()->check_possible_safepoint());
1528       // use generic signature handler
1529       method->set_signature_handler(Interpreter::slow_signature_handler());
1530     }
1531   }
1532 #ifdef ASSERT
1533   int handler_index = -1;
1534   int fingerprint_index = -2;
1535   {
1536     // '_handlers' and '_fingerprints' are 'GrowableArray's and are NOT synchronized
1537     // in any way if accessed from multiple threads. To avoid races with another
1538     // thread which may change the arrays in the above, mutex protected block, we
1539     // have to protect this read access here with the same mutex as well!
1540     MutexLocker mu(SignatureHandlerLibrary_lock);
1541     if (_handlers != nullptr) {
1542       handler_index = _handlers->find(method->signature_handler());
1543       uint64_t fingerprint = Fingerprinter(method).fingerprint();
1544       fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1545       fingerprint_index = _fingerprints->find(fingerprint);
1546     }
1547   }
1548   assert(method->signature_handler() == Interpreter::slow_signature_handler() ||
1549          handler_index == fingerprint_index, "sanity check");
1550 #endif // ASSERT
1551 }
1552 
1553 BufferBlob*              SignatureHandlerLibrary::_handler_blob = nullptr;
1554 address                  SignatureHandlerLibrary::_handler      = nullptr;
1555 GrowableArray<uint64_t>* SignatureHandlerLibrary::_fingerprints = nullptr;
1556 GrowableArray<address>*  SignatureHandlerLibrary::_handlers     = nullptr;
1557 address                  SignatureHandlerLibrary::_buffer       = nullptr;
1558 
1559 
1560 JRT_ENTRY(void, InterpreterRuntime::prepare_native_call(JavaThread* current, Method* method))
1561   methodHandle m(current, method);
1562   assert(m->is_native(), "sanity check");
1563   // lookup native function entry point if it doesn't exist
1564   if (!m->has_native_function()) {
1565     NativeLookup::lookup(m, CHECK);
1566   }
1567   // make sure signature handler is installed
1568   SignatureHandlerLibrary::add(m);
1569   // The interpreter entry point checks the signature handler first,
1570   // before trying to fetch the native entry point and klass mirror.
1571   // We must set the signature handler last, so that multiple processors
1572   // preparing the same method will be sure to see non-null entry & mirror.
1573 JRT_END
1574 
1575 #if defined(AMD64) || defined(ARM)
1576 JRT_LEAF(void, InterpreterRuntime::popframe_move_outgoing_args(JavaThread* current, void* src_address, void* dest_address))
1577   assert(current == JavaThread::current(), "pre-condition");
1578   if (src_address == dest_address) {
1579     return;
1580   }
1581   ResourceMark rm;
1582   LastFrameAccessor last_frame(current);
1583   assert(last_frame.is_interpreted_frame(), "");
1584   jint bci = last_frame.bci();
1585   methodHandle mh(current, last_frame.method());
1586   Bytecode_invoke invoke(mh, bci);
1587   ArgumentSizeComputer asc(invoke.signature());
1588   int size_of_arguments = (asc.size() + (invoke.has_receiver() ? 1 : 0)); // receiver
1589   Copy::conjoint_jbytes(src_address, dest_address,
1590                        size_of_arguments * Interpreter::stackElementSize);
1591 JRT_END
1592 #endif
1593 
1594 #if INCLUDE_JVMTI
1595 // This is a support of the JVMTI PopFrame interface.
1596 // Make sure it is an invokestatic of a polymorphic intrinsic that has a member_name argument
1597 // and return it as a vm_result_oop so that it can be reloaded in the list of invokestatic parameters.
1598 // The member_name argument is a saved reference (in local#0) to the member_name.
1599 // For backward compatibility with some JDK versions (7, 8) it can also be a direct method handle.
1600 // FIXME: remove DMH case after j.l.i.InvokerBytecodeGenerator code shape is updated.
1601 JRT_ENTRY(void, InterpreterRuntime::member_name_arg_or_null(JavaThread* current, address member_name,
1602                                                             Method* method, address bcp))
1603   Bytecodes::Code code = Bytecodes::code_at(method, bcp);
1604   if (code != Bytecodes::_invokestatic) {
1605     return;
1606   }
1607   ConstantPool* cpool = method->constants();
1608   int cp_index = Bytes::get_native_u2(bcp + 1);
1609   Symbol* cname = cpool->klass_name_at(cpool->klass_ref_index_at(cp_index, code));
1610   Symbol* mname = cpool->name_ref_at(cp_index, code);
1611 
1612   if (MethodHandles::has_member_arg(cname, mname)) {
1613     oop member_name_oop = cast_to_oop(member_name);
1614     if (java_lang_invoke_DirectMethodHandle::is_instance(member_name_oop)) {
1615       // FIXME: remove after j.l.i.InvokerBytecodeGenerator code shape is updated.
1616       member_name_oop = java_lang_invoke_DirectMethodHandle::member(member_name_oop);
1617     }
1618     current->set_vm_result_oop(member_name_oop);
1619   } else {
1620     current->set_vm_result_oop(nullptr);
1621   }
1622 JRT_END
1623 #endif // INCLUDE_JVMTI
1624 
1625 #ifndef PRODUCT
1626 // This must be a JRT_LEAF function because the interpreter must save registers on x86 to
1627 // call this, which changes rsp and makes the interpreter's expression stack not walkable.
1628 // The generated code still uses call_VM because that will set up the frame pointer for
1629 // bcp and method.
1630 JRT_LEAF(intptr_t, InterpreterRuntime::trace_bytecode(JavaThread* current, intptr_t preserve_this_value, intptr_t tos, intptr_t tos2))
1631   assert(current == JavaThread::current(), "pre-condition");
1632   LastFrameAccessor last_frame(current);
1633   assert(last_frame.is_interpreted_frame(), "must be an interpreted frame");
1634   methodHandle mh(current, last_frame.method());
1635   BytecodeTracer::trace_interpreter(mh, last_frame.bcp(), tos, tos2);
1636   return preserve_this_value;
1637 JRT_END
1638 #endif // !PRODUCT