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