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