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