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