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