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