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