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