method.cpp revision 10669:0b582be9fab0
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/metadataOnStackMark.hpp"
27#include "classfile/systemDictionary.hpp"
28#include "code/codeCache.hpp"
29#include "code/debugInfoRec.hpp"
30#include "gc/shared/collectedHeap.inline.hpp"
31#include "gc/shared/gcLocker.hpp"
32#include "gc/shared/generation.hpp"
33#include "gc/shared/referencePendingListLocker.hpp"
34#include "interpreter/bytecodeStream.hpp"
35#include "interpreter/bytecodeTracer.hpp"
36#include "interpreter/bytecodes.hpp"
37#include "interpreter/interpreter.hpp"
38#include "interpreter/oopMapCache.hpp"
39#include "memory/heapInspection.hpp"
40#include "memory/metadataFactory.hpp"
41#include "memory/oopFactory.hpp"
42#include "oops/constMethod.hpp"
43#include "oops/method.hpp"
44#include "oops/methodData.hpp"
45#include "oops/objArrayOop.inline.hpp"
46#include "oops/oop.inline.hpp"
47#include "oops/symbol.hpp"
48#include "prims/jvmtiExport.hpp"
49#include "prims/methodHandles.hpp"
50#include "prims/nativeLookup.hpp"
51#include "runtime/arguments.hpp"
52#include "runtime/compilationPolicy.hpp"
53#include "runtime/frame.inline.hpp"
54#include "runtime/handles.inline.hpp"
55#include "runtime/orderAccess.inline.hpp"
56#include "runtime/relocator.hpp"
57#include "runtime/sharedRuntime.hpp"
58#include "runtime/signature.hpp"
59#include "utilities/quickSort.hpp"
60#include "utilities/xmlstream.hpp"
61
62// Implementation of Method
63
64Method* Method::allocate(ClassLoaderData* loader_data,
65                         int byte_code_size,
66                         AccessFlags access_flags,
67                         InlineTableSizes* sizes,
68                         ConstMethod::MethodType method_type,
69                         TRAPS) {
70  assert(!access_flags.is_native() || byte_code_size == 0,
71         "native methods should not contain byte codes");
72  ConstMethod* cm = ConstMethod::allocate(loader_data,
73                                          byte_code_size,
74                                          sizes,
75                                          method_type,
76                                          CHECK_NULL);
77  int size = Method::size(access_flags.is_native());
78  return new (loader_data, size, false, MetaspaceObj::MethodType, THREAD) Method(cm, access_flags);
79}
80
81Method::Method(ConstMethod* xconst, AccessFlags access_flags) {
82  NoSafepointVerifier no_safepoint;
83  set_constMethod(xconst);
84  set_access_flags(access_flags);
85#ifdef CC_INTERP
86  set_result_index(T_VOID);
87#endif
88  set_intrinsic_id(vmIntrinsics::_none);
89  set_jfr_towrite(false);
90  set_force_inline(false);
91  set_hidden(false);
92  set_dont_inline(false);
93  set_has_injected_profile(false);
94  set_method_data(NULL);
95  clear_method_counters();
96  set_vtable_index(Method::garbage_vtable_index);
97
98  // Fix and bury in Method*
99  set_interpreter_entry(NULL); // sets i2i entry and from_int
100  set_adapter_entry(NULL);
101  clear_code(); // from_c/from_i get set to c2i/i2i
102
103  if (access_flags.is_native()) {
104    clear_native_function();
105    set_signature_handler(NULL);
106  }
107
108  NOT_PRODUCT(set_compiled_invocation_count(0);)
109}
110
111// Release Method*.  The nmethod will be gone when we get here because
112// we've walked the code cache.
113void Method::deallocate_contents(ClassLoaderData* loader_data) {
114  MetadataFactory::free_metadata(loader_data, constMethod());
115  set_constMethod(NULL);
116  MetadataFactory::free_metadata(loader_data, method_data());
117  set_method_data(NULL);
118  MetadataFactory::free_metadata(loader_data, method_counters());
119  clear_method_counters();
120  // The nmethod will be gone when we get here.
121  if (code() != NULL) _code = NULL;
122}
123
124address Method::get_i2c_entry() {
125  assert(_adapter != NULL, "must have");
126  return _adapter->get_i2c_entry();
127}
128
129address Method::get_c2i_entry() {
130  assert(_adapter != NULL, "must have");
131  return _adapter->get_c2i_entry();
132}
133
134address Method::get_c2i_unverified_entry() {
135  assert(_adapter != NULL, "must have");
136  return _adapter->get_c2i_unverified_entry();
137}
138
139char* Method::name_and_sig_as_C_string() const {
140  return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature());
141}
142
143char* Method::name_and_sig_as_C_string(char* buf, int size) const {
144  return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature(), buf, size);
145}
146
147char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature) {
148  const char* klass_name = klass->external_name();
149  int klass_name_len  = (int)strlen(klass_name);
150  int method_name_len = method_name->utf8_length();
151  int len             = klass_name_len + 1 + method_name_len + signature->utf8_length();
152  char* dest          = NEW_RESOURCE_ARRAY(char, len + 1);
153  strcpy(dest, klass_name);
154  dest[klass_name_len] = '.';
155  strcpy(&dest[klass_name_len + 1], method_name->as_C_string());
156  strcpy(&dest[klass_name_len + 1 + method_name_len], signature->as_C_string());
157  dest[len] = 0;
158  return dest;
159}
160
161char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature, char* buf, int size) {
162  Symbol* klass_name = klass->name();
163  klass_name->as_klass_external_name(buf, size);
164  int len = (int)strlen(buf);
165
166  if (len < size - 1) {
167    buf[len++] = '.';
168
169    method_name->as_C_string(&(buf[len]), size - len);
170    len = (int)strlen(buf);
171
172    signature->as_C_string(&(buf[len]), size - len);
173  }
174
175  return buf;
176}
177
178int Method::fast_exception_handler_bci_for(methodHandle mh, KlassHandle ex_klass, int throw_bci, TRAPS) {
179  // exception table holds quadruple entries of the form (beg_bci, end_bci, handler_bci, klass_index)
180  // access exception table
181  ExceptionTable table(mh());
182  int length = table.length();
183  // iterate through all entries sequentially
184  constantPoolHandle pool(THREAD, mh->constants());
185  for (int i = 0; i < length; i ++) {
186    //reacquire the table in case a GC happened
187    ExceptionTable table(mh());
188    int beg_bci = table.start_pc(i);
189    int end_bci = table.end_pc(i);
190    assert(beg_bci <= end_bci, "inconsistent exception table");
191    if (beg_bci <= throw_bci && throw_bci < end_bci) {
192      // exception handler bci range covers throw_bci => investigate further
193      int handler_bci = table.handler_pc(i);
194      int klass_index = table.catch_type_index(i);
195      if (klass_index == 0) {
196        return handler_bci;
197      } else if (ex_klass.is_null()) {
198        return handler_bci;
199      } else {
200        // we know the exception class => get the constraint class
201        // this may require loading of the constraint class; if verification
202        // fails or some other exception occurs, return handler_bci
203        Klass* k = pool->klass_at(klass_index, CHECK_(handler_bci));
204        KlassHandle klass = KlassHandle(THREAD, k);
205        assert(klass.not_null(), "klass not loaded");
206        if (ex_klass->is_subtype_of(klass())) {
207          return handler_bci;
208        }
209      }
210    }
211  }
212
213  return -1;
214}
215
216void Method::mask_for(int bci, InterpreterOopMap* mask) {
217
218  Thread* myThread    = Thread::current();
219  methodHandle h_this(myThread, this);
220#if defined(ASSERT) && !INCLUDE_JVMCI
221  bool has_capability = myThread->is_VM_thread() ||
222                        myThread->is_ConcurrentGC_thread() ||
223                        myThread->is_GC_task_thread();
224
225  if (!has_capability) {
226    if (!VerifyStack && !VerifyLastFrame) {
227      // verify stack calls this outside VM thread
228      warning("oopmap should only be accessed by the "
229              "VM, GC task or CMS threads (or during debugging)");
230      InterpreterOopMap local_mask;
231      method_holder()->mask_for(h_this, bci, &local_mask);
232      local_mask.print();
233    }
234  }
235#endif
236  method_holder()->mask_for(h_this, bci, mask);
237  return;
238}
239
240
241int Method::bci_from(address bcp) const {
242  if (is_native() && bcp == 0) {
243    return 0;
244  }
245#ifdef ASSERT
246  {
247    ResourceMark rm;
248    assert(is_native() && bcp == code_base() || contains(bcp) || is_error_reported(),
249           "bcp doesn't belong to this method: bcp: " INTPTR_FORMAT ", method: %s",
250           p2i(bcp), name_and_sig_as_C_string());
251  }
252#endif
253  return bcp - code_base();
254}
255
256
257int Method::validate_bci(int bci) const {
258  return (bci == 0 || bci < code_size()) ? bci : -1;
259}
260
261// Return bci if it appears to be a valid bcp
262// Return -1 otherwise.
263// Used by profiling code, when invalid data is a possibility.
264// The caller is responsible for validating the Method* itself.
265int Method::validate_bci_from_bcp(address bcp) const {
266  // keep bci as -1 if not a valid bci
267  int bci = -1;
268  if (bcp == 0 || bcp == code_base()) {
269    // code_size() may return 0 and we allow 0 here
270    // the method may be native
271    bci = 0;
272  } else if (contains(bcp)) {
273    bci = bcp - code_base();
274  }
275  // Assert that if we have dodged any asserts, bci is negative.
276  assert(bci == -1 || bci == bci_from(bcp_from(bci)), "sane bci if >=0");
277  return bci;
278}
279
280address Method::bcp_from(int bci) const {
281  assert((is_native() && bci == 0) || (!is_native() && 0 <= bci && bci < code_size()), "illegal bci: %d", bci);
282  address bcp = code_base() + bci;
283  assert(is_native() && bcp == code_base() || contains(bcp), "bcp doesn't belong to this method");
284  return bcp;
285}
286
287address Method::bcp_from(address bcp) const {
288  if (is_native() && bcp == NULL) {
289    return code_base();
290  } else {
291    return bcp;
292  }
293}
294
295int Method::size(bool is_native) {
296  // If native, then include pointers for native_function and signature_handler
297  int extra_bytes = (is_native) ? 2*sizeof(address*) : 0;
298  int extra_words = align_size_up(extra_bytes, BytesPerWord) / BytesPerWord;
299  return align_metadata_size(header_size() + extra_words);
300}
301
302
303Symbol* Method::klass_name() const {
304  return method_holder()->name();
305}
306
307
308// Attempt to return method oop to original state.  Clear any pointers
309// (to objects outside the shared spaces).  We won't be able to predict
310// where they should point in a new JVM.  Further initialize some
311// entries now in order allow them to be write protected later.
312
313void Method::remove_unshareable_info() {
314  unlink_method();
315}
316
317
318bool Method::was_executed_more_than(int n) {
319  // Invocation counter is reset when the Method* is compiled.
320  // If the method has compiled code we therefore assume it has
321  // be excuted more than n times.
322  if (is_accessor() || is_empty_method() || (code() != NULL)) {
323    // interpreter doesn't bump invocation counter of trivial methods
324    // compiler does not bump invocation counter of compiled methods
325    return true;
326  }
327  else if ((method_counters() != NULL &&
328            method_counters()->invocation_counter()->carry()) ||
329           (method_data() != NULL &&
330            method_data()->invocation_counter()->carry())) {
331    // The carry bit is set when the counter overflows and causes
332    // a compilation to occur.  We don't know how many times
333    // the counter has been reset, so we simply assume it has
334    // been executed more than n times.
335    return true;
336  } else {
337    return invocation_count() > n;
338  }
339}
340
341void Method::print_invocation_count() {
342  if (is_static()) tty->print("static ");
343  if (is_final()) tty->print("final ");
344  if (is_synchronized()) tty->print("synchronized ");
345  if (is_native()) tty->print("native ");
346  tty->print("%s::", method_holder()->external_name());
347  name()->print_symbol_on(tty);
348  signature()->print_symbol_on(tty);
349
350  if (WizardMode) {
351    // dump the size of the byte codes
352    tty->print(" {%d}", code_size());
353  }
354  tty->cr();
355
356  tty->print_cr ("  interpreter_invocation_count: %8d ", interpreter_invocation_count());
357  tty->print_cr ("  invocation_counter:           %8d ", invocation_count());
358  tty->print_cr ("  backedge_counter:             %8d ", backedge_count());
359#ifndef PRODUCT
360  if (CountCompiledCalls) {
361    tty->print_cr ("  compiled_invocation_count: %8d ", compiled_invocation_count());
362  }
363#endif
364}
365
366// Build a MethodData* object to hold information about this method
367// collected in the interpreter.
368void Method::build_interpreter_method_data(const methodHandle& method, TRAPS) {
369  // Do not profile the method if metaspace has hit an OOM previously
370  // allocating profiling data. Callers clear pending exception so don't
371  // add one here.
372  if (ClassLoaderDataGraph::has_metaspace_oom()) {
373    return;
374  }
375
376  // Do not profile method if current thread holds the pending list lock,
377  // which avoids deadlock for acquiring the MethodData_lock.
378  if (ReferencePendingListLocker::is_locked_by_self()) {
379    return;
380  }
381
382  // Grab a lock here to prevent multiple
383  // MethodData*s from being created.
384  MutexLocker ml(MethodData_lock, THREAD);
385  if (method->method_data() == NULL) {
386    ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
387    MethodData* method_data = MethodData::allocate(loader_data, method, THREAD);
388    if (HAS_PENDING_EXCEPTION) {
389      CompileBroker::log_metaspace_failure();
390      ClassLoaderDataGraph::set_metaspace_oom(true);
391      return;   // return the exception (which is cleared)
392    }
393
394    method->set_method_data(method_data);
395    if (PrintMethodData && (Verbose || WizardMode)) {
396      ResourceMark rm(THREAD);
397      tty->print("build_interpreter_method_data for ");
398      method->print_name(tty);
399      tty->cr();
400      // At the end of the run, the MDO, full of data, will be dumped.
401    }
402  }
403}
404
405MethodCounters* Method::build_method_counters(Method* m, TRAPS) {
406  // Do not profile the method if metaspace has hit an OOM previously
407  if (ClassLoaderDataGraph::has_metaspace_oom()) {
408    return NULL;
409  }
410
411  methodHandle mh(m);
412  MethodCounters* counters = MethodCounters::allocate(mh, THREAD);
413  if (HAS_PENDING_EXCEPTION) {
414    CompileBroker::log_metaspace_failure();
415    ClassLoaderDataGraph::set_metaspace_oom(true);
416    return NULL;   // return the exception (which is cleared)
417  }
418  if (!mh->init_method_counters(counters)) {
419    MetadataFactory::free_metadata(mh->method_holder()->class_loader_data(), counters);
420  }
421
422  if (LogTouchedMethods) {
423    mh->log_touched(CHECK_NULL);
424  }
425
426  return mh->method_counters();
427}
428
429void Method::cleanup_inline_caches() {
430  // The current system doesn't use inline caches in the interpreter
431  // => nothing to do (keep this method around for future use)
432}
433
434
435int Method::extra_stack_words() {
436  // not an inline function, to avoid a header dependency on Interpreter
437  return extra_stack_entries() * Interpreter::stackElementSize;
438}
439
440
441void Method::compute_size_of_parameters(Thread *thread) {
442  ArgumentSizeComputer asc(signature());
443  set_size_of_parameters(asc.size() + (is_static() ? 0 : 1));
444}
445
446#ifdef CC_INTERP
447void Method::set_result_index(BasicType type)          {
448  _result_index = Interpreter::BasicType_as_index(type);
449}
450#endif
451
452BasicType Method::result_type() const {
453  ResultTypeFinder rtf(signature());
454  return rtf.type();
455}
456
457
458bool Method::is_empty_method() const {
459  return  code_size() == 1
460      && *code_base() == Bytecodes::_return;
461}
462
463
464bool Method::is_vanilla_constructor() const {
465  // Returns true if this method is a vanilla constructor, i.e. an "<init>" "()V" method
466  // which only calls the superclass vanilla constructor and possibly does stores of
467  // zero constants to local fields:
468  //
469  //   aload_0
470  //   invokespecial
471  //   indexbyte1
472  //   indexbyte2
473  //
474  // followed by an (optional) sequence of:
475  //
476  //   aload_0
477  //   aconst_null / iconst_0 / fconst_0 / dconst_0
478  //   putfield
479  //   indexbyte1
480  //   indexbyte2
481  //
482  // followed by:
483  //
484  //   return
485
486  assert(name() == vmSymbols::object_initializer_name(),    "Should only be called for default constructors");
487  assert(signature() == vmSymbols::void_method_signature(), "Should only be called for default constructors");
488  int size = code_size();
489  // Check if size match
490  if (size == 0 || size % 5 != 0) return false;
491  address cb = code_base();
492  int last = size - 1;
493  if (cb[0] != Bytecodes::_aload_0 || cb[1] != Bytecodes::_invokespecial || cb[last] != Bytecodes::_return) {
494    // Does not call superclass default constructor
495    return false;
496  }
497  // Check optional sequence
498  for (int i = 4; i < last; i += 5) {
499    if (cb[i] != Bytecodes::_aload_0) return false;
500    if (!Bytecodes::is_zero_const(Bytecodes::cast(cb[i+1]))) return false;
501    if (cb[i+2] != Bytecodes::_putfield) return false;
502  }
503  return true;
504}
505
506
507bool Method::compute_has_loops_flag() {
508  BytecodeStream bcs(this);
509  Bytecodes::Code bc;
510
511  while ((bc = bcs.next()) >= 0) {
512    switch( bc ) {
513      case Bytecodes::_ifeq:
514      case Bytecodes::_ifnull:
515      case Bytecodes::_iflt:
516      case Bytecodes::_ifle:
517      case Bytecodes::_ifne:
518      case Bytecodes::_ifnonnull:
519      case Bytecodes::_ifgt:
520      case Bytecodes::_ifge:
521      case Bytecodes::_if_icmpeq:
522      case Bytecodes::_if_icmpne:
523      case Bytecodes::_if_icmplt:
524      case Bytecodes::_if_icmpgt:
525      case Bytecodes::_if_icmple:
526      case Bytecodes::_if_icmpge:
527      case Bytecodes::_if_acmpeq:
528      case Bytecodes::_if_acmpne:
529      case Bytecodes::_goto:
530      case Bytecodes::_jsr:
531        if( bcs.dest() < bcs.next_bci() ) _access_flags.set_has_loops();
532        break;
533
534      case Bytecodes::_goto_w:
535      case Bytecodes::_jsr_w:
536        if( bcs.dest_w() < bcs.next_bci() ) _access_flags.set_has_loops();
537        break;
538    }
539  }
540  _access_flags.set_loops_flag_init();
541  return _access_flags.has_loops();
542}
543
544bool Method::is_final_method(AccessFlags class_access_flags) const {
545  // or "does_not_require_vtable_entry"
546  // default method or overpass can occur, is not final (reuses vtable entry)
547  // private methods get vtable entries for backward class compatibility.
548  if (is_overpass() || is_default_method())  return false;
549  return is_final() || class_access_flags.is_final();
550}
551
552bool Method::is_final_method() const {
553  return is_final_method(method_holder()->access_flags());
554}
555
556bool Method::is_default_method() const {
557  if (method_holder() != NULL &&
558      method_holder()->is_interface() &&
559      !is_abstract()) {
560    return true;
561  } else {
562    return false;
563  }
564}
565
566bool Method::can_be_statically_bound(AccessFlags class_access_flags) const {
567  if (is_final_method(class_access_flags))  return true;
568#ifdef ASSERT
569  ResourceMark rm;
570  bool is_nonv = (vtable_index() == nonvirtual_vtable_index);
571  if (class_access_flags.is_interface()) {
572    assert(is_nonv == is_static(), "is_nonv=%s", name_and_sig_as_C_string());
573  }
574#endif
575  assert(valid_vtable_index() || valid_itable_index(), "method must be linked before we ask this question");
576  return vtable_index() == nonvirtual_vtable_index;
577}
578
579bool Method::can_be_statically_bound() const {
580  return can_be_statically_bound(method_holder()->access_flags());
581}
582
583bool Method::is_accessor() const {
584  return is_getter() || is_setter();
585}
586
587bool Method::is_getter() const {
588  if (code_size() != 5) return false;
589  if (size_of_parameters() != 1) return false;
590  if (java_code_at(0) != Bytecodes::_aload_0)  return false;
591  if (java_code_at(1) != Bytecodes::_getfield) return false;
592  switch (java_code_at(4)) {
593    case Bytecodes::_ireturn:
594    case Bytecodes::_lreturn:
595    case Bytecodes::_freturn:
596    case Bytecodes::_dreturn:
597    case Bytecodes::_areturn:
598      break;
599    default:
600      return false;
601  }
602  return true;
603}
604
605bool Method::is_setter() const {
606  if (code_size() != 6) return false;
607  if (java_code_at(0) != Bytecodes::_aload_0) return false;
608  switch (java_code_at(1)) {
609    case Bytecodes::_iload_1:
610    case Bytecodes::_aload_1:
611    case Bytecodes::_fload_1:
612      if (size_of_parameters() != 2) return false;
613      break;
614    case Bytecodes::_dload_1:
615    case Bytecodes::_lload_1:
616      if (size_of_parameters() != 3) return false;
617      break;
618    default:
619      return false;
620  }
621  if (java_code_at(2) != Bytecodes::_putfield) return false;
622  if (java_code_at(5) != Bytecodes::_return)   return false;
623  return true;
624}
625
626bool Method::is_constant_getter() const {
627  int last_index = code_size() - 1;
628  // Check if the first 1-3 bytecodes are a constant push
629  // and the last bytecode is a return.
630  return (2 <= code_size() && code_size() <= 4 &&
631          Bytecodes::is_const(java_code_at(0)) &&
632          Bytecodes::length_for(java_code_at(0)) == last_index &&
633          Bytecodes::is_return(java_code_at(last_index)));
634}
635
636bool Method::is_initializer() const {
637  return name() == vmSymbols::object_initializer_name() || is_static_initializer();
638}
639
640bool Method::has_valid_initializer_flags() const {
641  return (is_static() ||
642          method_holder()->major_version() < 51);
643}
644
645bool Method::is_static_initializer() const {
646  // For classfiles version 51 or greater, ensure that the clinit method is
647  // static.  Non-static methods with the name "<clinit>" are not static
648  // initializers. (older classfiles exempted for backward compatibility)
649  return name() == vmSymbols::class_initializer_name() &&
650         has_valid_initializer_flags();
651}
652
653
654objArrayHandle Method::resolved_checked_exceptions_impl(Method* method, TRAPS) {
655  int length = method->checked_exceptions_length();
656  if (length == 0) {  // common case
657    return objArrayHandle(THREAD, Universe::the_empty_class_klass_array());
658  } else {
659    methodHandle h_this(THREAD, method);
660    objArrayOop m_oop = oopFactory::new_objArray(SystemDictionary::Class_klass(), length, CHECK_(objArrayHandle()));
661    objArrayHandle mirrors (THREAD, m_oop);
662    for (int i = 0; i < length; i++) {
663      CheckedExceptionElement* table = h_this->checked_exceptions_start(); // recompute on each iteration, not gc safe
664      Klass* k = h_this->constants()->klass_at(table[i].class_cp_index, CHECK_(objArrayHandle()));
665      assert(k->is_subclass_of(SystemDictionary::Throwable_klass()), "invalid exception class");
666      mirrors->obj_at_put(i, k->java_mirror());
667    }
668    return mirrors;
669  }
670};
671
672
673int Method::line_number_from_bci(int bci) const {
674  if (bci == SynchronizationEntryBCI) bci = 0;
675  assert(bci == 0 || 0 <= bci && bci < code_size(), "illegal bci");
676  int best_bci  =  0;
677  int best_line = -1;
678
679  if (has_linenumber_table()) {
680    // The line numbers are a short array of 2-tuples [start_pc, line_number].
681    // Not necessarily sorted and not necessarily one-to-one.
682    CompressedLineNumberReadStream stream(compressed_linenumber_table());
683    while (stream.read_pair()) {
684      if (stream.bci() == bci) {
685        // perfect match
686        return stream.line();
687      } else {
688        // update best_bci/line
689        if (stream.bci() < bci && stream.bci() >= best_bci) {
690          best_bci  = stream.bci();
691          best_line = stream.line();
692        }
693      }
694    }
695  }
696  return best_line;
697}
698
699
700bool Method::is_klass_loaded_by_klass_index(int klass_index) const {
701  if( constants()->tag_at(klass_index).is_unresolved_klass() ) {
702    Thread *thread = Thread::current();
703    Symbol* klass_name = constants()->klass_name_at(klass_index);
704    Handle loader(thread, method_holder()->class_loader());
705    Handle prot  (thread, method_holder()->protection_domain());
706    return SystemDictionary::find(klass_name, loader, prot, thread) != NULL;
707  } else {
708    return true;
709  }
710}
711
712
713bool Method::is_klass_loaded(int refinfo_index, bool must_be_resolved) const {
714  int klass_index = constants()->klass_ref_index_at(refinfo_index);
715  if (must_be_resolved) {
716    // Make sure klass is resolved in constantpool.
717    if (constants()->tag_at(klass_index).is_unresolved_klass()) return false;
718  }
719  return is_klass_loaded_by_klass_index(klass_index);
720}
721
722
723void Method::set_native_function(address function, bool post_event_flag) {
724  assert(function != NULL, "use clear_native_function to unregister natives");
725  assert(!is_method_handle_intrinsic() || function == SharedRuntime::native_method_throw_unsatisfied_link_error_entry(), "");
726  address* native_function = native_function_addr();
727
728  // We can see racers trying to place the same native function into place. Once
729  // is plenty.
730  address current = *native_function;
731  if (current == function) return;
732  if (post_event_flag && JvmtiExport::should_post_native_method_bind() &&
733      function != NULL) {
734    // native_method_throw_unsatisfied_link_error_entry() should only
735    // be passed when post_event_flag is false.
736    assert(function !=
737      SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
738      "post_event_flag mis-match");
739
740    // post the bind event, and possible change the bind function
741    JvmtiExport::post_native_method_bind(this, &function);
742  }
743  *native_function = function;
744  // This function can be called more than once. We must make sure that we always
745  // use the latest registered method -> check if a stub already has been generated.
746  // If so, we have to make it not_entrant.
747  nmethod* nm = code(); // Put it into local variable to guard against concurrent updates
748  if (nm != NULL) {
749    nm->make_not_entrant();
750  }
751}
752
753
754bool Method::has_native_function() const {
755  if (is_method_handle_intrinsic())
756    return false;  // special-cased in SharedRuntime::generate_native_wrapper
757  address func = native_function();
758  return (func != NULL && func != SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
759}
760
761
762void Method::clear_native_function() {
763  // Note: is_method_handle_intrinsic() is allowed here.
764  set_native_function(
765    SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
766    !native_bind_event_is_interesting);
767  clear_code();
768}
769
770address Method::critical_native_function() {
771  methodHandle mh(this);
772  return NativeLookup::lookup_critical_entry(mh);
773}
774
775
776void Method::set_signature_handler(address handler) {
777  address* signature_handler =  signature_handler_addr();
778  *signature_handler = handler;
779}
780
781
782void Method::print_made_not_compilable(int comp_level, bool is_osr, bool report, const char* reason) {
783  if (PrintCompilation && report) {
784    ttyLocker ttyl;
785    tty->print("made not %scompilable on ", is_osr ? "OSR " : "");
786    if (comp_level == CompLevel_all) {
787      tty->print("all levels ");
788    } else {
789      tty->print("levels ");
790      for (int i = (int)CompLevel_none; i <= comp_level; i++) {
791        tty->print("%d ", i);
792      }
793    }
794    this->print_short_name(tty);
795    int size = this->code_size();
796    if (size > 0) {
797      tty->print(" (%d bytes)", size);
798    }
799    if (reason != NULL) {
800      tty->print("   %s", reason);
801    }
802    tty->cr();
803  }
804  if ((TraceDeoptimization || LogCompilation) && (xtty != NULL)) {
805    ttyLocker ttyl;
806    xtty->begin_elem("make_not_compilable thread='" UINTX_FORMAT "' osr='%d' level='%d'",
807                     os::current_thread_id(), is_osr, comp_level);
808    if (reason != NULL) {
809      xtty->print(" reason=\'%s\'", reason);
810    }
811    xtty->method(this);
812    xtty->stamp();
813    xtty->end_elem();
814  }
815}
816
817bool Method::is_always_compilable() const {
818  // Generated adapters must be compiled
819  if (is_method_handle_intrinsic() && is_synthetic()) {
820    assert(!is_not_c1_compilable(), "sanity check");
821    assert(!is_not_c2_compilable(), "sanity check");
822    return true;
823  }
824
825  return false;
826}
827
828bool Method::is_not_compilable(int comp_level) const {
829  if (number_of_breakpoints() > 0)
830    return true;
831  if (is_always_compilable())
832    return false;
833  if (comp_level == CompLevel_any)
834    return is_not_c1_compilable() || is_not_c2_compilable();
835  if (is_c1_compile(comp_level))
836    return is_not_c1_compilable();
837  if (is_c2_compile(comp_level))
838    return is_not_c2_compilable();
839  return false;
840}
841
842// call this when compiler finds that this method is not compilable
843void Method::set_not_compilable(int comp_level, bool report, const char* reason) {
844  if (is_always_compilable()) {
845    // Don't mark a method which should be always compilable
846    return;
847  }
848  print_made_not_compilable(comp_level, /*is_osr*/ false, report, reason);
849  if (comp_level == CompLevel_all) {
850    set_not_c1_compilable();
851    set_not_c2_compilable();
852  } else {
853    if (is_c1_compile(comp_level))
854      set_not_c1_compilable();
855    if (is_c2_compile(comp_level))
856      set_not_c2_compilable();
857  }
858  CompilationPolicy::policy()->disable_compilation(this);
859  assert(!CompilationPolicy::can_be_compiled(this, comp_level), "sanity check");
860}
861
862bool Method::is_not_osr_compilable(int comp_level) const {
863  if (is_not_compilable(comp_level))
864    return true;
865  if (comp_level == CompLevel_any)
866    return is_not_c1_osr_compilable() || is_not_c2_osr_compilable();
867  if (is_c1_compile(comp_level))
868    return is_not_c1_osr_compilable();
869  if (is_c2_compile(comp_level))
870    return is_not_c2_osr_compilable();
871  return false;
872}
873
874void Method::set_not_osr_compilable(int comp_level, bool report, const char* reason) {
875  print_made_not_compilable(comp_level, /*is_osr*/ true, report, reason);
876  if (comp_level == CompLevel_all) {
877    set_not_c1_osr_compilable();
878    set_not_c2_osr_compilable();
879  } else {
880    if (is_c1_compile(comp_level))
881      set_not_c1_osr_compilable();
882    if (is_c2_compile(comp_level))
883      set_not_c2_osr_compilable();
884  }
885  CompilationPolicy::policy()->disable_compilation(this);
886  assert(!CompilationPolicy::can_be_osr_compiled(this, comp_level), "sanity check");
887}
888
889// Revert to using the interpreter and clear out the nmethod
890void Method::clear_code() {
891
892  // this may be NULL if c2i adapters have not been made yet
893  // Only should happen at allocate time.
894  if (_adapter == NULL) {
895    _from_compiled_entry    = NULL;
896  } else {
897    _from_compiled_entry    = _adapter->get_c2i_entry();
898  }
899  OrderAccess::storestore();
900  _from_interpreted_entry = _i2i_entry;
901  OrderAccess::storestore();
902  _code = NULL;
903}
904
905// Called by class data sharing to remove any entry points (which are not shared)
906void Method::unlink_method() {
907  _code = NULL;
908  _i2i_entry = NULL;
909  _from_interpreted_entry = NULL;
910  if (is_native()) {
911    *native_function_addr() = NULL;
912    set_signature_handler(NULL);
913  }
914  NOT_PRODUCT(set_compiled_invocation_count(0);)
915  _adapter = NULL;
916  _from_compiled_entry = NULL;
917
918  // In case of DumpSharedSpaces, _method_data should always be NULL.
919  //
920  // During runtime (!DumpSharedSpaces), when we are cleaning a
921  // shared class that failed to load, this->link_method() may
922  // have already been called (before an exception happened), so
923  // this->_method_data may not be NULL.
924  assert(!DumpSharedSpaces || _method_data == NULL, "unexpected method data?");
925
926  set_method_data(NULL);
927  clear_method_counters();
928}
929
930// Called when the method_holder is getting linked. Setup entrypoints so the method
931// is ready to be called from interpreter, compiler, and vtables.
932void Method::link_method(const methodHandle& h_method, TRAPS) {
933  // If the code cache is full, we may reenter this function for the
934  // leftover methods that weren't linked.
935  if (_i2i_entry != NULL) return;
936
937  assert(_adapter == NULL, "init'd to NULL" );
938  assert( _code == NULL, "nothing compiled yet" );
939
940  // Setup interpreter entrypoint
941  assert(this == h_method(), "wrong h_method()" );
942  address entry = Interpreter::entry_for_method(h_method);
943  assert(entry != NULL, "interpreter entry must be non-null");
944  // Sets both _i2i_entry and _from_interpreted_entry
945  set_interpreter_entry(entry);
946
947  // Don't overwrite already registered native entries.
948  if (is_native() && !has_native_function()) {
949    set_native_function(
950      SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
951      !native_bind_event_is_interesting);
952  }
953
954  // Setup compiler entrypoint.  This is made eagerly, so we do not need
955  // special handling of vtables.  An alternative is to make adapters more
956  // lazily by calling make_adapter() from from_compiled_entry() for the
957  // normal calls.  For vtable calls life gets more complicated.  When a
958  // call-site goes mega-morphic we need adapters in all methods which can be
959  // called from the vtable.  We need adapters on such methods that get loaded
960  // later.  Ditto for mega-morphic itable calls.  If this proves to be a
961  // problem we'll make these lazily later.
962  (void) make_adapters(h_method, CHECK);
963
964  // ONLY USE the h_method now as make_adapter may have blocked
965
966}
967
968address Method::make_adapters(methodHandle mh, TRAPS) {
969  // Adapters for compiled code are made eagerly here.  They are fairly
970  // small (generally < 100 bytes) and quick to make (and cached and shared)
971  // so making them eagerly shouldn't be too expensive.
972  AdapterHandlerEntry* adapter = AdapterHandlerLibrary::get_adapter(mh);
973  if (adapter == NULL ) {
974    THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(), "Out of space in CodeCache for adapters");
975  }
976
977  mh->set_adapter_entry(adapter);
978  mh->_from_compiled_entry = adapter->get_c2i_entry();
979  return adapter->get_c2i_entry();
980}
981
982void Method::restore_unshareable_info(TRAPS) {
983  // Since restore_unshareable_info can be called more than once for a method, don't
984  // redo any work.   If this field is restored, there is nothing to do.
985  if (_from_compiled_entry == NULL) {
986    // restore method's vtable by calling a virtual function
987    restore_vtable();
988
989    methodHandle mh(THREAD, this);
990    link_method(mh, CHECK);
991  }
992}
993
994
995// The verified_code_entry() must be called when a invoke is resolved
996// on this method.
997
998// It returns the compiled code entry point, after asserting not null.
999// This function is called after potential safepoints so that nmethod
1000// or adapter that it points to is still live and valid.
1001// This function must not hit a safepoint!
1002address Method::verified_code_entry() {
1003  debug_only(NoSafepointVerifier nsv;)
1004  assert(_from_compiled_entry != NULL, "must be set");
1005  return _from_compiled_entry;
1006}
1007
1008// Check that if an nmethod ref exists, it has a backlink to this or no backlink at all
1009// (could be racing a deopt).
1010// Not inline to avoid circular ref.
1011bool Method::check_code() const {
1012  // cached in a register or local.  There's a race on the value of the field.
1013  nmethod *code = (nmethod *)OrderAccess::load_ptr_acquire(&_code);
1014  return code == NULL || (code->method() == NULL) || (code->method() == (Method*)this && !code->is_osr_method());
1015}
1016
1017// Install compiled code.  Instantly it can execute.
1018void Method::set_code(methodHandle mh, nmethod *code) {
1019  assert( code, "use clear_code to remove code" );
1020  assert( mh->check_code(), "" );
1021
1022  guarantee(mh->adapter() != NULL, "Adapter blob must already exist!");
1023
1024  // These writes must happen in this order, because the interpreter will
1025  // directly jump to from_interpreted_entry which jumps to an i2c adapter
1026  // which jumps to _from_compiled_entry.
1027  mh->_code = code;             // Assign before allowing compiled code to exec
1028
1029  int comp_level = code->comp_level();
1030  // In theory there could be a race here. In practice it is unlikely
1031  // and not worth worrying about.
1032  if (comp_level > mh->highest_comp_level()) {
1033    mh->set_highest_comp_level(comp_level);
1034  }
1035
1036  OrderAccess::storestore();
1037#ifdef SHARK
1038  mh->_from_interpreted_entry = code->insts_begin();
1039#else //!SHARK
1040  mh->_from_compiled_entry = code->verified_entry_point();
1041  OrderAccess::storestore();
1042  // Instantly compiled code can execute.
1043  if (!mh->is_method_handle_intrinsic())
1044    mh->_from_interpreted_entry = mh->get_i2c_entry();
1045#endif //!SHARK
1046}
1047
1048
1049bool Method::is_overridden_in(Klass* k) const {
1050  InstanceKlass* ik = InstanceKlass::cast(k);
1051
1052  if (ik->is_interface()) return false;
1053
1054  // If method is an interface, we skip it - except if it
1055  // is a miranda method
1056  if (method_holder()->is_interface()) {
1057    // Check that method is not a miranda method
1058    if (ik->lookup_method(name(), signature()) == NULL) {
1059      // No implementation exist - so miranda method
1060      return false;
1061    }
1062    return true;
1063  }
1064
1065  assert(ik->is_subclass_of(method_holder()), "should be subklass");
1066  assert(ik->vtable() != NULL, "vtable should exist");
1067  if (!has_vtable_index()) {
1068    return false;
1069  } else {
1070    Method* vt_m = ik->method_at_vtable(vtable_index());
1071    return vt_m != this;
1072  }
1073}
1074
1075
1076// give advice about whether this Method* should be cached or not
1077bool Method::should_not_be_cached() const {
1078  if (is_old()) {
1079    // This method has been redefined. It is either EMCP or obsolete
1080    // and we don't want to cache it because that would pin the method
1081    // down and prevent it from being collectible if and when it
1082    // finishes executing.
1083    return true;
1084  }
1085
1086  // caching this method should be just fine
1087  return false;
1088}
1089
1090
1091/**
1092 *  Returns true if this is one of the specially treated methods for
1093 *  security related stack walks (like Reflection.getCallerClass).
1094 */
1095bool Method::is_ignored_by_security_stack_walk() const {
1096  if (intrinsic_id() == vmIntrinsics::_invoke) {
1097    // This is Method.invoke() -- ignore it
1098    return true;
1099  }
1100  if (method_holder()->is_subclass_of(SystemDictionary::reflect_MethodAccessorImpl_klass())) {
1101    // This is an auxilary frame -- ignore it
1102    return true;
1103  }
1104  if (is_method_handle_intrinsic() || is_compiled_lambda_form()) {
1105    // This is an internal adapter frame for method handles -- ignore it
1106    return true;
1107  }
1108  return false;
1109}
1110
1111
1112// Constant pool structure for invoke methods:
1113enum {
1114  _imcp_invoke_name = 1,        // utf8: 'invokeExact', etc.
1115  _imcp_invoke_signature,       // utf8: (variable Symbol*)
1116  _imcp_limit
1117};
1118
1119// Test if this method is an MH adapter frame generated by Java code.
1120// Cf. java/lang/invoke/InvokerBytecodeGenerator
1121bool Method::is_compiled_lambda_form() const {
1122  return intrinsic_id() == vmIntrinsics::_compiledLambdaForm;
1123}
1124
1125// Test if this method is an internal MH primitive method.
1126bool Method::is_method_handle_intrinsic() const {
1127  vmIntrinsics::ID iid = intrinsic_id();
1128  return (MethodHandles::is_signature_polymorphic(iid) &&
1129          MethodHandles::is_signature_polymorphic_intrinsic(iid));
1130}
1131
1132bool Method::has_member_arg() const {
1133  vmIntrinsics::ID iid = intrinsic_id();
1134  return (MethodHandles::is_signature_polymorphic(iid) &&
1135          MethodHandles::has_member_arg(iid));
1136}
1137
1138// Make an instance of a signature-polymorphic internal MH primitive.
1139methodHandle Method::make_method_handle_intrinsic(vmIntrinsics::ID iid,
1140                                                         Symbol* signature,
1141                                                         TRAPS) {
1142  ResourceMark rm;
1143  methodHandle empty;
1144
1145  KlassHandle holder = SystemDictionary::MethodHandle_klass();
1146  Symbol* name = MethodHandles::signature_polymorphic_intrinsic_name(iid);
1147  assert(iid == MethodHandles::signature_polymorphic_name_id(name), "");
1148  if (TraceMethodHandles) {
1149    tty->print_cr("make_method_handle_intrinsic MH.%s%s", name->as_C_string(), signature->as_C_string());
1150  }
1151
1152  // invariant:   cp->symbol_at_put is preceded by a refcount increment (more usually a lookup)
1153  name->increment_refcount();
1154  signature->increment_refcount();
1155
1156  int cp_length = _imcp_limit;
1157  ClassLoaderData* loader_data = holder->class_loader_data();
1158  constantPoolHandle cp;
1159  {
1160    ConstantPool* cp_oop = ConstantPool::allocate(loader_data, cp_length, CHECK_(empty));
1161    cp = constantPoolHandle(THREAD, cp_oop);
1162  }
1163  cp->set_pool_holder(InstanceKlass::cast(holder()));
1164  cp->symbol_at_put(_imcp_invoke_name,       name);
1165  cp->symbol_at_put(_imcp_invoke_signature,  signature);
1166  cp->set_has_preresolution();
1167
1168  // decide on access bits:  public or not?
1169  int flags_bits = (JVM_ACC_NATIVE | JVM_ACC_SYNTHETIC | JVM_ACC_FINAL);
1170  bool must_be_static = MethodHandles::is_signature_polymorphic_static(iid);
1171  if (must_be_static)  flags_bits |= JVM_ACC_STATIC;
1172  assert((flags_bits & JVM_ACC_PUBLIC) == 0, "do not expose these methods");
1173
1174  methodHandle m;
1175  {
1176    InlineTableSizes sizes;
1177    Method* m_oop = Method::allocate(loader_data, 0,
1178                                     accessFlags_from(flags_bits), &sizes,
1179                                     ConstMethod::NORMAL, CHECK_(empty));
1180    m = methodHandle(THREAD, m_oop);
1181  }
1182  m->set_constants(cp());
1183  m->set_name_index(_imcp_invoke_name);
1184  m->set_signature_index(_imcp_invoke_signature);
1185  assert(MethodHandles::is_signature_polymorphic_name(m->name()), "");
1186  assert(m->signature() == signature, "");
1187#ifdef CC_INTERP
1188  ResultTypeFinder rtf(signature);
1189  m->set_result_index(rtf.type());
1190#endif
1191  m->compute_size_of_parameters(THREAD);
1192  m->init_intrinsic_id();
1193  assert(m->is_method_handle_intrinsic(), "");
1194#ifdef ASSERT
1195  if (!MethodHandles::is_signature_polymorphic(m->intrinsic_id()))  m->print();
1196  assert(MethodHandles::is_signature_polymorphic(m->intrinsic_id()), "must be an invoker");
1197  assert(m->intrinsic_id() == iid, "correctly predicted iid");
1198#endif //ASSERT
1199
1200  // Finally, set up its entry points.
1201  assert(m->can_be_statically_bound(), "");
1202  m->set_vtable_index(Method::nonvirtual_vtable_index);
1203  m->link_method(m, CHECK_(empty));
1204
1205  if (TraceMethodHandles && (Verbose || WizardMode)) {
1206    ttyLocker ttyl;
1207    m->print_on(tty);
1208  }
1209
1210  return m;
1211}
1212
1213Klass* Method::check_non_bcp_klass(Klass* klass) {
1214  if (klass != NULL && klass->class_loader() != NULL) {
1215    if (klass->is_objArray_klass())
1216      klass = ObjArrayKlass::cast(klass)->bottom_klass();
1217    return klass;
1218  }
1219  return NULL;
1220}
1221
1222
1223methodHandle Method::clone_with_new_data(methodHandle m, u_char* new_code, int new_code_length,
1224                                                u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS) {
1225  // Code below does not work for native methods - they should never get rewritten anyway
1226  assert(!m->is_native(), "cannot rewrite native methods");
1227  // Allocate new Method*
1228  AccessFlags flags = m->access_flags();
1229
1230  ConstMethod* cm = m->constMethod();
1231  int checked_exceptions_len = cm->checked_exceptions_length();
1232  int localvariable_len = cm->localvariable_table_length();
1233  int exception_table_len = cm->exception_table_length();
1234  int method_parameters_len = cm->method_parameters_length();
1235  int method_annotations_len = cm->method_annotations_length();
1236  int parameter_annotations_len = cm->parameter_annotations_length();
1237  int type_annotations_len = cm->type_annotations_length();
1238  int default_annotations_len = cm->default_annotations_length();
1239
1240  InlineTableSizes sizes(
1241      localvariable_len,
1242      new_compressed_linenumber_size,
1243      exception_table_len,
1244      checked_exceptions_len,
1245      method_parameters_len,
1246      cm->generic_signature_index(),
1247      method_annotations_len,
1248      parameter_annotations_len,
1249      type_annotations_len,
1250      default_annotations_len,
1251      0);
1252
1253  ClassLoaderData* loader_data = m->method_holder()->class_loader_data();
1254  Method* newm_oop = Method::allocate(loader_data,
1255                                      new_code_length,
1256                                      flags,
1257                                      &sizes,
1258                                      m->method_type(),
1259                                      CHECK_(methodHandle()));
1260  methodHandle newm (THREAD, newm_oop);
1261
1262  // Create a shallow copy of Method part, but be careful to preserve the new ConstMethod*
1263  ConstMethod* newcm = newm->constMethod();
1264  int new_const_method_size = newm->constMethod()->size();
1265
1266  memcpy(newm(), m(), sizeof(Method));
1267
1268  // Create shallow copy of ConstMethod.
1269  memcpy(newcm, m->constMethod(), sizeof(ConstMethod));
1270
1271  // Reset correct method/const method, method size, and parameter info
1272  newm->set_constMethod(newcm);
1273  newm->constMethod()->set_code_size(new_code_length);
1274  newm->constMethod()->set_constMethod_size(new_const_method_size);
1275  assert(newm->code_size() == new_code_length, "check");
1276  assert(newm->method_parameters_length() == method_parameters_len, "check");
1277  assert(newm->checked_exceptions_length() == checked_exceptions_len, "check");
1278  assert(newm->exception_table_length() == exception_table_len, "check");
1279  assert(newm->localvariable_table_length() == localvariable_len, "check");
1280  // Copy new byte codes
1281  memcpy(newm->code_base(), new_code, new_code_length);
1282  // Copy line number table
1283  if (new_compressed_linenumber_size > 0) {
1284    memcpy(newm->compressed_linenumber_table(),
1285           new_compressed_linenumber_table,
1286           new_compressed_linenumber_size);
1287  }
1288  // Copy method_parameters
1289  if (method_parameters_len > 0) {
1290    memcpy(newm->method_parameters_start(),
1291           m->method_parameters_start(),
1292           method_parameters_len * sizeof(MethodParametersElement));
1293  }
1294  // Copy checked_exceptions
1295  if (checked_exceptions_len > 0) {
1296    memcpy(newm->checked_exceptions_start(),
1297           m->checked_exceptions_start(),
1298           checked_exceptions_len * sizeof(CheckedExceptionElement));
1299  }
1300  // Copy exception table
1301  if (exception_table_len > 0) {
1302    memcpy(newm->exception_table_start(),
1303           m->exception_table_start(),
1304           exception_table_len * sizeof(ExceptionTableElement));
1305  }
1306  // Copy local variable number table
1307  if (localvariable_len > 0) {
1308    memcpy(newm->localvariable_table_start(),
1309           m->localvariable_table_start(),
1310           localvariable_len * sizeof(LocalVariableTableElement));
1311  }
1312  // Copy stackmap table
1313  if (m->has_stackmap_table()) {
1314    int code_attribute_length = m->stackmap_data()->length();
1315    Array<u1>* stackmap_data =
1316      MetadataFactory::new_array<u1>(loader_data, code_attribute_length, 0, CHECK_NULL);
1317    memcpy((void*)stackmap_data->adr_at(0),
1318           (void*)m->stackmap_data()->adr_at(0), code_attribute_length);
1319    newm->set_stackmap_data(stackmap_data);
1320  }
1321
1322  // copy annotations over to new method
1323  newcm->copy_annotations_from(cm);
1324  return newm;
1325}
1326
1327vmSymbols::SID Method::klass_id_for_intrinsics(const Klass* holder) {
1328  // if loader is not the default loader (i.e., != NULL), we can't know the intrinsics
1329  // because we are not loading from core libraries
1330  // exception: the AES intrinsics come from lib/ext/sunjce_provider.jar
1331  // which does not use the class default class loader so we check for its loader here
1332  const InstanceKlass* ik = InstanceKlass::cast(holder);
1333  if ((ik->class_loader() != NULL) && !SystemDictionary::is_ext_class_loader(ik->class_loader())) {
1334    return vmSymbols::NO_SID;   // regardless of name, no intrinsics here
1335  }
1336
1337  // see if the klass name is well-known:
1338  Symbol* klass_name = ik->name();
1339  return vmSymbols::find_sid(klass_name);
1340}
1341
1342void Method::init_intrinsic_id() {
1343  assert(_intrinsic_id == vmIntrinsics::_none, "do this just once");
1344  const uintptr_t max_id_uint = right_n_bits((int)(sizeof(_intrinsic_id) * BitsPerByte));
1345  assert((uintptr_t)vmIntrinsics::ID_LIMIT <= max_id_uint, "else fix size");
1346  assert(intrinsic_id_size_in_bytes() == sizeof(_intrinsic_id), "");
1347
1348  // the klass name is well-known:
1349  vmSymbols::SID klass_id = klass_id_for_intrinsics(method_holder());
1350  assert(klass_id != vmSymbols::NO_SID, "caller responsibility");
1351
1352  // ditto for method and signature:
1353  vmSymbols::SID  name_id = vmSymbols::find_sid(name());
1354  if (klass_id != vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1355      && name_id == vmSymbols::NO_SID)
1356    return;
1357  vmSymbols::SID   sig_id = vmSymbols::find_sid(signature());
1358  if (klass_id != vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1359      && sig_id == vmSymbols::NO_SID)  return;
1360  jshort flags = access_flags().as_short();
1361
1362  vmIntrinsics::ID id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
1363  if (id != vmIntrinsics::_none) {
1364    set_intrinsic_id(id);
1365    if (id == vmIntrinsics::_Class_cast) {
1366      // Even if the intrinsic is rejected, we want to inline this simple method.
1367      set_force_inline(true);
1368    }
1369    return;
1370  }
1371
1372  // A few slightly irregular cases:
1373  switch (klass_id) {
1374  case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_StrictMath):
1375    // Second chance: check in regular Math.
1376    switch (name_id) {
1377    case vmSymbols::VM_SYMBOL_ENUM_NAME(min_name):
1378    case vmSymbols::VM_SYMBOL_ENUM_NAME(max_name):
1379    case vmSymbols::VM_SYMBOL_ENUM_NAME(sqrt_name):
1380      // pretend it is the corresponding method in the non-strict class:
1381      klass_id = vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_Math);
1382      id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
1383      break;
1384    }
1385    break;
1386
1387  // Signature-polymorphic methods: MethodHandle.invoke*, InvokeDynamic.*.
1388  case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle):
1389    if (!is_native())  break;
1390    id = MethodHandles::signature_polymorphic_name_id(method_holder(), name());
1391    if (is_static() != MethodHandles::is_signature_polymorphic_static(id))
1392      id = vmIntrinsics::_none;
1393    break;
1394  }
1395
1396  if (id != vmIntrinsics::_none) {
1397    // Set up its iid.  It is an alias method.
1398    set_intrinsic_id(id);
1399    return;
1400  }
1401}
1402
1403// These two methods are static since a GC may move the Method
1404bool Method::load_signature_classes(methodHandle m, TRAPS) {
1405  if (!THREAD->can_call_java()) {
1406    // There is nothing useful this routine can do from within the Compile thread.
1407    // Hopefully, the signature contains only well-known classes.
1408    // We could scan for this and return true/false, but the caller won't care.
1409    return false;
1410  }
1411  bool sig_is_loaded = true;
1412  Handle class_loader(THREAD, m->method_holder()->class_loader());
1413  Handle protection_domain(THREAD, m->method_holder()->protection_domain());
1414  ResourceMark rm(THREAD);
1415  Symbol*  signature = m->signature();
1416  for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
1417    if (ss.is_object()) {
1418      Symbol* sym = ss.as_symbol(CHECK_(false));
1419      Symbol*  name  = sym;
1420      Klass* klass = SystemDictionary::resolve_or_null(name, class_loader,
1421                                             protection_domain, THREAD);
1422      // We are loading classes eagerly. If a ClassNotFoundException or
1423      // a LinkageError was generated, be sure to ignore it.
1424      if (HAS_PENDING_EXCEPTION) {
1425        if (PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass()) ||
1426            PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
1427          CLEAR_PENDING_EXCEPTION;
1428        } else {
1429          return false;
1430        }
1431      }
1432      if( klass == NULL) { sig_is_loaded = false; }
1433    }
1434  }
1435  return sig_is_loaded;
1436}
1437
1438bool Method::has_unloaded_classes_in_signature(methodHandle m, TRAPS) {
1439  Handle class_loader(THREAD, m->method_holder()->class_loader());
1440  Handle protection_domain(THREAD, m->method_holder()->protection_domain());
1441  ResourceMark rm(THREAD);
1442  Symbol*  signature = m->signature();
1443  for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
1444    if (ss.type() == T_OBJECT) {
1445      Symbol* name = ss.as_symbol_or_null();
1446      if (name == NULL) return true;
1447      Klass* klass = SystemDictionary::find(name, class_loader, protection_domain, THREAD);
1448      if (klass == NULL) return true;
1449    }
1450  }
1451  return false;
1452}
1453
1454// Exposed so field engineers can debug VM
1455void Method::print_short_name(outputStream* st) {
1456  ResourceMark rm;
1457#ifdef PRODUCT
1458  st->print(" %s::", method_holder()->external_name());
1459#else
1460  st->print(" %s::", method_holder()->internal_name());
1461#endif
1462  name()->print_symbol_on(st);
1463  if (WizardMode) signature()->print_symbol_on(st);
1464  else if (MethodHandles::is_signature_polymorphic(intrinsic_id()))
1465    MethodHandles::print_as_basic_type_signature_on(st, signature(), true);
1466}
1467
1468// Comparer for sorting an object array containing
1469// Method*s.
1470static int method_comparator(Method* a, Method* b) {
1471  return a->name()->fast_compare(b->name());
1472}
1473
1474// This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
1475// default_methods also uses this without the ordering for fast find_method
1476void Method::sort_methods(Array<Method*>* methods, bool idempotent, bool set_idnums) {
1477  int length = methods->length();
1478  if (length > 1) {
1479    {
1480      NoSafepointVerifier nsv;
1481      QuickSort::sort<Method*>(methods->data(), length, method_comparator, idempotent);
1482    }
1483    // Reset method ordering
1484    if (set_idnums) {
1485      for (int i = 0; i < length; i++) {
1486        Method* m = methods->at(i);
1487        m->set_method_idnum(i);
1488        m->set_orig_method_idnum(i);
1489      }
1490    }
1491  }
1492}
1493
1494//-----------------------------------------------------------------------------------
1495// Non-product code unless JVM/TI needs it
1496
1497#if !defined(PRODUCT) || INCLUDE_JVMTI
1498class SignatureTypePrinter : public SignatureTypeNames {
1499 private:
1500  outputStream* _st;
1501  bool _use_separator;
1502
1503  void type_name(const char* name) {
1504    if (_use_separator) _st->print(", ");
1505    _st->print("%s", name);
1506    _use_separator = true;
1507  }
1508
1509 public:
1510  SignatureTypePrinter(Symbol* signature, outputStream* st) : SignatureTypeNames(signature) {
1511    _st = st;
1512    _use_separator = false;
1513  }
1514
1515  void print_parameters()              { _use_separator = false; iterate_parameters(); }
1516  void print_returntype()              { _use_separator = false; iterate_returntype(); }
1517};
1518
1519
1520void Method::print_name(outputStream* st) {
1521  Thread *thread = Thread::current();
1522  ResourceMark rm(thread);
1523  st->print("%s ", is_static() ? "static" : "virtual");
1524  if (WizardMode) {
1525    st->print("%s.", method_holder()->internal_name());
1526    name()->print_symbol_on(st);
1527    signature()->print_symbol_on(st);
1528  } else {
1529    SignatureTypePrinter sig(signature(), st);
1530    sig.print_returntype();
1531    st->print(" %s.", method_holder()->internal_name());
1532    name()->print_symbol_on(st);
1533    st->print("(");
1534    sig.print_parameters();
1535    st->print(")");
1536  }
1537}
1538#endif // !PRODUCT || INCLUDE_JVMTI
1539
1540
1541void Method::print_codes_on(outputStream* st) const {
1542  print_codes_on(0, code_size(), st);
1543}
1544
1545void Method::print_codes_on(int from, int to, outputStream* st) const {
1546  Thread *thread = Thread::current();
1547  ResourceMark rm(thread);
1548  methodHandle mh (thread, (Method*)this);
1549  BytecodeStream s(mh);
1550  s.set_interval(from, to);
1551  BytecodeTracer::set_closure(BytecodeTracer::std_closure());
1552  while (s.next() >= 0) BytecodeTracer::trace(mh, s.bcp(), st);
1553}
1554
1555
1556// Simple compression of line number tables. We use a regular compressed stream, except that we compress deltas
1557// between (bci,line) pairs since they are smaller. If (bci delta, line delta) fits in (5-bit unsigned, 3-bit unsigned)
1558// we save it as one byte, otherwise we write a 0xFF escape character and use regular compression. 0x0 is used
1559// as end-of-stream terminator.
1560
1561void CompressedLineNumberWriteStream::write_pair_regular(int bci_delta, int line_delta) {
1562  // bci and line number does not compress into single byte.
1563  // Write out escape character and use regular compression for bci and line number.
1564  write_byte((jubyte)0xFF);
1565  write_signed_int(bci_delta);
1566  write_signed_int(line_delta);
1567}
1568
1569// See comment in method.hpp which explains why this exists.
1570#if defined(_M_AMD64) && _MSC_VER >= 1400
1571#pragma optimize("", off)
1572void CompressedLineNumberWriteStream::write_pair(int bci, int line) {
1573  write_pair_inline(bci, line);
1574}
1575#pragma optimize("", on)
1576#endif
1577
1578CompressedLineNumberReadStream::CompressedLineNumberReadStream(u_char* buffer) : CompressedReadStream(buffer) {
1579  _bci = 0;
1580  _line = 0;
1581};
1582
1583
1584bool CompressedLineNumberReadStream::read_pair() {
1585  jubyte next = read_byte();
1586  // Check for terminator
1587  if (next == 0) return false;
1588  if (next == 0xFF) {
1589    // Escape character, regular compression used
1590    _bci  += read_signed_int();
1591    _line += read_signed_int();
1592  } else {
1593    // Single byte compression used
1594    _bci  += next >> 3;
1595    _line += next & 0x7;
1596  }
1597  return true;
1598}
1599
1600
1601Bytecodes::Code Method::orig_bytecode_at(int bci) const {
1602  BreakpointInfo* bp = method_holder()->breakpoints();
1603  for (; bp != NULL; bp = bp->next()) {
1604    if (bp->match(this, bci)) {
1605      return bp->orig_bytecode();
1606    }
1607  }
1608  {
1609    ResourceMark rm;
1610    fatal("no original bytecode found in %s at bci %d", name_and_sig_as_C_string(), bci);
1611  }
1612  return Bytecodes::_shouldnotreachhere;
1613}
1614
1615void Method::set_orig_bytecode_at(int bci, Bytecodes::Code code) {
1616  assert(code != Bytecodes::_breakpoint, "cannot patch breakpoints this way");
1617  BreakpointInfo* bp = method_holder()->breakpoints();
1618  for (; bp != NULL; bp = bp->next()) {
1619    if (bp->match(this, bci)) {
1620      bp->set_orig_bytecode(code);
1621      // and continue, in case there is more than one
1622    }
1623  }
1624}
1625
1626void Method::set_breakpoint(int bci) {
1627  InstanceKlass* ik = method_holder();
1628  BreakpointInfo *bp = new BreakpointInfo(this, bci);
1629  bp->set_next(ik->breakpoints());
1630  ik->set_breakpoints(bp);
1631  // do this last:
1632  bp->set(this);
1633}
1634
1635static void clear_matches(Method* m, int bci) {
1636  InstanceKlass* ik = m->method_holder();
1637  BreakpointInfo* prev_bp = NULL;
1638  BreakpointInfo* next_bp;
1639  for (BreakpointInfo* bp = ik->breakpoints(); bp != NULL; bp = next_bp) {
1640    next_bp = bp->next();
1641    // bci value of -1 is used to delete all breakpoints in method m (ex: clear_all_breakpoint).
1642    if (bci >= 0 ? bp->match(m, bci) : bp->match(m)) {
1643      // do this first:
1644      bp->clear(m);
1645      // unhook it
1646      if (prev_bp != NULL)
1647        prev_bp->set_next(next_bp);
1648      else
1649        ik->set_breakpoints(next_bp);
1650      delete bp;
1651      // When class is redefined JVMTI sets breakpoint in all versions of EMCP methods
1652      // at same location. So we have multiple matching (method_index and bci)
1653      // BreakpointInfo nodes in BreakpointInfo list. We should just delete one
1654      // breakpoint for clear_breakpoint request and keep all other method versions
1655      // BreakpointInfo for future clear_breakpoint request.
1656      // bcivalue of -1 is used to clear all breakpoints (see clear_all_breakpoints)
1657      // which is being called when class is unloaded. We delete all the Breakpoint
1658      // information for all versions of method. We may not correctly restore the original
1659      // bytecode in all method versions, but that is ok. Because the class is being unloaded
1660      // so these methods won't be used anymore.
1661      if (bci >= 0) {
1662        break;
1663      }
1664    } else {
1665      // This one is a keeper.
1666      prev_bp = bp;
1667    }
1668  }
1669}
1670
1671void Method::clear_breakpoint(int bci) {
1672  assert(bci >= 0, "");
1673  clear_matches(this, bci);
1674}
1675
1676void Method::clear_all_breakpoints() {
1677  clear_matches(this, -1);
1678}
1679
1680
1681int Method::invocation_count() {
1682  MethodCounters *mcs = method_counters();
1683  if (TieredCompilation) {
1684    MethodData* const mdo = method_data();
1685    if (((mcs != NULL) ? mcs->invocation_counter()->carry() : false) ||
1686        ((mdo != NULL) ? mdo->invocation_counter()->carry() : false)) {
1687      return InvocationCounter::count_limit;
1688    } else {
1689      return ((mcs != NULL) ? mcs->invocation_counter()->count() : 0) +
1690             ((mdo != NULL) ? mdo->invocation_counter()->count() : 0);
1691    }
1692  } else {
1693    return (mcs == NULL) ? 0 : mcs->invocation_counter()->count();
1694  }
1695}
1696
1697int Method::backedge_count() {
1698  MethodCounters *mcs = method_counters();
1699  if (TieredCompilation) {
1700    MethodData* const mdo = method_data();
1701    if (((mcs != NULL) ? mcs->backedge_counter()->carry() : false) ||
1702        ((mdo != NULL) ? mdo->backedge_counter()->carry() : false)) {
1703      return InvocationCounter::count_limit;
1704    } else {
1705      return ((mcs != NULL) ? mcs->backedge_counter()->count() : 0) +
1706             ((mdo != NULL) ? mdo->backedge_counter()->count() : 0);
1707    }
1708  } else {
1709    return (mcs == NULL) ? 0 : mcs->backedge_counter()->count();
1710  }
1711}
1712
1713int Method::highest_comp_level() const {
1714  const MethodCounters* mcs = method_counters();
1715  if (mcs != NULL) {
1716    return mcs->highest_comp_level();
1717  } else {
1718    return CompLevel_none;
1719  }
1720}
1721
1722int Method::highest_osr_comp_level() const {
1723  const MethodCounters* mcs = method_counters();
1724  if (mcs != NULL) {
1725    return mcs->highest_osr_comp_level();
1726  } else {
1727    return CompLevel_none;
1728  }
1729}
1730
1731void Method::set_highest_comp_level(int level) {
1732  MethodCounters* mcs = method_counters();
1733  if (mcs != NULL) {
1734    mcs->set_highest_comp_level(level);
1735  }
1736}
1737
1738void Method::set_highest_osr_comp_level(int level) {
1739  MethodCounters* mcs = method_counters();
1740  if (mcs != NULL) {
1741    mcs->set_highest_osr_comp_level(level);
1742  }
1743}
1744
1745BreakpointInfo::BreakpointInfo(Method* m, int bci) {
1746  _bci = bci;
1747  _name_index = m->name_index();
1748  _signature_index = m->signature_index();
1749  _orig_bytecode = (Bytecodes::Code) *m->bcp_from(_bci);
1750  if (_orig_bytecode == Bytecodes::_breakpoint)
1751    _orig_bytecode = m->orig_bytecode_at(_bci);
1752  _next = NULL;
1753}
1754
1755void BreakpointInfo::set(Method* method) {
1756#ifdef ASSERT
1757  {
1758    Bytecodes::Code code = (Bytecodes::Code) *method->bcp_from(_bci);
1759    if (code == Bytecodes::_breakpoint)
1760      code = method->orig_bytecode_at(_bci);
1761    assert(orig_bytecode() == code, "original bytecode must be the same");
1762  }
1763#endif
1764  Thread *thread = Thread::current();
1765  *method->bcp_from(_bci) = Bytecodes::_breakpoint;
1766  method->incr_number_of_breakpoints(thread);
1767  SystemDictionary::notice_modification();
1768  {
1769    // Deoptimize all dependents on this method
1770    HandleMark hm(thread);
1771    methodHandle mh(thread, method);
1772    CodeCache::flush_dependents_on_method(mh);
1773  }
1774}
1775
1776void BreakpointInfo::clear(Method* method) {
1777  *method->bcp_from(_bci) = orig_bytecode();
1778  assert(method->number_of_breakpoints() > 0, "must not go negative");
1779  method->decr_number_of_breakpoints(Thread::current());
1780}
1781
1782// jmethodID handling
1783
1784// This is a block allocating object, sort of like JNIHandleBlock, only a
1785// lot simpler.
1786// It's allocated on the CHeap because once we allocate a jmethodID, we can
1787// never get rid of it.
1788
1789static const int min_block_size = 8;
1790
1791class JNIMethodBlockNode : public CHeapObj<mtClass> {
1792  friend class JNIMethodBlock;
1793  Method**        _methods;
1794  int             _number_of_methods;
1795  int             _top;
1796  JNIMethodBlockNode* _next;
1797
1798 public:
1799
1800  JNIMethodBlockNode(int num_methods = min_block_size);
1801
1802  ~JNIMethodBlockNode() { FREE_C_HEAP_ARRAY(Method*, _methods); }
1803
1804  void ensure_methods(int num_addl_methods) {
1805    if (_top < _number_of_methods) {
1806      num_addl_methods -= _number_of_methods - _top;
1807      if (num_addl_methods <= 0) {
1808        return;
1809      }
1810    }
1811    if (_next == NULL) {
1812      _next = new JNIMethodBlockNode(MAX2(num_addl_methods, min_block_size));
1813    } else {
1814      _next->ensure_methods(num_addl_methods);
1815    }
1816  }
1817};
1818
1819class JNIMethodBlock : public CHeapObj<mtClass> {
1820  JNIMethodBlockNode _head;
1821  JNIMethodBlockNode *_last_free;
1822 public:
1823  static Method* const _free_method;
1824
1825  JNIMethodBlock(int initial_capacity = min_block_size)
1826      : _head(initial_capacity), _last_free(&_head) {}
1827
1828  void ensure_methods(int num_addl_methods) {
1829    _last_free->ensure_methods(num_addl_methods);
1830  }
1831
1832  Method** add_method(Method* m) {
1833    for (JNIMethodBlockNode* b = _last_free; b != NULL; b = b->_next) {
1834      if (b->_top < b->_number_of_methods) {
1835        // top points to the next free entry.
1836        int i = b->_top;
1837        b->_methods[i] = m;
1838        b->_top++;
1839        _last_free = b;
1840        return &(b->_methods[i]);
1841      } else if (b->_top == b->_number_of_methods) {
1842        // if the next free entry ran off the block see if there's a free entry
1843        for (int i = 0; i < b->_number_of_methods; i++) {
1844          if (b->_methods[i] == _free_method) {
1845            b->_methods[i] = m;
1846            _last_free = b;
1847            return &(b->_methods[i]);
1848          }
1849        }
1850        // Only check each block once for frees.  They're very unlikely.
1851        // Increment top past the end of the block.
1852        b->_top++;
1853      }
1854      // need to allocate a next block.
1855      if (b->_next == NULL) {
1856        b->_next = _last_free = new JNIMethodBlockNode();
1857      }
1858    }
1859    guarantee(false, "Should always allocate a free block");
1860    return NULL;
1861  }
1862
1863  bool contains(Method** m) {
1864    if (m == NULL) return false;
1865    for (JNIMethodBlockNode* b = &_head; b != NULL; b = b->_next) {
1866      if (b->_methods <= m && m < b->_methods + b->_number_of_methods) {
1867        // This is a bit of extra checking, for two reasons.  One is
1868        // that contains() deals with pointers that are passed in by
1869        // JNI code, so making sure that the pointer is aligned
1870        // correctly is valuable.  The other is that <= and > are
1871        // technically not defined on pointers, so the if guard can
1872        // pass spuriously; no modern compiler is likely to make that
1873        // a problem, though (and if one did, the guard could also
1874        // fail spuriously, which would be bad).
1875        ptrdiff_t idx = m - b->_methods;
1876        if (b->_methods + idx == m) {
1877          return true;
1878        }
1879      }
1880    }
1881    return false;  // not found
1882  }
1883
1884  // Doesn't really destroy it, just marks it as free so it can be reused.
1885  void destroy_method(Method** m) {
1886#ifdef ASSERT
1887    assert(contains(m), "should be a methodID");
1888#endif // ASSERT
1889    *m = _free_method;
1890  }
1891
1892  // During class unloading the methods are cleared, which is different
1893  // than freed.
1894  void clear_all_methods() {
1895    for (JNIMethodBlockNode* b = &_head; b != NULL; b = b->_next) {
1896      for (int i = 0; i< b->_number_of_methods; i++) {
1897        b->_methods[i] = NULL;
1898      }
1899    }
1900  }
1901#ifndef PRODUCT
1902  int count_methods() {
1903    // count all allocated methods
1904    int count = 0;
1905    for (JNIMethodBlockNode* b = &_head; b != NULL; b = b->_next) {
1906      for (int i = 0; i< b->_number_of_methods; i++) {
1907        if (b->_methods[i] != _free_method) count++;
1908      }
1909    }
1910    return count;
1911  }
1912#endif // PRODUCT
1913};
1914
1915// Something that can't be mistaken for an address or a markOop
1916Method* const JNIMethodBlock::_free_method = (Method*)55;
1917
1918JNIMethodBlockNode::JNIMethodBlockNode(int num_methods) : _next(NULL), _top(0) {
1919  _number_of_methods = MAX2(num_methods, min_block_size);
1920  _methods = NEW_C_HEAP_ARRAY(Method*, _number_of_methods, mtInternal);
1921  for (int i = 0; i < _number_of_methods; i++) {
1922    _methods[i] = JNIMethodBlock::_free_method;
1923  }
1924}
1925
1926void Method::ensure_jmethod_ids(ClassLoaderData* loader_data, int capacity) {
1927  ClassLoaderData* cld = loader_data;
1928  if (!SafepointSynchronize::is_at_safepoint()) {
1929    // Have to add jmethod_ids() to class loader data thread-safely.
1930    // Also have to add the method to the list safely, which the cld lock
1931    // protects as well.
1932    MutexLockerEx ml(cld->metaspace_lock(),  Mutex::_no_safepoint_check_flag);
1933    if (cld->jmethod_ids() == NULL) {
1934      cld->set_jmethod_ids(new JNIMethodBlock(capacity));
1935    } else {
1936      cld->jmethod_ids()->ensure_methods(capacity);
1937    }
1938  } else {
1939    // At safepoint, we are single threaded and can set this.
1940    if (cld->jmethod_ids() == NULL) {
1941      cld->set_jmethod_ids(new JNIMethodBlock(capacity));
1942    } else {
1943      cld->jmethod_ids()->ensure_methods(capacity);
1944    }
1945  }
1946}
1947
1948// Add a method id to the jmethod_ids
1949jmethodID Method::make_jmethod_id(ClassLoaderData* loader_data, Method* m) {
1950  ClassLoaderData* cld = loader_data;
1951
1952  if (!SafepointSynchronize::is_at_safepoint()) {
1953    // Have to add jmethod_ids() to class loader data thread-safely.
1954    // Also have to add the method to the list safely, which the cld lock
1955    // protects as well.
1956    MutexLockerEx ml(cld->metaspace_lock(),  Mutex::_no_safepoint_check_flag);
1957    if (cld->jmethod_ids() == NULL) {
1958      cld->set_jmethod_ids(new JNIMethodBlock());
1959    }
1960    // jmethodID is a pointer to Method*
1961    return (jmethodID)cld->jmethod_ids()->add_method(m);
1962  } else {
1963    // At safepoint, we are single threaded and can set this.
1964    if (cld->jmethod_ids() == NULL) {
1965      cld->set_jmethod_ids(new JNIMethodBlock());
1966    }
1967    // jmethodID is a pointer to Method*
1968    return (jmethodID)cld->jmethod_ids()->add_method(m);
1969  }
1970}
1971
1972// Mark a jmethodID as free.  This is called when there is a data race in
1973// InstanceKlass while creating the jmethodID cache.
1974void Method::destroy_jmethod_id(ClassLoaderData* loader_data, jmethodID m) {
1975  ClassLoaderData* cld = loader_data;
1976  Method** ptr = (Method**)m;
1977  assert(cld->jmethod_ids() != NULL, "should have method handles");
1978  cld->jmethod_ids()->destroy_method(ptr);
1979}
1980
1981void Method::change_method_associated_with_jmethod_id(jmethodID jmid, Method* new_method) {
1982  // Can't assert the method_holder is the same because the new method has the
1983  // scratch method holder.
1984  assert(resolve_jmethod_id(jmid)->method_holder()->class_loader()
1985           == new_method->method_holder()->class_loader(),
1986         "changing to a different class loader");
1987  // Just change the method in place, jmethodID pointer doesn't change.
1988  *((Method**)jmid) = new_method;
1989}
1990
1991bool Method::is_method_id(jmethodID mid) {
1992  Method* m = resolve_jmethod_id(mid);
1993  assert(m != NULL, "should be called with non-null method");
1994  InstanceKlass* ik = m->method_holder();
1995  ClassLoaderData* cld = ik->class_loader_data();
1996  if (cld->jmethod_ids() == NULL) return false;
1997  return (cld->jmethod_ids()->contains((Method**)mid));
1998}
1999
2000Method* Method::checked_resolve_jmethod_id(jmethodID mid) {
2001  if (mid == NULL) return NULL;
2002  Method* o = resolve_jmethod_id(mid);
2003  if (o == NULL || o == JNIMethodBlock::_free_method || !((Metadata*)o)->is_method()) {
2004    return NULL;
2005  }
2006  return o;
2007};
2008
2009void Method::set_on_stack(const bool value) {
2010  // Set both the method itself and its constant pool.  The constant pool
2011  // on stack means some method referring to it is also on the stack.
2012  constants()->set_on_stack(value);
2013
2014  bool already_set = on_stack();
2015  _access_flags.set_on_stack(value);
2016  if (value && !already_set) {
2017    MetadataOnStackMark::record(this);
2018  }
2019}
2020
2021// Called when the class loader is unloaded to make all methods weak.
2022void Method::clear_jmethod_ids(ClassLoaderData* loader_data) {
2023  loader_data->jmethod_ids()->clear_all_methods();
2024}
2025
2026bool Method::has_method_vptr(const void* ptr) {
2027  Method m;
2028  // This assumes that the vtbl pointer is the first word of a C++ object.
2029  // This assumption is also in universe.cpp patch_klass_vtble
2030  return dereference_vptr(&m) == dereference_vptr(ptr);
2031}
2032
2033// Check that this pointer is valid by checking that the vtbl pointer matches
2034bool Method::is_valid_method() const {
2035  if (this == NULL) {
2036    return false;
2037  } else if ((intptr_t(this) & (wordSize-1)) != 0) {
2038    // Quick sanity check on pointer.
2039    return false;
2040  } else if (!is_metaspace_object()) {
2041    return false;
2042  } else {
2043    return has_method_vptr((const void*)this);
2044  }
2045}
2046
2047#ifndef PRODUCT
2048void Method::print_jmethod_ids(ClassLoaderData* loader_data, outputStream* out) {
2049  out->print_cr("jni_method_id count = %d", loader_data->jmethod_ids()->count_methods());
2050}
2051#endif // PRODUCT
2052
2053
2054// Printing
2055
2056#ifndef PRODUCT
2057
2058void Method::print_on(outputStream* st) const {
2059  ResourceMark rm;
2060  assert(is_method(), "must be method");
2061  st->print_cr("%s", internal_name());
2062  // get the effect of PrintOopAddress, always, for methods:
2063  st->print_cr(" - this oop:          " INTPTR_FORMAT, p2i(this));
2064  st->print   (" - method holder:     "); method_holder()->print_value_on(st); st->cr();
2065  st->print   (" - constants:         " INTPTR_FORMAT " ", p2i(constants()));
2066  constants()->print_value_on(st); st->cr();
2067  st->print   (" - access:            0x%x  ", access_flags().as_int()); access_flags().print_on(st); st->cr();
2068  st->print   (" - name:              ");    name()->print_value_on(st); st->cr();
2069  st->print   (" - signature:         ");    signature()->print_value_on(st); st->cr();
2070  st->print_cr(" - max stack:         %d",   max_stack());
2071  st->print_cr(" - max locals:        %d",   max_locals());
2072  st->print_cr(" - size of params:    %d",   size_of_parameters());
2073  st->print_cr(" - method size:       %d",   method_size());
2074  if (intrinsic_id() != vmIntrinsics::_none)
2075    st->print_cr(" - intrinsic id:      %d %s", intrinsic_id(), vmIntrinsics::name_at(intrinsic_id()));
2076  if (highest_comp_level() != CompLevel_none)
2077    st->print_cr(" - highest level:     %d", highest_comp_level());
2078  st->print_cr(" - vtable index:      %d",   _vtable_index);
2079  st->print_cr(" - i2i entry:         " INTPTR_FORMAT, p2i(interpreter_entry()));
2080  st->print(   " - adapters:          ");
2081  AdapterHandlerEntry* a = ((Method*)this)->adapter();
2082  if (a == NULL)
2083    st->print_cr(INTPTR_FORMAT, p2i(a));
2084  else
2085    a->print_adapter_on(st);
2086  st->print_cr(" - compiled entry     " INTPTR_FORMAT, p2i(from_compiled_entry()));
2087  st->print_cr(" - code size:         %d",   code_size());
2088  if (code_size() != 0) {
2089    st->print_cr(" - code start:        " INTPTR_FORMAT, p2i(code_base()));
2090    st->print_cr(" - code end (excl):   " INTPTR_FORMAT, p2i(code_base() + code_size()));
2091  }
2092  if (method_data() != NULL) {
2093    st->print_cr(" - method data:       " INTPTR_FORMAT, p2i(method_data()));
2094  }
2095  st->print_cr(" - checked ex length: %d",   checked_exceptions_length());
2096  if (checked_exceptions_length() > 0) {
2097    CheckedExceptionElement* table = checked_exceptions_start();
2098    st->print_cr(" - checked ex start:  " INTPTR_FORMAT, p2i(table));
2099    if (Verbose) {
2100      for (int i = 0; i < checked_exceptions_length(); i++) {
2101        st->print_cr("   - throws %s", constants()->printable_name_at(table[i].class_cp_index));
2102      }
2103    }
2104  }
2105  if (has_linenumber_table()) {
2106    u_char* table = compressed_linenumber_table();
2107    st->print_cr(" - linenumber start:  " INTPTR_FORMAT, p2i(table));
2108    if (Verbose) {
2109      CompressedLineNumberReadStream stream(table);
2110      while (stream.read_pair()) {
2111        st->print_cr("   - line %d: %d", stream.line(), stream.bci());
2112      }
2113    }
2114  }
2115  st->print_cr(" - localvar length:   %d",   localvariable_table_length());
2116  if (localvariable_table_length() > 0) {
2117    LocalVariableTableElement* table = localvariable_table_start();
2118    st->print_cr(" - localvar start:    " INTPTR_FORMAT, p2i(table));
2119    if (Verbose) {
2120      for (int i = 0; i < localvariable_table_length(); i++) {
2121        int bci = table[i].start_bci;
2122        int len = table[i].length;
2123        const char* name = constants()->printable_name_at(table[i].name_cp_index);
2124        const char* desc = constants()->printable_name_at(table[i].descriptor_cp_index);
2125        int slot = table[i].slot;
2126        st->print_cr("   - %s %s bci=%d len=%d slot=%d", desc, name, bci, len, slot);
2127      }
2128    }
2129  }
2130  if (code() != NULL) {
2131    st->print   (" - compiled code: ");
2132    code()->print_value_on(st);
2133  }
2134  if (is_native()) {
2135    st->print_cr(" - native function:   " INTPTR_FORMAT, p2i(native_function()));
2136    st->print_cr(" - signature handler: " INTPTR_FORMAT, p2i(signature_handler()));
2137  }
2138}
2139
2140void Method::print_linkage_flags(outputStream* st) {
2141  access_flags().print_on(st);
2142  if (is_default_method()) {
2143    st->print("default ");
2144  }
2145  if (is_overpass()) {
2146    st->print("overpass ");
2147  }
2148}
2149#endif //PRODUCT
2150
2151void Method::print_value_on(outputStream* st) const {
2152  assert(is_method(), "must be method");
2153  st->print("%s", internal_name());
2154  print_address_on(st);
2155  st->print(" ");
2156  name()->print_value_on(st);
2157  st->print(" ");
2158  signature()->print_value_on(st);
2159  st->print(" in ");
2160  method_holder()->print_value_on(st);
2161  if (WizardMode) st->print("#%d", _vtable_index);
2162  if (WizardMode) st->print("[%d,%d]", size_of_parameters(), max_locals());
2163  if (WizardMode && code() != NULL) st->print(" ((nmethod*)%p)", code());
2164}
2165
2166#if INCLUDE_SERVICES
2167// Size Statistics
2168void Method::collect_statistics(KlassSizeStats *sz) const {
2169  int mysize = sz->count(this);
2170  sz->_method_bytes += mysize;
2171  sz->_method_all_bytes += mysize;
2172  sz->_rw_bytes += mysize;
2173
2174  if (constMethod()) {
2175    constMethod()->collect_statistics(sz);
2176  }
2177  if (method_data()) {
2178    method_data()->collect_statistics(sz);
2179  }
2180}
2181#endif // INCLUDE_SERVICES
2182
2183// LogTouchedMethods and PrintTouchedMethods
2184
2185// TouchedMethodRecord -- we can't use a HashtableEntry<Method*> because
2186// the Method may be garbage collected. Let's roll our own hash table.
2187class TouchedMethodRecord : CHeapObj<mtTracing> {
2188public:
2189  // It's OK to store Symbols here because they will NOT be GC'ed if
2190  // LogTouchedMethods is enabled.
2191  TouchedMethodRecord* _next;
2192  Symbol* _class_name;
2193  Symbol* _method_name;
2194  Symbol* _method_signature;
2195};
2196
2197static const int TOUCHED_METHOD_TABLE_SIZE = 20011;
2198static TouchedMethodRecord** _touched_method_table = NULL;
2199
2200void Method::log_touched(TRAPS) {
2201
2202  const int table_size = TOUCHED_METHOD_TABLE_SIZE;
2203  Symbol* my_class = klass_name();
2204  Symbol* my_name  = name();
2205  Symbol* my_sig   = signature();
2206
2207  unsigned int hash = my_class->identity_hash() +
2208                      my_name->identity_hash() +
2209                      my_sig->identity_hash();
2210  juint index = juint(hash) % table_size;
2211
2212  MutexLocker ml(TouchedMethodLog_lock, THREAD);
2213  if (_touched_method_table == NULL) {
2214    _touched_method_table = NEW_C_HEAP_ARRAY2(TouchedMethodRecord*, table_size,
2215                                              mtTracing, CURRENT_PC);
2216    memset(_touched_method_table, 0, sizeof(TouchedMethodRecord*)*table_size);
2217  }
2218
2219  TouchedMethodRecord* ptr = _touched_method_table[index];
2220  while (ptr) {
2221    if (ptr->_class_name       == my_class &&
2222        ptr->_method_name      == my_name &&
2223        ptr->_method_signature == my_sig) {
2224      return;
2225    }
2226    if (ptr->_next == NULL) break;
2227    ptr = ptr->_next;
2228  }
2229  TouchedMethodRecord* nptr = NEW_C_HEAP_OBJ(TouchedMethodRecord, mtTracing);
2230  my_class->set_permanent();  // prevent reclaimed by GC
2231  my_name->set_permanent();
2232  my_sig->set_permanent();
2233  nptr->_class_name         = my_class;
2234  nptr->_method_name        = my_name;
2235  nptr->_method_signature   = my_sig;
2236  nptr->_next               = NULL;
2237
2238  if (ptr == NULL) {
2239    // first
2240    _touched_method_table[index] = nptr;
2241  } else {
2242    ptr->_next = nptr;
2243  }
2244}
2245
2246void Method::print_touched_methods(outputStream* out) {
2247  MutexLockerEx ml(Thread::current()->is_VM_thread() ? NULL : TouchedMethodLog_lock);
2248  out->print_cr("# Method::print_touched_methods version 1");
2249  if (_touched_method_table) {
2250    for (int i = 0; i < TOUCHED_METHOD_TABLE_SIZE; i++) {
2251      TouchedMethodRecord* ptr = _touched_method_table[i];
2252      while(ptr) {
2253        ptr->_class_name->print_symbol_on(out);       out->print(".");
2254        ptr->_method_name->print_symbol_on(out);      out->print(":");
2255        ptr->_method_signature->print_symbol_on(out); out->cr();
2256        ptr = ptr->_next;
2257      }
2258    }
2259  }
2260}
2261
2262// Verification
2263
2264void Method::verify_on(outputStream* st) {
2265  guarantee(is_method(), "object must be method");
2266  guarantee(constants()->is_constantPool(), "should be constant pool");
2267  guarantee(constMethod()->is_constMethod(), "should be ConstMethod*");
2268  MethodData* md = method_data();
2269  guarantee(md == NULL ||
2270      md->is_methodData(), "should be method data");
2271}
2272