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