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