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::_ldc ||
 129          bytecode == Bytecodes::_ldc_w ||
 130          bytecode == Bytecodes::_ldc2_w ||
 131          bytecode == Bytecodes::_fast_aldc ||
 132          bytecode == Bytecodes::_fast_aldc_w, "wrong bc");
 133   ResourceMark rm(thread);
 134   const bool is_fast_aldc = (bytecode == Bytecodes::_fast_aldc ||
 135                              bytecode == Bytecodes::_fast_aldc_w);
 136   LastFrameAccessor last_frame(thread);
 137   methodHandle m (thread, last_frame.method());
 138   Bytecode_loadconstant ldc(m, last_frame.bci());
 139 
 140   // Double-check the size.  (Condy can have any type.)
 141   BasicType type = ldc.result_type();
 142   switch (type2size[type]) {
 143   case 2: guarantee(bytecode == Bytecodes::_ldc2_w, ""); break;
 144   case 1: guarantee(bytecode != Bytecodes::_ldc2_w, ""); break;
 145   default: ShouldNotReachHere();
 146   }
 147 
 148   // Resolve the constant.  This does not do unboxing.
 149   // But it does replace Universe::the_null_sentinel by null.
 150   oop result = ldc.resolve_constant(CHECK);
 151   assert(result != NULL || is_fast_aldc, "null result only valid for fast_aldc");
 152 
 153 #ifdef ASSERT
 154   {
 155     // The bytecode wrappers aren't GC-safe so construct a new one
 156     Bytecode_loadconstant ldc2(m, last_frame.bci());
 157     int rindex = ldc2.cache_index();
 158     if (rindex < 0)
 159       rindex = m->constants()->cp_to_object_index(ldc2.pool_index());
 160     if (rindex >= 0) {
 161       oop coop = m->constants()->resolved_references()->obj_at(rindex);
 162       oop roop = (result == NULL ? Universe::the_null_sentinel() : result);
 163       assert(roop == coop, "expected result for assembly code");
 164     }
 165   }
 166 #endif
 167   thread->set_vm_result(result);
 168   if (!is_fast_aldc) {
 169     // Tell the interpreter how to unbox the primitive.
 170     guarantee(java_lang_boxing_object::is_instance(result, type), "");
 171     int offset = java_lang_boxing_object::value_offset_in_bytes(type);
 172     intptr_t flags = ((as_TosState(type) << ConstantPoolCacheEntry::tos_state_shift)
 173                       | (offset & ConstantPoolCacheEntry::field_index_mask));
 174     thread->set_vm_result_2((Metadata*)flags);
 175   }
 176 }
 177 IRT_END
 178 
 179 
 180 //------------------------------------------------------------------------------------------------------------------------
 181 // Allocation
 182 
 183 IRT_ENTRY(void, InterpreterRuntime::_new(JavaThread* thread, ConstantPool* pool, int index))
 184   Klass* k = pool->klass_at(index, CHECK);
 185   InstanceKlass* klass = InstanceKlass::cast(k);
 186 
 187   // Make sure we are not instantiating an abstract klass
 188   klass->check_valid_for_instantiation(true, CHECK);
 189 
 190   // Make sure klass is initialized
 191   klass->initialize(CHECK);
 192 
 193   // At this point the class may not be fully initialized
 194   // because of recursive initialization. If it is fully
 195   // initialized & has_finalized is not set, we rewrite
 196   // it into its fast version (Note: no locking is needed
 197   // here since this is an atomic byte write and can be
 198   // done more than once).
 199   //
 200   // Note: In case of classes with has_finalized we don't
 201   //       rewrite since that saves us an extra check in
 202   //       the fast version which then would call the
 203   //       slow version anyway (and do a call back into
 204   //       Java).
 205   //       If we have a breakpoint, then we don't rewrite
 206   //       because the _breakpoint bytecode would be lost.
 207   oop obj = klass->allocate_instance(CHECK);
 208   thread->set_vm_result(obj);
 209 IRT_END
 210 
 211 void copy_primitive_argument(intptr_t* addr, Handle instance, int offset, BasicType type) {
 212   switch (type) {
 213   case T_BOOLEAN:
 214     instance()->bool_field_put(offset, (jboolean)*((int*)addr));
 215     break;
 216   case T_CHAR:
 217     instance()->char_field_put(offset, (jchar) *((int*)addr));
 218     break;
 219   case T_FLOAT:
 220     instance()->float_field_put(offset, (jfloat)*((float*)addr));
 221     break;
 222   case T_DOUBLE:
 223     instance()->double_field_put(offset, (jdouble)*((double*)addr));
 224     break;
 225   case T_BYTE:
 226     instance()->byte_field_put(offset, (jbyte)*((int*)addr));
 227     break;
 228   case T_SHORT:
 229     instance()->short_field_put(offset, (jshort)*((int*)addr));
 230     break;
 231   case T_INT:
 232     instance()->int_field_put(offset, (jint)*((int*)addr));
 233     break;
 234   case T_LONG:
 235     instance()->long_field_put(offset, (jlong)*((long long*)addr));
 236     break;
 237   case T_OBJECT:
 238   case T_ARRAY:
 239   case T_VALUETYPE:
 240     fatal("Should not be handled with this method");
 241     break;
 242   default:
 243     fatal("Unsupported BasicType");
 244   }
 245 }
 246 
 247 IRT_ENTRY(void, InterpreterRuntime::defaultvalue(JavaThread* thread, ConstantPool* pool, int index))
 248   // Getting the ValueKlass
 249   Klass* k = pool->klass_at(index, CHECK);
 250   assert(k->is_value(), "defaultvalue argument must be the value type class");
 251   ValueKlass* vklass = ValueKlass::cast(k);
 252 
 253   vklass->initialize(THREAD);
 254   oop res = vklass->default_value();
 255   thread->set_vm_result(res);
 256 IRT_END
 257 
 258 IRT_ENTRY(int, InterpreterRuntime::withfield(JavaThread* thread, ConstantPoolCache* cp_cache))
 259   LastFrameAccessor last_frame(thread);
 260   // Getting the ValueKlass
 261   int index = ConstantPool::decode_cpcache_index(last_frame.get_index_u2_cpcache(Bytecodes::_withfield));
 262   ConstantPoolCacheEntry* cp_entry = cp_cache->entry_at(index);
 263   assert(cp_entry->is_resolved(Bytecodes::_withfield), "Should have been resolved");
 264   Klass* klass = cp_entry->f1_as_klass();
 265   assert(klass->is_value(), "withfield only applies to value types");
 266   ValueKlass* vklass = ValueKlass::cast(klass);
 267 
 268   // Getting Field information
 269   int offset = cp_entry->f2_as_index();
 270   int field_index = cp_entry->field_index();
 271   int field_offset = cp_entry->f2_as_offset();
 272   Symbol* field_signature = vklass->field_signature(field_index);
 273   ResourceMark rm(THREAD);
 274   const char* signature = (const char *) field_signature->as_utf8();
 275   BasicType field_type = char2type(signature[0]);
 276 
 277   // Getting old value
 278   frame& f = last_frame.get_frame();
 279   jint tos_idx = f.interpreter_frame_expression_stack_size() - 1;
 280   int vt_offset = type2size[field_type];
 281   oop old_value = *(oop*)f.interpreter_frame_expression_stack_at(tos_idx - vt_offset);
 282   assert(old_value != NULL && oopDesc::is_oop(old_value) && old_value->is_value(),"Verifying receiver");
 283   Handle old_value_h(THREAD, old_value);
 284 
 285   // Creating new value by copying the one passed in argument
 286   bool in_heap;
 287   instanceOop new_value = vklass->allocate_buffered_or_heap_instance(&in_heap,
 288       CHECK_((type2size[field_type]) * AbstractInterpreter::stackElementSize));
 289   Handle new_value_h = Handle(THREAD, new_value);
 290   int first_offset = vklass->first_field_offset();
 291   vklass->value_store(vklass->data_for_oop(old_value_h()),
 292       vklass->data_for_oop(new_value_h()), in_heap, false);
 293 
 294   // Updating the field specified in arguments
 295   if (field_type == T_OBJECT || field_type == T_ARRAY) {
 296     oop aoop = *(oop*)f.interpreter_frame_expression_stack_at(tos_idx);
 297     assert(aoop == NULL || (oopDesc::is_oop(aoop) && (!aoop->is_value())),"argument must be a reference type");
 298     if (in_heap) {
 299       new_value_h()->obj_field_put(field_offset, aoop);
 300     } else {
 301       new_value_h()->obj_field_put_raw(field_offset, aoop);
 302     }
 303   } else if (field_type == T_VALUETYPE) {
 304     if (cp_entry->is_flattened()) {
 305       Klass* field_k = vklass->get_value_field_klass(field_index);
 306       ValueKlass* field_vk = ValueKlass::cast(field_k);
 307       oop vt_oop = *(oop*)f.interpreter_frame_expression_stack_at(tos_idx);
 308       assert(vt_oop != NULL && oopDesc::is_oop(vt_oop) && vt_oop->is_value(),"argument must be a value type");
 309       assert(field_vk == vt_oop->klass(), "Must match");
 310       field_vk->value_store(field_vk->data_for_oop(vt_oop),
 311           ((char*)(oopDesc*)new_value_h()) + field_offset, in_heap, false);
 312     } else {
 313       oop voop = *(oop*)f.interpreter_frame_expression_stack_at(tos_idx);
 314       assert(voop != NULL || (oopDesc::is_oop(voop) && (voop->is_value())),"argument must be a value type");
 315       if (VTBuffer::is_in_vt_buffer(voop)) {
 316         // new value field is currently allocated in a TLVB, a heap allocated
 317         // copy must be created because a field must never point to a TLVB allocated value
 318         Handle voop_h = Handle(THREAD, voop);
 319         ValueKlass* field_vk = ValueKlass::cast(voop->klass());
 320         assert(field_vk == vklass->get_value_field_klass(field_index), "Sanity check");
 321         instanceOop field_copy = field_vk->allocate_instance(CHECK_((type2size[field_type]) * AbstractInterpreter::stackElementSize));
 322         Handle field_copy_h = Handle(THREAD, field_copy);
 323         field_vk->value_store(field_vk->data_for_oop(voop_h()), field_vk->data_for_oop(field_copy_h()), true, false);
 324         if (in_heap) {
 325           new_value_h()->obj_field_put(field_offset, field_copy_h());
 326         } else {
 327           new_value_h()->obj_field_put_raw(field_offset, field_copy_h());
 328         }
 329       } else {
 330         if (in_heap) {
 331           new_value_h()->obj_field_put(field_offset, voop);
 332         } else {
 333           new_value_h()->obj_field_put_raw(field_offset, voop);
 334         }
 335       }
 336     }
 337   } else {
 338     intptr_t* addr = f.interpreter_frame_expression_stack_at(tos_idx);
 339     copy_primitive_argument(addr, new_value_h, field_offset, field_type);
 340   }
 341 
 342   // returning result
 343   thread->set_vm_result(new_value_h());
 344   return (type2size[field_type] + type2size[T_OBJECT]) * AbstractInterpreter::stackElementSize;
 345 IRT_END
 346 
 347 IRT_ENTRY(void, InterpreterRuntime::qgetfield(JavaThread* thread, oopDesc* obj, int index, Klass* field_holder))
 348   Handle value_h(THREAD, obj);
 349   InstanceKlass* klass = InstanceKlass::cast(field_holder);
 350 
 351   Klass* field_k = klass->get_value_field_klass(index);
 352   ValueKlass* field_vklass = ValueKlass::cast(field_k);
 353   field_vklass->initialize(THREAD);
 354 
 355   instanceOop res;
 356   bool in_heap;
 357   if (klass->field_is_flattened(index)) {
 358     // allocate instance
 359     res = field_vklass->allocate_buffered_or_heap_instance(&in_heap, CHECK);
 360     instanceHandle res_h(THREAD, res);
 361     // copy value
 362     field_vklass->value_store(((char*)(oopDesc*)value_h()) + klass->field_offset(index),
 363                               field_vklass->data_for_oop(res), in_heap, false);
 364     thread->set_vm_result(res_h());
 365   } else {
 366     oop res = value_h()->obj_field_acquire(klass->field_offset(index));
 367     if (res == NULL) {
 368       res = field_vklass->default_value();
 369     } else {
 370       assert(res->klass() == field_k, "Sanity check");
 371       assert(!VTBuffer::is_in_vt_buffer(res), "Sanity check");
 372     }
 373     thread->set_vm_result(res);
 374   }
 375   assert(thread->vm_result()->klass() == field_vklass, "sanity check");
 376 IRT_END
 377 
 378 IRT_ENTRY(void, InterpreterRuntime::uninitialized_static_value_field(JavaThread* thread, oopDesc* mirror, int index))
 379   instanceHandle mirror_h(THREAD, (instanceOop)mirror);
 380   InstanceKlass* klass = InstanceKlass::cast(java_lang_Class::as_Klass(mirror));
 381   int offset = klass->field_offset(index);
 382   Klass* field_k = klass->get_value_field_klass_or_null(index);
 383   assert(field_k != NULL, "Must have been initialized");
 384   ValueKlass* field_vklass = ValueKlass::cast(field_k);
 385   instanceOop res = (instanceOop)field_vklass->default_value();
 386   thread->set_vm_result(res);
 387 IRT_END
 388 
 389 IRT_ENTRY(void, InterpreterRuntime::uninitialized_instance_value_field(JavaThread* thread, oopDesc* obj, int index))
 390   instanceHandle obj_h(THREAD, (instanceOop)obj);
 391   InstanceKlass* klass = InstanceKlass::cast(obj_h()->klass());
 392   int offset = klass->field_offset(index);
 393   Klass* field_k = klass->get_value_field_klass_or_null(index);
 394   assert(field_k != NULL, "Must have been initialized");
 395   ValueKlass* field_vklass = ValueKlass::cast(field_k);
 396   instanceOop res = (instanceOop)field_vklass->default_value();
 397   thread->set_vm_result(res);
 398 IRT_END
 399 
 400 IRT_ENTRY(void, InterpreterRuntime::qputfield(JavaThread* thread, oopDesc* obj, oopDesc* value, ConstantPoolCache* cp_cache))
 401   LastFrameAccessor last_frame(thread);
 402   Handle value_h(THREAD, value);
 403   Handle obj_h(THREAD, obj);
 404   assert(!obj_h()->klass()->is_value(), "obj must be an object");
 405   assert(value_h()->klass()->is_value(), "value must be an value type");
 406 
 407   int idx = ConstantPool::decode_cpcache_index(last_frame.get_index_u2_cpcache(Bytecodes::_putfield));
 408   ConstantPoolCacheEntry* cp_entry = cp_cache->entry_at(idx);
 409 
 410   int index = cp_entry->field_index();
 411   bool flatten = cp_entry->is_flattened();
 412 
 413   InstanceKlass* klass = InstanceKlass::cast(cp_entry->f1_as_klass());
 414   Klass* field_k = klass->get_value_field_klass(index);
 415   ValueKlass* field_vklass = ValueKlass::cast(value->klass());
 416   assert(value_h()->klass() == field_k, "Sanity check");
 417   assert(field_k == field_vklass, "Field descriptor and argument must match");
 418   if (flatten) {
 419     // copy value
 420     field_vklass->value_store(field_vklass->data_for_oop(value_h()),
 421                               ((char*)(oopDesc*)obj_h()) + klass->field_offset(index), true, false);
 422   } else {
 423     if (!VTBuffer::is_in_vt_buffer(value_h())) {
 424       obj_h()->obj_field_put(klass->field_offset(index), value_h());
 425     } else {
 426       // allocate heap instance
 427       instanceOop val = field_vklass->allocate_instance(CHECK);
 428       instanceHandle res_h(THREAD, val);
 429       // copy value
 430       field_vklass->value_store(field_vklass->data_for_oop(value_h()),
 431                                 field_vklass->data_for_oop(res_h()), true, false);
 432 
 433 
 434       obj_h()->obj_field_put(klass->field_offset(index), res_h());
 435     }
 436   }
 437 IRT_END
 438 
 439 IRT_ENTRY(void, InterpreterRuntime::qputstatic(JavaThread* thread, oopDesc* value, int offset, oopDesc* mirror))
 440   instanceHandle value_h(THREAD, (instanceOop)value);
 441   assert(value_h()->is_value(), "qputstatic only deals with value arguments");
 442   if (!VTBuffer::is_in_vt_buffer(value_h())) {
 443       mirror->obj_field_put(offset, value_h());
 444   } else {
 445     // The argument is a buffered value, a copy must be created in the Java heap
 446     // because a static field cannot point to a thread-local buffered value
 447     ValueKlass* field_vklass = ValueKlass::cast(value_h()->klass());
 448     Handle mirror_h(THREAD, mirror);
 449     // allocate heap instance
 450     instanceOop res = field_vklass->allocate_instance(CHECK);
 451     assert(Universe::heap()->is_in_reserved(res), "Must be in the Java heap");
 452     instanceHandle res_h(THREAD, res);
 453     // copy value
 454     field_vklass->value_store(field_vklass->data_for_oop(value_h()),
 455                               field_vklass->data_for_oop(res), true, false);
 456     // writing static field
 457     mirror_h->obj_field_put(offset, res_h());
 458     assert(mirror_h->obj_field(offset) != NULL,"Sanity check");
 459   }
 460 IRT_END
 461 
 462 IRT_ENTRY(void, InterpreterRuntime::newarray(JavaThread* thread, BasicType type, jint size))
 463   oop obj = oopFactory::new_typeArray(type, size, CHECK);
 464   thread->set_vm_result(obj);
 465 IRT_END
 466 
 467 
 468 IRT_ENTRY(void, InterpreterRuntime::anewarray(JavaThread* thread, ConstantPool* pool, int index, jint size))
 469   Klass*    klass = pool->klass_at(index, CHECK);
 470   if (klass->is_value()) { // Logically creates elements, ensure klass init
 471     klass->initialize(CHECK);
 472   }
 473   arrayOop obj = oopFactory::new_array(klass, size, CHECK);
 474   thread->set_vm_result(obj);
 475 IRT_END
 476 
 477 IRT_ENTRY(void, InterpreterRuntime::value_array_load(JavaThread* thread, arrayOopDesc* array, int index))
 478   Klass* klass = array->klass();
 479   assert(klass->is_valueArray_klass() || klass->is_objArray_klass(), "expected value or object array oop");
 480 
 481   if (klass->is_objArray_klass()) {
 482     thread->set_vm_result(((objArrayOop) array)->obj_at(index));
 483   } else {
 484     ValueArrayKlass* vaklass = ValueArrayKlass::cast(klass);
 485     ValueKlass* vklass = vaklass->element_klass();
 486     arrayHandle ah(THREAD, array);
 487     bool in_heap;
 488     instanceOop value_holder = vklass->allocate_buffered_or_heap_instance(&in_heap, CHECK);
 489     void* src = ((valueArrayOop)ah())->value_at_addr(index, vaklass->layout_helper());
 490     vklass->value_store(src, vklass->data_for_oop(value_holder),
 491                           vaklass->element_byte_size(), in_heap, false);
 492     thread->set_vm_result(value_holder);
 493   }
 494 IRT_END
 495 
 496 IRT_ENTRY(void, InterpreterRuntime::value_array_store(JavaThread* thread, arrayOopDesc* array, int index, void* val))
 497   Klass* klass = array->klass();
 498   assert(klass->is_valueArray_klass() || klass->is_objArray_klass(), "expected value or object array oop");
 499   Handle array_h(THREAD, array);
 500 
 501   if (ArrayKlass::cast(klass)->element_klass() != ((oop)val)->klass()) {
 502     THROW(vmSymbols::java_lang_ArrayStoreException());
 503   }
 504   if (klass->is_objArray_klass()) {
 505     if(VTBuffer::is_in_vt_buffer(val)) {
 506       // A Java heap allocated copy must be made because an array cannot
 507       // reference a thread-local buffered value
 508       Handle val_h(THREAD, (oop)val);
 509       ObjArrayKlass* aklass = ObjArrayKlass::cast(klass);
 510       Klass* eklass = aklass->element_klass();
 511       assert(eklass->is_value(), "Sanity check");
 512       assert(eklass == ((oop)val)->klass(), "Sanity check");
 513       ValueKlass* vklass = ValueKlass::cast(eklass);
 514       // allocate heap instance
 515       instanceOop res = vklass->allocate_instance(CHECK);
 516       Handle res_h(THREAD, res);
 517       // copy value
 518       vklass->value_store(((char*)(oopDesc*)val_h()) + vklass->first_field_offset(),
 519                             ((char*)(oopDesc*)res_h()) + vklass->first_field_offset(),true, false);
 520       val = res_h();
 521     }
 522     ((objArrayOop) array_h())->obj_at_put(index, (oop)val);
 523   } else {
 524     valueArrayOop varray = (valueArrayOop)array;
 525     ValueArrayKlass* vaklass = ValueArrayKlass::cast(klass);
 526     ValueKlass* vklass = vaklass->element_klass();
 527     const int lh = vaklass->layout_helper();
 528     vklass->value_store(vklass->data_for_oop((oop)val), varray->value_at_addr(index, lh),
 529                         vaklass->element_byte_size(), true, false);
 530   }
 531 IRT_END
 532 
 533 IRT_ENTRY(void, InterpreterRuntime::multianewarray(JavaThread* thread, jint* first_size_address))
 534   // We may want to pass in more arguments - could make this slightly faster
 535   LastFrameAccessor last_frame(thread);
 536   ConstantPool* constants = last_frame.method()->constants();
 537   int          i = last_frame.get_index_u2(Bytecodes::_multianewarray);
 538   Klass* klass   = constants->klass_at(i, CHECK);
 539   int   nof_dims = last_frame.number_of_dimensions();
 540   assert(klass->is_klass(), "not a class");
 541   assert(nof_dims >= 1, "multianewarray rank must be nonzero");
 542 
 543   if (klass->is_value()) { // Logically creates elements, ensure klass init
 544     klass->initialize(CHECK);
 545   }
 546 
 547   // We must create an array of jints to pass to multi_allocate.
 548   ResourceMark rm(thread);
 549   const int small_dims = 10;
 550   jint dim_array[small_dims];
 551   jint *dims = &dim_array[0];
 552   if (nof_dims > small_dims) {
 553     dims = (jint*) NEW_RESOURCE_ARRAY(jint, nof_dims);
 554   }
 555   for (int index = 0; index < nof_dims; index++) {
 556     // offset from first_size_address is addressed as local[index]
 557     int n = Interpreter::local_offset_in_bytes(index)/jintSize;
 558     dims[index] = first_size_address[n];
 559   }
 560   oop obj = ArrayKlass::cast(klass)->multi_allocate(nof_dims, dims, CHECK);
 561   thread->set_vm_result(obj);
 562 IRT_END
 563 
 564 IRT_LEAF(void, InterpreterRuntime::recycle_vtbuffer(void* alloc_ptr))
 565   JavaThread* thread = (JavaThread*)Thread::current();
 566   VTBuffer::recycle_vtbuffer(thread, alloc_ptr);
 567 IRT_END
 568 
 569 IRT_ENTRY(void, InterpreterRuntime::recycle_buffered_values(JavaThread* thread))
 570   frame f = thread->last_frame();
 571   assert(f.is_interpreted_frame(), "recycling can only be triggered from interpreted frames");
 572   VTBuffer::recycle_vt_in_frame(thread, &f);
 573 IRT_END
 574 
 575 IRT_ENTRY(void, InterpreterRuntime::fix_frame_vt_alloc_ptr(JavaThread* thread))
 576   frame f = thread->last_frame();
 577   VTBuffer::fix_frame_vt_alloc_ptr(f, VTBufferChunk::chunk(thread->vt_alloc_ptr()));
 578 IRT_END
 579 
 580 IRT_ENTRY(void, InterpreterRuntime::return_value(JavaThread* thread, oopDesc* obj))
 581   if (!VTBuffer::is_in_vt_buffer(obj)) {
 582     thread->set_vm_result(obj);
 583     return;
 584   }
 585   assert(obj->klass()->is_value(), "Sanity check");
 586   ValueKlass* vk = ValueKlass::cast(obj->klass());
 587   RegisterMap reg_map(thread, false);
 588   frame current_frame = thread->last_frame();
 589   frame caller_frame = current_frame.sender(&reg_map);
 590   if (!caller_frame.is_interpreted_frame()) {
 591     // caller is not an interpreted frame, creating a new value in Java heap
 592     Handle obj_h(THREAD, obj);
 593     instanceOop res = vk->allocate_instance(CHECK);
 594     Handle res_h(THREAD, res);
 595     // copy value
 596     vk->value_store(vk->data_for_oop(obj_h()),
 597                     vk->data_for_oop(res_h()), true, false);
 598     thread->set_vm_result(res_h());
 599     return;
 600   } else {
 601     // A buffered value is being returned to an interpreted frame,
 602     // but the work has to be delayed to remove_activation() because
 603     // the frame cannot be modified now (GC can run at the safepoint
 604     // when exiting runtime, and frame layout must be kept consistent
 605     // with the OopMap).
 606     thread->set_return_buffered_value(obj);
 607     thread->set_vm_result(obj);
 608   }
 609 IRT_END
 610 
 611 IRT_LEAF(void, InterpreterRuntime::return_value_step2(oopDesc* obj, void* alloc_ptr))
 612 
 613   JavaThread* thread = (JavaThread*)Thread::current();
 614   assert(obj == thread->return_buffered_value(), "Consistency check");
 615   assert(!Universe::heap()->is_in_reserved(obj), "Should only apply to buffered values");
 616 
 617   oop dest = VTBuffer::relocate_return_value(thread, alloc_ptr, obj);
 618   thread->set_return_buffered_value(NULL);
 619   thread->set_vm_result(dest);
 620 IRT_END
 621 
 622 IRT_ENTRY(void, InterpreterRuntime::check_areturn(JavaThread* thread, oopDesc* obj))
 623   if (obj != NULL) {
 624     Klass* k = obj->klass();
 625     if (k->is_value()) {
 626       // ResourceMark rm(thread);
 627       // tty->print_cr("areturn used on a value from %s", k->name()->as_C_string());
 628     }
 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::_withfield);
 990   bool is_static = (bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic);
 991   bool is_value  = bytecode == Bytecodes::_withfield;
 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::_withfield);
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_flattened(),
1057     info.is_flattenable(),
1058     pool->pool_holder()
1059   );
1060 }
1061 
1062 
1063 //------------------------------------------------------------------------------------------------------------------------
1064 // Synchronization
1065 //
1066 // The interpreter's synchronization code is factored out so that it can
1067 // be shared by method invocation and synchronized blocks.
1068 //%note synchronization_3
1069 
1070 //%note monitor_1
1071 IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* thread, BasicObjectLock* elem))
1072 #ifdef ASSERT
1073   thread->last_frame().interpreter_frame_verify_monitor(elem);
1074 #endif
1075   if (PrintBiasedLockingStatistics) {
1076     Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
1077   }
1078   Handle h_obj(thread, elem->obj());
1079   assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
1080          "must be NULL or an object");
1081   if (UseBiasedLocking) {
1082     // Retry fast entry if bias is revoked to avoid unnecessary inflation
1083     ObjectSynchronizer::fast_enter(h_obj, elem->lock(), true, CHECK);
1084   } else {
1085     ObjectSynchronizer::slow_enter(h_obj, elem->lock(), CHECK);
1086   }
1087   assert(Universe::heap()->is_in_reserved_or_null(elem->obj()),
1088          "must be NULL or an object");
1089 #ifdef ASSERT
1090   thread->last_frame().interpreter_frame_verify_monitor(elem);
1091 #endif
1092 IRT_END
1093 
1094 
1095 //%note monitor_1
1096 IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorexit(JavaThread* thread, BasicObjectLock* elem))
1097 #ifdef ASSERT
1098   thread->last_frame().interpreter_frame_verify_monitor(elem);
1099 #endif
1100   Handle h_obj(thread, elem->obj());
1101   assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
1102          "must be NULL or an object");
1103   if (elem == NULL || h_obj()->is_unlocked()) {
1104     THROW(vmSymbols::java_lang_IllegalMonitorStateException());
1105   }
1106   ObjectSynchronizer::slow_exit(h_obj(), elem->lock(), thread);
1107   // Free entry. This must be done here, since a pending exception might be installed on
1108   // exit. If it is not cleared, the exception handling code will try to unlock the monitor again.
1109   elem->set_obj(NULL);
1110 #ifdef ASSERT
1111   thread->last_frame().interpreter_frame_verify_monitor(elem);
1112 #endif
1113 IRT_END
1114 
1115 
1116 IRT_ENTRY(void, InterpreterRuntime::throw_illegal_monitor_state_exception(JavaThread* thread))
1117   THROW(vmSymbols::java_lang_IllegalMonitorStateException());
1118 IRT_END
1119 
1120 
1121 IRT_ENTRY(void, InterpreterRuntime::new_illegal_monitor_state_exception(JavaThread* thread))
1122   // Returns an illegal exception to install into the current thread. The
1123   // pending_exception flag is cleared so normal exception handling does not
1124   // trigger. Any current installed exception will be overwritten. This
1125   // method will be called during an exception unwind.
1126 
1127   assert(!HAS_PENDING_EXCEPTION, "no pending exception");
1128   Handle exception(thread, thread->vm_result());
1129   assert(exception() != NULL, "vm result should be set");
1130   thread->set_vm_result(NULL); // clear vm result before continuing (may cause memory leaks and assert failures)
1131   if (!exception->is_a(SystemDictionary::ThreadDeath_klass())) {
1132     exception = get_preinitialized_exception(
1133                        SystemDictionary::IllegalMonitorStateException_klass(),
1134                        CATCH);
1135   }
1136   thread->set_vm_result(exception());
1137 IRT_END
1138 
1139 
1140 //------------------------------------------------------------------------------------------------------------------------
1141 // Invokes
1142 
1143 IRT_ENTRY(Bytecodes::Code, InterpreterRuntime::get_original_bytecode_at(JavaThread* thread, Method* method, address bcp))
1144   return method->orig_bytecode_at(method->bci_from(bcp));
1145 IRT_END
1146 
1147 IRT_ENTRY(void, InterpreterRuntime::set_original_bytecode_at(JavaThread* thread, Method* method, address bcp, Bytecodes::Code new_code))
1148   method->set_orig_bytecode_at(method->bci_from(bcp), new_code);
1149 IRT_END
1150 
1151 IRT_ENTRY(void, InterpreterRuntime::_breakpoint(JavaThread* thread, Method* method, address bcp))
1152   JvmtiExport::post_raw_breakpoint(thread, method, bcp);
1153 IRT_END
1154 
1155 void InterpreterRuntime::resolve_invoke(JavaThread* thread, Bytecodes::Code bytecode) {
1156   Thread* THREAD = thread;
1157   LastFrameAccessor last_frame(thread);
1158   // extract receiver from the outgoing argument list if necessary
1159   Handle receiver(thread, NULL);
1160   if (bytecode == Bytecodes::_invokevirtual || bytecode == Bytecodes::_invokeinterface ||
1161       bytecode == Bytecodes::_invokespecial) {
1162     ResourceMark rm(thread);
1163     methodHandle m (thread, last_frame.method());
1164     Bytecode_invoke call(m, last_frame.bci());
1165     Symbol* signature = call.signature();
1166     receiver = Handle(thread, last_frame.callee_receiver(signature));
1167 
1168     assert(Universe::heap()->is_in_reserved_or_null(receiver())
1169            || VTBuffer::is_in_vt_buffer(receiver()),
1170            "sanity check");
1171     assert(receiver.is_null() ||
1172            !Universe::heap()->is_in_reserved(receiver->klass()),
1173            "sanity check");
1174   }
1175 
1176   // resolve method
1177   CallInfo info;
1178   constantPoolHandle pool(thread, last_frame.method()->constants());
1179 
1180   {
1181     JvmtiHideSingleStepping jhss(thread);
1182     LinkResolver::resolve_invoke(info, receiver, pool,
1183                                  last_frame.get_index_u2_cpcache(bytecode), bytecode,
1184                                  CHECK);
1185     if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
1186       int retry_count = 0;
1187       while (info.resolved_method()->is_old()) {
1188         // It is very unlikely that method is redefined more than 100 times
1189         // in the middle of resolve. If it is looping here more than 100 times
1190         // means then there could be a bug here.
1191         guarantee((retry_count++ < 100),
1192                   "Could not resolve to latest version of redefined method");
1193         // method is redefined in the middle of resolve so re-try.
1194         LinkResolver::resolve_invoke(info, receiver, pool,
1195                                      last_frame.get_index_u2_cpcache(bytecode), bytecode,
1196                                      CHECK);
1197       }
1198     }
1199   } // end JvmtiHideSingleStepping
1200 
1201   // check if link resolution caused cpCache to be updated
1202   ConstantPoolCacheEntry* cp_cache_entry = last_frame.cache_entry();
1203   if (cp_cache_entry->is_resolved(bytecode)) return;
1204 
1205 #ifdef ASSERT
1206   if (bytecode == Bytecodes::_invokeinterface) {
1207     if (info.resolved_method()->method_holder() ==
1208                                             SystemDictionary::Object_klass()) {
1209       // NOTE: THIS IS A FIX FOR A CORNER CASE in the JVM spec
1210       // (see also CallInfo::set_interface for details)
1211       assert(info.call_kind() == CallInfo::vtable_call ||
1212              info.call_kind() == CallInfo::direct_call, "");
1213       methodHandle rm = info.resolved_method();
1214       assert(rm->is_final() || info.has_vtable_index(),
1215              "should have been set already");
1216     } else if (!info.resolved_method()->has_itable_index()) {
1217       // Resolved something like CharSequence.toString.  Use vtable not itable.
1218       assert(info.call_kind() != CallInfo::itable_call, "");
1219     } else {
1220       // Setup itable entry
1221       assert(info.call_kind() == CallInfo::itable_call, "");
1222       int index = info.resolved_method()->itable_index();
1223       assert(info.itable_index() == index, "");
1224     }
1225   } else if (bytecode == Bytecodes::_invokespecial) {
1226     assert(info.call_kind() == CallInfo::direct_call, "must be direct call");
1227   } else {
1228     assert(info.call_kind() == CallInfo::direct_call ||
1229            info.call_kind() == CallInfo::vtable_call, "");
1230   }
1231 #endif
1232   // Get sender or sender's host_klass, and only set cpCache entry to resolved if
1233   // it is not an interface.  The receiver for invokespecial calls within interface
1234   // methods must be checked for every call.
1235   InstanceKlass* sender = pool->pool_holder();
1236   sender = sender->has_host_klass() ? sender->host_klass() : sender;
1237 
1238   switch (info.call_kind()) {
1239   case CallInfo::direct_call:
1240     cp_cache_entry->set_direct_call(
1241       bytecode,
1242       info.resolved_method(),
1243       sender->is_interface());
1244     break;
1245   case CallInfo::vtable_call:
1246     cp_cache_entry->set_vtable_call(
1247       bytecode,
1248       info.resolved_method(),
1249       info.vtable_index());
1250     break;
1251   case CallInfo::itable_call:
1252     cp_cache_entry->set_itable_call(
1253       bytecode,
1254       info.resolved_klass(),
1255       info.resolved_method(),
1256       info.itable_index());
1257     break;
1258   default:  ShouldNotReachHere();
1259   }
1260 }
1261 
1262 
1263 // First time execution:  Resolve symbols, create a permanent MethodType object.
1264 void InterpreterRuntime::resolve_invokehandle(JavaThread* thread) {
1265   Thread* THREAD = thread;
1266   const Bytecodes::Code bytecode = Bytecodes::_invokehandle;
1267   LastFrameAccessor last_frame(thread);
1268 
1269   // resolve method
1270   CallInfo info;
1271   constantPoolHandle pool(thread, last_frame.method()->constants());
1272   {
1273     JvmtiHideSingleStepping jhss(thread);
1274     LinkResolver::resolve_invoke(info, Handle(), pool,
1275                                  last_frame.get_index_u2_cpcache(bytecode), bytecode,
1276                                  CHECK);
1277   } // end JvmtiHideSingleStepping
1278 
1279   ConstantPoolCacheEntry* cp_cache_entry = last_frame.cache_entry();
1280   cp_cache_entry->set_method_handle(pool, info);
1281 }
1282 
1283 // First time execution:  Resolve symbols, create a permanent CallSite object.
1284 void InterpreterRuntime::resolve_invokedynamic(JavaThread* thread) {
1285   Thread* THREAD = thread;
1286   LastFrameAccessor last_frame(thread);
1287   const Bytecodes::Code bytecode = Bytecodes::_invokedynamic;
1288 
1289   //TO DO: consider passing BCI to Java.
1290   //  int caller_bci = last_frame.method()->bci_from(last_frame.bcp());
1291 
1292   // resolve method
1293   CallInfo info;
1294   constantPoolHandle pool(thread, last_frame.method()->constants());
1295   int index = last_frame.get_index_u4(bytecode);
1296   {
1297     JvmtiHideSingleStepping jhss(thread);
1298     LinkResolver::resolve_invoke(info, Handle(), pool,
1299                                  index, bytecode, CHECK);
1300   } // end JvmtiHideSingleStepping
1301 
1302   ConstantPoolCacheEntry* cp_cache_entry = pool->invokedynamic_cp_cache_entry_at(index);
1303   cp_cache_entry->set_dynamic_call(pool, info);
1304 }
1305 
1306 // This function is the interface to the assembly code. It returns the resolved
1307 // cpCache entry.  This doesn't safepoint, but the helper routines safepoint.
1308 // This function will check for redefinition!
1309 IRT_ENTRY(void, InterpreterRuntime::resolve_from_cache(JavaThread* thread, Bytecodes::Code bytecode)) {
1310   switch (bytecode) {
1311   case Bytecodes::_getstatic:
1312   case Bytecodes::_putstatic:
1313   case Bytecodes::_getfield:
1314   case Bytecodes::_putfield:
1315   case Bytecodes::_withfield:
1316     resolve_get_put(thread, bytecode);
1317     break;
1318   case Bytecodes::_invokevirtual:
1319   case Bytecodes::_invokespecial:
1320   case Bytecodes::_invokestatic:
1321   case Bytecodes::_invokeinterface:
1322     resolve_invoke(thread, bytecode);
1323     break;
1324   case Bytecodes::_invokehandle:
1325     resolve_invokehandle(thread);
1326     break;
1327   case Bytecodes::_invokedynamic:
1328     resolve_invokedynamic(thread);
1329     break;
1330   default:
1331     fatal("unexpected bytecode: %s", Bytecodes::name(bytecode));
1332     break;
1333   }
1334 }
1335 IRT_END
1336 
1337 //------------------------------------------------------------------------------------------------------------------------
1338 // Miscellaneous
1339 
1340 
1341 nmethod* InterpreterRuntime::frequency_counter_overflow(JavaThread* thread, address branch_bcp) {
1342   nmethod* nm = frequency_counter_overflow_inner(thread, branch_bcp);
1343   assert(branch_bcp != NULL || nm == NULL, "always returns null for non OSR requests");
1344   if (branch_bcp != NULL && nm != NULL) {
1345     // This was a successful request for an OSR nmethod.  Because
1346     // frequency_counter_overflow_inner ends with a safepoint check,
1347     // nm could have been unloaded so look it up again.  It's unsafe
1348     // to examine nm directly since it might have been freed and used
1349     // for something else.
1350     LastFrameAccessor last_frame(thread);
1351     Method* method =  last_frame.method();
1352     int bci = method->bci_from(last_frame.bcp());
1353     nm = method->lookup_osr_nmethod_for(bci, CompLevel_none, false);
1354   }
1355   if (nm != NULL && thread->is_interp_only_mode()) {
1356     // Normally we never get an nm if is_interp_only_mode() is true, because
1357     // policy()->event has a check for this and won't compile the method when
1358     // true. However, it's possible for is_interp_only_mode() to become true
1359     // during the compilation. We don't want to return the nm in that case
1360     // because we want to continue to execute interpreted.
1361     nm = NULL;
1362   }
1363 #ifndef PRODUCT
1364   if (TraceOnStackReplacement) {
1365     if (nm != NULL) {
1366       tty->print("OSR entry @ pc: " INTPTR_FORMAT ": ", p2i(nm->osr_entry()));
1367       nm->print();
1368     }
1369   }
1370 #endif
1371   return nm;
1372 }
1373 
1374 IRT_ENTRY(nmethod*,
1375           InterpreterRuntime::frequency_counter_overflow_inner(JavaThread* thread, address branch_bcp))
1376   // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
1377   // flag, in case this method triggers classloading which will call into Java.
1378   UnlockFlagSaver fs(thread);
1379 
1380   LastFrameAccessor last_frame(thread);
1381   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1382   methodHandle method(thread, last_frame.method());
1383   const int branch_bci = branch_bcp != NULL ? method->bci_from(branch_bcp) : InvocationEntryBci;
1384   const int bci = branch_bcp != NULL ? method->bci_from(last_frame.bcp()) : InvocationEntryBci;
1385 
1386   assert(!HAS_PENDING_EXCEPTION, "Should not have any exceptions pending");
1387   nmethod* osr_nm = CompilationPolicy::policy()->event(method, method, branch_bci, bci, CompLevel_none, NULL, thread);
1388   assert(!HAS_PENDING_EXCEPTION, "Event handler should not throw any exceptions");
1389 
1390   if (osr_nm != NULL) {
1391     // We may need to do on-stack replacement which requires that no
1392     // monitors in the activation are biased because their
1393     // BasicObjectLocks will need to migrate during OSR. Force
1394     // unbiasing of all monitors in the activation now (even though
1395     // the OSR nmethod might be invalidated) because we don't have a
1396     // safepoint opportunity later once the migration begins.
1397     if (UseBiasedLocking) {
1398       ResourceMark rm;
1399       GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
1400       for( BasicObjectLock *kptr = last_frame.monitor_end();
1401            kptr < last_frame.monitor_begin();
1402            kptr = last_frame.next_monitor(kptr) ) {
1403         if( kptr->obj() != NULL ) {
1404           objects_to_revoke->append(Handle(THREAD, kptr->obj()));
1405         }
1406       }
1407       BiasedLocking::revoke(objects_to_revoke);
1408     }
1409   }
1410   return osr_nm;
1411 IRT_END
1412 
1413 IRT_LEAF(jint, InterpreterRuntime::bcp_to_di(Method* method, address cur_bcp))
1414   assert(ProfileInterpreter, "must be profiling interpreter");
1415   int bci = method->bci_from(cur_bcp);
1416   MethodData* mdo = method->method_data();
1417   if (mdo == NULL)  return 0;
1418   return mdo->bci_to_di(bci);
1419 IRT_END
1420 
1421 IRT_ENTRY(void, InterpreterRuntime::profile_method(JavaThread* thread))
1422   // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
1423   // flag, in case this method triggers classloading which will call into Java.
1424   UnlockFlagSaver fs(thread);
1425 
1426   assert(ProfileInterpreter, "must be profiling interpreter");
1427   LastFrameAccessor last_frame(thread);
1428   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1429   methodHandle method(thread, last_frame.method());
1430   Method::build_interpreter_method_data(method, THREAD);
1431   if (HAS_PENDING_EXCEPTION) {
1432     assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
1433     CLEAR_PENDING_EXCEPTION;
1434     // and fall through...
1435   }
1436 IRT_END
1437 
1438 
1439 #ifdef ASSERT
1440 IRT_LEAF(void, InterpreterRuntime::verify_mdp(Method* method, address bcp, address mdp))
1441   assert(ProfileInterpreter, "must be profiling interpreter");
1442 
1443   MethodData* mdo = method->method_data();
1444   assert(mdo != NULL, "must not be null");
1445 
1446   int bci = method->bci_from(bcp);
1447 
1448   address mdp2 = mdo->bci_to_dp(bci);
1449   if (mdp != mdp2) {
1450     ResourceMark rm;
1451     ResetNoHandleMark rnm; // In a LEAF entry.
1452     HandleMark hm;
1453     tty->print_cr("FAILED verify : actual mdp %p   expected mdp %p @ bci %d", mdp, mdp2, bci);
1454     int current_di = mdo->dp_to_di(mdp);
1455     int expected_di  = mdo->dp_to_di(mdp2);
1456     tty->print_cr("  actual di %d   expected di %d", current_di, expected_di);
1457     int expected_approx_bci = mdo->data_at(expected_di)->bci();
1458     int approx_bci = -1;
1459     if (current_di >= 0) {
1460       approx_bci = mdo->data_at(current_di)->bci();
1461     }
1462     tty->print_cr("  actual bci is %d  expected bci %d", approx_bci, expected_approx_bci);
1463     mdo->print_on(tty);
1464     method->print_codes();
1465   }
1466   assert(mdp == mdp2, "wrong mdp");
1467 IRT_END
1468 #endif // ASSERT
1469 
1470 IRT_ENTRY(void, InterpreterRuntime::update_mdp_for_ret(JavaThread* thread, int return_bci))
1471   assert(ProfileInterpreter, "must be profiling interpreter");
1472   ResourceMark rm(thread);
1473   HandleMark hm(thread);
1474   LastFrameAccessor last_frame(thread);
1475   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1476   MethodData* h_mdo = last_frame.method()->method_data();
1477 
1478   // Grab a lock to ensure atomic access to setting the return bci and
1479   // the displacement.  This can block and GC, invalidating all naked oops.
1480   MutexLocker ml(RetData_lock);
1481 
1482   // ProfileData is essentially a wrapper around a derived oop, so we
1483   // need to take the lock before making any ProfileData structures.
1484   ProfileData* data = h_mdo->data_at(h_mdo->dp_to_di(last_frame.mdp()));
1485   guarantee(data != NULL, "profile data must be valid");
1486   RetData* rdata = data->as_RetData();
1487   address new_mdp = rdata->fixup_ret(return_bci, h_mdo);
1488   last_frame.set_mdp(new_mdp);
1489 IRT_END
1490 
1491 IRT_ENTRY(MethodCounters*, InterpreterRuntime::build_method_counters(JavaThread* thread, Method* m))
1492   MethodCounters* mcs = Method::build_method_counters(m, thread);
1493   if (HAS_PENDING_EXCEPTION) {
1494     assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
1495     CLEAR_PENDING_EXCEPTION;
1496   }
1497   return mcs;
1498 IRT_END
1499 
1500 
1501 IRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* thread))
1502   // We used to need an explict preserve_arguments here for invoke bytecodes. However,
1503   // stack traversal automatically takes care of preserving arguments for invoke, so
1504   // this is no longer needed.
1505 
1506   // IRT_END does an implicit safepoint check, hence we are guaranteed to block
1507   // if this is called during a safepoint
1508 
1509   if (JvmtiExport::should_post_single_step()) {
1510     // We are called during regular safepoints and when the VM is
1511     // single stepping. If any thread is marked for single stepping,
1512     // then we may have JVMTI work to do.
1513     LastFrameAccessor last_frame(thread);
1514     JvmtiExport::at_single_stepping_point(thread, last_frame.method(), last_frame.bcp());
1515   }
1516 IRT_END
1517 
1518 IRT_ENTRY(void, InterpreterRuntime::post_field_access(JavaThread *thread, oopDesc* obj,
1519 ConstantPoolCacheEntry *cp_entry))
1520 
1521   // check the access_flags for the field in the klass
1522 
1523   InstanceKlass* ik = InstanceKlass::cast(cp_entry->f1_as_klass());
1524   int index = cp_entry->field_index();
1525   if ((ik->field_access_flags(index) & JVM_ACC_FIELD_ACCESS_WATCHED) == 0) return;
1526 
1527   bool is_static = (obj == NULL);
1528   HandleMark hm(thread);
1529 
1530   Handle h_obj;
1531   if (!is_static) {
1532     // non-static field accessors have an object, but we need a handle
1533     h_obj = Handle(thread, obj);
1534   }
1535   InstanceKlass* cp_entry_f1 = InstanceKlass::cast(cp_entry->f1_as_klass());
1536   jfieldID fid = jfieldIDWorkaround::to_jfieldID(cp_entry_f1, cp_entry->f2_as_index(), is_static);
1537   LastFrameAccessor last_frame(thread);
1538   JvmtiExport::post_field_access(thread, last_frame.method(), last_frame.bcp(), cp_entry_f1, h_obj, fid);
1539 IRT_END
1540 
1541 IRT_ENTRY(void, InterpreterRuntime::post_field_modification(JavaThread *thread,
1542   oopDesc* obj, ConstantPoolCacheEntry *cp_entry, jvalue *value))
1543 
1544   Klass* k = cp_entry->f1_as_klass();
1545 
1546   // check the access_flags for the field in the klass
1547   InstanceKlass* ik = InstanceKlass::cast(k);
1548   int index = cp_entry->field_index();
1549   // bail out if field modifications are not watched
1550   if ((ik->field_access_flags(index) & JVM_ACC_FIELD_MODIFICATION_WATCHED) == 0) return;
1551 
1552   char sig_type = '\0';
1553 
1554   switch(cp_entry->flag_state()) {
1555     case btos: sig_type = 'B'; break;
1556     case ztos: sig_type = 'Z'; break;
1557     case ctos: sig_type = 'C'; break;
1558     case stos: sig_type = 'S'; break;
1559     case itos: sig_type = 'I'; break;
1560     case ftos: sig_type = 'F'; break;
1561     case atos: sig_type = 'L'; break;
1562     case ltos: sig_type = 'J'; break;
1563     case dtos: sig_type = 'D'; break;
1564     default:  ShouldNotReachHere(); return;
1565   }
1566   bool is_static = (obj == NULL);
1567 
1568   HandleMark hm(thread);
1569   jfieldID fid = jfieldIDWorkaround::to_jfieldID(ik, cp_entry->f2_as_index(), is_static);
1570   jvalue fvalue;
1571 #ifdef _LP64
1572   fvalue = *value;
1573 #else
1574   // Long/double values are stored unaligned and also noncontiguously with
1575   // tagged stacks.  We can't just do a simple assignment even in the non-
1576   // J/D cases because a C++ compiler is allowed to assume that a jvalue is
1577   // 8-byte aligned, and interpreter stack slots are only 4-byte aligned.
1578   // We assume that the two halves of longs/doubles are stored in interpreter
1579   // stack slots in platform-endian order.
1580   jlong_accessor u;
1581   jint* newval = (jint*)value;
1582   u.words[0] = newval[0];
1583   u.words[1] = newval[Interpreter::stackElementWords]; // skip if tag
1584   fvalue.j = u.long_value;
1585 #endif // _LP64
1586 
1587   Handle h_obj;
1588   if (!is_static) {
1589     // non-static field accessors have an object, but we need a handle
1590     h_obj = Handle(thread, obj);
1591   }
1592 
1593   LastFrameAccessor last_frame(thread);
1594   JvmtiExport::post_raw_field_modification(thread, last_frame.method(), last_frame.bcp(), ik, h_obj,
1595                                            fid, sig_type, &fvalue);
1596 IRT_END
1597 
1598 IRT_ENTRY(void, InterpreterRuntime::post_method_entry(JavaThread *thread))
1599   LastFrameAccessor last_frame(thread);
1600   JvmtiExport::post_method_entry(thread, last_frame.method(), last_frame.get_frame());
1601 IRT_END
1602 
1603 
1604 IRT_ENTRY(void, InterpreterRuntime::post_method_exit(JavaThread *thread))
1605   LastFrameAccessor last_frame(thread);
1606   JvmtiExport::post_method_exit(thread, last_frame.method(), last_frame.get_frame());
1607 IRT_END
1608 
1609 IRT_LEAF(int, InterpreterRuntime::interpreter_contains(address pc))
1610 {
1611   return (Interpreter::contains(pc) ? 1 : 0);
1612 }
1613 IRT_END
1614 
1615 
1616 // Implementation of SignatureHandlerLibrary
1617 
1618 #ifndef SHARING_FAST_NATIVE_FINGERPRINTS
1619 // Dummy definition (else normalization method is defined in CPU
1620 // dependant code)
1621 uint64_t InterpreterRuntime::normalize_fast_native_fingerprint(uint64_t fingerprint) {
1622   return fingerprint;
1623 }
1624 #endif
1625 
1626 address SignatureHandlerLibrary::set_handler_blob() {
1627   BufferBlob* handler_blob = BufferBlob::create("native signature handlers", blob_size);
1628   if (handler_blob == NULL) {
1629     return NULL;
1630   }
1631   address handler = handler_blob->code_begin();
1632   _handler_blob = handler_blob;
1633   _handler = handler;
1634   return handler;
1635 }
1636 
1637 void SignatureHandlerLibrary::initialize() {
1638   if (_fingerprints != NULL) {
1639     return;
1640   }
1641   if (set_handler_blob() == NULL) {
1642     vm_exit_out_of_memory(blob_size, OOM_MALLOC_ERROR, "native signature handlers");
1643   }
1644 
1645   BufferBlob* bb = BufferBlob::create("Signature Handler Temp Buffer",
1646                                       SignatureHandlerLibrary::buffer_size);
1647   _buffer = bb->code_begin();
1648 
1649   _fingerprints = new(ResourceObj::C_HEAP, mtCode)GrowableArray<uint64_t>(32, true);
1650   _handlers     = new(ResourceObj::C_HEAP, mtCode)GrowableArray<address>(32, true);
1651 }
1652 
1653 address SignatureHandlerLibrary::set_handler(CodeBuffer* buffer) {
1654   address handler   = _handler;
1655   int     insts_size = buffer->pure_insts_size();
1656   if (handler + insts_size > _handler_blob->code_end()) {
1657     // get a new handler blob
1658     handler = set_handler_blob();
1659   }
1660   if (handler != NULL) {
1661     memcpy(handler, buffer->insts_begin(), insts_size);
1662     pd_set_handler(handler);
1663     ICache::invalidate_range(handler, insts_size);
1664     _handler = handler + insts_size;
1665   }
1666   return handler;
1667 }
1668 
1669 void SignatureHandlerLibrary::add(const methodHandle& method) {
1670   if (method->signature_handler() == NULL) {
1671     // use slow signature handler if we can't do better
1672     int handler_index = -1;
1673     // check if we can use customized (fast) signature handler
1674     if (UseFastSignatureHandlers && method->size_of_parameters() <= Fingerprinter::max_size_of_parameters) {
1675       // use customized signature handler
1676       MutexLocker mu(SignatureHandlerLibrary_lock);
1677       // make sure data structure is initialized
1678       initialize();
1679       // lookup method signature's fingerprint
1680       uint64_t fingerprint = Fingerprinter(method).fingerprint();
1681       // allow CPU dependant code to optimize the fingerprints for the fast handler
1682       fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1683       handler_index = _fingerprints->find(fingerprint);
1684       // create handler if necessary
1685       if (handler_index < 0) {
1686         ResourceMark rm;
1687         ptrdiff_t align_offset = align_up(_buffer, CodeEntryAlignment) - (address)_buffer;
1688         CodeBuffer buffer((address)(_buffer + align_offset),
1689                           SignatureHandlerLibrary::buffer_size - align_offset);
1690         InterpreterRuntime::SignatureHandlerGenerator(method, &buffer).generate(fingerprint);
1691         // copy into code heap
1692         address handler = set_handler(&buffer);
1693         if (handler == NULL) {
1694           // use slow signature handler (without memorizing it in the fingerprints)
1695         } else {
1696           // debugging suppport
1697           if (PrintSignatureHandlers && (handler != Interpreter::slow_signature_handler())) {
1698             ttyLocker ttyl;
1699             tty->cr();
1700             tty->print_cr("argument handler #%d for: %s %s (fingerprint = " UINT64_FORMAT ", %d bytes generated)",
1701                           _handlers->length(),
1702                           (method->is_static() ? "static" : "receiver"),
1703                           method->name_and_sig_as_C_string(),
1704                           fingerprint,
1705                           buffer.insts_size());
1706             if (buffer.insts_size() > 0) {
1707               Disassembler::decode(handler, handler + buffer.insts_size());
1708             }
1709 #ifndef PRODUCT
1710             address rh_begin = Interpreter::result_handler(method()->result_type());
1711             if (CodeCache::contains(rh_begin)) {
1712               // else it might be special platform dependent values
1713               tty->print_cr(" --- associated result handler ---");
1714               address rh_end = rh_begin;
1715               while (*(int*)rh_end != 0) {
1716                 rh_end += sizeof(int);
1717               }
1718               Disassembler::decode(rh_begin, rh_end);
1719             } else {
1720               tty->print_cr(" associated result handler: " PTR_FORMAT, p2i(rh_begin));
1721             }
1722 #endif
1723           }
1724           // add handler to library
1725           _fingerprints->append(fingerprint);
1726           _handlers->append(handler);
1727           // set handler index
1728           assert(_fingerprints->length() == _handlers->length(), "sanity check");
1729           handler_index = _fingerprints->length() - 1;
1730         }
1731       }
1732       // Set handler under SignatureHandlerLibrary_lock
1733       if (handler_index < 0) {
1734         // use generic signature handler
1735         method->set_signature_handler(Interpreter::slow_signature_handler());
1736       } else {
1737         // set handler
1738         method->set_signature_handler(_handlers->at(handler_index));
1739       }
1740     } else {
1741       CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
1742       // use generic signature handler
1743       method->set_signature_handler(Interpreter::slow_signature_handler());
1744     }
1745   }
1746 #ifdef ASSERT
1747   int handler_index = -1;
1748   int fingerprint_index = -2;
1749   {
1750     // '_handlers' and '_fingerprints' are 'GrowableArray's and are NOT synchronized
1751     // in any way if accessed from multiple threads. To avoid races with another
1752     // thread which may change the arrays in the above, mutex protected block, we
1753     // have to protect this read access here with the same mutex as well!
1754     MutexLocker mu(SignatureHandlerLibrary_lock);
1755     if (_handlers != NULL) {
1756       handler_index = _handlers->find(method->signature_handler());
1757       uint64_t fingerprint = Fingerprinter(method).fingerprint();
1758       fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1759       fingerprint_index = _fingerprints->find(fingerprint);
1760     }
1761   }
1762   assert(method->signature_handler() == Interpreter::slow_signature_handler() ||
1763          handler_index == fingerprint_index, "sanity check");
1764 #endif // ASSERT
1765 }
1766 
1767 void SignatureHandlerLibrary::add(uint64_t fingerprint, address handler) {
1768   int handler_index = -1;
1769   // use customized signature handler
1770   MutexLocker mu(SignatureHandlerLibrary_lock);
1771   // make sure data structure is initialized
1772   initialize();
1773   fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1774   handler_index = _fingerprints->find(fingerprint);
1775   // create handler if necessary
1776   if (handler_index < 0) {
1777     if (PrintSignatureHandlers && (handler != Interpreter::slow_signature_handler())) {
1778       tty->cr();
1779       tty->print_cr("argument handler #%d at " PTR_FORMAT " for fingerprint " UINT64_FORMAT,
1780                     _handlers->length(),
1781                     p2i(handler),
1782                     fingerprint);
1783     }
1784     _fingerprints->append(fingerprint);
1785     _handlers->append(handler);
1786   } else {
1787     if (PrintSignatureHandlers) {
1788       tty->cr();
1789       tty->print_cr("duplicate argument handler #%d for fingerprint " UINT64_FORMAT "(old: " PTR_FORMAT ", new : " PTR_FORMAT ")",
1790                     _handlers->length(),
1791                     fingerprint,
1792                     p2i(_handlers->at(handler_index)),
1793                     p2i(handler));
1794     }
1795   }
1796 }
1797 
1798 
1799 BufferBlob*              SignatureHandlerLibrary::_handler_blob = NULL;
1800 address                  SignatureHandlerLibrary::_handler      = NULL;
1801 GrowableArray<uint64_t>* SignatureHandlerLibrary::_fingerprints = NULL;
1802 GrowableArray<address>*  SignatureHandlerLibrary::_handlers     = NULL;
1803 address                  SignatureHandlerLibrary::_buffer       = NULL;
1804 
1805 
1806 IRT_ENTRY(void, InterpreterRuntime::prepare_native_call(JavaThread* thread, Method* method))
1807   methodHandle m(thread, method);
1808   assert(m->is_native(), "sanity check");
1809   // lookup native function entry point if it doesn't exist
1810   bool in_base_library;
1811   if (!m->has_native_function()) {
1812     NativeLookup::lookup(m, in_base_library, CHECK);
1813   }
1814   // make sure signature handler is installed
1815   SignatureHandlerLibrary::add(m);
1816   // The interpreter entry point checks the signature handler first,
1817   // before trying to fetch the native entry point and klass mirror.
1818   // We must set the signature handler last, so that multiple processors
1819   // preparing the same method will be sure to see non-null entry & mirror.
1820 IRT_END
1821 
1822 #if defined(IA32) || defined(AMD64) || defined(ARM)
1823 IRT_LEAF(void, InterpreterRuntime::popframe_move_outgoing_args(JavaThread* thread, void* src_address, void* dest_address))
1824   if (src_address == dest_address) {
1825     return;
1826   }
1827   ResetNoHandleMark rnm; // In a LEAF entry.
1828   HandleMark hm;
1829   ResourceMark rm;
1830   LastFrameAccessor last_frame(thread);
1831   assert(last_frame.is_interpreted_frame(), "");
1832   jint bci = last_frame.bci();
1833   methodHandle mh(thread, last_frame.method());
1834   Bytecode_invoke invoke(mh, bci);
1835   ArgumentSizeComputer asc(invoke.signature());
1836   int size_of_arguments = (asc.size() + (invoke.has_receiver() ? 1 : 0)); // receiver
1837   Copy::conjoint_jbytes(src_address, dest_address,
1838                        size_of_arguments * Interpreter::stackElementSize);
1839 IRT_END
1840 #endif
1841 
1842 #if INCLUDE_JVMTI
1843 // This is a support of the JVMTI PopFrame interface.
1844 // Make sure it is an invokestatic of a polymorphic intrinsic that has a member_name argument
1845 // and return it as a vm_result so that it can be reloaded in the list of invokestatic parameters.
1846 // The member_name argument is a saved reference (in local#0) to the member_name.
1847 // For backward compatibility with some JDK versions (7, 8) it can also be a direct method handle.
1848 // FIXME: remove DMH case after j.l.i.InvokerBytecodeGenerator code shape is updated.
1849 IRT_ENTRY(void, InterpreterRuntime::member_name_arg_or_null(JavaThread* thread, address member_name,
1850                                                             Method* method, address bcp))
1851   Bytecodes::Code code = Bytecodes::code_at(method, bcp);
1852   if (code != Bytecodes::_invokestatic) {
1853     return;
1854   }
1855   ConstantPool* cpool = method->constants();
1856   int cp_index = Bytes::get_native_u2(bcp + 1) + ConstantPool::CPCACHE_INDEX_TAG;
1857   Symbol* cname = cpool->klass_name_at(cpool->klass_ref_index_at(cp_index));
1858   Symbol* mname = cpool->name_ref_at(cp_index);
1859 
1860   if (MethodHandles::has_member_arg(cname, mname)) {
1861     oop member_name_oop = (oop) member_name;
1862     if (java_lang_invoke_DirectMethodHandle::is_instance(member_name_oop)) {
1863       // FIXME: remove after j.l.i.InvokerBytecodeGenerator code shape is updated.
1864       member_name_oop = java_lang_invoke_DirectMethodHandle::member(member_name_oop);
1865     }
1866     thread->set_vm_result(member_name_oop);
1867   } else {
1868     thread->set_vm_result(NULL);
1869   }
1870 IRT_END
1871 #endif // INCLUDE_JVMTI
1872 
1873 #ifndef PRODUCT
1874 // This must be a IRT_LEAF function because the interpreter must save registers on x86 to
1875 // call this, which changes rsp and makes the interpreter's expression stack not walkable.
1876 // The generated code still uses call_VM because that will set up the frame pointer for
1877 // bcp and method.
1878 IRT_LEAF(intptr_t, InterpreterRuntime::trace_bytecode(JavaThread* thread, intptr_t preserve_this_value, intptr_t tos, intptr_t tos2))
1879   LastFrameAccessor last_frame(thread);
1880   assert(last_frame.is_interpreted_frame(), "must be an interpreted frame");
1881   methodHandle mh(thread, last_frame.method());
1882   BytecodeTracer::trace(mh, last_frame.bcp(), tos, tos2);
1883   return preserve_this_value;
1884 IRT_END
1885 #endif // !PRODUCT