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