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