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