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