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