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