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