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