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