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