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