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