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