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