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