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