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