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