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::return_value(JavaThread* thread, oopDesc* obj))
 594   if (!VTBuffer::is_in_vt_buffer(obj)) {
 595     thread->set_vm_result(obj);
 596     return;
 597   }
 598   assert(obj->klass()->is_value(), "Sanity check");
 599   ValueKlass* vk = ValueKlass::cast(obj->klass());
 600   RegisterMap reg_map(thread, false);
 601   frame current_frame = thread->last_frame();
 602   frame caller_frame = current_frame.sender(&reg_map);
 603   if (!caller_frame.is_interpreted_frame()) {
 604     // caller is not an interpreted frame, creating a new value in Java heap
 605     Handle obj_h(THREAD, obj);
 606     instanceOop res = vk->allocate_instance(CHECK);
 607     Handle res_h(THREAD, res);
 608     // copy value
 609     vk->value_store(vk->data_for_oop(obj_h()),
 610                     vk->data_for_oop(res_h()), true, false);
 611     thread->set_vm_result(res_h());
 612     return;
 613   } else {
 614     // A buffered value is being returned to an interpreted frame,
 615     // but the work has to be delayed to remove_activation() because
 616     // the frame cannot be modified now (GC can run at the safepoint
 617     // when exiting runtime, and frame layout must be kept consistent
 618     // with the OopMap).
 619     thread->set_return_buffered_value(obj);
 620     thread->set_vm_result(obj);
 621   }
 622 IRT_END
 623 
 624 IRT_LEAF(void, InterpreterRuntime::return_value_step2(oopDesc* obj, void* alloc_ptr))
 625 
 626   JavaThread* thread = (JavaThread*)Thread::current();
 627   assert(obj == thread->return_buffered_value(), "Consistency check");
 628   assert(!Universe::heap()->is_in_reserved(obj), "Should only apply to buffered values");
 629 
 630   oop dest = VTBuffer::relocate_return_value(thread, alloc_ptr, obj);



 631   thread->set_return_buffered_value(NULL);
 632   thread->set_vm_result(dest);
 633 IRT_END
 634 
 635 IRT_ENTRY(void, InterpreterRuntime::check_areturn(JavaThread* thread, oopDesc* obj))
 636   if (obj != NULL) {
 637     Klass* k = obj->klass();
 638     if (k->is_value()) {
 639       ResourceMark rm(thread);
 640       tty->print_cr("areturn used on a value from %s", k->name()->as_C_string());
 641     }
 642     assert(!k->is_value(), "areturn should never be used on values");
 643   }
 644   thread->set_vm_result(obj);
 645 IRT_END
 646 
 647 IRT_ENTRY(void, InterpreterRuntime::register_finalizer(JavaThread* thread, oopDesc* obj))
 648   assert(oopDesc::is_oop(obj), "must be a valid oop");
 649   assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise");
 650   InstanceKlass::register_finalizer(instanceOop(obj), CHECK);
 651 IRT_END
 652 
 653 
 654 // Quicken instance-of and check-cast bytecodes
 655 IRT_ENTRY(void, InterpreterRuntime::quicken_io_cc(JavaThread* thread))
 656   // Force resolving; quicken the bytecode
 657   LastFrameAccessor last_frame(thread);
 658   int which = last_frame.get_index_u2(Bytecodes::_checkcast);
 659   ConstantPool* cpool = last_frame.method()->constants();
 660   // We'd expect to assert that we're only here to quicken bytecodes, but in a multithreaded
 661   // program we might have seen an unquick'd bytecode in the interpreter but have another
 662   // thread quicken the bytecode before we get here.
 663   // assert( cpool->tag_at(which).is_unresolved_klass(), "should only come here to quicken bytecodes" );
 664   Klass* klass = cpool->klass_at(which, CHECK);
 665   thread->set_vm_result_2(klass);
 666 IRT_END
 667 
 668 
 669 //------------------------------------------------------------------------------------------------------------------------
 670 // Exceptions
 671 
 672 void InterpreterRuntime::note_trap_inner(JavaThread* thread, int reason,
 673                                          const methodHandle& trap_method, int trap_bci, TRAPS) {
 674   if (trap_method.not_null()) {
 675     MethodData* trap_mdo = trap_method->method_data();
 676     if (trap_mdo == NULL) {
 677       Method::build_interpreter_method_data(trap_method, THREAD);
 678       if (HAS_PENDING_EXCEPTION) {
 679         assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())),
 680                "we expect only an OOM error here");
 681         CLEAR_PENDING_EXCEPTION;
 682       }
 683       trap_mdo = trap_method->method_data();
 684       // and fall through...
 685     }
 686     if (trap_mdo != NULL) {
 687       // Update per-method count of trap events.  The interpreter
 688       // is updating the MDO to simulate the effect of compiler traps.
 689       Deoptimization::update_method_data_from_interpreter(trap_mdo, trap_bci, reason);
 690     }
 691   }
 692 }
 693 
 694 // Assume the compiler is (or will be) interested in this event.
 695 // If necessary, create an MDO to hold the information, and record it.
 696 void InterpreterRuntime::note_trap(JavaThread* thread, int reason, TRAPS) {
 697   assert(ProfileTraps, "call me only if profiling");
 698   LastFrameAccessor last_frame(thread);
 699   methodHandle trap_method(thread, last_frame.method());
 700   int trap_bci = trap_method->bci_from(last_frame.bcp());
 701   note_trap_inner(thread, reason, trap_method, trap_bci, THREAD);
 702 }
 703 
 704 #ifdef CC_INTERP
 705 // As legacy note_trap, but we have more arguments.
 706 IRT_ENTRY(void, InterpreterRuntime::note_trap(JavaThread* thread, int reason, Method *method, int trap_bci))
 707   methodHandle trap_method(method);
 708   note_trap_inner(thread, reason, trap_method, trap_bci, THREAD);
 709 IRT_END
 710 
 711 // Class Deoptimization is not visible in BytecodeInterpreter, so we need a wrapper
 712 // for each exception.
 713 void InterpreterRuntime::note_nullCheck_trap(JavaThread* thread, Method *method, int trap_bci)
 714   { if (ProfileTraps) note_trap(thread, Deoptimization::Reason_null_check, method, trap_bci); }
 715 void InterpreterRuntime::note_div0Check_trap(JavaThread* thread, Method *method, int trap_bci)
 716   { if (ProfileTraps) note_trap(thread, Deoptimization::Reason_div0_check, method, trap_bci); }
 717 void InterpreterRuntime::note_rangeCheck_trap(JavaThread* thread, Method *method, int trap_bci)
 718   { if (ProfileTraps) note_trap(thread, Deoptimization::Reason_range_check, method, trap_bci); }
 719 void InterpreterRuntime::note_classCheck_trap(JavaThread* thread, Method *method, int trap_bci)
 720   { if (ProfileTraps) note_trap(thread, Deoptimization::Reason_class_check, method, trap_bci); }
 721 void InterpreterRuntime::note_arrayCheck_trap(JavaThread* thread, Method *method, int trap_bci)
 722   { if (ProfileTraps) note_trap(thread, Deoptimization::Reason_array_check, method, trap_bci); }
 723 #endif // CC_INTERP
 724 
 725 
 726 static Handle get_preinitialized_exception(Klass* k, TRAPS) {
 727   // get klass
 728   InstanceKlass* klass = InstanceKlass::cast(k);
 729   assert(klass->is_initialized(),
 730          "this klass should have been initialized during VM initialization");
 731   // create instance - do not call constructor since we may have no
 732   // (java) stack space left (should assert constructor is empty)
 733   Handle exception;
 734   oop exception_oop = klass->allocate_instance(CHECK_(exception));
 735   exception = Handle(THREAD, exception_oop);
 736   if (StackTraceInThrowable) {
 737     java_lang_Throwable::fill_in_stack_trace(exception);
 738   }
 739   return exception;
 740 }
 741 
 742 // Special handling for stack overflow: since we don't have any (java) stack
 743 // space left we use the pre-allocated & pre-initialized StackOverflowError
 744 // klass to create an stack overflow error instance.  We do not call its
 745 // constructor for the same reason (it is empty, anyway).
 746 IRT_ENTRY(void, InterpreterRuntime::throw_StackOverflowError(JavaThread* thread))
 747   Handle exception = get_preinitialized_exception(
 748                                  SystemDictionary::StackOverflowError_klass(),
 749                                  CHECK);
 750   // Increment counter for hs_err file reporting
 751   Atomic::inc(&Exceptions::_stack_overflow_errors);
 752   THROW_HANDLE(exception);
 753 IRT_END
 754 
 755 IRT_ENTRY(void, InterpreterRuntime::throw_delayed_StackOverflowError(JavaThread* thread))
 756   Handle exception = get_preinitialized_exception(
 757                                  SystemDictionary::StackOverflowError_klass(),
 758                                  CHECK);
 759   java_lang_Throwable::set_message(exception(),
 760           Universe::delayed_stack_overflow_error_message());
 761   // Increment counter for hs_err file reporting
 762   Atomic::inc(&Exceptions::_stack_overflow_errors);
 763   THROW_HANDLE(exception);
 764 IRT_END
 765 
 766 IRT_ENTRY(void, InterpreterRuntime::create_exception(JavaThread* thread, char* name, char* message))
 767   // lookup exception klass
 768   TempNewSymbol s = SymbolTable::new_symbol(name, CHECK);
 769   if (ProfileTraps) {
 770     if (s == vmSymbols::java_lang_ArithmeticException()) {
 771       note_trap(thread, Deoptimization::Reason_div0_check, CHECK);
 772     } else if (s == vmSymbols::java_lang_NullPointerException()) {
 773       note_trap(thread, Deoptimization::Reason_null_check, CHECK);
 774     }
 775   }
 776   // create exception
 777   Handle exception = Exceptions::new_exception(thread, s, message);
 778   thread->set_vm_result(exception());
 779 IRT_END
 780 
 781 
 782 IRT_ENTRY(void, InterpreterRuntime::create_klass_exception(JavaThread* thread, char* name, oopDesc* obj))
 783   ResourceMark rm(thread);
 784   const char* klass_name = obj->klass()->external_name();
 785   // lookup exception klass
 786   TempNewSymbol s = SymbolTable::new_symbol(name, CHECK);
 787   if (ProfileTraps) {
 788     note_trap(thread, Deoptimization::Reason_class_check, CHECK);
 789   }
 790   // create exception, with klass name as detail message
 791   Handle exception = Exceptions::new_exception(thread, s, klass_name);
 792   thread->set_vm_result(exception());
 793 IRT_END
 794 
 795 
 796 IRT_ENTRY(void, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException(JavaThread* thread, char* name, jint index))
 797   char message[jintAsStringSize];
 798   // lookup exception klass
 799   TempNewSymbol s = SymbolTable::new_symbol(name, CHECK);
 800   if (ProfileTraps) {
 801     note_trap(thread, Deoptimization::Reason_range_check, CHECK);
 802   }
 803   // create exception
 804   sprintf(message, "%d", index);
 805   THROW_MSG(s, message);
 806 IRT_END
 807 
 808 IRT_ENTRY(void, InterpreterRuntime::throw_ClassCastException(
 809   JavaThread* thread, oopDesc* obj))
 810 
 811   ResourceMark rm(thread);
 812   char* message = SharedRuntime::generate_class_cast_message(
 813     thread, obj->klass());
 814 
 815   if (ProfileTraps) {
 816     note_trap(thread, Deoptimization::Reason_class_check, CHECK);
 817   }
 818 
 819   // create exception
 820   THROW_MSG(vmSymbols::java_lang_ClassCastException(), message);
 821 IRT_END
 822 
 823 // exception_handler_for_exception(...) returns the continuation address,
 824 // the exception oop (via TLS) and sets the bci/bcp for the continuation.
 825 // The exception oop is returned to make sure it is preserved over GC (it
 826 // is only on the stack if the exception was thrown explicitly via athrow).
 827 // During this operation, the expression stack contains the values for the
 828 // bci where the exception happened. If the exception was propagated back
 829 // from a call, the expression stack contains the values for the bci at the
 830 // invoke w/o arguments (i.e., as if one were inside the call).
 831 IRT_ENTRY(address, InterpreterRuntime::exception_handler_for_exception(JavaThread* thread, oopDesc* exception))
 832 
 833   LastFrameAccessor last_frame(thread);
 834   Handle             h_exception(thread, exception);
 835   methodHandle       h_method   (thread, last_frame.method());
 836   constantPoolHandle h_constants(thread, h_method->constants());
 837   bool               should_repeat;
 838   int                handler_bci;
 839   int                current_bci = last_frame.bci();
 840 
 841   if (thread->frames_to_pop_failed_realloc() > 0) {
 842     // Allocation of scalar replaced object used in this frame
 843     // failed. Unconditionally pop the frame.
 844     thread->dec_frames_to_pop_failed_realloc();
 845     thread->set_vm_result(h_exception());
 846     // If the method is synchronized we already unlocked the monitor
 847     // during deoptimization so the interpreter needs to skip it when
 848     // the frame is popped.
 849     thread->set_do_not_unlock_if_synchronized(true);
 850 #ifdef CC_INTERP
 851     return (address) -1;
 852 #else
 853     return Interpreter::remove_activation_entry();
 854 #endif
 855   }
 856 
 857   // Need to do this check first since when _do_not_unlock_if_synchronized
 858   // is set, we don't want to trigger any classloading which may make calls
 859   // into java, or surprisingly find a matching exception handler for bci 0
 860   // since at this moment the method hasn't been "officially" entered yet.
 861   if (thread->do_not_unlock_if_synchronized()) {
 862     ResourceMark rm;
 863     assert(current_bci == 0,  "bci isn't zero for do_not_unlock_if_synchronized");
 864     thread->set_vm_result(exception);
 865 #ifdef CC_INTERP
 866     return (address) -1;
 867 #else
 868     return Interpreter::remove_activation_entry();
 869 #endif
 870   }
 871 
 872   do {
 873     should_repeat = false;
 874 
 875     // assertions
 876 #ifdef ASSERT
 877     assert(h_exception.not_null(), "NULL exceptions should be handled by athrow");
 878     // Check that exception is a subclass of Throwable, otherwise we have a VerifyError
 879     if (!(h_exception->is_a(SystemDictionary::Throwable_klass()))) {
 880       if (ExitVMOnVerifyError) vm_exit(-1);
 881       ShouldNotReachHere();
 882     }
 883 #endif
 884 
 885     // tracing
 886     if (log_is_enabled(Info, exceptions)) {
 887       ResourceMark rm(thread);
 888       stringStream tempst;
 889       tempst.print("interpreter method <%s>\n"
 890                    " at bci %d for thread " INTPTR_FORMAT,
 891                    h_method->print_value_string(), current_bci, p2i(thread));
 892       Exceptions::log_exception(h_exception, tempst);
 893     }
 894 // Don't go paging in something which won't be used.
 895 //     else if (extable->length() == 0) {
 896 //       // disabled for now - interpreter is not using shortcut yet
 897 //       // (shortcut is not to call runtime if we have no exception handlers)
 898 //       // warning("performance bug: should not call runtime if method has no exception handlers");
 899 //     }
 900     // for AbortVMOnException flag
 901     Exceptions::debug_check_abort(h_exception);
 902 
 903     // exception handler lookup
 904     Klass* klass = h_exception->klass();
 905     handler_bci = Method::fast_exception_handler_bci_for(h_method, klass, current_bci, THREAD);
 906     if (HAS_PENDING_EXCEPTION) {
 907       // We threw an exception while trying to find the exception handler.
 908       // Transfer the new exception to the exception handle which will
 909       // be set into thread local storage, and do another lookup for an
 910       // exception handler for this exception, this time starting at the
 911       // BCI of the exception handler which caused the exception to be
 912       // thrown (bug 4307310).
 913       h_exception = Handle(THREAD, PENDING_EXCEPTION);
 914       CLEAR_PENDING_EXCEPTION;
 915       if (handler_bci >= 0) {
 916         current_bci = handler_bci;
 917         should_repeat = true;
 918       }
 919     }
 920   } while (should_repeat == true);
 921 
 922 #if INCLUDE_JVMCI
 923   if (EnableJVMCI && h_method->method_data() != NULL) {
 924     ResourceMark rm(thread);
 925     ProfileData* pdata = h_method->method_data()->allocate_bci_to_data(current_bci, NULL);
 926     if (pdata != NULL && pdata->is_BitData()) {
 927       BitData* bit_data = (BitData*) pdata;
 928       bit_data->set_exception_seen();
 929     }
 930   }
 931 #endif
 932 
 933   // notify JVMTI of an exception throw; JVMTI will detect if this is a first
 934   // time throw or a stack unwinding throw and accordingly notify the debugger
 935   if (JvmtiExport::can_post_on_exceptions()) {
 936     JvmtiExport::post_exception_throw(thread, h_method(), last_frame.bcp(), h_exception());
 937   }
 938 
 939 #ifdef CC_INTERP
 940   address continuation = (address)(intptr_t) handler_bci;
 941 #else
 942   address continuation = NULL;
 943 #endif
 944   address handler_pc = NULL;
 945   if (handler_bci < 0 || !thread->reguard_stack((address) &continuation)) {
 946     // Forward exception to callee (leaving bci/bcp untouched) because (a) no
 947     // handler in this method, or (b) after a stack overflow there is not yet
 948     // enough stack space available to reprotect the stack.
 949 #ifndef CC_INTERP
 950     continuation = Interpreter::remove_activation_entry();
 951 #endif
 952 #if COMPILER2_OR_JVMCI
 953     // Count this for compilation purposes
 954     h_method->interpreter_throwout_increment(THREAD);
 955 #endif
 956   } else {
 957     // handler in this method => change bci/bcp to handler bci/bcp and continue there
 958     handler_pc = h_method->code_base() + handler_bci;
 959 #ifndef CC_INTERP
 960     set_bcp_and_mdp(handler_pc, thread);
 961     continuation = Interpreter::dispatch_table(vtos)[*handler_pc];
 962 #endif
 963   }
 964   // notify debugger of an exception catch
 965   // (this is good for exceptions caught in native methods as well)
 966   if (JvmtiExport::can_post_on_exceptions()) {
 967     JvmtiExport::notice_unwind_due_to_exception(thread, h_method(), handler_pc, h_exception(), (handler_pc != NULL));
 968   }
 969 
 970   thread->set_vm_result(h_exception());
 971   return continuation;
 972 IRT_END
 973 
 974 
 975 IRT_ENTRY(void, InterpreterRuntime::throw_pending_exception(JavaThread* thread))
 976   assert(thread->has_pending_exception(), "must only ne called if there's an exception pending");
 977   // nothing to do - eventually we should remove this code entirely (see comments @ call sites)
 978 IRT_END
 979 
 980 
 981 IRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodError(JavaThread* thread))
 982   THROW(vmSymbols::java_lang_AbstractMethodError());
 983 IRT_END
 984 
 985 
 986 IRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeError(JavaThread* thread))
 987   THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
 988 IRT_END
 989 
 990 
 991 //------------------------------------------------------------------------------------------------------------------------
 992 // Fields
 993 //
 994 
 995 void InterpreterRuntime::resolve_get_put(JavaThread* thread, Bytecodes::Code bytecode) {
 996   Thread* THREAD = thread;
 997   // resolve field
 998   fieldDescriptor info;
 999   LastFrameAccessor last_frame(thread);
1000   constantPoolHandle pool(thread, last_frame.method()->constants());
1001   methodHandle m(thread, last_frame.method());
1002   bool is_put    = (bytecode == Bytecodes::_putfield  || bytecode == Bytecodes::_nofast_putfield ||
1003                     bytecode == Bytecodes::_putstatic || bytecode == Bytecodes::_vwithfield);
1004   bool is_static = (bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic);
1005   bool is_value  = bytecode == Bytecodes::_vwithfield;
1006 
1007   {
1008     JvmtiHideSingleStepping jhss(thread);
1009     LinkResolver::resolve_field_access(info, pool, last_frame.get_index_u2_cpcache(bytecode),
1010                                        m, bytecode, CHECK);
1011   } // end JvmtiHideSingleStepping
1012 
1013   // check if link resolution caused cpCache to be updated
1014   ConstantPoolCacheEntry* cp_cache_entry = last_frame.cache_entry();
1015   if (cp_cache_entry->is_resolved(bytecode)) return;
1016 
1017   // compute auxiliary field attributes
1018   TosState state  = as_TosState(info.field_type());
1019 
1020   // Resolution of put instructions on final fields is delayed. That is required so that
1021   // exceptions are thrown at the correct place (when the instruction is actually invoked).
1022   // If we do not resolve an instruction in the current pass, leaving the put_code
1023   // set to zero will cause the next put instruction to the same field to reresolve.
1024 
1025   // Resolution of put instructions to final instance fields with invalid updates (i.e.,
1026   // to final instance fields with updates originating from a method different than <init>)
1027   // is inhibited. A putfield instruction targeting an instance final field must throw
1028   // an IllegalAccessError if the instruction is not in an instance
1029   // initializer method <init>. If resolution were not inhibited, a putfield
1030   // in an initializer method could be resolved in the initializer. Subsequent
1031   // putfield instructions to the same field would then use cached information.
1032   // As a result, those instructions would not pass through the VM. That is,
1033   // checks in resolve_field_access() would not be executed for those instructions
1034   // and the required IllegalAccessError would not be thrown.
1035   //
1036   // Also, we need to delay resolving getstatic and putstatic instructions until the
1037   // class is initialized.  This is required so that access to the static
1038   // field will call the initialization function every time until the class
1039   // is completely initialized ala. in 2.17.5 in JVM Specification.
1040   InstanceKlass* klass = InstanceKlass::cast(info.field_holder());
1041   bool uninitialized_static = is_static && !klass->is_initialized();
1042   bool has_initialized_final_update = info.field_holder()->major_version() >= 53 &&
1043                                       info.has_initialized_final_update();
1044   assert(!(has_initialized_final_update && !info.access_flags().is_final()), "Fields with initialized final updates must be final");
1045 
1046   Bytecodes::Code get_code = (Bytecodes::Code)0;
1047   Bytecodes::Code put_code = (Bytecodes::Code)0;
1048   if (!uninitialized_static) {
1049     if (is_static) {
1050       get_code = Bytecodes::_getstatic;
1051     } else {
1052       get_code = Bytecodes::_getfield;
1053     }
1054     if (is_put && is_value) {
1055         put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_vwithfield);
1056     } else if ((is_put && !has_initialized_final_update) || !info.access_flags().is_final()) {
1057         put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_putfield);
1058     }
1059   }
1060 
1061   cp_cache_entry->set_field(
1062     get_code,
1063     put_code,
1064     info.field_holder(),
1065     info.index(),
1066     info.offset(),
1067     state,
1068     info.access_flags().is_final(),
1069     info.access_flags().is_volatile(),
1070     info.is_flatten(),
1071     pool->pool_holder()
1072   );
1073 }
1074 
1075 
1076 //------------------------------------------------------------------------------------------------------------------------
1077 // Synchronization
1078 //
1079 // The interpreter's synchronization code is factored out so that it can
1080 // be shared by method invocation and synchronized blocks.
1081 //%note synchronization_3
1082 
1083 //%note monitor_1
1084 IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* thread, BasicObjectLock* elem))
1085 #ifdef ASSERT
1086   thread->last_frame().interpreter_frame_verify_monitor(elem);
1087 #endif
1088   if (PrintBiasedLockingStatistics) {
1089     Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
1090   }
1091   Handle h_obj(thread, elem->obj());
1092   assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
1093          "must be NULL or an object");
1094   if (UseBiasedLocking) {
1095     // Retry fast entry if bias is revoked to avoid unnecessary inflation
1096     ObjectSynchronizer::fast_enter(h_obj, elem->lock(), true, CHECK);
1097   } else {
1098     ObjectSynchronizer::slow_enter(h_obj, elem->lock(), CHECK);
1099   }
1100   assert(Universe::heap()->is_in_reserved_or_null(elem->obj()),
1101          "must be NULL or an object");
1102 #ifdef ASSERT
1103   thread->last_frame().interpreter_frame_verify_monitor(elem);
1104 #endif
1105 IRT_END
1106 
1107 
1108 //%note monitor_1
1109 IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorexit(JavaThread* thread, BasicObjectLock* elem))
1110 #ifdef ASSERT
1111   thread->last_frame().interpreter_frame_verify_monitor(elem);
1112 #endif
1113   Handle h_obj(thread, elem->obj());
1114   assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
1115          "must be NULL or an object");
1116   if (elem == NULL || h_obj()->is_unlocked()) {
1117     THROW(vmSymbols::java_lang_IllegalMonitorStateException());
1118   }
1119   ObjectSynchronizer::slow_exit(h_obj(), elem->lock(), thread);
1120   // Free entry. This must be done here, since a pending exception might be installed on
1121   // exit. If it is not cleared, the exception handling code will try to unlock the monitor again.
1122   elem->set_obj(NULL);
1123 #ifdef ASSERT
1124   thread->last_frame().interpreter_frame_verify_monitor(elem);
1125 #endif
1126 IRT_END
1127 
1128 
1129 IRT_ENTRY(void, InterpreterRuntime::throw_illegal_monitor_state_exception(JavaThread* thread))
1130   THROW(vmSymbols::java_lang_IllegalMonitorStateException());
1131 IRT_END
1132 
1133 
1134 IRT_ENTRY(void, InterpreterRuntime::new_illegal_monitor_state_exception(JavaThread* thread))
1135   // Returns an illegal exception to install into the current thread. The
1136   // pending_exception flag is cleared so normal exception handling does not
1137   // trigger. Any current installed exception will be overwritten. This
1138   // method will be called during an exception unwind.
1139 
1140   assert(!HAS_PENDING_EXCEPTION, "no pending exception");
1141   Handle exception(thread, thread->vm_result());
1142   assert(exception() != NULL, "vm result should be set");
1143   thread->set_vm_result(NULL); // clear vm result before continuing (may cause memory leaks and assert failures)
1144   if (!exception->is_a(SystemDictionary::ThreadDeath_klass())) {
1145     exception = get_preinitialized_exception(
1146                        SystemDictionary::IllegalMonitorStateException_klass(),
1147                        CATCH);
1148   }
1149   thread->set_vm_result(exception());
1150 IRT_END
1151 
1152 
1153 //------------------------------------------------------------------------------------------------------------------------
1154 // Invokes
1155 
1156 IRT_ENTRY(Bytecodes::Code, InterpreterRuntime::get_original_bytecode_at(JavaThread* thread, Method* method, address bcp))
1157   return method->orig_bytecode_at(method->bci_from(bcp));
1158 IRT_END
1159 
1160 IRT_ENTRY(void, InterpreterRuntime::set_original_bytecode_at(JavaThread* thread, Method* method, address bcp, Bytecodes::Code new_code))
1161   method->set_orig_bytecode_at(method->bci_from(bcp), new_code);
1162 IRT_END
1163 
1164 IRT_ENTRY(void, InterpreterRuntime::_breakpoint(JavaThread* thread, Method* method, address bcp))
1165   JvmtiExport::post_raw_breakpoint(thread, method, bcp);
1166 IRT_END
1167 
1168 void InterpreterRuntime::resolve_invoke(JavaThread* thread, Bytecodes::Code bytecode) {
1169   Thread* THREAD = thread;
1170   LastFrameAccessor last_frame(thread);
1171   // extract receiver from the outgoing argument list if necessary
1172   Handle receiver(thread, NULL);
1173   if (bytecode == Bytecodes::_invokevirtual || bytecode == Bytecodes::_invokeinterface ||
1174       bytecode == Bytecodes::_invokespecial) {
1175     ResourceMark rm(thread);
1176     methodHandle m (thread, last_frame.method());
1177     Bytecode_invoke call(m, last_frame.bci());
1178     Symbol* signature = call.signature();
1179     receiver = Handle(thread, last_frame.callee_receiver(signature));
1180 
1181     assert(Universe::heap()->is_in_reserved_or_null(receiver())
1182            || VTBuffer::is_in_vt_buffer(receiver()),
1183            "sanity check");
1184     assert(receiver.is_null() ||
1185            !Universe::heap()->is_in_reserved(receiver->klass()),
1186            "sanity check");
1187   }
1188 
1189   // resolve method
1190   CallInfo info;
1191   constantPoolHandle pool(thread, last_frame.method()->constants());
1192 
1193   {
1194     JvmtiHideSingleStepping jhss(thread);
1195     LinkResolver::resolve_invoke(info, receiver, pool,
1196                                  last_frame.get_index_u2_cpcache(bytecode), bytecode,
1197                                  CHECK);
1198     if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
1199       int retry_count = 0;
1200       while (info.resolved_method()->is_old()) {
1201         // It is very unlikely that method is redefined more than 100 times
1202         // in the middle of resolve. If it is looping here more than 100 times
1203         // means then there could be a bug here.
1204         guarantee((retry_count++ < 100),
1205                   "Could not resolve to latest version of redefined method");
1206         // method is redefined in the middle of resolve so re-try.
1207         LinkResolver::resolve_invoke(info, receiver, pool,
1208                                      last_frame.get_index_u2_cpcache(bytecode), bytecode,
1209                                      CHECK);
1210       }
1211     }
1212   } // end JvmtiHideSingleStepping
1213 
1214   // check if link resolution caused cpCache to be updated
1215   ConstantPoolCacheEntry* cp_cache_entry = last_frame.cache_entry();
1216   if (cp_cache_entry->is_resolved(bytecode)) return;
1217 
1218 #ifdef ASSERT
1219   if (bytecode == Bytecodes::_invokeinterface) {
1220     if (info.resolved_method()->method_holder() ==
1221                                             SystemDictionary::Object_klass()) {
1222       // NOTE: THIS IS A FIX FOR A CORNER CASE in the JVM spec
1223       // (see also CallInfo::set_interface for details)
1224       assert(info.call_kind() == CallInfo::vtable_call ||
1225              info.call_kind() == CallInfo::direct_call, "");
1226       methodHandle rm = info.resolved_method();
1227       assert(rm->is_final() || info.has_vtable_index(),
1228              "should have been set already");
1229     } else if (!info.resolved_method()->has_itable_index()) {
1230       // Resolved something like CharSequence.toString.  Use vtable not itable.
1231       assert(info.call_kind() != CallInfo::itable_call, "");
1232     } else {
1233       // Setup itable entry
1234       assert(info.call_kind() == CallInfo::itable_call, "");
1235       int index = info.resolved_method()->itable_index();
1236       assert(info.itable_index() == index, "");
1237     }
1238   } else if (bytecode == Bytecodes::_invokespecial) {
1239     assert(info.call_kind() == CallInfo::direct_call, "must be direct call");
1240   } else {
1241     assert(info.call_kind() == CallInfo::direct_call ||
1242            info.call_kind() == CallInfo::vtable_call, "");
1243   }
1244 #endif
1245   // Get sender or sender's host_klass, and only set cpCache entry to resolved if
1246   // it is not an interface.  The receiver for invokespecial calls within interface
1247   // methods must be checked for every call.
1248   InstanceKlass* sender = pool->pool_holder();
1249   sender = sender->is_anonymous() ? sender->host_klass() : sender;
1250 
1251   switch (info.call_kind()) {
1252   case CallInfo::direct_call:
1253     cp_cache_entry->set_direct_call(
1254       bytecode,
1255       info.resolved_method(),
1256       sender->is_interface());
1257     break;
1258   case CallInfo::vtable_call:
1259     cp_cache_entry->set_vtable_call(
1260       bytecode,
1261       info.resolved_method(),
1262       info.vtable_index());
1263     break;
1264   case CallInfo::itable_call:
1265     cp_cache_entry->set_itable_call(
1266       bytecode,
1267       info.resolved_method(),
1268       info.itable_index());
1269     break;
1270   default:  ShouldNotReachHere();
1271   }
1272 }
1273 
1274 
1275 // First time execution:  Resolve symbols, create a permanent MethodType object.
1276 void InterpreterRuntime::resolve_invokehandle(JavaThread* thread) {
1277   Thread* THREAD = thread;
1278   const Bytecodes::Code bytecode = Bytecodes::_invokehandle;
1279   LastFrameAccessor last_frame(thread);
1280 
1281   // resolve method
1282   CallInfo info;
1283   constantPoolHandle pool(thread, last_frame.method()->constants());
1284   {
1285     JvmtiHideSingleStepping jhss(thread);
1286     LinkResolver::resolve_invoke(info, Handle(), pool,
1287                                  last_frame.get_index_u2_cpcache(bytecode), bytecode,
1288                                  CHECK);
1289   } // end JvmtiHideSingleStepping
1290 
1291   ConstantPoolCacheEntry* cp_cache_entry = last_frame.cache_entry();
1292   cp_cache_entry->set_method_handle(pool, info);
1293 }
1294 
1295 // First time execution:  Resolve symbols, create a permanent CallSite object.
1296 void InterpreterRuntime::resolve_invokedynamic(JavaThread* thread) {
1297   Thread* THREAD = thread;
1298   LastFrameAccessor last_frame(thread);
1299   const Bytecodes::Code bytecode = Bytecodes::_invokedynamic;
1300 
1301   //TO DO: consider passing BCI to Java.
1302   //  int caller_bci = last_frame.method()->bci_from(last_frame.bcp());
1303 
1304   // resolve method
1305   CallInfo info;
1306   constantPoolHandle pool(thread, last_frame.method()->constants());
1307   int index = last_frame.get_index_u4(bytecode);
1308   {
1309     JvmtiHideSingleStepping jhss(thread);
1310     LinkResolver::resolve_invoke(info, Handle(), pool,
1311                                  index, bytecode, CHECK);
1312   } // end JvmtiHideSingleStepping
1313 
1314   ConstantPoolCacheEntry* cp_cache_entry = pool->invokedynamic_cp_cache_entry_at(index);
1315   cp_cache_entry->set_dynamic_call(pool, info);
1316 }
1317 
1318 // This function is the interface to the assembly code. It returns the resolved
1319 // cpCache entry.  This doesn't safepoint, but the helper routines safepoint.
1320 // This function will check for redefinition!
1321 IRT_ENTRY(void, InterpreterRuntime::resolve_from_cache(JavaThread* thread, Bytecodes::Code bytecode)) {
1322   switch (bytecode) {
1323   case Bytecodes::_getstatic:
1324   case Bytecodes::_putstatic:
1325   case Bytecodes::_getfield:
1326   case Bytecodes::_putfield:
1327   case Bytecodes::_vwithfield:
1328     resolve_get_put(thread, bytecode);
1329     break;
1330   case Bytecodes::_invokevirtual:
1331   case Bytecodes::_invokespecial:
1332   case Bytecodes::_invokestatic:
1333   case Bytecodes::_invokeinterface:
1334     resolve_invoke(thread, bytecode);
1335     break;
1336   case Bytecodes::_invokehandle:
1337     resolve_invokehandle(thread);
1338     break;
1339   case Bytecodes::_invokedynamic:
1340     resolve_invokedynamic(thread);
1341     break;
1342   default:
1343     fatal("unexpected bytecode: %s", Bytecodes::name(bytecode));
1344     break;
1345   }
1346 }
1347 IRT_END
1348 
1349 //------------------------------------------------------------------------------------------------------------------------
1350 // Miscellaneous
1351 
1352 
1353 nmethod* InterpreterRuntime::frequency_counter_overflow(JavaThread* thread, address branch_bcp) {
1354   nmethod* nm = frequency_counter_overflow_inner(thread, branch_bcp);
1355   assert(branch_bcp != NULL || nm == NULL, "always returns null for non OSR requests");
1356   if (branch_bcp != NULL && nm != NULL) {
1357     // This was a successful request for an OSR nmethod.  Because
1358     // frequency_counter_overflow_inner ends with a safepoint check,
1359     // nm could have been unloaded so look it up again.  It's unsafe
1360     // to examine nm directly since it might have been freed and used
1361     // for something else.
1362     LastFrameAccessor last_frame(thread);
1363     Method* method =  last_frame.method();
1364     int bci = method->bci_from(last_frame.bcp());
1365     nm = method->lookup_osr_nmethod_for(bci, CompLevel_none, false);
1366   }
1367   if (nm != NULL && thread->is_interp_only_mode()) {
1368     // Normally we never get an nm if is_interp_only_mode() is true, because
1369     // policy()->event has a check for this and won't compile the method when
1370     // true. However, it's possible for is_interp_only_mode() to become true
1371     // during the compilation. We don't want to return the nm in that case
1372     // because we want to continue to execute interpreted.
1373     nm = NULL;
1374   }
1375 #ifndef PRODUCT
1376   if (TraceOnStackReplacement) {
1377     if (nm != NULL) {
1378       tty->print("OSR entry @ pc: " INTPTR_FORMAT ": ", p2i(nm->osr_entry()));
1379       nm->print();
1380     }
1381   }
1382 #endif
1383   return nm;
1384 }
1385 
1386 IRT_ENTRY(nmethod*,
1387           InterpreterRuntime::frequency_counter_overflow_inner(JavaThread* thread, address branch_bcp))
1388   // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
1389   // flag, in case this method triggers classloading which will call into Java.
1390   UnlockFlagSaver fs(thread);
1391 
1392   LastFrameAccessor last_frame(thread);
1393   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1394   methodHandle method(thread, last_frame.method());
1395   const int branch_bci = branch_bcp != NULL ? method->bci_from(branch_bcp) : InvocationEntryBci;
1396   const int bci = branch_bcp != NULL ? method->bci_from(last_frame.bcp()) : InvocationEntryBci;
1397 
1398   assert(!HAS_PENDING_EXCEPTION, "Should not have any exceptions pending");
1399   nmethod* osr_nm = CompilationPolicy::policy()->event(method, method, branch_bci, bci, CompLevel_none, NULL, thread);
1400   assert(!HAS_PENDING_EXCEPTION, "Event handler should not throw any exceptions");
1401 
1402   if (osr_nm != NULL) {
1403     // We may need to do on-stack replacement which requires that no
1404     // monitors in the activation are biased because their
1405     // BasicObjectLocks will need to migrate during OSR. Force
1406     // unbiasing of all monitors in the activation now (even though
1407     // the OSR nmethod might be invalidated) because we don't have a
1408     // safepoint opportunity later once the migration begins.
1409     if (UseBiasedLocking) {
1410       ResourceMark rm;
1411       GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
1412       for( BasicObjectLock *kptr = last_frame.monitor_end();
1413            kptr < last_frame.monitor_begin();
1414            kptr = last_frame.next_monitor(kptr) ) {
1415         if( kptr->obj() != NULL ) {
1416           objects_to_revoke->append(Handle(THREAD, kptr->obj()));
1417         }
1418       }
1419       BiasedLocking::revoke(objects_to_revoke);
1420     }
1421   }
1422   return osr_nm;
1423 IRT_END
1424 
1425 IRT_LEAF(jint, InterpreterRuntime::bcp_to_di(Method* method, address cur_bcp))
1426   assert(ProfileInterpreter, "must be profiling interpreter");
1427   int bci = method->bci_from(cur_bcp);
1428   MethodData* mdo = method->method_data();
1429   if (mdo == NULL)  return 0;
1430   return mdo->bci_to_di(bci);
1431 IRT_END
1432 
1433 IRT_ENTRY(void, InterpreterRuntime::profile_method(JavaThread* thread))
1434   // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
1435   // flag, in case this method triggers classloading which will call into Java.
1436   UnlockFlagSaver fs(thread);
1437 
1438   assert(ProfileInterpreter, "must be profiling interpreter");
1439   LastFrameAccessor last_frame(thread);
1440   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1441   methodHandle method(thread, last_frame.method());
1442   Method::build_interpreter_method_data(method, THREAD);
1443   if (HAS_PENDING_EXCEPTION) {
1444     assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
1445     CLEAR_PENDING_EXCEPTION;
1446     // and fall through...
1447   }
1448 IRT_END
1449 
1450 
1451 #ifdef ASSERT
1452 IRT_LEAF(void, InterpreterRuntime::verify_mdp(Method* method, address bcp, address mdp))
1453   assert(ProfileInterpreter, "must be profiling interpreter");
1454 
1455   MethodData* mdo = method->method_data();
1456   assert(mdo != NULL, "must not be null");
1457 
1458   int bci = method->bci_from(bcp);
1459 
1460   address mdp2 = mdo->bci_to_dp(bci);
1461   if (mdp != mdp2) {
1462     ResourceMark rm;
1463     ResetNoHandleMark rnm; // In a LEAF entry.
1464     HandleMark hm;
1465     tty->print_cr("FAILED verify : actual mdp %p   expected mdp %p @ bci %d", mdp, mdp2, bci);
1466     int current_di = mdo->dp_to_di(mdp);
1467     int expected_di  = mdo->dp_to_di(mdp2);
1468     tty->print_cr("  actual di %d   expected di %d", current_di, expected_di);
1469     int expected_approx_bci = mdo->data_at(expected_di)->bci();
1470     int approx_bci = -1;
1471     if (current_di >= 0) {
1472       approx_bci = mdo->data_at(current_di)->bci();
1473     }
1474     tty->print_cr("  actual bci is %d  expected bci %d", approx_bci, expected_approx_bci);
1475     mdo->print_on(tty);
1476     method->print_codes();
1477   }
1478   assert(mdp == mdp2, "wrong mdp");
1479 IRT_END
1480 #endif // ASSERT
1481 
1482 IRT_ENTRY(void, InterpreterRuntime::update_mdp_for_ret(JavaThread* thread, int return_bci))
1483   assert(ProfileInterpreter, "must be profiling interpreter");
1484   ResourceMark rm(thread);
1485   HandleMark hm(thread);
1486   LastFrameAccessor last_frame(thread);
1487   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1488   MethodData* h_mdo = last_frame.method()->method_data();
1489 
1490   // Grab a lock to ensure atomic access to setting the return bci and
1491   // the displacement.  This can block and GC, invalidating all naked oops.
1492   MutexLocker ml(RetData_lock);
1493 
1494   // ProfileData is essentially a wrapper around a derived oop, so we
1495   // need to take the lock before making any ProfileData structures.
1496   ProfileData* data = h_mdo->data_at(h_mdo->dp_to_di(last_frame.mdp()));
1497   guarantee(data != NULL, "profile data must be valid");
1498   RetData* rdata = data->as_RetData();
1499   address new_mdp = rdata->fixup_ret(return_bci, h_mdo);
1500   last_frame.set_mdp(new_mdp);
1501 IRT_END
1502 
1503 IRT_ENTRY(MethodCounters*, InterpreterRuntime::build_method_counters(JavaThread* thread, Method* m))
1504   MethodCounters* mcs = Method::build_method_counters(m, thread);
1505   if (HAS_PENDING_EXCEPTION) {
1506     assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
1507     CLEAR_PENDING_EXCEPTION;
1508   }
1509   return mcs;
1510 IRT_END
1511 
1512 
1513 IRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* thread))
1514   // We used to need an explict preserve_arguments here for invoke bytecodes. However,
1515   // stack traversal automatically takes care of preserving arguments for invoke, so
1516   // this is no longer needed.
1517 
1518   // IRT_END does an implicit safepoint check, hence we are guaranteed to block
1519   // if this is called during a safepoint
1520 
1521   if (JvmtiExport::should_post_single_step()) {
1522     // We are called during regular safepoints and when the VM is
1523     // single stepping. If any thread is marked for single stepping,
1524     // then we may have JVMTI work to do.
1525     LastFrameAccessor last_frame(thread);
1526     JvmtiExport::at_single_stepping_point(thread, last_frame.method(), last_frame.bcp());
1527   }
1528 IRT_END
1529 
1530 IRT_ENTRY(void, InterpreterRuntime::post_field_access(JavaThread *thread, oopDesc* obj,
1531 ConstantPoolCacheEntry *cp_entry))
1532 
1533   // check the access_flags for the field in the klass
1534 
1535   InstanceKlass* ik = InstanceKlass::cast(cp_entry->f1_as_klass());
1536   int index = cp_entry->field_index();
1537   if ((ik->field_access_flags(index) & JVM_ACC_FIELD_ACCESS_WATCHED) == 0) return;
1538 
1539   bool is_static = (obj == NULL);
1540   HandleMark hm(thread);
1541 
1542   Handle h_obj;
1543   if (!is_static) {
1544     // non-static field accessors have an object, but we need a handle
1545     h_obj = Handle(thread, obj);
1546   }
1547   InstanceKlass* cp_entry_f1 = InstanceKlass::cast(cp_entry->f1_as_klass());
1548   jfieldID fid = jfieldIDWorkaround::to_jfieldID(cp_entry_f1, cp_entry->f2_as_index(), is_static);
1549   LastFrameAccessor last_frame(thread);
1550   JvmtiExport::post_field_access(thread, last_frame.method(), last_frame.bcp(), cp_entry_f1, h_obj, fid);
1551 IRT_END
1552 
1553 IRT_ENTRY(void, InterpreterRuntime::post_field_modification(JavaThread *thread,
1554   oopDesc* obj, ConstantPoolCacheEntry *cp_entry, jvalue *value))
1555 
1556   Klass* k = cp_entry->f1_as_klass();
1557 
1558   // check the access_flags for the field in the klass
1559   InstanceKlass* ik = InstanceKlass::cast(k);
1560   int index = cp_entry->field_index();
1561   // bail out if field modifications are not watched
1562   if ((ik->field_access_flags(index) & JVM_ACC_FIELD_MODIFICATION_WATCHED) == 0) return;
1563 
1564   char sig_type = '\0';
1565 
1566   switch(cp_entry->flag_state()) {
1567     case btos: sig_type = 'B'; break;
1568     case ztos: sig_type = 'Z'; break;
1569     case ctos: sig_type = 'C'; break;
1570     case stos: sig_type = 'S'; break;
1571     case itos: sig_type = 'I'; break;
1572     case ftos: sig_type = 'F'; break;
1573     case atos: sig_type = 'L'; break;
1574     case ltos: sig_type = 'J'; break;
1575     case dtos: sig_type = 'D'; break;
1576     default:  ShouldNotReachHere(); return;
1577   }
1578   bool is_static = (obj == NULL);
1579 
1580   HandleMark hm(thread);
1581   jfieldID fid = jfieldIDWorkaround::to_jfieldID(ik, cp_entry->f2_as_index(), is_static);
1582   jvalue fvalue;
1583 #ifdef _LP64
1584   fvalue = *value;
1585 #else
1586   // Long/double values are stored unaligned and also noncontiguously with
1587   // tagged stacks.  We can't just do a simple assignment even in the non-
1588   // J/D cases because a C++ compiler is allowed to assume that a jvalue is
1589   // 8-byte aligned, and interpreter stack slots are only 4-byte aligned.
1590   // We assume that the two halves of longs/doubles are stored in interpreter
1591   // stack slots in platform-endian order.
1592   jlong_accessor u;
1593   jint* newval = (jint*)value;
1594   u.words[0] = newval[0];
1595   u.words[1] = newval[Interpreter::stackElementWords]; // skip if tag
1596   fvalue.j = u.long_value;
1597 #endif // _LP64
1598 
1599   Handle h_obj;
1600   if (!is_static) {
1601     // non-static field accessors have an object, but we need a handle
1602     h_obj = Handle(thread, obj);
1603   }
1604 
1605   LastFrameAccessor last_frame(thread);
1606   JvmtiExport::post_raw_field_modification(thread, last_frame.method(), last_frame.bcp(), ik, h_obj,
1607                                            fid, sig_type, &fvalue);
1608 IRT_END
1609 
1610 IRT_ENTRY(void, InterpreterRuntime::post_method_entry(JavaThread *thread))
1611   LastFrameAccessor last_frame(thread);
1612   JvmtiExport::post_method_entry(thread, last_frame.method(), last_frame.get_frame());
1613 IRT_END
1614 
1615 
1616 IRT_ENTRY(void, InterpreterRuntime::post_method_exit(JavaThread *thread))
1617   LastFrameAccessor last_frame(thread);
1618   JvmtiExport::post_method_exit(thread, last_frame.method(), last_frame.get_frame());
1619 IRT_END
1620 
1621 IRT_LEAF(int, InterpreterRuntime::interpreter_contains(address pc))
1622 {
1623   return (Interpreter::contains(pc) ? 1 : 0);
1624 }
1625 IRT_END
1626 
1627 
1628 // Implementation of SignatureHandlerLibrary
1629 
1630 #ifndef SHARING_FAST_NATIVE_FINGERPRINTS
1631 // Dummy definition (else normalization method is defined in CPU
1632 // dependant code)
1633 uint64_t InterpreterRuntime::normalize_fast_native_fingerprint(uint64_t fingerprint) {
1634   return fingerprint;
1635 }
1636 #endif
1637 
1638 address SignatureHandlerLibrary::set_handler_blob() {
1639   BufferBlob* handler_blob = BufferBlob::create("native signature handlers", blob_size);
1640   if (handler_blob == NULL) {
1641     return NULL;
1642   }
1643   address handler = handler_blob->code_begin();
1644   _handler_blob = handler_blob;
1645   _handler = handler;
1646   return handler;
1647 }
1648 
1649 void SignatureHandlerLibrary::initialize() {
1650   if (_fingerprints != NULL) {
1651     return;
1652   }
1653   if (set_handler_blob() == NULL) {
1654     vm_exit_out_of_memory(blob_size, OOM_MALLOC_ERROR, "native signature handlers");
1655   }
1656 
1657   BufferBlob* bb = BufferBlob::create("Signature Handler Temp Buffer",
1658                                       SignatureHandlerLibrary::buffer_size);
1659   _buffer = bb->code_begin();
1660 
1661   _fingerprints = new(ResourceObj::C_HEAP, mtCode)GrowableArray<uint64_t>(32, true);
1662   _handlers     = new(ResourceObj::C_HEAP, mtCode)GrowableArray<address>(32, true);
1663 }
1664 
1665 address SignatureHandlerLibrary::set_handler(CodeBuffer* buffer) {
1666   address handler   = _handler;
1667   int     insts_size = buffer->pure_insts_size();
1668   if (handler + insts_size > _handler_blob->code_end()) {
1669     // get a new handler blob
1670     handler = set_handler_blob();
1671   }
1672   if (handler != NULL) {
1673     memcpy(handler, buffer->insts_begin(), insts_size);
1674     pd_set_handler(handler);
1675     ICache::invalidate_range(handler, insts_size);
1676     _handler = handler + insts_size;
1677   }
1678   return handler;
1679 }
1680 
1681 void SignatureHandlerLibrary::add(const methodHandle& method) {
1682   if (method->signature_handler() == NULL) {
1683     // use slow signature handler if we can't do better
1684     int handler_index = -1;
1685     // check if we can use customized (fast) signature handler
1686     if (UseFastSignatureHandlers && method->size_of_parameters() <= Fingerprinter::max_size_of_parameters) {
1687       // use customized signature handler
1688       MutexLocker mu(SignatureHandlerLibrary_lock);
1689       // make sure data structure is initialized
1690       initialize();
1691       // lookup method signature's fingerprint
1692       uint64_t fingerprint = Fingerprinter(method).fingerprint();
1693       // allow CPU dependant code to optimize the fingerprints for the fast handler
1694       fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1695       handler_index = _fingerprints->find(fingerprint);
1696       // create handler if necessary
1697       if (handler_index < 0) {
1698         ResourceMark rm;
1699         ptrdiff_t align_offset = align_up(_buffer, CodeEntryAlignment) - (address)_buffer;
1700         CodeBuffer buffer((address)(_buffer + align_offset),
1701                           SignatureHandlerLibrary::buffer_size - align_offset);
1702         InterpreterRuntime::SignatureHandlerGenerator(method, &buffer).generate(fingerprint);
1703         // copy into code heap
1704         address handler = set_handler(&buffer);
1705         if (handler == NULL) {
1706           // use slow signature handler (without memorizing it in the fingerprints)
1707         } else {
1708           // debugging suppport
1709           if (PrintSignatureHandlers && (handler != Interpreter::slow_signature_handler())) {
1710             ttyLocker ttyl;
1711             tty->cr();
1712             tty->print_cr("argument handler #%d for: %s %s (fingerprint = " UINT64_FORMAT ", %d bytes generated)",
1713                           _handlers->length(),
1714                           (method->is_static() ? "static" : "receiver"),
1715                           method->name_and_sig_as_C_string(),
1716                           fingerprint,
1717                           buffer.insts_size());
1718             if (buffer.insts_size() > 0) {
1719               Disassembler::decode(handler, handler + buffer.insts_size());
1720             }
1721 #ifndef PRODUCT
1722             address rh_begin = Interpreter::result_handler(method()->result_type());
1723             if (CodeCache::contains(rh_begin)) {
1724               // else it might be special platform dependent values
1725               tty->print_cr(" --- associated result handler ---");
1726               address rh_end = rh_begin;
1727               while (*(int*)rh_end != 0) {
1728                 rh_end += sizeof(int);
1729               }
1730               Disassembler::decode(rh_begin, rh_end);
1731             } else {
1732               tty->print_cr(" associated result handler: " PTR_FORMAT, p2i(rh_begin));
1733             }
1734 #endif
1735           }
1736           // add handler to library
1737           _fingerprints->append(fingerprint);
1738           _handlers->append(handler);
1739           // set handler index
1740           assert(_fingerprints->length() == _handlers->length(), "sanity check");
1741           handler_index = _fingerprints->length() - 1;
1742         }
1743       }
1744       // Set handler under SignatureHandlerLibrary_lock
1745       if (handler_index < 0) {
1746         // use generic signature handler
1747         method->set_signature_handler(Interpreter::slow_signature_handler());
1748       } else {
1749         // set handler
1750         method->set_signature_handler(_handlers->at(handler_index));
1751       }
1752     } else {
1753       CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
1754       // use generic signature handler
1755       method->set_signature_handler(Interpreter::slow_signature_handler());
1756     }
1757   }
1758 #ifdef ASSERT
1759   int handler_index = -1;
1760   int fingerprint_index = -2;
1761   {
1762     // '_handlers' and '_fingerprints' are 'GrowableArray's and are NOT synchronized
1763     // in any way if accessed from multiple threads. To avoid races with another
1764     // thread which may change the arrays in the above, mutex protected block, we
1765     // have to protect this read access here with the same mutex as well!
1766     MutexLocker mu(SignatureHandlerLibrary_lock);
1767     if (_handlers != NULL) {
1768       handler_index = _handlers->find(method->signature_handler());
1769       uint64_t fingerprint = Fingerprinter(method).fingerprint();
1770       fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1771       fingerprint_index = _fingerprints->find(fingerprint);
1772     }
1773   }
1774   assert(method->signature_handler() == Interpreter::slow_signature_handler() ||
1775          handler_index == fingerprint_index, "sanity check");
1776 #endif // ASSERT
1777 }
1778 
1779 void SignatureHandlerLibrary::add(uint64_t fingerprint, address handler) {
1780   int handler_index = -1;
1781   // use customized signature handler
1782   MutexLocker mu(SignatureHandlerLibrary_lock);
1783   // make sure data structure is initialized
1784   initialize();
1785   fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1786   handler_index = _fingerprints->find(fingerprint);
1787   // create handler if necessary
1788   if (handler_index < 0) {
1789     if (PrintSignatureHandlers && (handler != Interpreter::slow_signature_handler())) {
1790       tty->cr();
1791       tty->print_cr("argument handler #%d at " PTR_FORMAT " for fingerprint " UINT64_FORMAT,
1792                     _handlers->length(),
1793                     p2i(handler),
1794                     fingerprint);
1795     }
1796     _fingerprints->append(fingerprint);
1797     _handlers->append(handler);
1798   } else {
1799     if (PrintSignatureHandlers) {
1800       tty->cr();
1801       tty->print_cr("duplicate argument handler #%d for fingerprint " UINT64_FORMAT "(old: " PTR_FORMAT ", new : " PTR_FORMAT ")",
1802                     _handlers->length(),
1803                     fingerprint,
1804                     p2i(_handlers->at(handler_index)),
1805                     p2i(handler));
1806     }
1807   }
1808 }
1809 
1810 
1811 BufferBlob*              SignatureHandlerLibrary::_handler_blob = NULL;
1812 address                  SignatureHandlerLibrary::_handler      = NULL;
1813 GrowableArray<uint64_t>* SignatureHandlerLibrary::_fingerprints = NULL;
1814 GrowableArray<address>*  SignatureHandlerLibrary::_handlers     = NULL;
1815 address                  SignatureHandlerLibrary::_buffer       = NULL;
1816 
1817 
1818 IRT_ENTRY(void, InterpreterRuntime::prepare_native_call(JavaThread* thread, Method* method))
1819   methodHandle m(thread, method);
1820   assert(m->is_native(), "sanity check");
1821   // lookup native function entry point if it doesn't exist
1822   bool in_base_library;
1823   if (!m->has_native_function()) {
1824     NativeLookup::lookup(m, in_base_library, CHECK);
1825   }
1826   // make sure signature handler is installed
1827   SignatureHandlerLibrary::add(m);
1828   // The interpreter entry point checks the signature handler first,
1829   // before trying to fetch the native entry point and klass mirror.
1830   // We must set the signature handler last, so that multiple processors
1831   // preparing the same method will be sure to see non-null entry & mirror.
1832 IRT_END
1833 
1834 #if defined(IA32) || defined(AMD64) || defined(ARM)
1835 IRT_LEAF(void, InterpreterRuntime::popframe_move_outgoing_args(JavaThread* thread, void* src_address, void* dest_address))
1836   if (src_address == dest_address) {
1837     return;
1838   }
1839   ResetNoHandleMark rnm; // In a LEAF entry.
1840   HandleMark hm;
1841   ResourceMark rm;
1842   LastFrameAccessor last_frame(thread);
1843   assert(last_frame.is_interpreted_frame(), "");
1844   jint bci = last_frame.bci();
1845   methodHandle mh(thread, last_frame.method());
1846   Bytecode_invoke invoke(mh, bci);
1847   ArgumentSizeComputer asc(invoke.signature());
1848   int size_of_arguments = (asc.size() + (invoke.has_receiver() ? 1 : 0)); // receiver
1849   Copy::conjoint_jbytes(src_address, dest_address,
1850                        size_of_arguments * Interpreter::stackElementSize);
1851 IRT_END
1852 #endif
1853 
1854 #if INCLUDE_JVMTI
1855 // This is a support of the JVMTI PopFrame interface.
1856 // Make sure it is an invokestatic of a polymorphic intrinsic that has a member_name argument
1857 // and return it as a vm_result so that it can be reloaded in the list of invokestatic parameters.
1858 // The member_name argument is a saved reference (in local#0) to the member_name.
1859 // For backward compatibility with some JDK versions (7, 8) it can also be a direct method handle.
1860 // FIXME: remove DMH case after j.l.i.InvokerBytecodeGenerator code shape is updated.
1861 IRT_ENTRY(void, InterpreterRuntime::member_name_arg_or_null(JavaThread* thread, address member_name,
1862                                                             Method* method, address bcp))
1863   Bytecodes::Code code = Bytecodes::code_at(method, bcp);
1864   if (code != Bytecodes::_invokestatic) {
1865     return;
1866   }
1867   ConstantPool* cpool = method->constants();
1868   int cp_index = Bytes::get_native_u2(bcp + 1) + ConstantPool::CPCACHE_INDEX_TAG;
1869   Symbol* cname = cpool->klass_name_at(cpool->klass_ref_index_at(cp_index));
1870   Symbol* mname = cpool->name_ref_at(cp_index);
1871 
1872   if (MethodHandles::has_member_arg(cname, mname)) {
1873     oop member_name_oop = (oop) member_name;
1874     if (java_lang_invoke_DirectMethodHandle::is_instance(member_name_oop)) {
1875       // FIXME: remove after j.l.i.InvokerBytecodeGenerator code shape is updated.
1876       member_name_oop = java_lang_invoke_DirectMethodHandle::member(member_name_oop);
1877     }
1878     thread->set_vm_result(member_name_oop);
1879   } else {
1880     thread->set_vm_result(NULL);
1881   }
1882 IRT_END
1883 #endif // INCLUDE_JVMTI
1884 
1885 #ifndef PRODUCT
1886 // This must be a IRT_LEAF function because the interpreter must save registers on x86 to
1887 // call this, which changes rsp and makes the interpreter's expression stack not walkable.
1888 // The generated code still uses call_VM because that will set up the frame pointer for
1889 // bcp and method.
1890 IRT_LEAF(intptr_t, InterpreterRuntime::trace_bytecode(JavaThread* thread, intptr_t preserve_this_value, intptr_t tos, intptr_t tos2))
1891   LastFrameAccessor last_frame(thread);
1892   assert(last_frame.is_interpreted_frame(), "must be an interpreted frame");
1893   methodHandle mh(thread, last_frame.method());
1894   BytecodeTracer::trace(mh, last_frame.bcp(), tos, tos2);
1895   return preserve_this_value;
1896 IRT_END
1897 #endif // !PRODUCT
--- EOF ---