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 IRT_ENTRY(address, InterpreterRuntime::check_ReservedStackAccess_annotated_methods(JavaThread* thread))
 318   frame fr = thread->last_frame();
 319   assert(fr.is_java_frame(), "Must be a Java frame");
 320   frame activation = SharedRuntime::look_for_reserved_stack_annotated_method(thread, fr);
 321   if (activation.sp() != NULL) {
 322     thread->disable_stack_reserved_zone();
 323     thread->set_reserved_stack_activation((address)activation.unextended_sp());
 324   }
 325   return (address)activation.sp();
 326 IRT_END
 327 
 328  IRT_ENTRY(void, InterpreterRuntime::throw_delayed_StackOverflowError(JavaThread* thread))
 329   Handle exception = get_preinitialized_exception(
 330                                  SystemDictionary::StackOverflowError_klass(),
 331                                  CHECK);
 332   java_lang_Throwable::set_message(exception(),
 333           Universe::delayed_stack_overflow_error_message());
 334   // Increment counter for hs_err file reporting
 335   Atomic::inc(&Exceptions::_stack_overflow_errors);
 336   THROW_HANDLE(exception);
 337 IRT_END 
 338 
 339 IRT_ENTRY(void, InterpreterRuntime::create_exception(JavaThread* thread, char* name, char* message))
 340   // lookup exception klass
 341   TempNewSymbol s = SymbolTable::new_symbol(name, CHECK);
 342   if (ProfileTraps) {
 343     if (s == vmSymbols::java_lang_ArithmeticException()) {
 344       note_trap(thread, Deoptimization::Reason_div0_check, CHECK);
 345     } else if (s == vmSymbols::java_lang_NullPointerException()) {
 346       note_trap(thread, Deoptimization::Reason_null_check, CHECK);
 347     }
 348   }
 349   // create exception
 350   Handle exception = Exceptions::new_exception(thread, s, message);
 351   thread->set_vm_result(exception());
 352 IRT_END
 353 
 354 
 355 IRT_ENTRY(void, InterpreterRuntime::create_klass_exception(JavaThread* thread, char* name, oopDesc* obj))
 356   ResourceMark rm(thread);
 357   const char* klass_name = obj->klass()->external_name();
 358   // lookup exception klass
 359   TempNewSymbol s = SymbolTable::new_symbol(name, CHECK);
 360   if (ProfileTraps) {
 361     note_trap(thread, Deoptimization::Reason_class_check, CHECK);
 362   }
 363   // create exception, with klass name as detail message
 364   Handle exception = Exceptions::new_exception(thread, s, klass_name);
 365   thread->set_vm_result(exception());
 366 IRT_END
 367 
 368 
 369 IRT_ENTRY(void, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException(JavaThread* thread, char* name, jint index))
 370   char message[jintAsStringSize];
 371   // lookup exception klass
 372   TempNewSymbol s = SymbolTable::new_symbol(name, CHECK);
 373   if (ProfileTraps) {
 374     note_trap(thread, Deoptimization::Reason_range_check, CHECK);
 375   }
 376   // create exception
 377   sprintf(message, "%d", index);
 378   THROW_MSG(s, message);
 379 IRT_END
 380 
 381 IRT_ENTRY(void, InterpreterRuntime::throw_ClassCastException(
 382   JavaThread* thread, oopDesc* obj))
 383 
 384   ResourceMark rm(thread);
 385   char* message = SharedRuntime::generate_class_cast_message(
 386     thread, obj->klass()->external_name());
 387 
 388   if (ProfileTraps) {
 389     note_trap(thread, Deoptimization::Reason_class_check, CHECK);
 390   }
 391 
 392   // create exception
 393   THROW_MSG(vmSymbols::java_lang_ClassCastException(), message);
 394 IRT_END
 395 
 396 // exception_handler_for_exception(...) returns the continuation address,
 397 // the exception oop (via TLS) and sets the bci/bcp for the continuation.
 398 // The exception oop is returned to make sure it is preserved over GC (it
 399 // is only on the stack if the exception was thrown explicitly via athrow).
 400 // During this operation, the expression stack contains the values for the
 401 // bci where the exception happened. If the exception was propagated back
 402 // from a call, the expression stack contains the values for the bci at the
 403 // invoke w/o arguments (i.e., as if one were inside the call).
 404 IRT_ENTRY(address, InterpreterRuntime::exception_handler_for_exception(JavaThread* thread, oopDesc* exception))
 405 
 406   Handle             h_exception(thread, exception);
 407   methodHandle       h_method   (thread, method(thread));
 408   constantPoolHandle h_constants(thread, h_method->constants());
 409   bool               should_repeat;
 410   int                handler_bci;
 411   int                current_bci = bci(thread);
 412 
 413   if (thread->frames_to_pop_failed_realloc() > 0) {
 414     // Allocation of scalar replaced object used in this frame
 415     // failed. Unconditionally pop the frame.
 416     thread->dec_frames_to_pop_failed_realloc();
 417     thread->set_vm_result(h_exception());
 418     // If the method is synchronized we already unlocked the monitor
 419     // during deoptimization so the interpreter needs to skip it when
 420     // the frame is popped.
 421     thread->set_do_not_unlock_if_synchronized(true);
 422 #ifdef CC_INTERP
 423     return (address) -1;
 424 #else
 425     return Interpreter::remove_activation_entry();
 426 #endif
 427   }
 428 
 429   // Need to do this check first since when _do_not_unlock_if_synchronized
 430   // is set, we don't want to trigger any classloading which may make calls
 431   // into java, or surprisingly find a matching exception handler for bci 0
 432   // since at this moment the method hasn't been "officially" entered yet.
 433   if (thread->do_not_unlock_if_synchronized()) {
 434     ResourceMark rm;
 435     assert(current_bci == 0,  "bci isn't zero for do_not_unlock_if_synchronized");
 436     thread->set_vm_result(exception);
 437 #ifdef CC_INTERP
 438     return (address) -1;
 439 #else
 440     return Interpreter::remove_activation_entry();
 441 #endif
 442   }
 443 
 444   do {
 445     should_repeat = false;
 446 
 447     // assertions
 448 #ifdef ASSERT
 449     assert(h_exception.not_null(), "NULL exceptions should be handled by athrow");
 450     assert(h_exception->is_oop(), "just checking");
 451     // Check that exception is a subclass of Throwable, otherwise we have a VerifyError
 452     if (!(h_exception->is_a(SystemDictionary::Throwable_klass()))) {
 453       if (ExitVMOnVerifyError) vm_exit(-1);
 454       ShouldNotReachHere();
 455     }
 456 #endif
 457 
 458     // tracing
 459     if (TraceExceptions) {
 460       ResourceMark rm(thread);
 461       Symbol* message = java_lang_Throwable::detail_message(h_exception());
 462       ttyLocker ttyl;  // Lock after getting the detail message
 463       if (message != NULL) {
 464         tty->print_cr("Exception <%s: %s> (" INTPTR_FORMAT ")",
 465                       h_exception->print_value_string(), message->as_C_string(),
 466                       p2i(h_exception()));
 467       } else {
 468         tty->print_cr("Exception <%s> (" INTPTR_FORMAT ")",
 469                       h_exception->print_value_string(),
 470                       p2i(h_exception()));
 471       }
 472       tty->print_cr(" thrown in interpreter method <%s>", h_method->print_value_string());
 473       tty->print_cr(" at bci %d for thread " INTPTR_FORMAT, current_bci, p2i(thread));
 474     }
 475 // Don't go paging in something which won't be used.
 476 //     else if (extable->length() == 0) {
 477 //       // disabled for now - interpreter is not using shortcut yet
 478 //       // (shortcut is not to call runtime if we have no exception handlers)
 479 //       // warning("performance bug: should not call runtime if method has no exception handlers");
 480 //     }
 481     // for AbortVMOnException flag
 482     Exceptions::debug_check_abort(h_exception);
 483 
 484     // exception handler lookup
 485     KlassHandle h_klass(THREAD, h_exception->klass());
 486     handler_bci = Method::fast_exception_handler_bci_for(h_method, h_klass, current_bci, THREAD);
 487     if (HAS_PENDING_EXCEPTION) {
 488       // We threw an exception while trying to find the exception handler.
 489       // Transfer the new exception to the exception handle which will
 490       // be set into thread local storage, and do another lookup for an
 491       // exception handler for this exception, this time starting at the
 492       // BCI of the exception handler which caused the exception to be
 493       // thrown (bug 4307310).
 494       h_exception = Handle(THREAD, PENDING_EXCEPTION);
 495       CLEAR_PENDING_EXCEPTION;
 496       if (handler_bci >= 0) {
 497         current_bci = handler_bci;
 498         should_repeat = true;
 499       }
 500     }
 501   } while (should_repeat == true);
 502 
 503 #if INCLUDE_JVMCI
 504   if (UseJVMCICompiler && h_method->method_data() != NULL) {
 505     ResourceMark rm(thread);
 506     ProfileData* pdata = h_method->method_data()->allocate_bci_to_data(current_bci, NULL);
 507     if (pdata != NULL && pdata->is_BitData()) {
 508       BitData* bit_data = (BitData*) pdata;
 509       bit_data->set_exception_seen();
 510     }
 511   }
 512 #endif
 513 
 514   // notify JVMTI of an exception throw; JVMTI will detect if this is a first
 515   // time throw or a stack unwinding throw and accordingly notify the debugger
 516   if (JvmtiExport::can_post_on_exceptions()) {
 517     JvmtiExport::post_exception_throw(thread, h_method(), bcp(thread), h_exception());
 518   }
 519 
 520 #ifdef CC_INTERP
 521   address continuation = (address)(intptr_t) handler_bci;
 522 #else
 523   address continuation = NULL;
 524 #endif
 525   address handler_pc = NULL;
 526   if (handler_bci < 0 || !thread->reguard_stack((address) &continuation)) {
 527     // Forward exception to callee (leaving bci/bcp untouched) because (a) no
 528     // handler in this method, or (b) after a stack overflow there is not yet
 529     // enough stack space available to reprotect the stack.
 530 #ifndef CC_INTERP
 531     continuation = Interpreter::remove_activation_entry();
 532 #endif
 533     // Count this for compilation purposes
 534     h_method->interpreter_throwout_increment(THREAD);
 535   } else {
 536     // handler in this method => change bci/bcp to handler bci/bcp and continue there
 537     handler_pc = h_method->code_base() + handler_bci;
 538 #ifndef CC_INTERP
 539     set_bcp_and_mdp(handler_pc, thread);
 540     continuation = Interpreter::dispatch_table(vtos)[*handler_pc];
 541 #endif
 542   }
 543   // notify debugger of an exception catch
 544   // (this is good for exceptions caught in native methods as well)
 545   if (JvmtiExport::can_post_on_exceptions()) {
 546     JvmtiExport::notice_unwind_due_to_exception(thread, h_method(), handler_pc, h_exception(), (handler_pc != NULL));
 547   }
 548 
 549   thread->set_vm_result(h_exception());
 550   return continuation;
 551 IRT_END
 552 
 553 
 554 IRT_ENTRY(void, InterpreterRuntime::throw_pending_exception(JavaThread* thread))
 555   assert(thread->has_pending_exception(), "must only ne called if there's an exception pending");
 556   // nothing to do - eventually we should remove this code entirely (see comments @ call sites)
 557 IRT_END
 558 
 559 
 560 IRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodError(JavaThread* thread))
 561   THROW(vmSymbols::java_lang_AbstractMethodError());
 562 IRT_END
 563 
 564 
 565 IRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeError(JavaThread* thread))
 566   THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
 567 IRT_END
 568 
 569 
 570 //------------------------------------------------------------------------------------------------------------------------
 571 // Fields
 572 //
 573 
 574 void InterpreterRuntime::resolve_get_put(JavaThread* thread, Bytecodes::Code bytecode) {
 575   Thread* THREAD = thread;
 576   // resolve field
 577   fieldDescriptor info;
 578   constantPoolHandle pool(thread, method(thread)->constants());
 579   bool is_put    = (bytecode == Bytecodes::_putfield  || bytecode == Bytecodes::_nofast_putfield ||
 580                     bytecode == Bytecodes::_putstatic);
 581   bool is_static = (bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic);
 582 
 583   {
 584     JvmtiHideSingleStepping jhss(thread);
 585     LinkResolver::resolve_field_access(info, pool, get_index_u2_cpcache(thread, bytecode),
 586                                        bytecode, CHECK);
 587   } // end JvmtiHideSingleStepping
 588 
 589   // check if link resolution caused cpCache to be updated
 590   ConstantPoolCacheEntry* cp_cache_entry = cache_entry(thread);
 591   if (cp_cache_entry->is_resolved(bytecode)) return;
 592 
 593   // compute auxiliary field attributes
 594   TosState state  = as_TosState(info.field_type());
 595 
 596   // We need to delay resolving put instructions on final fields
 597   // until we actually invoke one. This is required so we throw
 598   // exceptions at the correct place. If we do not resolve completely
 599   // in the current pass, leaving the put_code set to zero will
 600   // cause the next put instruction to reresolve.
 601   Bytecodes::Code put_code = (Bytecodes::Code)0;
 602 
 603   // We also need to delay resolving getstatic instructions until the
 604   // class is intitialized.  This is required so that access to the static
 605   // field will call the initialization function every time until the class
 606   // is completely initialized ala. in 2.17.5 in JVM Specification.
 607   InstanceKlass* klass = InstanceKlass::cast(info.field_holder());
 608   bool uninitialized_static = ((bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic) &&
 609                                !klass->is_initialized());
 610   Bytecodes::Code get_code = (Bytecodes::Code)0;
 611 
 612   if (!uninitialized_static) {
 613     get_code = ((is_static) ? Bytecodes::_getstatic : Bytecodes::_getfield);
 614     if (is_put || !info.access_flags().is_final()) {
 615       put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_putfield);
 616     }
 617   }
 618 
 619   cp_cache_entry->set_field(
 620     get_code,
 621     put_code,
 622     info.field_holder(),
 623     info.index(),
 624     info.offset(),
 625     state,
 626     info.access_flags().is_final(),
 627     info.access_flags().is_volatile(),
 628     pool->pool_holder()
 629   );
 630 }
 631 
 632 
 633 //------------------------------------------------------------------------------------------------------------------------
 634 // Synchronization
 635 //
 636 // The interpreter's synchronization code is factored out so that it can
 637 // be shared by method invocation and synchronized blocks.
 638 //%note synchronization_3
 639 
 640 //%note monitor_1
 641 IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* thread, BasicObjectLock* elem))
 642 #ifdef ASSERT
 643   thread->last_frame().interpreter_frame_verify_monitor(elem);
 644 #endif
 645   if (PrintBiasedLockingStatistics) {
 646     Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
 647   }
 648   Handle h_obj(thread, elem->obj());
 649   assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
 650          "must be NULL or an object");
 651   if (UseBiasedLocking) {
 652     // Retry fast entry if bias is revoked to avoid unnecessary inflation
 653     ObjectSynchronizer::fast_enter(h_obj, elem->lock(), true, CHECK);
 654   } else {
 655     ObjectSynchronizer::slow_enter(h_obj, elem->lock(), CHECK);
 656   }
 657   assert(Universe::heap()->is_in_reserved_or_null(elem->obj()),
 658          "must be NULL or an object");
 659 #ifdef ASSERT
 660   thread->last_frame().interpreter_frame_verify_monitor(elem);
 661 #endif
 662 IRT_END
 663 
 664 
 665 //%note monitor_1
 666 IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorexit(JavaThread* thread, BasicObjectLock* elem))
 667 #ifdef ASSERT
 668   thread->last_frame().interpreter_frame_verify_monitor(elem);
 669 #endif
 670   Handle h_obj(thread, elem->obj());
 671   assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
 672          "must be NULL or an object");
 673   if (elem == NULL || h_obj()->is_unlocked()) {
 674     THROW(vmSymbols::java_lang_IllegalMonitorStateException());
 675   }
 676   ObjectSynchronizer::slow_exit(h_obj(), elem->lock(), thread);
 677   // Free entry. This must be done here, since a pending exception might be installed on
 678   // exit. If it is not cleared, the exception handling code will try to unlock the monitor again.
 679   elem->set_obj(NULL);
 680 #ifdef ASSERT
 681   thread->last_frame().interpreter_frame_verify_monitor(elem);
 682 #endif
 683 IRT_END
 684 
 685 
 686 IRT_ENTRY(void, InterpreterRuntime::throw_illegal_monitor_state_exception(JavaThread* thread))
 687   THROW(vmSymbols::java_lang_IllegalMonitorStateException());
 688 IRT_END
 689 
 690 
 691 IRT_ENTRY(void, InterpreterRuntime::new_illegal_monitor_state_exception(JavaThread* thread))
 692   // Returns an illegal exception to install into the current thread. The
 693   // pending_exception flag is cleared so normal exception handling does not
 694   // trigger. Any current installed exception will be overwritten. This
 695   // method will be called during an exception unwind.
 696 
 697   assert(!HAS_PENDING_EXCEPTION, "no pending exception");
 698   Handle exception(thread, thread->vm_result());
 699   assert(exception() != NULL, "vm result should be set");
 700   thread->set_vm_result(NULL); // clear vm result before continuing (may cause memory leaks and assert failures)
 701   if (!exception->is_a(SystemDictionary::ThreadDeath_klass())) {
 702     exception = get_preinitialized_exception(
 703                        SystemDictionary::IllegalMonitorStateException_klass(),
 704                        CATCH);
 705   }
 706   thread->set_vm_result(exception());
 707 IRT_END
 708 
 709 
 710 //------------------------------------------------------------------------------------------------------------------------
 711 // Invokes
 712 
 713 IRT_ENTRY(Bytecodes::Code, InterpreterRuntime::get_original_bytecode_at(JavaThread* thread, Method* method, address bcp))
 714   return method->orig_bytecode_at(method->bci_from(bcp));
 715 IRT_END
 716 
 717 IRT_ENTRY(void, InterpreterRuntime::set_original_bytecode_at(JavaThread* thread, Method* method, address bcp, Bytecodes::Code new_code))
 718   method->set_orig_bytecode_at(method->bci_from(bcp), new_code);
 719 IRT_END
 720 
 721 IRT_ENTRY(void, InterpreterRuntime::_breakpoint(JavaThread* thread, Method* method, address bcp))
 722   JvmtiExport::post_raw_breakpoint(thread, method, bcp);
 723 IRT_END
 724 
 725 void InterpreterRuntime::resolve_invoke(JavaThread* thread, Bytecodes::Code bytecode) {
 726   Thread* THREAD = thread;
 727   // extract receiver from the outgoing argument list if necessary
 728   Handle receiver(thread, NULL);
 729   if (bytecode == Bytecodes::_invokevirtual || bytecode == Bytecodes::_invokeinterface) {
 730     ResourceMark rm(thread);
 731     methodHandle m (thread, method(thread));
 732     Bytecode_invoke call(m, bci(thread));
 733     Symbol* signature = call.signature();
 734     receiver = Handle(thread,
 735                   thread->last_frame().interpreter_callee_receiver(signature));
 736     assert(Universe::heap()->is_in_reserved_or_null(receiver()),
 737            "sanity check");
 738     assert(receiver.is_null() ||
 739            !Universe::heap()->is_in_reserved(receiver->klass()),
 740            "sanity check");
 741   }
 742 
 743   // resolve method
 744   CallInfo info;
 745   constantPoolHandle pool(thread, method(thread)->constants());
 746 
 747   {
 748     JvmtiHideSingleStepping jhss(thread);
 749     LinkResolver::resolve_invoke(info, receiver, pool,
 750                                  get_index_u2_cpcache(thread, bytecode), bytecode,
 751                                  CHECK);
 752     if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
 753       int retry_count = 0;
 754       while (info.resolved_method()->is_old()) {
 755         // It is very unlikely that method is redefined more than 100 times
 756         // in the middle of resolve. If it is looping here more than 100 times
 757         // means then there could be a bug here.
 758         guarantee((retry_count++ < 100),
 759                   "Could not resolve to latest version of redefined method");
 760         // method is redefined in the middle of resolve so re-try.
 761         LinkResolver::resolve_invoke(info, receiver, pool,
 762                                      get_index_u2_cpcache(thread, bytecode), bytecode,
 763                                      CHECK);
 764       }
 765     }
 766   } // end JvmtiHideSingleStepping
 767 
 768   // check if link resolution caused cpCache to be updated
 769   ConstantPoolCacheEntry* cp_cache_entry = cache_entry(thread);
 770   if (cp_cache_entry->is_resolved(bytecode)) return;
 771 
 772   if (bytecode == Bytecodes::_invokeinterface) {
 773     if (TraceItables && Verbose) {
 774       ResourceMark rm(thread);
 775       tty->print_cr("Resolving: klass: %s to method: %s", info.resolved_klass()->name()->as_C_string(), info.resolved_method()->name()->as_C_string());
 776     }
 777   }
 778 #ifdef ASSERT
 779   if (bytecode == Bytecodes::_invokeinterface) {
 780     if (info.resolved_method()->method_holder() ==
 781                                             SystemDictionary::Object_klass()) {
 782       // NOTE: THIS IS A FIX FOR A CORNER CASE in the JVM spec
 783       // (see also CallInfo::set_interface for details)
 784       assert(info.call_kind() == CallInfo::vtable_call ||
 785              info.call_kind() == CallInfo::direct_call, "");
 786       methodHandle rm = info.resolved_method();
 787       assert(rm->is_final() || info.has_vtable_index(),
 788              "should have been set already");
 789     } else if (!info.resolved_method()->has_itable_index()) {
 790       // Resolved something like CharSequence.toString.  Use vtable not itable.
 791       assert(info.call_kind() != CallInfo::itable_call, "");
 792     } else {
 793       // Setup itable entry
 794       assert(info.call_kind() == CallInfo::itable_call, "");
 795       int index = info.resolved_method()->itable_index();
 796       assert(info.itable_index() == index, "");
 797     }
 798   } else {
 799     assert(info.call_kind() == CallInfo::direct_call ||
 800            info.call_kind() == CallInfo::vtable_call, "");
 801   }
 802 #endif
 803   switch (info.call_kind()) {
 804   case CallInfo::direct_call:
 805     cp_cache_entry->set_direct_call(
 806       bytecode,
 807       info.resolved_method());
 808     break;
 809   case CallInfo::vtable_call:
 810     cp_cache_entry->set_vtable_call(
 811       bytecode,
 812       info.resolved_method(),
 813       info.vtable_index());
 814     break;
 815   case CallInfo::itable_call:
 816     cp_cache_entry->set_itable_call(
 817       bytecode,
 818       info.resolved_method(),
 819       info.itable_index());
 820     break;
 821   default:  ShouldNotReachHere();
 822   }
 823 }
 824 
 825 
 826 // First time execution:  Resolve symbols, create a permanent MethodType object.
 827 void InterpreterRuntime::resolve_invokehandle(JavaThread* thread) {
 828   Thread* THREAD = thread;
 829   const Bytecodes::Code bytecode = Bytecodes::_invokehandle;
 830 
 831   // resolve method
 832   CallInfo info;
 833   constantPoolHandle pool(thread, method(thread)->constants());
 834   {
 835     JvmtiHideSingleStepping jhss(thread);
 836     LinkResolver::resolve_invoke(info, Handle(), pool,
 837                                  get_index_u2_cpcache(thread, bytecode), bytecode,
 838                                  CHECK);
 839   } // end JvmtiHideSingleStepping
 840 
 841   ConstantPoolCacheEntry* cp_cache_entry = cache_entry(thread);
 842   cp_cache_entry->set_method_handle(pool, info);
 843 }
 844 
 845 // First time execution:  Resolve symbols, create a permanent CallSite object.
 846 void InterpreterRuntime::resolve_invokedynamic(JavaThread* thread) {
 847   Thread* THREAD = thread;
 848   const Bytecodes::Code bytecode = Bytecodes::_invokedynamic;
 849 
 850   //TO DO: consider passing BCI to Java.
 851   //  int caller_bci = method(thread)->bci_from(bcp(thread));
 852 
 853   // resolve method
 854   CallInfo info;
 855   constantPoolHandle pool(thread, method(thread)->constants());
 856   int index = get_index_u4(thread, bytecode);
 857   {
 858     JvmtiHideSingleStepping jhss(thread);
 859     LinkResolver::resolve_invoke(info, Handle(), pool,
 860                                  index, bytecode, CHECK);
 861   } // end JvmtiHideSingleStepping
 862 
 863   ConstantPoolCacheEntry* cp_cache_entry = pool->invokedynamic_cp_cache_entry_at(index);
 864   cp_cache_entry->set_dynamic_call(pool, info);
 865 }
 866 
 867 // This function is the interface to the assembly code. It returns the resolved
 868 // cpCache entry.  This doesn't safepoint, but the helper routines safepoint.
 869 // This function will check for redefinition!
 870 IRT_ENTRY(void, InterpreterRuntime::resolve_from_cache(JavaThread* thread, Bytecodes::Code bytecode)) {
 871   switch (bytecode) {
 872   case Bytecodes::_getstatic:
 873   case Bytecodes::_putstatic:
 874   case Bytecodes::_getfield:
 875   case Bytecodes::_putfield:
 876     resolve_get_put(thread, bytecode);
 877     break;
 878   case Bytecodes::_invokevirtual:
 879   case Bytecodes::_invokespecial:
 880   case Bytecodes::_invokestatic:
 881   case Bytecodes::_invokeinterface:
 882     resolve_invoke(thread, bytecode);
 883     break;
 884   case Bytecodes::_invokehandle:
 885     resolve_invokehandle(thread);
 886     break;
 887   case Bytecodes::_invokedynamic:
 888     resolve_invokedynamic(thread);
 889     break;
 890   default:
 891     fatal("unexpected bytecode: %s", Bytecodes::name(bytecode));
 892     break;
 893   }
 894 }
 895 IRT_END
 896 
 897 //------------------------------------------------------------------------------------------------------------------------
 898 // Miscellaneous
 899 
 900 
 901 nmethod* InterpreterRuntime::frequency_counter_overflow(JavaThread* thread, address branch_bcp) {
 902   nmethod* nm = frequency_counter_overflow_inner(thread, branch_bcp);
 903   assert(branch_bcp != NULL || nm == NULL, "always returns null for non OSR requests");
 904   if (branch_bcp != NULL && nm != NULL) {
 905     // This was a successful request for an OSR nmethod.  Because
 906     // frequency_counter_overflow_inner ends with a safepoint check,
 907     // nm could have been unloaded so look it up again.  It's unsafe
 908     // to examine nm directly since it might have been freed and used
 909     // for something else.
 910     frame fr = thread->last_frame();
 911     Method* method =  fr.interpreter_frame_method();
 912     int bci = method->bci_from(fr.interpreter_frame_bcp());
 913     nm = method->lookup_osr_nmethod_for(bci, CompLevel_none, false);
 914   }
 915 #ifndef PRODUCT
 916   if (TraceOnStackReplacement) {
 917     if (nm != NULL) {
 918       tty->print("OSR entry @ pc: " INTPTR_FORMAT ": ", p2i(nm->osr_entry()));
 919       nm->print();
 920     }
 921   }
 922 #endif
 923   return nm;
 924 }
 925 
 926 IRT_ENTRY(nmethod*,
 927           InterpreterRuntime::frequency_counter_overflow_inner(JavaThread* thread, address branch_bcp))
 928   // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
 929   // flag, in case this method triggers classloading which will call into Java.
 930   UnlockFlagSaver fs(thread);
 931 
 932   frame fr = thread->last_frame();
 933   assert(fr.is_interpreted_frame(), "must come from interpreter");
 934   methodHandle method(thread, fr.interpreter_frame_method());
 935   const int branch_bci = branch_bcp != NULL ? method->bci_from(branch_bcp) : InvocationEntryBci;
 936   const int bci = branch_bcp != NULL ? method->bci_from(fr.interpreter_frame_bcp()) : InvocationEntryBci;
 937 
 938   assert(!HAS_PENDING_EXCEPTION, "Should not have any exceptions pending");
 939   nmethod* osr_nm = CompilationPolicy::policy()->event(method, method, branch_bci, bci, CompLevel_none, NULL, thread);
 940   assert(!HAS_PENDING_EXCEPTION, "Event handler should not throw any exceptions");
 941 
 942   if (osr_nm != NULL) {
 943     // We may need to do on-stack replacement which requires that no
 944     // monitors in the activation are biased because their
 945     // BasicObjectLocks will need to migrate during OSR. Force
 946     // unbiasing of all monitors in the activation now (even though
 947     // the OSR nmethod might be invalidated) because we don't have a
 948     // safepoint opportunity later once the migration begins.
 949     if (UseBiasedLocking) {
 950       ResourceMark rm;
 951       GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
 952       for( BasicObjectLock *kptr = fr.interpreter_frame_monitor_end();
 953            kptr < fr.interpreter_frame_monitor_begin();
 954            kptr = fr.next_monitor_in_interpreter_frame(kptr) ) {
 955         if( kptr->obj() != NULL ) {
 956           objects_to_revoke->append(Handle(THREAD, kptr->obj()));
 957         }
 958       }
 959       BiasedLocking::revoke(objects_to_revoke);
 960     }
 961   }
 962   return osr_nm;
 963 IRT_END
 964 
 965 IRT_LEAF(jint, InterpreterRuntime::bcp_to_di(Method* method, address cur_bcp))
 966   assert(ProfileInterpreter, "must be profiling interpreter");
 967   int bci = method->bci_from(cur_bcp);
 968   MethodData* mdo = method->method_data();
 969   if (mdo == NULL)  return 0;
 970   return mdo->bci_to_di(bci);
 971 IRT_END
 972 
 973 IRT_ENTRY(void, InterpreterRuntime::profile_method(JavaThread* thread))
 974   // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
 975   // flag, in case this method triggers classloading which will call into Java.
 976   UnlockFlagSaver fs(thread);
 977 
 978   assert(ProfileInterpreter, "must be profiling interpreter");
 979   frame fr = thread->last_frame();
 980   assert(fr.is_interpreted_frame(), "must come from interpreter");
 981   methodHandle method(thread, fr.interpreter_frame_method());
 982   Method::build_interpreter_method_data(method, THREAD);
 983   if (HAS_PENDING_EXCEPTION) {
 984     assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
 985     CLEAR_PENDING_EXCEPTION;
 986     // and fall through...
 987   }
 988 IRT_END
 989 
 990 
 991 #ifdef ASSERT
 992 IRT_LEAF(void, InterpreterRuntime::verify_mdp(Method* method, address bcp, address mdp))
 993   assert(ProfileInterpreter, "must be profiling interpreter");
 994 
 995   MethodData* mdo = method->method_data();
 996   assert(mdo != NULL, "must not be null");
 997 
 998   int bci = method->bci_from(bcp);
 999 
1000   address mdp2 = mdo->bci_to_dp(bci);
1001   if (mdp != mdp2) {
1002     ResourceMark rm;
1003     ResetNoHandleMark rnm; // In a LEAF entry.
1004     HandleMark hm;
1005     tty->print_cr("FAILED verify : actual mdp %p   expected mdp %p @ bci %d", mdp, mdp2, bci);
1006     int current_di = mdo->dp_to_di(mdp);
1007     int expected_di  = mdo->dp_to_di(mdp2);
1008     tty->print_cr("  actual di %d   expected di %d", current_di, expected_di);
1009     int expected_approx_bci = mdo->data_at(expected_di)->bci();
1010     int approx_bci = -1;
1011     if (current_di >= 0) {
1012       approx_bci = mdo->data_at(current_di)->bci();
1013     }
1014     tty->print_cr("  actual bci is %d  expected bci %d", approx_bci, expected_approx_bci);
1015     mdo->print_on(tty);
1016     method->print_codes();
1017   }
1018   assert(mdp == mdp2, "wrong mdp");
1019 IRT_END
1020 #endif // ASSERT
1021 
1022 IRT_ENTRY(void, InterpreterRuntime::update_mdp_for_ret(JavaThread* thread, int return_bci))
1023   assert(ProfileInterpreter, "must be profiling interpreter");
1024   ResourceMark rm(thread);
1025   HandleMark hm(thread);
1026   frame fr = thread->last_frame();
1027   assert(fr.is_interpreted_frame(), "must come from interpreter");
1028   MethodData* h_mdo = fr.interpreter_frame_method()->method_data();
1029 
1030   // Grab a lock to ensure atomic access to setting the return bci and
1031   // the displacement.  This can block and GC, invalidating all naked oops.
1032   MutexLocker ml(RetData_lock);
1033 
1034   // ProfileData is essentially a wrapper around a derived oop, so we
1035   // need to take the lock before making any ProfileData structures.
1036   ProfileData* data = h_mdo->data_at(h_mdo->dp_to_di(fr.interpreter_frame_mdp()));
1037   RetData* rdata = data->as_RetData();
1038   address new_mdp = rdata->fixup_ret(return_bci, h_mdo);
1039   fr.interpreter_frame_set_mdp(new_mdp);
1040 IRT_END
1041 
1042 IRT_ENTRY(MethodCounters*, InterpreterRuntime::build_method_counters(JavaThread* thread, Method* m))
1043   MethodCounters* mcs = Method::build_method_counters(m, thread);
1044   if (HAS_PENDING_EXCEPTION) {
1045     assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
1046     CLEAR_PENDING_EXCEPTION;
1047   }
1048   return mcs;
1049 IRT_END
1050 
1051 
1052 IRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* thread))
1053   // We used to need an explict preserve_arguments here for invoke bytecodes. However,
1054   // stack traversal automatically takes care of preserving arguments for invoke, so
1055   // this is no longer needed.
1056 
1057   // IRT_END does an implicit safepoint check, hence we are guaranteed to block
1058   // if this is called during a safepoint
1059 
1060   if (JvmtiExport::should_post_single_step()) {
1061     // We are called during regular safepoints and when the VM is
1062     // single stepping. If any thread is marked for single stepping,
1063     // then we may have JVMTI work to do.
1064     JvmtiExport::at_single_stepping_point(thread, method(thread), bcp(thread));
1065   }
1066 IRT_END
1067 
1068 IRT_ENTRY(void, InterpreterRuntime::post_field_access(JavaThread *thread, oopDesc* obj,
1069 ConstantPoolCacheEntry *cp_entry))
1070 
1071   // check the access_flags for the field in the klass
1072 
1073   InstanceKlass* ik = InstanceKlass::cast(cp_entry->f1_as_klass());
1074   int index = cp_entry->field_index();
1075   if ((ik->field_access_flags(index) & JVM_ACC_FIELD_ACCESS_WATCHED) == 0) return;
1076 
1077   bool is_static = (obj == NULL);
1078   HandleMark hm(thread);
1079 
1080   Handle h_obj;
1081   if (!is_static) {
1082     // non-static field accessors have an object, but we need a handle
1083     h_obj = Handle(thread, obj);
1084   }
1085   instanceKlassHandle h_cp_entry_f1(thread, (Klass*)cp_entry->f1_as_klass());
1086   jfieldID fid = jfieldIDWorkaround::to_jfieldID(h_cp_entry_f1, cp_entry->f2_as_index(), is_static);
1087   JvmtiExport::post_field_access(thread, method(thread), bcp(thread), h_cp_entry_f1, h_obj, fid);
1088 IRT_END
1089 
1090 IRT_ENTRY(void, InterpreterRuntime::post_field_modification(JavaThread *thread,
1091   oopDesc* obj, ConstantPoolCacheEntry *cp_entry, jvalue *value))
1092 
1093   Klass* k = (Klass*)cp_entry->f1_as_klass();
1094 
1095   // check the access_flags for the field in the klass
1096   InstanceKlass* ik = InstanceKlass::cast(k);
1097   int index = cp_entry->field_index();
1098   // bail out if field modifications are not watched
1099   if ((ik->field_access_flags(index) & JVM_ACC_FIELD_MODIFICATION_WATCHED) == 0) return;
1100 
1101   char sig_type = '\0';
1102 
1103   switch(cp_entry->flag_state()) {
1104     case btos: sig_type = 'Z'; break;
1105     case ctos: sig_type = 'C'; break;
1106     case stos: sig_type = 'S'; break;
1107     case itos: sig_type = 'I'; break;
1108     case ftos: sig_type = 'F'; break;
1109     case atos: sig_type = 'L'; break;
1110     case ltos: sig_type = 'J'; break;
1111     case dtos: sig_type = 'D'; break;
1112     default:  ShouldNotReachHere(); return;
1113   }
1114   bool is_static = (obj == NULL);
1115 
1116   HandleMark hm(thread);
1117   instanceKlassHandle h_klass(thread, k);
1118   jfieldID fid = jfieldIDWorkaround::to_jfieldID(h_klass, cp_entry->f2_as_index(), is_static);
1119   jvalue fvalue;
1120 #ifdef _LP64
1121   fvalue = *value;
1122 #else
1123   // Long/double values are stored unaligned and also noncontiguously with
1124   // tagged stacks.  We can't just do a simple assignment even in the non-
1125   // J/D cases because a C++ compiler is allowed to assume that a jvalue is
1126   // 8-byte aligned, and interpreter stack slots are only 4-byte aligned.
1127   // We assume that the two halves of longs/doubles are stored in interpreter
1128   // stack slots in platform-endian order.
1129   jlong_accessor u;
1130   jint* newval = (jint*)value;
1131   u.words[0] = newval[0];
1132   u.words[1] = newval[Interpreter::stackElementWords]; // skip if tag
1133   fvalue.j = u.long_value;
1134 #endif // _LP64
1135 
1136   Handle h_obj;
1137   if (!is_static) {
1138     // non-static field accessors have an object, but we need a handle
1139     h_obj = Handle(thread, obj);
1140   }
1141 
1142   JvmtiExport::post_raw_field_modification(thread, method(thread), bcp(thread), h_klass, h_obj,
1143                                            fid, sig_type, &fvalue);
1144 IRT_END
1145 
1146 IRT_ENTRY(void, InterpreterRuntime::post_method_entry(JavaThread *thread))
1147   JvmtiExport::post_method_entry(thread, InterpreterRuntime::method(thread), InterpreterRuntime::last_frame(thread));
1148 IRT_END
1149 
1150 
1151 IRT_ENTRY(void, InterpreterRuntime::post_method_exit(JavaThread *thread))
1152   JvmtiExport::post_method_exit(thread, InterpreterRuntime::method(thread), InterpreterRuntime::last_frame(thread));
1153 IRT_END
1154 
1155 IRT_LEAF(int, InterpreterRuntime::interpreter_contains(address pc))
1156 {
1157   return (Interpreter::contains(pc) ? 1 : 0);
1158 }
1159 IRT_END
1160 
1161 
1162 // Implementation of SignatureHandlerLibrary
1163 
1164 #ifndef SHARING_FAST_NATIVE_FINGERPRINTS
1165 // Dummy definition (else normalization method is defined in CPU
1166 // dependant code)
1167 uint64_t InterpreterRuntime::normalize_fast_native_fingerprint(uint64_t fingerprint) {
1168   return fingerprint;
1169 }
1170 #endif
1171 
1172 address SignatureHandlerLibrary::set_handler_blob() {
1173   BufferBlob* handler_blob = BufferBlob::create("native signature handlers", blob_size);
1174   if (handler_blob == NULL) {
1175     return NULL;
1176   }
1177   address handler = handler_blob->code_begin();
1178   _handler_blob = handler_blob;
1179   _handler = handler;
1180   return handler;
1181 }
1182 
1183 void SignatureHandlerLibrary::initialize() {
1184   if (_fingerprints != NULL) {
1185     return;
1186   }
1187   if (set_handler_blob() == NULL) {
1188     vm_exit_out_of_memory(blob_size, OOM_MALLOC_ERROR, "native signature handlers");
1189   }
1190 
1191   BufferBlob* bb = BufferBlob::create("Signature Handler Temp Buffer",
1192                                       SignatureHandlerLibrary::buffer_size);
1193   _buffer = bb->code_begin();
1194 
1195   _fingerprints = new(ResourceObj::C_HEAP, mtCode)GrowableArray<uint64_t>(32, true);
1196   _handlers     = new(ResourceObj::C_HEAP, mtCode)GrowableArray<address>(32, true);
1197 }
1198 
1199 address SignatureHandlerLibrary::set_handler(CodeBuffer* buffer) {
1200   address handler   = _handler;
1201   int     insts_size = buffer->pure_insts_size();
1202   if (handler + insts_size > _handler_blob->code_end()) {
1203     // get a new handler blob
1204     handler = set_handler_blob();
1205   }
1206   if (handler != NULL) {
1207     memcpy(handler, buffer->insts_begin(), insts_size);
1208     pd_set_handler(handler);
1209     ICache::invalidate_range(handler, insts_size);
1210     _handler = handler + insts_size;
1211   }
1212   CodeCacheExtensions::handle_generated_handler(handler, buffer->name(), _handler);
1213   return handler;
1214 }
1215 
1216 void SignatureHandlerLibrary::add(methodHandle method) {
1217   if (method->signature_handler() == NULL) {
1218     // use slow signature handler if we can't do better
1219     int handler_index = -1;
1220     // check if we can use customized (fast) signature handler
1221     if (UseFastSignatureHandlers && CodeCacheExtensions::support_fast_signature_handlers() && method->size_of_parameters() <= Fingerprinter::max_size_of_parameters) {
1222       // use customized signature handler
1223       MutexLocker mu(SignatureHandlerLibrary_lock);
1224       // make sure data structure is initialized
1225       initialize();
1226       // lookup method signature's fingerprint
1227       uint64_t fingerprint = Fingerprinter(method).fingerprint();
1228       // allow CPU dependant code to optimize the fingerprints for the fast handler
1229       fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1230       handler_index = _fingerprints->find(fingerprint);
1231       // create handler if necessary
1232       if (handler_index < 0) {
1233         ResourceMark rm;
1234         ptrdiff_t align_offset = (address)
1235           round_to((intptr_t)_buffer, CodeEntryAlignment) - (address)_buffer;
1236         CodeBuffer buffer((address)(_buffer + align_offset),
1237                           SignatureHandlerLibrary::buffer_size - align_offset);
1238         if (!CodeCacheExtensions::support_dynamic_code()) {
1239           // we need a name for the signature (for lookups or saving)
1240           const int SYMBOL_SIZE = 50;
1241           char *symbolName = NEW_RESOURCE_ARRAY(char, SYMBOL_SIZE);
1242           // support for named signatures
1243           jio_snprintf(symbolName, SYMBOL_SIZE,
1244                        "native_" UINT64_FORMAT, fingerprint);
1245           buffer.set_name(symbolName);
1246         }
1247         InterpreterRuntime::SignatureHandlerGenerator(method, &buffer).generate(fingerprint);
1248         // copy into code heap
1249         address handler = set_handler(&buffer);
1250         if (handler == NULL) {
1251           // use slow signature handler (without memorizing it in the fingerprints)
1252         } else {
1253           // debugging suppport
1254           if (PrintSignatureHandlers && (handler != Interpreter::slow_signature_handler())) {
1255             tty->cr();
1256             tty->print_cr("argument handler #%d for: %s %s (fingerprint = " UINT64_FORMAT ", %d bytes generated)",
1257                           _handlers->length(),
1258                           (method->is_static() ? "static" : "receiver"),
1259                           method->name_and_sig_as_C_string(),
1260                           fingerprint,
1261                           buffer.insts_size());
1262             if (buffer.insts_size() > 0) {
1263               // buffer may be empty for pregenerated handlers
1264               Disassembler::decode(handler, handler + buffer.insts_size());
1265             }
1266 #ifndef PRODUCT
1267             address rh_begin = Interpreter::result_handler(method()->result_type());
1268             if (CodeCache::contains(rh_begin)) {
1269               // else it might be special platform dependent values
1270               tty->print_cr(" --- associated result handler ---");
1271               address rh_end = rh_begin;
1272               while (*(int*)rh_end != 0) {
1273                 rh_end += sizeof(int);
1274               }
1275               Disassembler::decode(rh_begin, rh_end);
1276             } else {
1277               tty->print_cr(" associated result handler: " PTR_FORMAT, p2i(rh_begin));
1278             }
1279 #endif
1280           }
1281           // add handler to library
1282           _fingerprints->append(fingerprint);
1283           _handlers->append(handler);
1284           // set handler index
1285           assert(_fingerprints->length() == _handlers->length(), "sanity check");
1286           handler_index = _fingerprints->length() - 1;
1287         }
1288       }
1289       // Set handler under SignatureHandlerLibrary_lock
1290       if (handler_index < 0) {
1291         // use generic signature handler
1292         method->set_signature_handler(Interpreter::slow_signature_handler());
1293       } else {
1294         // set handler
1295         method->set_signature_handler(_handlers->at(handler_index));
1296       }
1297     } else {
1298       CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
1299       // use generic signature handler
1300       method->set_signature_handler(Interpreter::slow_signature_handler());
1301     }
1302   }
1303 #ifdef ASSERT
1304   int handler_index = -1;
1305   int fingerprint_index = -2;
1306   {
1307     // '_handlers' and '_fingerprints' are 'GrowableArray's and are NOT synchronized
1308     // in any way if accessed from multiple threads. To avoid races with another
1309     // thread which may change the arrays in the above, mutex protected block, we
1310     // have to protect this read access here with the same mutex as well!
1311     MutexLocker mu(SignatureHandlerLibrary_lock);
1312     if (_handlers != NULL) {
1313       handler_index = _handlers->find(method->signature_handler());
1314       uint64_t fingerprint = Fingerprinter(method).fingerprint();
1315       fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1316       fingerprint_index = _fingerprints->find(fingerprint);
1317     }
1318   }
1319   assert(method->signature_handler() == Interpreter::slow_signature_handler() ||
1320          handler_index == fingerprint_index, "sanity check");
1321 #endif // ASSERT
1322 }
1323 
1324 void SignatureHandlerLibrary::add(uint64_t fingerprint, address handler) {
1325   int handler_index = -1;
1326   // use customized signature handler
1327   MutexLocker mu(SignatureHandlerLibrary_lock);
1328   // make sure data structure is initialized
1329   initialize();
1330   fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1331   handler_index = _fingerprints->find(fingerprint);
1332   // create handler if necessary
1333   if (handler_index < 0) {
1334     if (PrintSignatureHandlers && (handler != Interpreter::slow_signature_handler())) {
1335       tty->cr();
1336       tty->print_cr("argument handler #%d at " PTR_FORMAT " for fingerprint " UINT64_FORMAT,
1337                     _handlers->length(),
1338                     p2i(handler),
1339                     fingerprint);
1340     }
1341     _fingerprints->append(fingerprint);
1342     _handlers->append(handler);
1343   } else {
1344     if (PrintSignatureHandlers) {
1345       tty->cr();
1346       tty->print_cr("duplicate argument handler #%d for fingerprint " UINT64_FORMAT "(old: " PTR_FORMAT ", new : " PTR_FORMAT ")",
1347                     _handlers->length(),
1348                     fingerprint,
1349                     p2i(_handlers->at(handler_index)),
1350                     p2i(handler));
1351     }
1352   }
1353 }
1354 
1355 
1356 BufferBlob*              SignatureHandlerLibrary::_handler_blob = NULL;
1357 address                  SignatureHandlerLibrary::_handler      = NULL;
1358 GrowableArray<uint64_t>* SignatureHandlerLibrary::_fingerprints = NULL;
1359 GrowableArray<address>*  SignatureHandlerLibrary::_handlers     = NULL;
1360 address                  SignatureHandlerLibrary::_buffer       = NULL;
1361 
1362 
1363 IRT_ENTRY(void, InterpreterRuntime::prepare_native_call(JavaThread* thread, Method* method))
1364   methodHandle m(thread, method);
1365   assert(m->is_native(), "sanity check");
1366   // lookup native function entry point if it doesn't exist
1367   bool in_base_library;
1368   if (!m->has_native_function()) {
1369     NativeLookup::lookup(m, in_base_library, CHECK);
1370   }
1371   // make sure signature handler is installed
1372   SignatureHandlerLibrary::add(m);
1373   // The interpreter entry point checks the signature handler first,
1374   // before trying to fetch the native entry point and klass mirror.
1375   // We must set the signature handler last, so that multiple processors
1376   // preparing the same method will be sure to see non-null entry & mirror.
1377 IRT_END
1378 
1379 #if defined(IA32) || defined(AMD64) || defined(ARM)
1380 IRT_LEAF(void, InterpreterRuntime::popframe_move_outgoing_args(JavaThread* thread, void* src_address, void* dest_address))
1381   if (src_address == dest_address) {
1382     return;
1383   }
1384   ResetNoHandleMark rnm; // In a LEAF entry.
1385   HandleMark hm;
1386   ResourceMark rm;
1387   frame fr = thread->last_frame();
1388   assert(fr.is_interpreted_frame(), "");
1389   jint bci = fr.interpreter_frame_bci();
1390   methodHandle mh(thread, fr.interpreter_frame_method());
1391   Bytecode_invoke invoke(mh, bci);
1392   ArgumentSizeComputer asc(invoke.signature());
1393   int size_of_arguments = (asc.size() + (invoke.has_receiver() ? 1 : 0)); // receiver
1394   Copy::conjoint_jbytes(src_address, dest_address,
1395                        size_of_arguments * Interpreter::stackElementSize);
1396 IRT_END
1397 #endif
1398 
1399 #if INCLUDE_JVMTI
1400 // This is a support of the JVMTI PopFrame interface.
1401 // Make sure it is an invokestatic of a polymorphic intrinsic that has a member_name argument
1402 // and return it as a vm_result so that it can be reloaded in the list of invokestatic parameters.
1403 // The member_name argument is a saved reference (in local#0) to the member_name.
1404 // For backward compatibility with some JDK versions (7, 8) it can also be a direct method handle.
1405 // FIXME: remove DMH case after j.l.i.InvokerBytecodeGenerator code shape is updated.
1406 IRT_ENTRY(void, InterpreterRuntime::member_name_arg_or_null(JavaThread* thread, address member_name,
1407                                                             Method* method, address bcp))
1408   Bytecodes::Code code = Bytecodes::code_at(method, bcp);
1409   if (code != Bytecodes::_invokestatic) {
1410     return;
1411   }
1412   ConstantPool* cpool = method->constants();
1413   int cp_index = Bytes::get_native_u2(bcp + 1) + ConstantPool::CPCACHE_INDEX_TAG;
1414   Symbol* cname = cpool->klass_name_at(cpool->klass_ref_index_at(cp_index));
1415   Symbol* mname = cpool->name_ref_at(cp_index);
1416 
1417   if (MethodHandles::has_member_arg(cname, mname)) {
1418     oop member_name_oop = (oop) member_name;
1419     if (java_lang_invoke_DirectMethodHandle::is_instance(member_name_oop)) {
1420       // FIXME: remove after j.l.i.InvokerBytecodeGenerator code shape is updated.
1421       member_name_oop = java_lang_invoke_DirectMethodHandle::member(member_name_oop);
1422     }
1423     thread->set_vm_result(member_name_oop);
1424   } else {
1425     thread->set_vm_result(NULL);
1426   }
1427 IRT_END
1428 #endif // INCLUDE_JVMTI