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 "precompiled.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "classfile/symbolTable.hpp"
  28 #include "classfile/systemDictionary.hpp"
  29 #include "classfile/vmClasses.hpp"
  30 #include "classfile/vmSymbols.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "compiler/compilationPolicy.hpp"
  33 #include "compiler/compileBroker.hpp"
  34 #include "compiler/disassembler.hpp"
  35 #include "gc/shared/barrierSetNMethod.hpp"
  36 #include "gc/shared/collectedHeap.hpp"
  37 #include "interpreter/bytecodeTracer.hpp"
  38 #include "interpreter/interpreter.hpp"
  39 #include "interpreter/interpreterRuntime.hpp"
  40 #include "interpreter/linkResolver.hpp"
  41 #include "interpreter/templateTable.hpp"
  42 #include "jvm_io.h"
  43 #include "logging/log.hpp"
  44 #include "memory/oopFactory.hpp"
  45 #include "memory/resourceArea.hpp"
  46 #include "memory/universe.hpp"
  47 #include "oops/constantPool.inline.hpp"
  48 #include "oops/cpCache.inline.hpp"
  49 #include "oops/flatArrayKlass.hpp"
  50 #include "oops/flatArrayOop.inline.hpp"
  51 #include "oops/inlineKlass.inline.hpp"
  52 #include "oops/instanceKlass.inline.hpp"
  53 #include "oops/klass.inline.hpp"
  54 #include "oops/methodData.hpp"
  55 #include "oops/method.inline.hpp"
  56 #include "oops/objArrayKlass.hpp"
  57 #include "oops/objArrayOop.inline.hpp"
  58 #include "oops/oop.inline.hpp"
  59 #include "oops/symbol.hpp"
  60 #include "prims/jvmtiExport.hpp"
  61 #include "prims/methodHandles.hpp"
  62 #include "prims/nativeLookup.hpp"
  63 #include "runtime/atomic.hpp"
  64 #include "runtime/continuation.hpp"
  65 #include "runtime/deoptimization.hpp"
  66 #include "runtime/fieldDescriptor.inline.hpp"
  67 #include "runtime/frame.inline.hpp"
  68 #include "runtime/handles.inline.hpp"
  69 #include "runtime/icache.hpp"
  70 #include "runtime/interfaceSupport.inline.hpp"
  71 #include "runtime/java.hpp"
  72 #include "runtime/javaCalls.hpp"
  73 #include "runtime/jfieldIDWorkaround.hpp"
  74 #include "runtime/osThread.hpp"
  75 #include "runtime/sharedRuntime.hpp"
  76 #include "runtime/stackWatermarkSet.hpp"
  77 #include "runtime/stubRoutines.hpp"
  78 #include "runtime/synchronizer.inline.hpp"
  79 #include "runtime/threadCritical.hpp"
  80 #include "utilities/align.hpp"
  81 #include "utilities/checkedCast.hpp"
  82 #include "utilities/copy.hpp"
  83 #include "utilities/events.hpp"
  84 #include "utilities/globalDefinitions.hpp"
  85 #ifdef COMPILER2
  86 #include "opto/runtime.hpp"
  87 #endif
  88 
  89 // Helper class to access current interpreter state
  90 class LastFrameAccessor : public StackObj {
  91   frame _last_frame;
  92 public:
  93   LastFrameAccessor(JavaThread* current) {
  94     assert(current == Thread::current(), "sanity");
  95     _last_frame = current->last_frame();
  96   }
  97   bool is_interpreted_frame() const              { return _last_frame.is_interpreted_frame(); }
  98   Method*   method() const                       { return _last_frame.interpreter_frame_method(); }
  99   address   bcp() const                          { return _last_frame.interpreter_frame_bcp(); }
 100   int       bci() const                          { return _last_frame.interpreter_frame_bci(); }
 101   address   mdp() const                          { return _last_frame.interpreter_frame_mdp(); }
 102 
 103   void      set_bcp(address bcp)                 { _last_frame.interpreter_frame_set_bcp(bcp); }
 104   void      set_mdp(address dp)                  { _last_frame.interpreter_frame_set_mdp(dp); }
 105 
 106   // pass method to avoid calling unsafe bcp_to_method (partial fix 4926272)
 107   Bytecodes::Code code() const                   { return Bytecodes::code_at(method(), bcp()); }
 108 
 109   Bytecode  bytecode() const                     { return Bytecode(method(), bcp()); }
 110   int get_index_u1(Bytecodes::Code bc) const     { return bytecode().get_index_u1(bc); }
 111   int get_index_u2(Bytecodes::Code bc) const     { return bytecode().get_index_u2(bc); }
 112   int get_index_u4(Bytecodes::Code bc) const     { return bytecode().get_index_u4(bc); }
 113   int number_of_dimensions() const               { return bcp()[3]; }
 114 
 115   oop callee_receiver(Symbol* signature) {
 116     return _last_frame.interpreter_callee_receiver(signature);
 117   }
 118   BasicObjectLock* monitor_begin() const {
 119     return _last_frame.interpreter_frame_monitor_begin();
 120   }
 121   BasicObjectLock* monitor_end() const {
 122     return _last_frame.interpreter_frame_monitor_end();
 123   }
 124   BasicObjectLock* next_monitor(BasicObjectLock* current) const {
 125     return _last_frame.next_monitor_in_interpreter_frame(current);
 126   }
 127 
 128   frame& get_frame()                             { return _last_frame; }
 129 };
 130 
 131 //------------------------------------------------------------------------------------------------------------------------
 132 // State accessors
 133 
 134 void InterpreterRuntime::set_bcp_and_mdp(address bcp, JavaThread* current) {
 135   LastFrameAccessor last_frame(current);
 136   last_frame.set_bcp(bcp);
 137   if (ProfileInterpreter) {
 138     // ProfileTraps uses MDOs independently of ProfileInterpreter.
 139     // That is why we must check both ProfileInterpreter and mdo != nullptr.
 140     MethodData* mdo = last_frame.method()->method_data();
 141     if (mdo != nullptr) {
 142       NEEDS_CLEANUP;
 143       last_frame.set_mdp(mdo->bci_to_dp(last_frame.bci()));
 144     }
 145   }
 146 }
 147 
 148 //------------------------------------------------------------------------------------------------------------------------
 149 // Constants
 150 
 151 
 152 JRT_ENTRY(void, InterpreterRuntime::ldc(JavaThread* current, bool wide))
 153   // access constant pool
 154   LastFrameAccessor last_frame(current);
 155   ConstantPool* pool = last_frame.method()->constants();
 156   int cp_index = wide ? last_frame.get_index_u2(Bytecodes::_ldc_w) : last_frame.get_index_u1(Bytecodes::_ldc);
 157   constantTag tag = pool->tag_at(cp_index);
 158 
 159   assert (tag.is_unresolved_klass() || tag.is_klass(), "wrong ldc call");
 160   Klass* klass = pool->klass_at(cp_index, CHECK);
 161   oop java_class = klass->java_mirror();
 162   current->set_vm_result(java_class);
 163 JRT_END
 164 
 165 JRT_ENTRY(void, InterpreterRuntime::resolve_ldc(JavaThread* current, Bytecodes::Code bytecode)) {
 166   assert(bytecode == Bytecodes::_ldc ||
 167          bytecode == Bytecodes::_ldc_w ||
 168          bytecode == Bytecodes::_ldc2_w ||
 169          bytecode == Bytecodes::_fast_aldc ||
 170          bytecode == Bytecodes::_fast_aldc_w, "wrong bc");
 171   ResourceMark rm(current);
 172   const bool is_fast_aldc = (bytecode == Bytecodes::_fast_aldc ||
 173                              bytecode == Bytecodes::_fast_aldc_w);
 174   LastFrameAccessor last_frame(current);
 175   methodHandle m (current, last_frame.method());
 176   Bytecode_loadconstant ldc(m, last_frame.bci());
 177 
 178   // Double-check the size.  (Condy can have any type.)
 179   BasicType type = ldc.result_type();
 180   switch (type2size[type]) {
 181   case 2: guarantee(bytecode == Bytecodes::_ldc2_w, ""); break;
 182   case 1: guarantee(bytecode != Bytecodes::_ldc2_w, ""); break;
 183   default: ShouldNotReachHere();
 184   }
 185 
 186   // Resolve the constant.  This does not do unboxing.
 187   // But it does replace Universe::the_null_sentinel by null.
 188   oop result = ldc.resolve_constant(CHECK);
 189   assert(result != nullptr || is_fast_aldc, "null result only valid for fast_aldc");
 190 
 191 #ifdef ASSERT
 192   {
 193     // The bytecode wrappers aren't GC-safe so construct a new one
 194     Bytecode_loadconstant ldc2(m, last_frame.bci());
 195     int rindex = ldc2.cache_index();
 196     if (rindex < 0)
 197       rindex = m->constants()->cp_to_object_index(ldc2.pool_index());
 198     if (rindex >= 0) {
 199       oop coop = m->constants()->resolved_reference_at(rindex);
 200       oop roop = (result == nullptr ? Universe::the_null_sentinel() : result);
 201       assert(roop == coop, "expected result for assembly code");
 202     }
 203   }
 204 #endif
 205   current->set_vm_result(result);
 206   if (!is_fast_aldc) {
 207     // Tell the interpreter how to unbox the primitive.
 208     guarantee(java_lang_boxing_object::is_instance(result, type), "");
 209     int offset = java_lang_boxing_object::value_offset(type);
 210     intptr_t flags = ((as_TosState(type) << ConstantPoolCache::tos_state_shift)
 211                       | (offset & ConstantPoolCache::field_index_mask));
 212     current->set_vm_result_2((Metadata*)flags);
 213   }
 214 }
 215 JRT_END
 216 
 217 
 218 //------------------------------------------------------------------------------------------------------------------------
 219 // Allocation
 220 
 221 JRT_ENTRY(void, InterpreterRuntime::_new(JavaThread* current, ConstantPool* pool, int index))
 222   Klass* k = pool->klass_at(index, CHECK);
 223   InstanceKlass* klass = InstanceKlass::cast(k);
 224 
 225   // Make sure we are not instantiating an abstract klass
 226   klass->check_valid_for_instantiation(true, CHECK);
 227 
 228   // Make sure klass is initialized
 229   klass->initialize(CHECK);
 230 
 231   oop obj = klass->allocate_instance(CHECK);
 232   current->set_vm_result(obj);
 233 JRT_END
 234 
 235 JRT_ENTRY(void, InterpreterRuntime::uninitialized_static_inline_type_field(JavaThread* current, oopDesc* mirror, ResolvedFieldEntry* entry))
 236   // The interpreter tries to access an inline static field that has not been initialized.
 237   // This situation can happen in different scenarios:
 238   //   1 - if the load or initialization of the field failed during step 8 of
 239   //       the initialization of the holder of the field, in this case the access to the field
 240   //       must fail
 241   //   2 - it can also happen when the initialization of the holder class triggered the initialization of
 242   //       another class which accesses this field in its static initializer, in this case the
 243   //       access must succeed to allow circularity
 244   // The code below tries to load and initialize the field's class again before returning the default value.
 245   // If the field was not initialized because of an error, an exception should be thrown.
 246   // If the class is being initialized, the default value is returned.
 247   assert(entry->is_valid(), "Invalid ResolvedFieldEntry");
 248   instanceHandle mirror_h(THREAD, (instanceOop)mirror);
 249   InstanceKlass* klass = entry->field_holder();
 250   u2 index = entry->field_index();
 251   assert(klass == java_lang_Class::as_Klass(mirror), "Not the field holder klass");
 252   assert(klass->field_is_null_free_inline_type(index), "Sanity check");
 253   if (klass->is_being_initialized() && klass->is_reentrant_initialization(THREAD)) {
 254     int offset = klass->field_offset(index);
 255     Klass* field_k = klass->get_inline_type_field_klass_or_null(index);
 256     if (field_k == nullptr) {
 257       field_k = SystemDictionary::resolve_or_fail(klass->field_signature(index)->fundamental_name(THREAD),
 258           Handle(THREAD, klass->class_loader()),
 259           Handle(THREAD, klass->protection_domain()),
 260           true, CHECK);
 261       assert(field_k != nullptr, "Should have been loaded or an exception thrown above");
 262       if (!field_k->is_inline_klass()) {
 263         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
 264                   err_msg("class %s expects class %s to be a concrete value class but it is not",
 265                   klass->name()->as_C_string(), field_k->external_name()));
 266       }
 267       InlineLayoutInfo* li = klass->inline_layout_info_adr(index);
 268       li->set_klass(InlineKlass::cast(field_k));
 269       li->set_kind(LayoutKind::REFERENCE);
 270     }
 271     field_k->initialize(CHECK);
 272     oop defaultvalue = InlineKlass::cast(field_k)->default_value();
 273     // It is safe to initialize the static field because 1) the current thread is the initializing thread
 274     // and is the only one that can access it, and 2) the field is actually not initialized (i.e. null)
 275     // otherwise the JVM should not be executing this code.
 276     mirror_h()->obj_field_put(offset, defaultvalue);
 277     current->set_vm_result(defaultvalue);
 278   } else {
 279     assert(klass->is_in_error_state(), "If not initializing, initialization must have failed to get there");
 280     ResourceMark rm(THREAD);
 281     const char* desc = "Could not initialize class ";
 282     const char* className = klass->external_name();
 283     size_t msglen = strlen(desc) + strlen(className) + 1;
 284     char* message = NEW_RESOURCE_ARRAY(char, msglen);
 285     if (nullptr == message) {
 286       // Out of memory: can't create detailed error message
 287       THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
 288     } else {
 289       jio_snprintf(message, msglen, "%s%s", desc, className);
 290       THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
 291     }
 292   }
 293 JRT_END
 294 
 295 JRT_ENTRY(void, InterpreterRuntime::read_flat_field(JavaThread* current, oopDesc* obj, ResolvedFieldEntry* entry))
 296   assert(oopDesc::is_oop(obj), "Sanity check");
 297   Handle obj_h(THREAD, obj);
 298 
 299   InstanceKlass* holder = InstanceKlass::cast(entry->field_holder());
 300   assert(entry->field_holder()->field_is_flat(entry->field_index()), "Sanity check");
 301 
 302   InlineLayoutInfo* layout_info = holder->inline_layout_info_adr(entry->field_index());
 303   InlineKlass* field_vklass = layout_info->klass();
 304 
 305 #ifdef ASSERT
 306   fieldDescriptor fd;
 307   bool found = holder->find_field_from_offset(entry->field_offset(), false, &fd);
 308   assert(found, "Field not found");
 309   assert(fd.is_flat(), "Field must be flat");
 310 #endif // ASSERT
 311 
 312   oop res = field_vklass->read_payload_from_addr(obj_h(), entry->field_offset(), layout_info->kind(), CHECK);
 313   current->set_vm_result(res);
 314 JRT_END
 315 
 316 JRT_ENTRY(void, InterpreterRuntime::read_nullable_flat_field(JavaThread* current, oopDesc* obj, ResolvedFieldEntry* entry))
 317   assert(oopDesc::is_oop(obj), "Sanity check");
 318   assert(entry->has_null_marker(), "Otherwise should not get there");
 319   Handle obj_h(THREAD, obj);
 320 
 321   InstanceKlass* holder = entry->field_holder();
 322   int field_index = entry->field_index();
 323   InlineLayoutInfo* li= holder->inline_layout_info_adr(field_index);
 324 
 325 #ifdef ASSERT
 326   fieldDescriptor fd;
 327   bool found = holder->find_field_from_offset(entry->field_offset(), false, &fd);
 328   assert(found, "Field not found");
 329   assert(fd.is_flat(), "Field must be flat");
 330 #endif // ASSERT
 331 
 332   InlineKlass* field_vklass = InlineKlass::cast(li->klass());
 333   oop res = field_vklass->read_payload_from_addr(obj_h(), entry->field_offset(), li->kind(), CHECK);
 334   current->set_vm_result(res);
 335 
 336 JRT_END
 337 
 338 JRT_ENTRY(void, InterpreterRuntime::write_nullable_flat_field(JavaThread* current, oopDesc* obj, oopDesc* value, ResolvedFieldEntry* entry))
 339   assert(oopDesc::is_oop(obj), "Sanity check");
 340   Handle obj_h(THREAD, obj);
 341   assert(value == nullptr || oopDesc::is_oop(value), "Sanity check");
 342   Handle val_h(THREAD, value);
 343 
 344   InstanceKlass* holder = entry->field_holder();
 345   InlineLayoutInfo* li = holder->inline_layout_info_adr(entry->field_index());
 346   InlineKlass* vk = li->klass();
 347   vk->write_value_to_addr(val_h(), ((char*)(oopDesc*)obj_h()) + entry->field_offset(), li->kind(), true, CHECK);
 348 JRT_END
 349 
 350 JRT_ENTRY(void, 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(void, InterpreterRuntime::anewarray(JavaThread* current, ConstantPool* pool, int index, jint size))
 357   Klass*    klass = pool->klass_at(index, CHECK);
 358   arrayOop obj = oopFactory::new_objArray(klass, size, CHECK);
 359   current->set_vm_result(obj);
 360 JRT_END
 361 
 362 JRT_ENTRY(void, InterpreterRuntime::flat_array_load(JavaThread* current, arrayOopDesc* array, int index))
 363   assert(array->is_flatArray(), "Must be");
 364   flatArrayOop farray = (flatArrayOop)array;
 365   oop res = farray->read_value_from_flat_array(index, CHECK);
 366   current->set_vm_result(res);
 367 JRT_END
 368 
 369 JRT_ENTRY(void, InterpreterRuntime::flat_array_store(JavaThread* current, oopDesc* val, arrayOopDesc* array, int index))
 370   assert(array->is_flatArray(), "Must be");
 371   flatArrayOop farray = (flatArrayOop)array;
 372   farray->write_value_to_flat_array(val, index, CHECK);
 373 JRT_END
 374 
 375 JRT_ENTRY(void, InterpreterRuntime::multianewarray(JavaThread* current, jint* first_size_address))
 376   // We may want to pass in more arguments - could make this slightly faster
 377   LastFrameAccessor last_frame(current);
 378   ConstantPool* constants = last_frame.method()->constants();
 379   int i = last_frame.get_index_u2(Bytecodes::_multianewarray);
 380   Klass* klass = constants->klass_at(i, CHECK);
 381   int   nof_dims = last_frame.number_of_dimensions();
 382   assert(klass->is_klass(), "not a class");
 383   assert(nof_dims >= 1, "multianewarray rank must be nonzero");
 384 
 385   // We must create an array of jints to pass to multi_allocate.
 386   ResourceMark rm(current);
 387   const int small_dims = 10;
 388   jint dim_array[small_dims];
 389   jint *dims = &dim_array[0];
 390   if (nof_dims > small_dims) {
 391     dims = (jint*) NEW_RESOURCE_ARRAY(jint, nof_dims);
 392   }
 393   for (int index = 0; index < nof_dims; index++) {
 394     // offset from first_size_address is addressed as local[index]
 395     int n = Interpreter::local_offset_in_bytes(index)/jintSize;
 396     dims[index] = first_size_address[n];
 397   }
 398   oop obj = ArrayKlass::cast(klass)->multi_allocate(nof_dims, dims, CHECK);
 399   current->set_vm_result(obj);
 400 JRT_END
 401 
 402 
 403 JRT_ENTRY(void, InterpreterRuntime::register_finalizer(JavaThread* current, oopDesc* obj))
 404   assert(oopDesc::is_oop(obj), "must be a valid oop");
 405   assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise");
 406   InstanceKlass::register_finalizer(instanceOop(obj), CHECK);
 407 JRT_END
 408 
 409 JRT_ENTRY(jboolean, InterpreterRuntime::is_substitutable(JavaThread* current, oopDesc* aobj, oopDesc* bobj))
 410   assert(oopDesc::is_oop(aobj) && oopDesc::is_oop(bobj), "must be valid oops");
 411 
 412   Handle ha(THREAD, aobj);
 413   Handle hb(THREAD, bobj);
 414   JavaValue result(T_BOOLEAN);
 415   JavaCallArguments args;
 416   args.push_oop(ha);
 417   args.push_oop(hb);
 418   methodHandle method(current, Universe::is_substitutable_method());
 419   method->method_holder()->initialize(CHECK_false); // Ensure class ValueObjectMethods is initialized
 420   JavaCalls::call(&result, method, &args, THREAD);
 421   if (HAS_PENDING_EXCEPTION) {
 422     // Something really bad happened because isSubstitutable() should not throw exceptions
 423     // If it is an error, just let it propagate
 424     // If it is an exception, wrap it into an InternalError
 425     if (!PENDING_EXCEPTION->is_a(vmClasses::Error_klass())) {
 426       Handle e(THREAD, PENDING_EXCEPTION);
 427       CLEAR_PENDING_EXCEPTION;
 428       THROW_MSG_CAUSE_(vmSymbols::java_lang_InternalError(), "Internal error in substitutability test", e, false);
 429     }
 430   }
 431   return result.get_jboolean();
 432 JRT_END
 433 
 434 // Quicken instance-of and check-cast bytecodes
 435 JRT_ENTRY(void, InterpreterRuntime::quicken_io_cc(JavaThread* current))
 436   // Force resolving; quicken the bytecode
 437   LastFrameAccessor last_frame(current);
 438   int which = last_frame.get_index_u2(Bytecodes::_checkcast);
 439   ConstantPool* cpool = last_frame.method()->constants();
 440   // We'd expect to assert that we're only here to quicken bytecodes, but in a multithreaded
 441   // program we might have seen an unquick'd bytecode in the interpreter but have another
 442   // thread quicken the bytecode before we get here.
 443   // assert( cpool->tag_at(which).is_unresolved_klass(), "should only come here to quicken bytecodes" );
 444   Klass* klass = cpool->klass_at(which, CHECK);
 445   current->set_vm_result_2(klass);
 446 JRT_END
 447 
 448 
 449 //------------------------------------------------------------------------------------------------------------------------
 450 // Exceptions
 451 
 452 void InterpreterRuntime::note_trap_inner(JavaThread* current, int reason,
 453                                          const methodHandle& trap_method, int trap_bci) {
 454   if (trap_method.not_null()) {
 455     MethodData* trap_mdo = trap_method->method_data();
 456     if (trap_mdo == nullptr) {
 457       ExceptionMark em(current);
 458       JavaThread* THREAD = current; // For exception macros.
 459       Method::build_profiling_method_data(trap_method, THREAD);
 460       if (HAS_PENDING_EXCEPTION) {
 461         // Only metaspace OOM is expected. No Java code executed.
 462         assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())),
 463                "we expect only an OOM error here");
 464         CLEAR_PENDING_EXCEPTION;
 465       }
 466       trap_mdo = trap_method->method_data();
 467       // and fall through...
 468     }
 469     if (trap_mdo != nullptr) {
 470       // Update per-method count of trap events.  The interpreter
 471       // is updating the MDO to simulate the effect of compiler traps.
 472       Deoptimization::update_method_data_from_interpreter(trap_mdo, trap_bci, reason);
 473     }
 474   }
 475 }
 476 
 477 // Assume the compiler is (or will be) interested in this event.
 478 // If necessary, create an MDO to hold the information, and record it.
 479 void InterpreterRuntime::note_trap(JavaThread* current, int reason) {
 480   assert(ProfileTraps, "call me only if profiling");
 481   LastFrameAccessor last_frame(current);
 482   methodHandle trap_method(current, last_frame.method());
 483   int trap_bci = trap_method->bci_from(last_frame.bcp());
 484   note_trap_inner(current, reason, trap_method, trap_bci);
 485 }
 486 
 487 static Handle get_preinitialized_exception(Klass* k, TRAPS) {
 488   // get klass
 489   InstanceKlass* klass = InstanceKlass::cast(k);
 490   assert(klass->is_initialized(),
 491          "this klass should have been initialized during VM initialization");
 492   // create instance - do not call constructor since we may have no
 493   // (java) stack space left (should assert constructor is empty)
 494   Handle exception;
 495   oop exception_oop = klass->allocate_instance(CHECK_(exception));
 496   exception = Handle(THREAD, exception_oop);
 497   if (StackTraceInThrowable) {
 498     java_lang_Throwable::fill_in_stack_trace(exception);
 499   }
 500   return exception;
 501 }
 502 
 503 // Special handling for stack overflow: since we don't have any (java) stack
 504 // space left we use the pre-allocated & pre-initialized StackOverflowError
 505 // klass to create an stack overflow error instance.  We do not call its
 506 // constructor for the same reason (it is empty, anyway).
 507 JRT_ENTRY(void, InterpreterRuntime::throw_StackOverflowError(JavaThread* current))
 508   Handle exception = get_preinitialized_exception(
 509                                  vmClasses::StackOverflowError_klass(),
 510                                  CHECK);
 511   // Increment counter for hs_err file reporting
 512   Atomic::inc(&Exceptions::_stack_overflow_errors);
 513   // Remove the ScopedValue bindings in case we got a StackOverflowError
 514   // while we were trying to manipulate ScopedValue bindings.
 515   current->clear_scopedValueBindings();
 516   THROW_HANDLE(exception);
 517 JRT_END
 518 
 519 JRT_ENTRY(void, InterpreterRuntime::throw_delayed_StackOverflowError(JavaThread* current))
 520   Handle exception = get_preinitialized_exception(
 521                                  vmClasses::StackOverflowError_klass(),
 522                                  CHECK);
 523   java_lang_Throwable::set_message(exception(),
 524           Universe::delayed_stack_overflow_error_message());
 525   // Increment counter for hs_err file reporting
 526   Atomic::inc(&Exceptions::_stack_overflow_errors);
 527   // Remove the ScopedValue bindings in case we got a StackOverflowError
 528   // while we were trying to manipulate ScopedValue bindings.
 529   current->clear_scopedValueBindings();
 530   THROW_HANDLE(exception);
 531 JRT_END
 532 
 533 JRT_ENTRY(void, InterpreterRuntime::create_exception(JavaThread* current, char* name, char* message))
 534   // lookup exception klass
 535   TempNewSymbol s = SymbolTable::new_symbol(name);
 536   if (ProfileTraps) {
 537     if (s == vmSymbols::java_lang_ArithmeticException()) {
 538       note_trap(current, Deoptimization::Reason_div0_check);
 539     } else if (s == vmSymbols::java_lang_NullPointerException()) {
 540       note_trap(current, Deoptimization::Reason_null_check);
 541     }
 542   }
 543   // create exception
 544   Handle exception = Exceptions::new_exception(current, s, message);
 545   current->set_vm_result(exception());
 546 JRT_END
 547 
 548 
 549 JRT_ENTRY(void, InterpreterRuntime::create_klass_exception(JavaThread* current, char* name, oopDesc* obj))
 550   // Produce the error message first because note_trap can safepoint
 551   ResourceMark rm(current);
 552   const char* klass_name = obj->klass()->external_name();
 553   // lookup exception klass
 554   TempNewSymbol s = SymbolTable::new_symbol(name);
 555   if (ProfileTraps) {
 556     if (s == vmSymbols::java_lang_ArrayStoreException()) {
 557       note_trap(current, Deoptimization::Reason_array_check);
 558     } else {
 559       note_trap(current, Deoptimization::Reason_class_check);
 560     }
 561   }
 562   // create exception, with klass name as detail message
 563   Handle exception = Exceptions::new_exception(current, s, klass_name);
 564   current->set_vm_result(exception());
 565 JRT_END
 566 
 567 JRT_ENTRY(void, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException(JavaThread* current, arrayOopDesc* a, jint index))
 568   // Produce the error message first because note_trap can safepoint
 569   ResourceMark rm(current);
 570   stringStream ss;
 571   ss.print("Index %d out of bounds for length %d", index, a->length());
 572 
 573   if (ProfileTraps) {
 574     note_trap(current, Deoptimization::Reason_range_check);
 575   }
 576 
 577   THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), ss.as_string());
 578 JRT_END
 579 
 580 JRT_ENTRY(void, InterpreterRuntime::throw_ClassCastException(
 581   JavaThread* current, oopDesc* obj))
 582 
 583   // Produce the error message first because note_trap can safepoint
 584   ResourceMark rm(current);
 585   char* message = SharedRuntime::generate_class_cast_message(
 586     current, obj->klass());
 587 
 588   if (ProfileTraps) {
 589     note_trap(current, Deoptimization::Reason_class_check);
 590   }
 591 
 592   // create exception
 593   THROW_MSG(vmSymbols::java_lang_ClassCastException(), message);
 594 JRT_END
 595 
 596 // exception_handler_for_exception(...) returns the continuation address,
 597 // the exception oop (via TLS) and sets the bci/bcp for the continuation.
 598 // The exception oop is returned to make sure it is preserved over GC (it
 599 // is only on the stack if the exception was thrown explicitly via athrow).
 600 // During this operation, the expression stack contains the values for the
 601 // bci where the exception happened. If the exception was propagated back
 602 // from a call, the expression stack contains the values for the bci at the
 603 // invoke w/o arguments (i.e., as if one were inside the call).
 604 // Note that the implementation of this method assumes it's only called when an exception has actually occured
 605 JRT_ENTRY(address, InterpreterRuntime::exception_handler_for_exception(JavaThread* current, oopDesc* exception))
 606   // We get here after we have unwound from a callee throwing an exception
 607   // into the interpreter. Any deferred stack processing is notified of
 608   // the event via the StackWatermarkSet.
 609   StackWatermarkSet::after_unwind(current);
 610 
 611   LastFrameAccessor last_frame(current);
 612   Handle             h_exception(current, exception);
 613   methodHandle       h_method   (current, last_frame.method());
 614   constantPoolHandle h_constants(current, h_method->constants());
 615   bool               should_repeat;
 616   int                handler_bci;
 617   int                current_bci = last_frame.bci();
 618 
 619   if (current->frames_to_pop_failed_realloc() > 0) {
 620     // Allocation of scalar replaced object used in this frame
 621     // failed. Unconditionally pop the frame.
 622     current->dec_frames_to_pop_failed_realloc();
 623     current->set_vm_result(h_exception());
 624     // If the method is synchronized we already unlocked the monitor
 625     // during deoptimization so the interpreter needs to skip it when
 626     // the frame is popped.
 627     current->set_do_not_unlock_if_synchronized(true);
 628     return Interpreter::remove_activation_entry();
 629   }
 630 
 631   // Need to do this check first since when _do_not_unlock_if_synchronized
 632   // is set, we don't want to trigger any classloading which may make calls
 633   // into java, or surprisingly find a matching exception handler for bci 0
 634   // since at this moment the method hasn't been "officially" entered yet.
 635   if (current->do_not_unlock_if_synchronized()) {
 636     ResourceMark rm;
 637     assert(current_bci == 0,  "bci isn't zero for do_not_unlock_if_synchronized");
 638     current->set_vm_result(exception);
 639     return Interpreter::remove_activation_entry();
 640   }
 641 
 642   do {
 643     should_repeat = false;
 644 
 645     // assertions
 646     assert(h_exception.not_null(), "null exceptions should be handled by athrow");
 647     // Check that exception is a subclass of Throwable.
 648     assert(h_exception->is_a(vmClasses::Throwable_klass()),
 649            "Exception not subclass of Throwable");
 650 
 651     // tracing
 652     if (log_is_enabled(Info, exceptions)) {
 653       ResourceMark rm(current);
 654       stringStream tempst;
 655       tempst.print("interpreter method <%s>\n"
 656                    " at bci %d for thread " INTPTR_FORMAT " (%s)",
 657                    h_method->print_value_string(), current_bci, p2i(current), current->name());
 658       Exceptions::log_exception(h_exception, tempst.as_string());
 659     }
 660 // Don't go paging in something which won't be used.
 661 //     else if (extable->length() == 0) {
 662 //       // disabled for now - interpreter is not using shortcut yet
 663 //       // (shortcut is not to call runtime if we have no exception handlers)
 664 //       // warning("performance bug: should not call runtime if method has no exception handlers");
 665 //     }
 666     // for AbortVMOnException flag
 667     Exceptions::debug_check_abort(h_exception);
 668 
 669     // exception handler lookup
 670     Klass* klass = h_exception->klass();
 671     handler_bci = Method::fast_exception_handler_bci_for(h_method, klass, current_bci, THREAD);
 672     if (HAS_PENDING_EXCEPTION) {
 673       // We threw an exception while trying to find the exception handler.
 674       // Transfer the new exception to the exception handle which will
 675       // be set into thread local storage, and do another lookup for an
 676       // exception handler for this exception, this time starting at the
 677       // BCI of the exception handler which caused the exception to be
 678       // thrown (bug 4307310).
 679       h_exception = Handle(THREAD, PENDING_EXCEPTION);
 680       CLEAR_PENDING_EXCEPTION;
 681       if (handler_bci >= 0) {
 682         current_bci = handler_bci;
 683         should_repeat = true;
 684       }
 685     }
 686   } while (should_repeat == true);
 687 
 688 #if INCLUDE_JVMCI
 689   if (EnableJVMCI && h_method->method_data() != nullptr) {
 690     ResourceMark rm(current);
 691     MethodData* mdo = h_method->method_data();
 692 
 693     // Lock to read ProfileData, and ensure lock is not broken by a safepoint
 694     MutexLocker ml(mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
 695 
 696     ProfileData* pdata = mdo->allocate_bci_to_data(current_bci, nullptr);
 697     if (pdata != nullptr && pdata->is_BitData()) {
 698       BitData* bit_data = (BitData*) pdata;
 699       bit_data->set_exception_seen();
 700     }
 701   }
 702 #endif
 703 
 704   // notify JVMTI of an exception throw; JVMTI will detect if this is a first
 705   // time throw or a stack unwinding throw and accordingly notify the debugger
 706   if (JvmtiExport::can_post_on_exceptions()) {
 707     JvmtiExport::post_exception_throw(current, h_method(), last_frame.bcp(), h_exception());
 708   }
 709 
 710   address continuation = nullptr;
 711   address handler_pc = nullptr;
 712   if (handler_bci < 0 || !current->stack_overflow_state()->reguard_stack((address) &continuation)) {
 713     // Forward exception to callee (leaving bci/bcp untouched) because (a) no
 714     // handler in this method, or (b) after a stack overflow there is not yet
 715     // enough stack space available to reprotect the stack.
 716     continuation = Interpreter::remove_activation_entry();
 717 #if COMPILER2_OR_JVMCI
 718     // Count this for compilation purposes
 719     h_method->interpreter_throwout_increment(THREAD);
 720 #endif
 721   } else {
 722     // handler in this method => change bci/bcp to handler bci/bcp and continue there
 723     handler_pc = h_method->code_base() + handler_bci;
 724     h_method->set_exception_handler_entered(handler_bci); // profiling
 725 #ifndef ZERO
 726     set_bcp_and_mdp(handler_pc, current);
 727     continuation = Interpreter::dispatch_table(vtos)[*handler_pc];
 728 #else
 729     continuation = (address)(intptr_t) handler_bci;
 730 #endif
 731   }
 732 
 733   // notify debugger of an exception catch
 734   // (this is good for exceptions caught in native methods as well)
 735   if (JvmtiExport::can_post_on_exceptions()) {
 736     JvmtiExport::notice_unwind_due_to_exception(current, h_method(), handler_pc, h_exception(), (handler_pc != nullptr));
 737   }
 738 
 739   current->set_vm_result(h_exception());
 740   return continuation;
 741 JRT_END
 742 
 743 
 744 JRT_ENTRY(void, InterpreterRuntime::throw_pending_exception(JavaThread* current))
 745   assert(current->has_pending_exception(), "must only be called if there's an exception pending");
 746   // nothing to do - eventually we should remove this code entirely (see comments @ call sites)
 747 JRT_END
 748 
 749 
 750 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodError(JavaThread* current))
 751   THROW(vmSymbols::java_lang_AbstractMethodError());
 752 JRT_END
 753 
 754 // This method is called from the "abstract_entry" of the interpreter.
 755 // At that point, the arguments have already been removed from the stack
 756 // and therefore we don't have the receiver object at our fingertips. (Though,
 757 // on some platforms the receiver still resides in a register...). Thus,
 758 // we have no choice but print an error message not containing the receiver
 759 // type.
 760 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorWithMethod(JavaThread* current,
 761                                                                         Method* missingMethod))
 762   ResourceMark rm(current);
 763   assert(missingMethod != nullptr, "sanity");
 764   methodHandle m(current, missingMethod);
 765   LinkResolver::throw_abstract_method_error(m, THREAD);
 766 JRT_END
 767 
 768 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorVerbose(JavaThread* current,
 769                                                                      Klass* recvKlass,
 770                                                                      Method* missingMethod))
 771   ResourceMark rm(current);
 772   methodHandle mh = methodHandle(current, missingMethod);
 773   LinkResolver::throw_abstract_method_error(mh, recvKlass, THREAD);
 774 JRT_END
 775 
 776 JRT_ENTRY(void, InterpreterRuntime::throw_InstantiationError(JavaThread* current))
 777   THROW(vmSymbols::java_lang_InstantiationError());
 778 JRT_END
 779 
 780 
 781 JRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeError(JavaThread* current))
 782   THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
 783 JRT_END
 784 
 785 JRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeErrorVerbose(JavaThread* current,
 786                                                                               Klass* recvKlass,
 787                                                                               Klass* interfaceKlass))
 788   ResourceMark rm(current);
 789   char buf[1000];
 790   buf[0] = '\0';
 791   jio_snprintf(buf, sizeof(buf),
 792                "Class %s does not implement the requested interface %s",
 793                recvKlass ? recvKlass->external_name() : "nullptr",
 794                interfaceKlass ? interfaceKlass->external_name() : "nullptr");
 795   THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), buf);
 796 JRT_END
 797 
 798 JRT_ENTRY(void, InterpreterRuntime::throw_NullPointerException(JavaThread* current))
 799   THROW(vmSymbols::java_lang_NullPointerException());
 800 JRT_END
 801 
 802 //------------------------------------------------------------------------------------------------------------------------
 803 // Fields
 804 //
 805 
 806 void InterpreterRuntime::resolve_get_put(JavaThread* current, Bytecodes::Code bytecode) {
 807   LastFrameAccessor last_frame(current);
 808   constantPoolHandle pool(current, last_frame.method()->constants());
 809   methodHandle m(current, last_frame.method());
 810 
 811   resolve_get_put(bytecode, last_frame.get_index_u2(bytecode), m, pool, true /*initialize_holder*/, current);
 812 }
 813 
 814 void InterpreterRuntime::resolve_get_put(Bytecodes::Code bytecode, int field_index,
 815                                          methodHandle& m,
 816                                          constantPoolHandle& pool,
 817                                          bool initialize_holder, TRAPS) {
 818   fieldDescriptor info;
 819   bool is_put    = (bytecode == Bytecodes::_putfield  || bytecode == Bytecodes::_nofast_putfield ||
 820                     bytecode == Bytecodes::_putstatic);
 821   bool is_static = (bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic);
 822 
 823   {
 824     JvmtiHideSingleStepping jhss(THREAD);
 825     LinkResolver::resolve_field_access(info, pool, field_index,
 826                                        m, bytecode, initialize_holder, CHECK);
 827   } // end JvmtiHideSingleStepping
 828 
 829   // check if link resolution caused cpCache to be updated
 830   if (pool->resolved_field_entry_at(field_index)->is_resolved(bytecode)) return;
 831 
 832   // compute auxiliary field attributes
 833   TosState state  = as_TosState(info.field_type());
 834 
 835   // Resolution of put instructions on final fields is delayed. That is required so that
 836   // exceptions are thrown at the correct place (when the instruction is actually invoked).
 837   // If we do not resolve an instruction in the current pass, leaving the put_code
 838   // set to zero will cause the next put instruction to the same field to reresolve.
 839 
 840   // Resolution of put instructions to final instance fields with invalid updates (i.e.,
 841   // to final instance fields with updates originating from a method different than <init>)
 842   // is inhibited. A putfield instruction targeting an instance final field must throw
 843   // an IllegalAccessError if the instruction is not in an instance
 844   // initializer method <init>. If resolution were not inhibited, a putfield
 845   // in an initializer method could be resolved in the initializer. Subsequent
 846   // putfield instructions to the same field would then use cached information.
 847   // As a result, those instructions would not pass through the VM. That is,
 848   // checks in resolve_field_access() would not be executed for those instructions
 849   // and the required IllegalAccessError would not be thrown.
 850   //
 851   // Also, we need to delay resolving getstatic and putstatic instructions until the
 852   // class is initialized.  This is required so that access to the static
 853   // field will call the initialization function every time until the class
 854   // is completely initialized ala. in 2.17.5 in JVM Specification.
 855   InstanceKlass* klass = info.field_holder();
 856   bool uninitialized_static = is_static && !klass->is_initialized();
 857   bool has_initialized_final_update = info.field_holder()->major_version() >= 53 &&
 858                                       info.has_initialized_final_update();
 859   assert(!(has_initialized_final_update && !info.access_flags().is_final()), "Fields with initialized final updates must be final");
 860 
 861   Bytecodes::Code get_code = (Bytecodes::Code)0;
 862   Bytecodes::Code put_code = (Bytecodes::Code)0;
 863   if (!uninitialized_static) {
 864     if (is_static) {
 865       get_code = Bytecodes::_getstatic;
 866     } else {
 867       get_code = Bytecodes::_getfield;
 868     }
 869     if ((is_put && !has_initialized_final_update) || !info.access_flags().is_final()) {
 870         put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_putfield);
 871     }
 872   }
 873 
 874   ResolvedFieldEntry* entry = pool->resolved_field_entry_at(field_index);
 875   entry->set_flags(info.access_flags().is_final(), info.access_flags().is_volatile(),
 876                    info.is_flat(), info.is_null_free_inline_type(),
 877                    info.has_null_marker());
 878 
 879   entry->fill_in(info.field_holder(), info.offset(),
 880                  checked_cast<u2>(info.index()), checked_cast<u1>(state),
 881                  static_cast<u1>(get_code), static_cast<u1>(put_code));
 882 }
 883 
 884 
 885 //------------------------------------------------------------------------------------------------------------------------
 886 // Synchronization
 887 //
 888 // The interpreter's synchronization code is factored out so that it can
 889 // be shared by method invocation and synchronized blocks.
 890 //%note synchronization_3
 891 
 892 //%note monitor_1
 893 JRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* current, BasicObjectLock* elem))
 894 #ifdef ASSERT
 895   current->last_frame().interpreter_frame_verify_monitor(elem);
 896 #endif
 897   Handle h_obj(current, elem->obj());
 898   assert(Universe::heap()->is_in_or_null(h_obj()),
 899          "must be null or an object");
 900   ObjectSynchronizer::enter(h_obj, elem->lock(), current);
 901   assert(Universe::heap()->is_in_or_null(elem->obj()),
 902          "must be null or an object");
 903 #ifdef ASSERT
 904   current->last_frame().interpreter_frame_verify_monitor(elem);
 905 #endif
 906 JRT_END
 907 
 908 JRT_LEAF(void, InterpreterRuntime::monitorexit(BasicObjectLock* elem))
 909   oop obj = elem->obj();
 910   assert(Universe::heap()->is_in(obj), "must be an object");
 911   // The object could become unlocked through a JNI call, which we have no other checks for.
 912   // Give a fatal message if CheckJNICalls. Otherwise we ignore it.
 913   if (obj->is_unlocked()) {
 914     if (CheckJNICalls) {
 915       fatal("Object has been unlocked by JNI");
 916     }
 917     return;
 918   }
 919   ObjectSynchronizer::exit(obj, elem->lock(), JavaThread::current());
 920   // Free entry. If it is not cleared, the exception handling code will try to unlock the monitor
 921   // again at method exit or in the case of an exception.
 922   elem->set_obj(nullptr);
 923 JRT_END
 924 
 925 JRT_ENTRY(void, InterpreterRuntime::throw_illegal_monitor_state_exception(JavaThread* current))
 926   THROW(vmSymbols::java_lang_IllegalMonitorStateException());
 927 JRT_END
 928 
 929 JRT_ENTRY(void, InterpreterRuntime::new_illegal_monitor_state_exception(JavaThread* current))
 930   // Returns an illegal exception to install into the current thread. The
 931   // pending_exception flag is cleared so normal exception handling does not
 932   // trigger. Any current installed exception will be overwritten. This
 933   // method will be called during an exception unwind.
 934 
 935   assert(!HAS_PENDING_EXCEPTION, "no pending exception");
 936   Handle exception(current, current->vm_result());
 937   assert(exception() != nullptr, "vm result should be set");
 938   current->set_vm_result(nullptr); // clear vm result before continuing (may cause memory leaks and assert failures)
 939   exception = get_preinitialized_exception(vmClasses::IllegalMonitorStateException_klass(), CATCH);
 940   current->set_vm_result(exception());
 941 JRT_END
 942 
 943 JRT_ENTRY(void, InterpreterRuntime::throw_identity_exception(JavaThread* current, oopDesc* obj))
 944   Klass* klass = cast_to_oop(obj)->klass();
 945   ResourceMark rm(THREAD);
 946   const char* desc = "Cannot synchronize on an instance of value class ";
 947   const char* className = klass->external_name();
 948   size_t msglen = strlen(desc) + strlen(className) + 1;
 949   char* message = NEW_RESOURCE_ARRAY(char, msglen);
 950   if (nullptr == message) {
 951     // Out of memory: can't create detailed error message
 952     THROW_MSG(vmSymbols::java_lang_IdentityException(), className);
 953   } else {
 954     jio_snprintf(message, msglen, "%s%s", desc, className);
 955     THROW_MSG(vmSymbols::java_lang_IdentityException(), message);
 956   }
 957 JRT_END
 958 
 959 //------------------------------------------------------------------------------------------------------------------------
 960 // Invokes
 961 
 962 JRT_ENTRY(Bytecodes::Code, InterpreterRuntime::get_original_bytecode_at(JavaThread* current, Method* method, address bcp))
 963   return method->orig_bytecode_at(method->bci_from(bcp));
 964 JRT_END
 965 
 966 JRT_ENTRY(void, InterpreterRuntime::set_original_bytecode_at(JavaThread* current, Method* method, address bcp, Bytecodes::Code new_code))
 967   method->set_orig_bytecode_at(method->bci_from(bcp), new_code);
 968 JRT_END
 969 
 970 JRT_ENTRY(void, InterpreterRuntime::_breakpoint(JavaThread* current, Method* method, address bcp))
 971   JvmtiExport::post_raw_breakpoint(current, method, bcp);
 972 JRT_END
 973 
 974 void InterpreterRuntime::resolve_invoke(JavaThread* current, Bytecodes::Code bytecode) {
 975   LastFrameAccessor last_frame(current);
 976   // extract receiver from the outgoing argument list if necessary
 977   Handle receiver(current, nullptr);
 978   if (bytecode == Bytecodes::_invokevirtual || bytecode == Bytecodes::_invokeinterface ||
 979       bytecode == Bytecodes::_invokespecial) {
 980     ResourceMark rm(current);
 981     methodHandle m (current, last_frame.method());
 982     Bytecode_invoke call(m, last_frame.bci());
 983     Symbol* signature = call.signature();
 984     receiver = Handle(current, last_frame.callee_receiver(signature));
 985 
 986     assert(Universe::heap()->is_in_or_null(receiver()),
 987            "sanity check");
 988     assert(receiver.is_null() ||
 989            !Universe::heap()->is_in(receiver->klass()),
 990            "sanity check");
 991   }
 992 
 993   // resolve method
 994   CallInfo info;
 995   constantPoolHandle pool(current, last_frame.method()->constants());
 996 
 997   methodHandle resolved_method;
 998 
 999   int method_index = last_frame.get_index_u2(bytecode);
1000   {
1001     JvmtiHideSingleStepping jhss(current);
1002     JavaThread* THREAD = current; // For exception macros.
1003     LinkResolver::resolve_invoke(info, receiver, pool,
1004                                  method_index, bytecode,
1005                                  THREAD);
1006 
1007     if (HAS_PENDING_EXCEPTION) {
1008       if (ProfileTraps && PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_NullPointerException()) {
1009         // Preserve the original exception across the call to note_trap()
1010         PreserveExceptionMark pm(current);
1011         // Recording the trap will help the compiler to potentially recognize this exception as "hot"
1012         note_trap(current, Deoptimization::Reason_null_check);
1013       }
1014       return;
1015     }
1016 
1017     resolved_method = methodHandle(current, info.resolved_method());
1018   } // end JvmtiHideSingleStepping
1019 
1020   update_invoke_cp_cache_entry(info, bytecode, resolved_method, pool, method_index);
1021 }
1022 
1023 void InterpreterRuntime::update_invoke_cp_cache_entry(CallInfo& info, Bytecodes::Code bytecode,
1024                                                       methodHandle& resolved_method,
1025                                                       constantPoolHandle& pool,
1026                                                       int method_index) {
1027   // Don't allow safepoints until the method is cached.
1028   NoSafepointVerifier nsv;
1029 
1030   // check if link resolution caused cpCache to be updated
1031   ConstantPoolCache* cache = pool->cache();
1032   if (cache->resolved_method_entry_at(method_index)->is_resolved(bytecode)) return;
1033 
1034 #ifdef ASSERT
1035   if (bytecode == Bytecodes::_invokeinterface) {
1036     if (resolved_method->method_holder() == vmClasses::Object_klass()) {
1037       // NOTE: THIS IS A FIX FOR A CORNER CASE in the JVM spec
1038       // (see also CallInfo::set_interface for details)
1039       assert(info.call_kind() == CallInfo::vtable_call ||
1040              info.call_kind() == CallInfo::direct_call, "");
1041       assert(resolved_method->is_final() || info.has_vtable_index(),
1042              "should have been set already");
1043     } else if (!resolved_method->has_itable_index()) {
1044       // Resolved something like CharSequence.toString.  Use vtable not itable.
1045       assert(info.call_kind() != CallInfo::itable_call, "");
1046     } else {
1047       // Setup itable entry
1048       assert(info.call_kind() == CallInfo::itable_call, "");
1049       int index = resolved_method->itable_index();
1050       assert(info.itable_index() == index, "");
1051     }
1052   } else if (bytecode == Bytecodes::_invokespecial) {
1053     assert(info.call_kind() == CallInfo::direct_call, "must be direct call");
1054   } else {
1055     assert(info.call_kind() == CallInfo::direct_call ||
1056            info.call_kind() == CallInfo::vtable_call, "");
1057   }
1058 #endif
1059   // Get sender and only set cpCache entry to resolved if it is not an
1060   // interface.  The receiver for invokespecial calls within interface
1061   // methods must be checked for every call.
1062   InstanceKlass* sender = pool->pool_holder();
1063 
1064   switch (info.call_kind()) {
1065   case CallInfo::direct_call:
1066     cache->set_direct_call(bytecode, method_index, resolved_method, sender->is_interface());
1067     break;
1068   case CallInfo::vtable_call:
1069     cache->set_vtable_call(bytecode, method_index, resolved_method, info.vtable_index());
1070     break;
1071   case CallInfo::itable_call:
1072     cache->set_itable_call(
1073       bytecode,
1074       method_index,
1075       info.resolved_klass(),
1076       resolved_method,
1077       info.itable_index());
1078     break;
1079   default:  ShouldNotReachHere();
1080   }
1081 }
1082 
1083 void InterpreterRuntime::cds_resolve_invoke(Bytecodes::Code bytecode, int method_index,
1084                                             constantPoolHandle& pool, TRAPS) {
1085   LinkInfo link_info(pool, method_index, bytecode, CHECK);
1086 
1087   if (!link_info.resolved_klass()->is_instance_klass() || InstanceKlass::cast(link_info.resolved_klass())->is_linked()) {
1088     CallInfo call_info;
1089     switch (bytecode) {
1090       case Bytecodes::_invokevirtual:   LinkResolver::cds_resolve_virtual_call  (call_info, link_info, CHECK); break;
1091       case Bytecodes::_invokeinterface: LinkResolver::cds_resolve_interface_call(call_info, link_info, CHECK); break;
1092       case Bytecodes::_invokespecial:   LinkResolver::cds_resolve_special_call  (call_info, link_info, CHECK); break;
1093 
1094       default: fatal("Unimplemented: %s", Bytecodes::name(bytecode));
1095     }
1096     methodHandle resolved_method(THREAD, call_info.resolved_method());
1097     guarantee(resolved_method->method_holder()->is_linked(), "");
1098     update_invoke_cp_cache_entry(call_info, bytecode, resolved_method, pool, method_index);
1099   } else {
1100     // FIXME: why a shared class is not linked yet?
1101     // Can't link it here since there are no guarantees it'll be prelinked on the next run.
1102     ResourceMark rm;
1103     InstanceKlass* resolved_iklass = InstanceKlass::cast(link_info.resolved_klass());
1104     log_info(cds, resolve)("Not resolved: class not linked: %s %s %s",
1105                            resolved_iklass->is_shared() ? "is_shared" : "",
1106                            resolved_iklass->init_state_name(),
1107                            resolved_iklass->external_name());
1108   }
1109 }
1110 
1111 // First time execution:  Resolve symbols, create a permanent MethodType object.
1112 void InterpreterRuntime::resolve_invokehandle(JavaThread* current) {
1113   const Bytecodes::Code bytecode = Bytecodes::_invokehandle;
1114   LastFrameAccessor last_frame(current);
1115 
1116   // resolve method
1117   CallInfo info;
1118   constantPoolHandle pool(current, last_frame.method()->constants());
1119   int method_index = last_frame.get_index_u2(bytecode);
1120   {
1121     JvmtiHideSingleStepping jhss(current);
1122     JavaThread* THREAD = current; // For exception macros.
1123     LinkResolver::resolve_invoke(info, Handle(), pool,
1124                                  method_index, bytecode,
1125                                  CHECK);
1126   } // end JvmtiHideSingleStepping
1127 
1128   pool->cache()->set_method_handle(method_index, info);
1129 }
1130 
1131 // First time execution:  Resolve symbols, create a permanent CallSite object.
1132 void 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 }
1149 
1150 // This function is the interface to the assembly code. It returns the resolved
1151 // cpCache entry.  This doesn't safepoint, but the helper routines safepoint.
1152 // This function will check for redefinition!
1153 JRT_ENTRY(void, InterpreterRuntime::resolve_from_cache(JavaThread* current, Bytecodes::Code bytecode)) {
1154   switch (bytecode) {
1155   case Bytecodes::_getstatic:
1156   case Bytecodes::_putstatic:
1157   case Bytecodes::_getfield:
1158   case Bytecodes::_putfield:
1159     resolve_get_put(current, bytecode);
1160     break;
1161   case Bytecodes::_invokevirtual:
1162   case Bytecodes::_invokespecial:
1163   case Bytecodes::_invokestatic:
1164   case Bytecodes::_invokeinterface:
1165     resolve_invoke(current, bytecode);
1166     break;
1167   case Bytecodes::_invokehandle:
1168     resolve_invokehandle(current);
1169     break;
1170   case Bytecodes::_invokedynamic:
1171     resolve_invokedynamic(current);
1172     break;
1173   default:
1174     fatal("unexpected bytecode: %s", Bytecodes::name(bytecode));
1175     break;
1176   }
1177 }
1178 JRT_END
1179 
1180 //------------------------------------------------------------------------------------------------------------------------
1181 // Miscellaneous
1182 
1183 
1184 nmethod* InterpreterRuntime::frequency_counter_overflow(JavaThread* current, address branch_bcp) {
1185   // Enable WXWrite: the function is called directly by interpreter.
1186   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
1187 
1188   // frequency_counter_overflow_inner can throw async exception.
1189   nmethod* nm = frequency_counter_overflow_inner(current, branch_bcp);
1190   assert(branch_bcp != nullptr || nm == nullptr, "always returns null for non OSR requests");
1191   if (branch_bcp != nullptr && nm != nullptr) {
1192     // This was a successful request for an OSR nmethod.  Because
1193     // frequency_counter_overflow_inner ends with a safepoint check,
1194     // nm could have been unloaded so look it up again.  It's unsafe
1195     // to examine nm directly since it might have been freed and used
1196     // for something else.
1197     LastFrameAccessor last_frame(current);
1198     Method* method =  last_frame.method();
1199     int bci = method->bci_from(last_frame.bcp());
1200     nm = method->lookup_osr_nmethod_for(bci, CompLevel_none, false);
1201     BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
1202     if (nm != nullptr && bs_nm != nullptr) {
1203       // in case the transition passed a safepoint we need to barrier this again
1204       if (!bs_nm->nmethod_osr_entry_barrier(nm)) {
1205         nm = nullptr;
1206       }
1207     }
1208   }
1209   if (nm != nullptr && current->is_interp_only_mode()) {
1210     // Normally we never get an nm if is_interp_only_mode() is true, because
1211     // policy()->event has a check for this and won't compile the method when
1212     // true. However, it's possible for is_interp_only_mode() to become true
1213     // during the compilation. We don't want to return the nm in that case
1214     // because we want to continue to execute interpreted.
1215     nm = nullptr;
1216   }
1217 #ifndef PRODUCT
1218   if (TraceOnStackReplacement) {
1219     if (nm != nullptr) {
1220       tty->print("OSR entry @ pc: " INTPTR_FORMAT ": ", p2i(nm->osr_entry()));
1221       nm->print();
1222     }
1223   }
1224 #endif
1225   return nm;
1226 }
1227 
1228 JRT_ENTRY(nmethod*,
1229           InterpreterRuntime::frequency_counter_overflow_inner(JavaThread* current, address branch_bcp))
1230   // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
1231   // flag, in case this method triggers classloading which will call into Java.
1232   UnlockFlagSaver fs(current);
1233 
1234   LastFrameAccessor last_frame(current);
1235   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1236   methodHandle method(current, last_frame.method());
1237   const int branch_bci = branch_bcp != nullptr ? method->bci_from(branch_bcp) : InvocationEntryBci;
1238   const int bci = branch_bcp != nullptr ? method->bci_from(last_frame.bcp()) : InvocationEntryBci;
1239 
1240   nmethod* osr_nm = CompilationPolicy::event(method, method, branch_bci, bci, CompLevel_none, nullptr, CHECK_NULL);
1241 
1242   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
1243   if (osr_nm != nullptr && bs_nm != nullptr) {
1244     if (!bs_nm->nmethod_osr_entry_barrier(osr_nm)) {
1245       osr_nm = nullptr;
1246     }
1247   }
1248   return osr_nm;
1249 JRT_END
1250 
1251 JRT_LEAF(jint, InterpreterRuntime::bcp_to_di(Method* method, address cur_bcp))
1252   assert(ProfileInterpreter, "must be profiling interpreter");
1253   int bci = method->bci_from(cur_bcp);
1254   MethodData* mdo = method->method_data();
1255   if (mdo == nullptr)  return 0;
1256   return mdo->bci_to_di(bci);
1257 JRT_END
1258 
1259 #ifdef ASSERT
1260 JRT_LEAF(void, InterpreterRuntime::verify_mdp(Method* method, address bcp, address mdp))
1261   assert(ProfileInterpreter, "must be profiling interpreter");
1262 
1263   MethodData* mdo = method->method_data();
1264   assert(mdo != nullptr, "must not be null");
1265 
1266   int bci = method->bci_from(bcp);
1267 
1268   address mdp2 = mdo->bci_to_dp(bci);
1269   if (mdp != mdp2) {
1270     ResourceMark rm;
1271     tty->print_cr("FAILED verify : actual mdp %p   expected mdp %p @ bci %d", mdp, mdp2, bci);
1272     int current_di = mdo->dp_to_di(mdp);
1273     int expected_di  = mdo->dp_to_di(mdp2);
1274     tty->print_cr("  actual di %d   expected di %d", current_di, expected_di);
1275     int expected_approx_bci = mdo->data_at(expected_di)->bci();
1276     int approx_bci = -1;
1277     if (current_di >= 0) {
1278       approx_bci = mdo->data_at(current_di)->bci();
1279     }
1280     tty->print_cr("  actual bci is %d  expected bci %d", approx_bci, expected_approx_bci);
1281     mdo->print_on(tty);
1282     method->print_codes();
1283   }
1284   assert(mdp == mdp2, "wrong mdp");
1285 JRT_END
1286 #endif // ASSERT
1287 
1288 JRT_ENTRY(void, InterpreterRuntime::update_mdp_for_ret(JavaThread* current, int return_bci))
1289   assert(ProfileInterpreter, "must be profiling interpreter");
1290   ResourceMark rm(current);
1291   LastFrameAccessor last_frame(current);
1292   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1293   MethodData* h_mdo = last_frame.method()->method_data();
1294 
1295   // Grab a lock to ensure atomic access to setting the return bci and
1296   // the displacement.  This can block and GC, invalidating all naked oops.
1297   MutexLocker ml(RetData_lock);
1298 
1299   // ProfileData is essentially a wrapper around a derived oop, so we
1300   // need to take the lock before making any ProfileData structures.
1301   ProfileData* data = h_mdo->data_at(h_mdo->dp_to_di(last_frame.mdp()));
1302   guarantee(data != nullptr, "profile data must be valid");
1303   RetData* rdata = data->as_RetData();
1304   address new_mdp = rdata->fixup_ret(return_bci, h_mdo);
1305   last_frame.set_mdp(new_mdp);
1306 JRT_END
1307 
1308 JRT_ENTRY(MethodCounters*, InterpreterRuntime::build_method_counters(JavaThread* current, Method* m))
1309   return Method::build_method_counters(current, m);
1310 JRT_END
1311 
1312 
1313 JRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* current))
1314   // We used to need an explicit preserve_arguments here for invoke bytecodes. However,
1315   // stack traversal automatically takes care of preserving arguments for invoke, so
1316   // this is no longer needed.
1317 
1318   // JRT_END does an implicit safepoint check, hence we are guaranteed to block
1319   // if this is called during a safepoint
1320 
1321   if (JvmtiExport::should_post_single_step()) {
1322     // This function is called by the interpreter when single stepping. Such single
1323     // stepping could unwind a frame. Then, it is important that we process any frames
1324     // that we might return into.
1325     StackWatermarkSet::before_unwind(current);
1326 
1327     // We are called during regular safepoints and when the VM is
1328     // single stepping. If any thread is marked for single stepping,
1329     // then we may have JVMTI work to do.
1330     LastFrameAccessor last_frame(current);
1331     JvmtiExport::at_single_stepping_point(current, last_frame.method(), last_frame.bcp());
1332   }
1333 JRT_END
1334 
1335 JRT_LEAF(void, InterpreterRuntime::at_unwind(JavaThread* current))
1336   assert(current == JavaThread::current(), "pre-condition");
1337   // This function is called by the interpreter when the return poll found a reason
1338   // to call the VM. The reason could be that we are returning into a not yet safe
1339   // to access frame. We handle that below.
1340   // Note that this path does not check for single stepping, because we do not want
1341   // to single step when unwinding frames for an exception being thrown. Instead,
1342   // such single stepping code will use the safepoint table, which will use the
1343   // InterpreterRuntime::at_safepoint callback.
1344   StackWatermarkSet::before_unwind(current);
1345 JRT_END
1346 
1347 JRT_ENTRY(void, InterpreterRuntime::post_field_access(JavaThread* current, oopDesc* obj,
1348                                                       ResolvedFieldEntry *entry))
1349 
1350   assert(entry->is_valid(), "Invalid ResolvedFieldEntry");
1351   // check the access_flags for the field in the klass
1352 
1353   InstanceKlass* ik = entry->field_holder();
1354   int index = entry->field_index();
1355   if (!ik->field_status(index).is_access_watched()) return;
1356 
1357   bool is_static = (obj == nullptr);
1358   bool is_flat = entry->is_flat();
1359   HandleMark hm(current);
1360 
1361   Handle h_obj;
1362   if (!is_static) {
1363     // non-static field accessors have an object, but we need a handle
1364     h_obj = Handle(current, obj);
1365   }
1366   InstanceKlass* field_holder = entry->field_holder(); // HERE
1367   jfieldID fid = jfieldIDWorkaround::to_jfieldID(field_holder, entry->field_offset(), is_static, is_flat);
1368   LastFrameAccessor last_frame(current);
1369   JvmtiExport::post_field_access(current, last_frame.method(), last_frame.bcp(), field_holder, h_obj, fid);
1370 JRT_END
1371 
1372 JRT_ENTRY(void, InterpreterRuntime::post_field_modification(JavaThread* current, oopDesc* obj,
1373                                                             ResolvedFieldEntry *entry, jvalue *value))
1374 
1375   assert(entry->is_valid(), "Invalid ResolvedFieldEntry");
1376   InstanceKlass* ik = entry->field_holder();
1377 
1378   // check the access_flags for the field in the klass
1379   int index = entry->field_index();
1380   // bail out if field modifications are not watched
1381   if (!ik->field_status(index).is_modification_watched()) return;
1382 
1383   char sig_type = '\0';
1384 
1385   switch((TosState)entry->tos_state()) {
1386     case btos: sig_type = JVM_SIGNATURE_BYTE;    break;
1387     case ztos: sig_type = JVM_SIGNATURE_BOOLEAN; break;
1388     case ctos: sig_type = JVM_SIGNATURE_CHAR;    break;
1389     case stos: sig_type = JVM_SIGNATURE_SHORT;   break;
1390     case itos: sig_type = JVM_SIGNATURE_INT;     break;
1391     case ftos: sig_type = JVM_SIGNATURE_FLOAT;   break;
1392     case atos: sig_type = JVM_SIGNATURE_CLASS;   break;
1393     case ltos: sig_type = JVM_SIGNATURE_LONG;    break;
1394     case dtos: sig_type = JVM_SIGNATURE_DOUBLE;  break;
1395     default:  ShouldNotReachHere(); return;
1396   }
1397 
1398   bool is_static = (obj == nullptr);
1399   bool is_flat = entry->is_flat();
1400 
1401   HandleMark hm(current);
1402   jfieldID fid = jfieldIDWorkaround::to_jfieldID(ik, entry->field_offset(), is_static, is_flat);
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(void, 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(void, 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(int, 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(void, 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(void, InterpreterRuntime::member_name_arg_or_null(JavaThread* current, address member_name,
1685                                                             Method* method, address bcp))
1686   Bytecodes::Code code = Bytecodes::code_at(method, bcp);
1687   if (code != Bytecodes::_invokestatic) {
1688     return;
1689   }
1690   ConstantPool* cpool = method->constants();
1691   int cp_index = Bytes::get_native_u2(bcp + 1);
1692   Symbol* cname = cpool->klass_name_at(cpool->klass_ref_index_at(cp_index, code));
1693   Symbol* mname = cpool->name_ref_at(cp_index, code);
1694 
1695   if (MethodHandles::has_member_arg(cname, mname)) {
1696     oop member_name_oop = cast_to_oop(member_name);
1697     if (java_lang_invoke_DirectMethodHandle::is_instance(member_name_oop)) {
1698       // FIXME: remove after j.l.i.InvokerBytecodeGenerator code shape is updated.
1699       member_name_oop = java_lang_invoke_DirectMethodHandle::member(member_name_oop);
1700     }
1701     current->set_vm_result(member_name_oop);
1702   } else {
1703     current->set_vm_result(nullptr);
1704   }
1705 JRT_END
1706 #endif // INCLUDE_JVMTI
1707 
1708 #ifndef PRODUCT
1709 // This must be a JRT_LEAF function because the interpreter must save registers on x86 to
1710 // call this, which changes rsp and makes the interpreter's expression stack not walkable.
1711 // The generated code still uses call_VM because that will set up the frame pointer for
1712 // bcp and method.
1713 JRT_LEAF(intptr_t, InterpreterRuntime::trace_bytecode(JavaThread* current, intptr_t preserve_this_value, intptr_t tos, intptr_t tos2))
1714   assert(current == JavaThread::current(), "pre-condition");
1715   LastFrameAccessor last_frame(current);
1716   assert(last_frame.is_interpreted_frame(), "must be an interpreted frame");
1717   methodHandle mh(current, last_frame.method());
1718   BytecodeTracer::trace_interpreter(mh, last_frame.bcp(), tos, tos2);
1719   return preserve_this_value;
1720 JRT_END
1721 #endif // !PRODUCT