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