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