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