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