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