1 #ifdef USE_PRAGMA_IDENT_SRC
   2 #pragma ident "@(#)methodOop.cpp        1.314 08/11/24 12:22:56 JVM"
   3 #endif
   4 /*
   5  * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
   6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   7  *
   8  * This code is free software; you can redistribute it and/or modify it
   9  * under the terms of the GNU General Public License version 2 only, as
  10  * published by the Free Software Foundation.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  23  * CA 95054 USA or visit www.sun.com if you need additional information or
  24  * have any questions.
  25  *  
  26  */
  27 
  28 # include "incls/_precompiled.incl"
  29 # include "incls/_methodOop.cpp.incl"
  30 
  31 
  32 // Implementation of methodOopDesc
  33 
  34 address methodOopDesc::get_i2c_entry() {
  35   assert(_adapter != NULL, "must have");
  36   return _adapter->get_i2c_entry();
  37 }
  38 
  39 address methodOopDesc::get_c2i_entry() {
  40   assert(_adapter != NULL, "must have");
  41   return _adapter->get_c2i_entry();
  42 }
  43 
  44 address methodOopDesc::get_c2i_unverified_entry() {
  45   assert(_adapter != NULL, "must have");
  46   return _adapter->get_c2i_unverified_entry();
  47 }
  48 
  49 char* methodOopDesc::name_and_sig_as_C_string() {
  50   return name_and_sig_as_C_string(Klass::cast(constants()->pool_holder()), name(), signature());
  51 }
  52 
  53 char* methodOopDesc::name_and_sig_as_C_string(char* buf, int size) {
  54   return name_and_sig_as_C_string(Klass::cast(constants()->pool_holder()), name(), signature(), buf, size);
  55 }
  56 
  57 char* methodOopDesc::name_and_sig_as_C_string(Klass* klass, symbolOop method_name, symbolOop signature) {
  58   const char* klass_name = klass->external_name();
  59   int klass_name_len  = (int)strlen(klass_name);
  60   int method_name_len = method_name->utf8_length();
  61   int len             = klass_name_len + 1 + method_name_len + signature->utf8_length();
  62   char* dest          = NEW_RESOURCE_ARRAY(char, len + 1);
  63   strcpy(dest, klass_name);
  64   dest[klass_name_len] = '.';
  65   strcpy(&dest[klass_name_len + 1], method_name->as_C_string());
  66   strcpy(&dest[klass_name_len + 1 + method_name_len], signature->as_C_string());
  67   dest[len] = 0;
  68   return dest;
  69 }
  70 
  71 char* methodOopDesc::name_and_sig_as_C_string(Klass* klass, symbolOop method_name, symbolOop signature, char* buf, int size) {
  72   symbolOop klass_name = klass->name();
  73   klass_name->as_klass_external_name(buf, size);
  74   int len = (int)strlen(buf);
  75 
  76   if (len < size - 1) {
  77     buf[len++] = '.';
  78 
  79     method_name->as_C_string(&(buf[len]), size - len);
  80     len = (int)strlen(buf);
  81 
  82     signature->as_C_string(&(buf[len]), size - len);
  83   }
  84 
  85   return buf;
  86 }
  87 
  88 int  methodOopDesc::fast_exception_handler_bci_for(KlassHandle ex_klass, int throw_bci, TRAPS) {
  89   // exception table holds quadruple entries of the form (beg_bci, end_bci, handler_bci, klass_index)
  90   const int beg_bci_offset     = 0;
  91   const int end_bci_offset     = 1;
  92   const int handler_bci_offset = 2;
  93   const int klass_index_offset = 3;
  94   const int entry_size         = 4;
  95   // access exception table
  96   typeArrayHandle table (THREAD, constMethod()->exception_table());
  97   int length = table->length();
  98   assert(length % entry_size == 0, "exception table format has changed");
  99   // iterate through all entries sequentially
 100   constantPoolHandle pool(THREAD, constants());
 101   for (int i = 0; i < length; i += entry_size) {
 102     int beg_bci = table->int_at(i + beg_bci_offset);
 103     int end_bci = table->int_at(i + end_bci_offset);
 104     assert(beg_bci <= end_bci, "inconsistent exception table");
 105     if (beg_bci <= throw_bci && throw_bci < end_bci) {
 106       // exception handler bci range covers throw_bci => investigate further
 107       int handler_bci = table->int_at(i + handler_bci_offset);
 108       int klass_index = table->int_at(i + klass_index_offset);
 109       if (klass_index == 0) {
 110         return handler_bci;
 111       } else if (ex_klass.is_null()) {
 112         return handler_bci;
 113       } else {
 114         // we know the exception class => get the constraint class
 115         // this may require loading of the constraint class; if verification
 116         // fails or some other exception occurs, return handler_bci
 117         klassOop k = pool->klass_at(klass_index, CHECK_(handler_bci));
 118         KlassHandle klass = KlassHandle(THREAD, k);
 119         assert(klass.not_null(), "klass not loaded");
 120         if (ex_klass->is_subtype_of(klass())) {
 121           return handler_bci;
 122         }
 123       }
 124     }
 125   }
 126 
 127   return -1;
 128 }
 129 
 130 methodOop methodOopDesc::method_from_bcp(address bcp) {
 131   debug_only(static int count = 0; count++);
 132   assert(Universe::heap()->is_in_permanent(bcp), "bcp not in perm_gen");
 133   // TO DO: this may be unsafe in some configurations
 134   HeapWord* p = Universe::heap()->block_start(bcp);
 135   assert(Universe::heap()->block_is_obj(p), "must be obj");
 136   assert(oop(p)->is_constMethod(), "not a method");
 137   return constMethodOop(p)->method();
 138 }
 139 
 140 
 141 void methodOopDesc::mask_for(int bci, InterpreterOopMap* mask) {
 142     
 143   Thread* myThread    = Thread::current();
 144   methodHandle h_this(myThread, this);
 145 #ifdef ASSERT
 146   bool has_capability = myThread->is_VM_thread() ||
 147                         myThread->is_ConcurrentGC_thread() ||
 148                         myThread->is_GC_task_thread();
 149 
 150   if (!has_capability) {
 151     if (!VerifyStack && !VerifyLastFrame) {
 152       // verify stack calls this outside VM thread
 153       warning("oopmap should only be accessed by the "
 154               "VM, GC task or CMS threads (or during debugging)");  
 155       InterpreterOopMap local_mask;
 156       instanceKlass::cast(method_holder())->mask_for(h_this, bci, &local_mask);
 157       local_mask.print();
 158     }
 159   }
 160 #endif
 161   instanceKlass::cast(method_holder())->mask_for(h_this, bci, mask);
 162   return;
 163 }
 164 
 165 
 166 int methodOopDesc::bci_from(address bcp) const {  
 167   assert(is_native() && bcp == code_base() || contains(bcp), "bcp doesn't belong to this method");
 168   return bcp - code_base();
 169 }
 170 
 171 
 172 // Return (int)bcx if it appears to be a valid BCI.
 173 // Return bci_from((address)bcx) if it appears to be a valid BCP.
 174 // Return -1 otherwise.
 175 // Used by profiling code, when invalid data is a possibility.
 176 // The caller is responsible for validating the methodOop itself.
 177 int methodOopDesc::validate_bci_from_bcx(intptr_t bcx) const {
 178   // keep bci as -1 if not a valid bci
 179   int bci = -1;
 180   if (bcx == 0 || (address)bcx == code_base()) {
 181     // code_size() may return 0 and we allow 0 here
 182     // the method may be native
 183     bci = 0;
 184   } else if (frame::is_bci(bcx)) {
 185     if (bcx < code_size()) {
 186       bci = (int)bcx;
 187     }
 188   } else if (contains((address)bcx)) {
 189     bci = (address)bcx - code_base();
 190   }
 191   // Assert that if we have dodged any asserts, bci is negative.
 192   assert(bci == -1 || bci == bci_from(bcp_from(bci)), "sane bci if >=0");
 193   return bci;
 194 }
 195 
 196 address methodOopDesc::bcp_from(int bci) const {
 197   assert((is_native() && bci == 0)  || (!is_native() && 0 <= bci && bci < code_size()), "illegal bci");
 198   address bcp = code_base() + bci;
 199   assert(is_native() && bcp == code_base() || contains(bcp), "bcp doesn't belong to this method");
 200   return bcp;
 201 }
 202 
 203 
 204 int methodOopDesc::object_size(bool is_native) {
 205   // If native, then include pointers for native_function and signature_handler
 206   int extra_bytes = (is_native) ? 2*sizeof(address*) : 0;
 207   int extra_words = align_size_up(extra_bytes, BytesPerWord) / BytesPerWord;
 208   return align_object_size(header_size() + extra_words);
 209 }
 210 
 211 
 212 symbolOop methodOopDesc::klass_name() const {
 213   klassOop k = method_holder();
 214   assert(k->is_klass(), "must be klass");
 215   instanceKlass* ik = (instanceKlass*) k->klass_part();
 216   return ik->name();
 217 }
 218 
 219 
 220 void methodOopDesc::set_interpreter_kind() {
 221   int kind = Interpreter::method_kind(methodOop(this));
 222   assert(kind != Interpreter::invalid,
 223          "interpreter entry must be valid");
 224   set_interpreter_kind(kind);
 225 }
 226 
 227 
 228 // Attempt to return method oop to original state.  Clear any pointers
 229 // (to objects outside the shared spaces).  We won't be able to predict
 230 // where they should point in a new JVM.  Further initialize some
 231 // entries now in order allow them to be write protected later.
 232 
 233 void methodOopDesc::remove_unshareable_info() {
 234   unlink_method();
 235   set_interpreter_kind();
 236 }
 237 
 238 
 239 bool methodOopDesc::was_executed_more_than(int n) const {
 240   // Invocation counter is reset when the methodOop is compiled.
 241   // If the method has compiled code we therefore assume it has
 242   // be excuted more than n times.
 243   if (is_accessor() || is_empty_method() || (code() != NULL)) {
 244     // interpreter doesn't bump invocation counter of trivial methods
 245     // compiler does not bump invocation counter of compiled methods
 246     return true;
 247   } else if (_invocation_counter.carry()) {
 248     // The carry bit is set when the counter overflows and causes
 249     // a compilation to occur.  We don't know how many times
 250     // the counter has been reset, so we simply assume it has
 251     // been executed more than n times.
 252     return true;
 253   } else {
 254     return invocation_count() > n;
 255   }
 256 }
 257 
 258 #ifndef PRODUCT
 259 void methodOopDesc::print_invocation_count() const {
 260   if (is_static()) tty->print("static ");
 261   if (is_final()) tty->print("final ");
 262   if (is_synchronized()) tty->print("synchronized ");
 263   if (is_native()) tty->print("native ");
 264   method_holder()->klass_part()->name()->print_symbol_on(tty);
 265   tty->print(".");
 266   name()->print_symbol_on(tty);
 267   signature()->print_symbol_on(tty);
 268 
 269   if (WizardMode) {
 270     // dump the size of the byte codes
 271     tty->print(" {%d}", code_size());
 272   }
 273   tty->cr();
 274 
 275   tty->print_cr ("  interpreter_invocation_count: %8d ", interpreter_invocation_count());
 276   tty->print_cr ("  invocation_counter:           %8d ", invocation_count());
 277   tty->print_cr ("  backedge_counter:             %8d ", backedge_count());
 278   if (CountCompiledCalls) {
 279     tty->print_cr ("  compiled_invocation_count: %8d ", compiled_invocation_count());
 280   }
 281 
 282 }
 283 #endif
 284 
 285 // Build a methodDataOop object to hold information about this method
 286 // collected in the interpreter.
 287 void methodOopDesc::build_interpreter_method_data(methodHandle method, TRAPS) {
 288   // Grab a lock here to prevent multiple
 289   // methodDataOops from being created.
 290   MutexLocker ml(MethodData_lock, THREAD);
 291   if (method->method_data() == NULL) {
 292     methodDataOop method_data = oopFactory::new_methodData(method, CHECK);
 293     method->set_method_data(method_data);
 294     if (PrintMethodData && (Verbose || WizardMode)) {
 295       ResourceMark rm(THREAD);
 296       tty->print("build_interpreter_method_data for ");
 297       method->print_name(tty);
 298       tty->cr();
 299       // At the end of the run, the MDO, full of data, will be dumped.
 300     }
 301   }
 302 }
 303 
 304 void methodOopDesc::cleanup_inline_caches() {
 305   // The current system doesn't use inline caches in the interpreter
 306   // => nothing to do (keep this method around for future use)
 307 }
 308 
 309 
 310 void methodOopDesc::compute_size_of_parameters(Thread *thread) {
 311   symbolHandle h_signature(thread, signature());
 312   ArgumentSizeComputer asc(h_signature);
 313   set_size_of_parameters(asc.size() + (is_static() ? 0 : 1));
 314 }
 315 
 316 #ifdef CC_INTERP
 317 void methodOopDesc::set_result_index(BasicType type)          { 
 318   _result_index = Interpreter::BasicType_as_index(type); 
 319 }
 320 #endif
 321 
 322 BasicType methodOopDesc::result_type() const {
 323   ResultTypeFinder rtf(signature());
 324   return rtf.type();
 325 }
 326 
 327 
 328 bool methodOopDesc::is_empty_method() const {
 329   return  code_size() == 1
 330       && *code_base() == Bytecodes::_return;
 331 }
 332 
 333 
 334 bool methodOopDesc::is_vanilla_constructor() const {
 335   // Returns true if this method is a vanilla constructor, i.e. an "<init>" "()V" method
 336   // which only calls the superclass vanilla constructor and possibly does stores of
 337   // zero constants to local fields:
 338   //
 339   //   aload_0
 340   //   invokespecial
 341   //   indexbyte1
 342   //   indexbyte2
 343   // 
 344   // followed by an (optional) sequence of:
 345   //
 346   //   aload_0
 347   //   aconst_null / iconst_0 / fconst_0 / dconst_0
 348   //   putfield
 349   //   indexbyte1
 350   //   indexbyte2
 351   //
 352   // followed by:
 353   //
 354   //   return
 355 
 356   assert(name() == vmSymbols::object_initializer_name(),    "Should only be called for default constructors");
 357   assert(signature() == vmSymbols::void_method_signature(), "Should only be called for default constructors");
 358   int size = code_size();
 359   // Check if size match
 360   if (size == 0 || size % 5 != 0) return false;
 361   address cb = code_base();
 362   int last = size - 1;
 363   if (cb[0] != Bytecodes::_aload_0 || cb[1] != Bytecodes::_invokespecial || cb[last] != Bytecodes::_return) {
 364     // Does not call superclass default constructor
 365     return false;
 366   }
 367   // Check optional sequence
 368   for (int i = 4; i < last; i += 5) {
 369     if (cb[i] != Bytecodes::_aload_0) return false;
 370     if (!Bytecodes::is_zero_const(Bytecodes::cast(cb[i+1]))) return false;
 371     if (cb[i+2] != Bytecodes::_putfield) return false;
 372   }
 373   return true;
 374 }
 375 
 376 
 377 bool methodOopDesc::compute_has_loops_flag() {  
 378   BytecodeStream bcs(methodOop(this));
 379   Bytecodes::Code bc;
 380     
 381   while ((bc = bcs.next()) >= 0) {    
 382     switch( bc ) {        
 383       case Bytecodes::_ifeq: 
 384       case Bytecodes::_ifnull: 
 385       case Bytecodes::_iflt: 
 386       case Bytecodes::_ifle: 
 387       case Bytecodes::_ifne: 
 388       case Bytecodes::_ifnonnull: 
 389       case Bytecodes::_ifgt: 
 390       case Bytecodes::_ifge: 
 391       case Bytecodes::_if_icmpeq: 
 392       case Bytecodes::_if_icmpne: 
 393       case Bytecodes::_if_icmplt: 
 394       case Bytecodes::_if_icmpgt: 
 395       case Bytecodes::_if_icmple: 
 396       case Bytecodes::_if_icmpge: 
 397       case Bytecodes::_if_acmpeq:
 398       case Bytecodes::_if_acmpne:
 399       case Bytecodes::_goto: 
 400       case Bytecodes::_jsr:     
 401         if( bcs.dest() < bcs.next_bci() ) _access_flags.set_has_loops();
 402         break;
 403 
 404       case Bytecodes::_goto_w:       
 405       case Bytecodes::_jsr_w:        
 406         if( bcs.dest_w() < bcs.next_bci() ) _access_flags.set_has_loops(); 
 407         break;
 408     }  
 409   }
 410   _access_flags.set_loops_flag_init();
 411   return _access_flags.has_loops(); 
 412 }
 413 
 414 
 415 bool methodOopDesc::is_final_method() const {
 416   // %%% Should return true for private methods also,
 417   // since there is no way to override them.
 418   return is_final() || Klass::cast(method_holder())->is_final();
 419 }
 420 
 421 
 422 bool methodOopDesc::is_strict_method() const {
 423   return is_strict();
 424 }
 425 
 426 
 427 bool methodOopDesc::can_be_statically_bound() const {
 428   if (is_final_method())  return true;
 429   return vtable_index() == nonvirtual_vtable_index;
 430 }
 431 
 432 
 433 bool methodOopDesc::is_accessor() const {
 434   if (code_size() != 5) return false;
 435   if (size_of_parameters() != 1) return false;
 436   methodOop m = (methodOop)this;  // pass to code_at() to avoid method_from_bcp
 437   if (Bytecodes::java_code_at(code_base()+0, m) != Bytecodes::_aload_0 ) return false;
 438   if (Bytecodes::java_code_at(code_base()+1, m) != Bytecodes::_getfield) return false;
 439   if (Bytecodes::java_code_at(code_base()+4, m) != Bytecodes::_areturn &&
 440       Bytecodes::java_code_at(code_base()+4, m) != Bytecodes::_ireturn ) return false;
 441   return true;
 442 }
 443 
 444 
 445 bool methodOopDesc::is_initializer() const {
 446   return name() == vmSymbols::object_initializer_name() || name() == vmSymbols::class_initializer_name();
 447 }
 448 
 449 
 450 objArrayHandle methodOopDesc::resolved_checked_exceptions_impl(methodOop this_oop, TRAPS) {
 451   int length = this_oop->checked_exceptions_length();
 452   if (length == 0) {  // common case
 453     return objArrayHandle(THREAD, Universe::the_empty_class_klass_array());
 454   } else {
 455     methodHandle h_this(THREAD, this_oop);
 456     objArrayOop m_oop = oopFactory::new_objArray(SystemDictionary::class_klass(), length, CHECK_(objArrayHandle()));
 457     objArrayHandle mirrors (THREAD, m_oop);
 458     for (int i = 0; i < length; i++) {
 459       CheckedExceptionElement* table = h_this->checked_exceptions_start(); // recompute on each iteration, not gc safe
 460       klassOop k = h_this->constants()->klass_at(table[i].class_cp_index, CHECK_(objArrayHandle()));
 461       assert(Klass::cast(k)->is_subclass_of(SystemDictionary::throwable_klass()), "invalid exception class");
 462       mirrors->obj_at_put(i, Klass::cast(k)->java_mirror());
 463     }
 464     return mirrors;
 465   }
 466 };
 467 
 468 
 469 int methodOopDesc::line_number_from_bci(int bci) const {
 470   if (bci == SynchronizationEntryBCI) bci = 0;
 471   assert(bci == 0 || 0 <= bci && bci < code_size(), "illegal bci");
 472   int best_bci  =  0;
 473   int best_line = -1;
 474 
 475   if (has_linenumber_table()) {
 476     // The line numbers are a short array of 2-tuples [start_pc, line_number].
 477     // Not necessarily sorted and not necessarily one-to-one.
 478     CompressedLineNumberReadStream stream(compressed_linenumber_table());
 479     while (stream.read_pair()) {
 480       if (stream.bci() == bci) {
 481         // perfect match
 482         return stream.line();
 483       } else {
 484         // update best_bci/line
 485         if (stream.bci() < bci && stream.bci() >= best_bci) {
 486           best_bci  = stream.bci();
 487           best_line = stream.line();
 488         }
 489       }
 490     }
 491   }
 492   return best_line;
 493 }
 494 
 495 
 496 bool methodOopDesc::is_klass_loaded_by_klass_index(int klass_index) const {
 497   if( _constants->tag_at(klass_index).is_unresolved_klass() ) {
 498     Thread *thread = Thread::current();
 499     symbolHandle klass_name(thread, _constants->klass_name_at(klass_index));
 500     Handle loader(thread, instanceKlass::cast(method_holder())->class_loader());
 501     Handle prot  (thread, Klass::cast(method_holder())->protection_domain());
 502     return SystemDictionary::find(klass_name, loader, prot, thread) != NULL;
 503   } else {
 504     return true;
 505   }
 506 }
 507 
 508 
 509 bool methodOopDesc::is_klass_loaded(int refinfo_index, bool must_be_resolved) const {
 510   int klass_index = _constants->klass_ref_index_at(refinfo_index);
 511   if (must_be_resolved) {
 512     // Make sure klass is resolved in constantpool.   
 513     if (constants()->tag_at(klass_index).is_unresolved_klass()) return false;
 514   }  
 515   return is_klass_loaded_by_klass_index(klass_index);
 516 }
 517 
 518 
 519 void methodOopDesc::set_native_function(address function, bool post_event_flag) {
 520   assert(function != NULL, "use clear_native_function to unregister natives");
 521   address* native_function = native_function_addr();
 522 
 523   // We can see racers trying to place the same native function into place. Once
 524   // is plenty. 
 525   address current = *native_function;
 526   if (current == function) return;
 527   if (post_event_flag && JvmtiExport::should_post_native_method_bind() &&
 528       function != NULL) {
 529     // native_method_throw_unsatisfied_link_error_entry() should only
 530     // be passed when post_event_flag is false.
 531     assert(function !=
 532       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 533       "post_event_flag mis-match");
 534 
 535     // post the bind event, and possible change the bind function
 536     JvmtiExport::post_native_method_bind(this, &function);
 537   }
 538   *native_function = function;
 539   // This function can be called more than once. We must make sure that we always
 540   // use the latest registered method -> check if a stub already has been generated.
 541   // If so, we have to make it not_entrant.
 542   nmethod* nm = code(); // Put it into local variable to guard against concurrent updates
 543   if (nm != NULL) {
 544     nm->make_not_entrant();
 545   }  
 546 }
 547 
 548 
 549 bool methodOopDesc::has_native_function() const {
 550   address func = native_function();
 551   return (func != NULL && func != SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
 552 }
 553 
 554 
 555 void methodOopDesc::clear_native_function() {
 556   set_native_function(
 557     SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 558     !native_bind_event_is_interesting);
 559   clear_code();
 560 }
 561 
 562 
 563 void methodOopDesc::set_signature_handler(address handler) { 
 564   address* signature_handler =  signature_handler_addr();
 565   *signature_handler = handler;
 566 }
 567 
 568 
 569 bool methodOopDesc::is_not_compilable(int comp_level) const {
 570   methodDataOop mdo = method_data();
 571   if (mdo != NULL
 572       && (uint)mdo->decompile_count() > (uint)PerMethodRecompilationCutoff) {
 573     // Since (uint)-1 is large, -1 really means 'no cutoff'.
 574     return true;
 575   }
 576 #ifdef COMPILER2
 577   if (is_tier1_compile(comp_level)) {
 578     if (is_not_tier1_compilable()) {
 579       return true;
 580     }
 581   }
 582 #endif // COMPILER2
 583   return (_invocation_counter.state() == InvocationCounter::wait_for_nothing)
 584           || (number_of_breakpoints() > 0);
 585 }
 586 
 587 // call this when compiler finds that this method is not compilable
 588 void methodOopDesc::set_not_compilable(int comp_level) {
 589   if ((TraceDeoptimization || LogCompilation) && (xtty != NULL)) {
 590     ttyLocker ttyl;
 591     xtty->begin_elem("make_not_compilable thread='%d'", (int) os::current_thread_id());
 592     xtty->method(methodOop(this));
 593     xtty->stamp();
 594     xtty->end_elem();
 595   }
 596 #ifdef COMPILER2
 597   if (is_tier1_compile(comp_level)) {
 598     set_not_tier1_compilable();
 599     return;
 600   }
 601 #endif /* COMPILER2 */
 602   assert(comp_level == CompLevel_highest_tier, "unexpected compilation level");
 603   invocation_counter()->set_state(InvocationCounter::wait_for_nothing);
 604   backedge_counter()->set_state(InvocationCounter::wait_for_nothing);
 605 }
 606 
 607 // Revert to using the interpreter and clear out the nmethod
 608 void methodOopDesc::clear_code() { 
 609   
 610   // this may be NULL if c2i adapters have not been made yet
 611   // Only should happen at allocate time.
 612   if (_adapter == NULL) {
 613     _from_compiled_entry    = NULL;
 614   } else {
 615     _from_compiled_entry    = _adapter->get_c2i_entry();
 616   }
 617   OrderAccess::storestore();
 618   _from_interpreted_entry = _i2i_entry;
 619   OrderAccess::storestore();
 620   _code = NULL;
 621 }
 622 
 623 // Called by class data sharing to remove any entry points (which are not shared)
 624 void methodOopDesc::unlink_method() {
 625   _code = NULL;
 626   _i2i_entry = NULL;
 627   _from_interpreted_entry = NULL;
 628   if (is_native()) {
 629     *native_function_addr() = NULL;
 630     set_signature_handler(NULL);
 631   }
 632   NOT_PRODUCT(set_compiled_invocation_count(0);)
 633   invocation_counter()->reset();
 634   backedge_counter()->reset();
 635   _adapter = NULL;
 636   _from_compiled_entry = NULL;
 637   assert(_method_data == NULL, "unexpected method data?");
 638   set_method_data(NULL);
 639   set_interpreter_throwout_count(0);
 640   set_interpreter_invocation_count(0);
 641   _highest_tier_compile = CompLevel_none;
 642 }
 643 
 644 // Called when the method_holder is getting linked. Setup entrypoints so the method
 645 // is ready to be called from interpreter, compiler, and vtables.
 646 void methodOopDesc::link_method(methodHandle h_method, TRAPS) {
 647   assert(_i2i_entry == NULL, "should only be called once");
 648   assert(_adapter == NULL, "init'd to NULL" );
 649   assert( _code == NULL, "nothing compiled yet" );
 650 
 651   // Setup interpreter entrypoint
 652   assert(this == h_method(), "wrong h_method()" );
 653   address entry = Interpreter::entry_for_method(h_method);
 654   assert(entry != NULL, "interpreter entry must be non-null");
 655   // Sets both _i2i_entry and _from_interpreted_entry
 656   set_interpreter_entry(entry);
 657   if (is_native()) {
 658     set_native_function(
 659       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 660       !native_bind_event_is_interesting);
 661   }
 662 
 663   // Setup compiler entrypoint.  This is made eagerly, so we do not need
 664   // special handling of vtables.  An alternative is to make adapters more
 665   // lazily by calling make_adapter() from from_compiled_entry() for the
 666   // normal calls.  For vtable calls life gets more complicated.  When a
 667   // call-site goes mega-morphic we need adapters in all methods which can be
 668   // called from the vtable.  We need adapters on such methods that get loaded
 669   // later.  Ditto for mega-morphic itable calls.  If this proves to be a
 670   // problem we'll make these lazily later.
 671   (void) make_adapters(h_method, CHECK);
 672 
 673   // ONLY USE the h_method now as make_adapter may have blocked
 674 
 675 }
 676 
 677 address methodOopDesc::make_adapters(methodHandle mh, TRAPS) {
 678   // Adapters for compiled code are made eagerly here.  They are fairly
 679   // small (generally < 100 bytes) and quick to make (and cached and shared)
 680   // so making them eagerly shouldn't be too expensive.
 681   AdapterHandlerEntry* adapter = AdapterHandlerLibrary::get_adapter(mh);
 682   if (adapter == NULL ) {
 683     THROW_0(vmSymbols::java_lang_OutOfMemoryError());
 684   }
 685 
 686   mh->set_adapter_entry(adapter);
 687   mh->_from_compiled_entry = adapter->get_c2i_entry();
 688   return adapter->get_c2i_entry();
 689 }
 690 
 691 // The verified_code_entry() must be called when a invoke is resolved
 692 // on this method.
 693 
 694 // It returns the compiled code entry point, after asserting not null.
 695 // This function is called after potential safepoints so that nmethod
 696 // or adapter that it points to is still live and valid.
 697 // This function must not hit a safepoint!
 698 address methodOopDesc::verified_code_entry() {
 699   debug_only(No_Safepoint_Verifier nsv;)
 700   assert(_from_compiled_entry != NULL, "must be set");
 701   return _from_compiled_entry;
 702 }
 703 
 704 // Check that if an nmethod ref exists, it has a backlink to this or no backlink at all
 705 // (could be racing a deopt).
 706 // Not inline to avoid circular ref.
 707 bool methodOopDesc::check_code() const {
 708   // cached in a register or local.  There's a race on the value of the field.
 709   nmethod *code = (nmethod *)OrderAccess::load_ptr_acquire(&_code);
 710   return code == NULL || (code->method() == NULL) || (code->method() == (methodOop)this && !code->is_osr_method()); 
 711 }
 712 
 713 // Install compiled code.  Instantly it can execute.
 714 void methodOopDesc::set_code(methodHandle mh, nmethod *code) { 
 715   assert( code, "use clear_code to remove code" );
 716   assert( mh->check_code(), "" );
 717 
 718   guarantee(mh->adapter() != NULL, "Adapter blob must already exist!");
 719 
 720   // These writes must happen in this order, because the interpreter will
 721   // directly jump to from_interpreted_entry which jumps to an i2c adapter
 722   // which jumps to _from_compiled_entry.
 723   mh->_code = code;          // Assign before allowing compiled code to exec
 724 
 725   int comp_level = code->comp_level();
 726   // In theory there could be a race here. In practice it is unlikely
 727   // and not worth worrying about.
 728   if (comp_level > highest_tier_compile()) {
 729     set_highest_tier_compile(comp_level);
 730   }
 731 
 732   OrderAccess::storestore();
 733   mh->_from_compiled_entry = code->verified_entry_point();
 734   OrderAccess::storestore();
 735   // Instantly compiled code can execute.
 736   mh->_from_interpreted_entry = mh->get_i2c_entry();
 737 
 738 }
 739 
 740 
 741 bool methodOopDesc::is_overridden_in(klassOop k) const {
 742   instanceKlass* ik = instanceKlass::cast(k);
 743 
 744   if (ik->is_interface()) return false;
 745 
 746   // If method is an interface, we skip it - except if it
 747   // is a miranda method
 748   if (instanceKlass::cast(method_holder())->is_interface()) {
 749     // Check that method is not a miranda method
 750     if (ik->lookup_method(name(), signature()) == NULL) {
 751       // No implementation exist - so miranda method
 752       return false;
 753     }
 754     return true;
 755   }  
 756 
 757   assert(ik->is_subclass_of(method_holder()), "should be subklass");
 758   assert(ik->vtable() != NULL, "vtable should exist");
 759   if (vtable_index() == nonvirtual_vtable_index) {
 760     return false;
 761   } else {
 762     methodOop vt_m = ik->method_at_vtable(vtable_index());
 763     return vt_m != methodOop(this);
 764   }
 765 }
 766 
 767 
 768 // give advice about whether this methodOop should be cached or not
 769 bool methodOopDesc::should_not_be_cached() const {
 770   if (is_old()) {
 771     // This method has been redefined. It is either EMCP or obsolete
 772     // and we don't want to cache it because that would pin the method
 773     // down and prevent it from being collectible if and when it
 774     // finishes executing.
 775     return true;
 776   }
 777 
 778   if (mark()->should_not_be_cached()) {
 779     // It is either not safe or not a good idea to cache this
 780     // method at this time because of the state of the embedded
 781     // markOop. See markOop.cpp for the gory details.
 782     return true;
 783   }
 784 
 785   // caching this method should be just fine
 786   return false;
 787 }
 788 
 789 
 790 methodHandle methodOopDesc:: clone_with_new_data(methodHandle m, u_char* new_code, int new_code_length,
 791                                                 u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS) {
 792   // Code below does not work for native methods - they should never get rewritten anyway
 793   assert(!m->is_native(), "cannot rewrite native methods");
 794   // Allocate new methodOop
 795   AccessFlags flags = m->access_flags();
 796   int checked_exceptions_len = m->checked_exceptions_length();
 797   int localvariable_len = m->localvariable_table_length();
 798   methodOop newm_oop = oopFactory::new_method(new_code_length, flags, new_compressed_linenumber_size, localvariable_len, checked_exceptions_len, CHECK_(methodHandle()));
 799   methodHandle newm (THREAD, newm_oop);
 800   int new_method_size = newm->method_size();
 801   // Create a shallow copy of methodOopDesc part, but be careful to preserve the new constMethodOop
 802   constMethodOop newcm = newm->constMethod();
 803   int new_const_method_size = newm->constMethod()->object_size();
 804   memcpy(newm(), m(), sizeof(methodOopDesc));
 805   // Create shallow copy of constMethodOopDesc, but be careful to preserve the methodOop
 806   memcpy(newcm, m->constMethod(), sizeof(constMethodOopDesc));
 807   // Reset correct method/const method, method size, and parameter info
 808   newcm->set_method(newm());
 809   newm->set_constMethod(newcm);
 810   assert(newcm->method() == newm(), "check");
 811   newm->constMethod()->set_code_size(new_code_length);
 812   newm->constMethod()->set_constMethod_size(new_const_method_size);
 813   newm->set_method_size(new_method_size);
 814   assert(newm->code_size() == new_code_length, "check");
 815   assert(newm->checked_exceptions_length() == checked_exceptions_len, "check");
 816   assert(newm->localvariable_table_length() == localvariable_len, "check");
 817   // Copy new byte codes
 818   memcpy(newm->code_base(), new_code, new_code_length);
 819   // Copy line number table
 820   if (new_compressed_linenumber_size > 0) {
 821     memcpy(newm->compressed_linenumber_table(),
 822            new_compressed_linenumber_table,
 823            new_compressed_linenumber_size);
 824   }
 825   // Copy checked_exceptions
 826   if (checked_exceptions_len > 0) {
 827     memcpy(newm->checked_exceptions_start(),
 828            m->checked_exceptions_start(),
 829            checked_exceptions_len * sizeof(CheckedExceptionElement));
 830   }
 831   // Copy local variable number table
 832   if (localvariable_len > 0) {
 833     memcpy(newm->localvariable_table_start(),
 834            m->localvariable_table_start(),
 835            localvariable_len * sizeof(LocalVariableTableElement));
 836   }
 837   return newm;
 838 }
 839 
 840 vmIntrinsics::ID methodOopDesc::compute_intrinsic_id() const {
 841   assert(vmIntrinsics::_none == 0, "correct coding of default case");
 842   const uintptr_t max_cache_uint = right_n_bits((int)(sizeof(_intrinsic_id_cache) * BitsPerByte));
 843   assert((uintptr_t)vmIntrinsics::ID_LIMIT <= max_cache_uint, "else fix cache size");
 844   // if loader is not the default loader (i.e., != NULL), we can't know the intrinsics
 845   // because we are not loading from core libraries
 846   if (instanceKlass::cast(method_holder())->class_loader() != NULL) return vmIntrinsics::_none;
 847 
 848   // see if the klass name is well-known:
 849   symbolOop klass_name    = instanceKlass::cast(method_holder())->name();
 850   vmSymbols::SID klass_id = vmSymbols::find_sid(klass_name);
 851   if (klass_id == vmSymbols::NO_SID)  return vmIntrinsics::_none;
 852 
 853   // ditto for method and signature:
 854   vmSymbols::SID  name_id = vmSymbols::find_sid(name());
 855   if (name_id  == vmSymbols::NO_SID)  return vmIntrinsics::_none;
 856   vmSymbols::SID   sig_id = vmSymbols::find_sid(signature());
 857   if (sig_id   == vmSymbols::NO_SID)  return vmIntrinsics::_none;
 858   jshort flags = access_flags().as_short();
 859 
 860   // A few slightly irregular cases:
 861   switch (klass_id) {
 862   case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_StrictMath):
 863     // Second chance: check in regular Math.
 864     switch (name_id) {
 865     case vmSymbols::VM_SYMBOL_ENUM_NAME(min_name):
 866     case vmSymbols::VM_SYMBOL_ENUM_NAME(max_name):
 867     case vmSymbols::VM_SYMBOL_ENUM_NAME(sqrt_name):
 868       // pretend it is the corresponding method in the non-strict class:
 869       klass_id = vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_Math);
 870       break;
 871     }
 872   }
 873 
 874   // return intrinsic id if any
 875   return vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
 876 }
 877 
 878 
 879 // These two methods are static since a GC may move the methodOopDesc
 880 bool methodOopDesc::load_signature_classes(methodHandle m, TRAPS) {
 881   bool sig_is_loaded = true;
 882   Handle class_loader(THREAD, instanceKlass::cast(m->method_holder())->class_loader());
 883   Handle protection_domain(THREAD, Klass::cast(m->method_holder())->protection_domain());
 884   symbolHandle signature(THREAD, m->signature());
 885   for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
 886     if (ss.is_object()) {
 887       symbolOop sym = ss.as_symbol(CHECK_(false));
 888       symbolHandle name (THREAD, sym);
 889       klassOop klass = SystemDictionary::resolve_or_null(name, class_loader,
 890                                              protection_domain, THREAD);
 891       // We are loading classes eagerly. If a ClassNotFoundException or
 892       // a LinkageError was generated, be sure to ignore it.
 893       if (HAS_PENDING_EXCEPTION) {
 894         if (PENDING_EXCEPTION->is_a(SystemDictionary::classNotFoundException_klass()) ||
 895             PENDING_EXCEPTION->is_a(SystemDictionary::linkageError_klass())) {
 896           CLEAR_PENDING_EXCEPTION;
 897         } else {
 898           return false;
 899         }
 900       }
 901       if( klass == NULL) { sig_is_loaded = false; }
 902     }
 903   }
 904   return sig_is_loaded;
 905 }
 906 
 907 bool methodOopDesc::has_unloaded_classes_in_signature(methodHandle m, TRAPS) {
 908   Handle class_loader(THREAD, instanceKlass::cast(m->method_holder())->class_loader());
 909   Handle protection_domain(THREAD, Klass::cast(m->method_holder())->protection_domain());
 910   symbolHandle signature(THREAD, m->signature());
 911   for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
 912     if (ss.type() == T_OBJECT) {
 913       symbolHandle name(THREAD, ss.as_symbol_or_null());
 914       if (name() == NULL) return true;   
 915       klassOop klass = SystemDictionary::find(name, class_loader, protection_domain, THREAD);
 916       if (klass == NULL) return true;
 917     }
 918   }
 919   return false;
 920 }
 921 
 922 // Exposed so field engineers can debug VM
 923 void methodOopDesc::print_short_name(outputStream* st) {
 924   ResourceMark rm;
 925 #ifdef PRODUCT
 926   st->print(" %s::", method_holder()->klass_part()->external_name());
 927 #else
 928   st->print(" %s::", method_holder()->klass_part()->internal_name());
 929 #endif
 930   name()->print_symbol_on(st);
 931   if (WizardMode) signature()->print_symbol_on(st);
 932 }
 933 
 934 
 935 extern "C" {
 936   static int method_compare(methodOop* a, methodOop* b) {
 937     return (*a)->name()->fast_compare((*b)->name());
 938   }
 939 
 940   // Prevent qsort from reordering a previous valid sort by
 941   // considering the address of the methodOops if two methods
 942   // would otherwise compare as equal.  Required to preserve
 943   // optimal access order in the shared archive.  Slower than
 944   // method_compare, only used for shared archive creation.
 945   static int method_compare_idempotent(methodOop* a, methodOop* b) {
 946     int i = method_compare(a, b);
 947     if (i != 0) return i;
 948     return ( a < b ? -1 : (a == b ? 0 : 1));
 949   }
 950 
 951   typedef int (*compareFn)(const void*, const void*);
 952 }
 953 
 954 
 955 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
 956 static void reorder_based_on_method_index(objArrayOop methods,
 957                                           objArrayOop annotations,
 958                                           GrowableArray<oop>* temp_array) {
 959   if (annotations == NULL) {
 960     return;
 961   }
 962 
 963   int length = methods->length();
 964   int i;
 965   // Copy to temp array
 966   temp_array->clear();
 967   for (i = 0; i < length; i++) {
 968     temp_array->append(annotations->obj_at(i));
 969   }
 970 
 971   // Copy back using old method indices
 972   for (i = 0; i < length; i++) {
 973     methodOop m = (methodOop) methods->obj_at(i);
 974     annotations->obj_at_put(i, temp_array->at(m->method_idnum()));
 975   }
 976 }
 977 
 978 
 979 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
 980 void methodOopDesc::sort_methods(objArrayOop methods,
 981                                  objArrayOop methods_annotations,
 982                                  objArrayOop methods_parameter_annotations,
 983                                  objArrayOop methods_default_annotations,
 984                                  bool idempotent) {
 985   int length = methods->length();
 986   if (length > 1) {
 987     bool do_annotations = false;
 988     if (methods_annotations != NULL ||
 989         methods_parameter_annotations != NULL ||
 990         methods_default_annotations != NULL) {
 991       do_annotations = true;
 992     }
 993     if (do_annotations) {
 994       // Remember current method ordering so we can reorder annotations
 995       for (int i = 0; i < length; i++) {
 996         methodOop m = (methodOop) methods->obj_at(i);
 997         m->set_method_idnum(i);
 998       }
 999     }
1000 
1001     // Use a simple bubble sort for small number of methods since
1002     // qsort requires a functional pointer call for each comparison.
1003     if (UseCompressedOops || length < 8) {
1004       bool sorted = true;
1005       for (int i=length-1; i>0; i--) {
1006         for (int j=0; j<i; j++) {
1007           methodOop m1 = (methodOop)methods->obj_at(j);
1008           methodOop m2 = (methodOop)methods->obj_at(j+1);
1009           if ((uintptr_t)m1->name() > (uintptr_t)m2->name()) {
1010             methods->obj_at_put(j, m2);
1011             methods->obj_at_put(j+1, m1);
1012             sorted = false;
1013           }
1014         }
1015         if (sorted) break;
1016           sorted = true;
1017       }
1018     } else {
1019       // XXX This doesn't work for UseCompressedOops because the compare fn
1020       // will have to decode the methodOop anyway making it not much faster
1021       // than above.
1022       compareFn compare = (compareFn) (idempotent ? method_compare_idempotent : method_compare);
1023       qsort(methods->base(), length, heapOopSize, compare);
1024     }
1025     
1026     // Sort annotations if necessary
1027     assert(methods_annotations == NULL           || methods_annotations->length() == methods->length(), "");
1028     assert(methods_parameter_annotations == NULL || methods_parameter_annotations->length() == methods->length(), "");
1029     assert(methods_default_annotations == NULL   || methods_default_annotations->length() == methods->length(), "");
1030     if (do_annotations) {
1031       ResourceMark rm;
1032       // Allocate temporary storage
1033       GrowableArray<oop>* temp_array = new GrowableArray<oop>(length);
1034       reorder_based_on_method_index(methods, methods_annotations, temp_array);
1035       reorder_based_on_method_index(methods, methods_parameter_annotations, temp_array);
1036       reorder_based_on_method_index(methods, methods_default_annotations, temp_array);
1037     }
1038 
1039     // Reset method ordering
1040     for (int i = 0; i < length; i++) {
1041       methodOop m = (methodOop) methods->obj_at(i);
1042       m->set_method_idnum(i);
1043     }
1044   }
1045 }
1046 
1047 
1048 //-----------------------------------------------------------------------------------
1049 // Non-product code
1050 
1051 #ifndef PRODUCT
1052 class SignatureTypePrinter : public SignatureTypeNames {
1053  private:
1054   outputStream* _st;
1055   bool _use_separator;
1056 
1057   void type_name(const char* name) {
1058     if (_use_separator) _st->print(", ");
1059     _st->print(name);
1060     _use_separator = true;
1061   }
1062 
1063  public:
1064   SignatureTypePrinter(symbolHandle signature, outputStream* st) : SignatureTypeNames(signature) {
1065     _st = st;
1066     _use_separator = false;
1067   }
1068 
1069   void print_parameters()              { _use_separator = false; iterate_parameters(); }
1070   void print_returntype()              { _use_separator = false; iterate_returntype(); }
1071 };
1072 
1073 
1074 void methodOopDesc::print_name(outputStream* st) {
1075   Thread *thread = Thread::current();
1076   ResourceMark rm(thread);
1077   SignatureTypePrinter sig(signature(), st);
1078   st->print("%s ", is_static() ? "static" : "virtual");
1079   sig.print_returntype();
1080   st->print(" %s.", method_holder()->klass_part()->internal_name());
1081   name()->print_symbol_on(st);
1082   st->print("(");
1083   sig.print_parameters();
1084   st->print(")");
1085 }
1086 
1087 
1088 void methodOopDesc::print_codes_on(outputStream* st) const {
1089   print_codes_on(0, code_size(), st);
1090 }
1091 
1092 void methodOopDesc::print_codes_on(int from, int to, outputStream* st) const {
1093   Thread *thread = Thread::current();
1094   ResourceMark rm(thread);
1095   methodHandle mh (thread, (methodOop)this);
1096   BytecodeStream s(mh);
1097   s.set_interval(from, to);
1098   BytecodeTracer::set_closure(BytecodeTracer::std_closure());
1099   while (s.next() >= 0) BytecodeTracer::trace(mh, s.bcp(), st);
1100 }
1101 #endif // not PRODUCT
1102 
1103 
1104 // Simple compression of line number tables. We use a regular compressed stream, except that we compress deltas
1105 // between (bci,line) pairs since they are smaller. If (bci delta, line delta) fits in (5-bit unsigned, 3-bit unsigned)
1106 // we save it as one byte, otherwise we write a 0xFF escape character and use regular compression. 0x0 is used
1107 // as end-of-stream terminator.
1108 
1109 void CompressedLineNumberWriteStream::write_pair_regular(int bci_delta, int line_delta) {
1110   // bci and line number does not compress into single byte.
1111   // Write out escape character and use regular compression for bci and line number.
1112   write_byte((jubyte)0xFF);
1113   write_signed_int(bci_delta);
1114   write_signed_int(line_delta);
1115 }
1116 
1117 // See comment in methodOop.hpp which explains why this exists.
1118 #if defined(_M_AMD64) && MSC_VER >= 1400
1119 #pragma optimize("", off)
1120 void CompressedLineNumberWriteStream::write_pair(int bci, int line) {
1121   write_pair_inline(bci, line);
1122 }
1123 #pragma optimize("", on)
1124 #endif
1125 
1126 CompressedLineNumberReadStream::CompressedLineNumberReadStream(u_char* buffer) : CompressedReadStream(buffer) {
1127   _bci = 0;
1128   _line = 0;
1129 };
1130 
1131 
1132 bool CompressedLineNumberReadStream::read_pair() {
1133   jubyte next = read_byte();
1134   // Check for terminator
1135   if (next == 0) return false;
1136   if (next == 0xFF) {
1137     // Escape character, regular compression used
1138     _bci  += read_signed_int();
1139     _line += read_signed_int();
1140   } else {
1141     // Single byte compression used
1142     _bci  += next >> 3;
1143     _line += next & 0x7;
1144   }
1145   return true;
1146 }
1147 
1148 
1149 Bytecodes::Code methodOopDesc::orig_bytecode_at(int bci) {
1150   BreakpointInfo* bp = instanceKlass::cast(method_holder())->breakpoints();
1151   for (; bp != NULL; bp = bp->next()) {
1152     if (bp->match(this, bci)) {
1153       return bp->orig_bytecode();
1154     }
1155   }
1156   ShouldNotReachHere();
1157   return Bytecodes::_shouldnotreachhere;
1158 }
1159 
1160 void methodOopDesc::set_orig_bytecode_at(int bci, Bytecodes::Code code) {
1161   assert(code != Bytecodes::_breakpoint, "cannot patch breakpoints this way");
1162   BreakpointInfo* bp = instanceKlass::cast(method_holder())->breakpoints();
1163   for (; bp != NULL; bp = bp->next()) {
1164     if (bp->match(this, bci)) {
1165       bp->set_orig_bytecode(code);
1166       // and continue, in case there is more than one
1167     }
1168   }
1169 }
1170 
1171 void methodOopDesc::set_breakpoint(int bci) {
1172   instanceKlass* ik = instanceKlass::cast(method_holder());
1173   BreakpointInfo *bp = new BreakpointInfo(this, bci);
1174   bp->set_next(ik->breakpoints());
1175   ik->set_breakpoints(bp);
1176   // do this last:
1177   bp->set(this);
1178 }
1179 
1180 static void clear_matches(methodOop m, int bci) {
1181   instanceKlass* ik = instanceKlass::cast(m->method_holder());
1182   BreakpointInfo* prev_bp = NULL;
1183   BreakpointInfo* next_bp;
1184   for (BreakpointInfo* bp = ik->breakpoints(); bp != NULL; bp = next_bp) {
1185     next_bp = bp->next();
1186     // bci value of -1 is used to delete all breakpoints in method m (ex: clear_all_breakpoint).
1187     if (bci >= 0 ? bp->match(m, bci) : bp->match(m)) {
1188       // do this first:
1189       bp->clear(m);
1190       // unhook it
1191       if (prev_bp != NULL)
1192         prev_bp->set_next(next_bp);
1193       else
1194         ik->set_breakpoints(next_bp);
1195       delete bp;
1196       // When class is redefined JVMTI sets breakpoint in all versions of EMCP methods
1197       // at same location. So we have multiple matching (method_index and bci)
1198       // BreakpointInfo nodes in BreakpointInfo list. We should just delete one
1199       // breakpoint for clear_breakpoint request and keep all other method versions
1200       // BreakpointInfo for future clear_breakpoint request.
1201       // bcivalue of -1 is used to clear all breakpoints (see clear_all_breakpoints)
1202       // which is being called when class is unloaded. We delete all the Breakpoint
1203       // information for all versions of method. We may not correctly restore the original
1204       // bytecode in all method versions, but that is ok. Because the class is being unloaded
1205       // so these methods won't be used anymore.
1206       if (bci >= 0) {
1207         break;
1208       }
1209     } else {
1210       // This one is a keeper.
1211       prev_bp = bp;
1212     }
1213   }
1214 }
1215 
1216 void methodOopDesc::clear_breakpoint(int bci) {
1217   assert(bci >= 0, "");
1218   clear_matches(this, bci);
1219 }
1220 
1221 void methodOopDesc::clear_all_breakpoints() {
1222   clear_matches(this, -1);
1223 }
1224 
1225 
1226 BreakpointInfo::BreakpointInfo(methodOop m, int bci) {
1227   _bci = bci;
1228   _name_index = m->name_index();
1229   _signature_index = m->signature_index();
1230   _orig_bytecode = (Bytecodes::Code) *m->bcp_from(_bci);
1231   if (_orig_bytecode == Bytecodes::_breakpoint)
1232     _orig_bytecode = m->orig_bytecode_at(_bci);
1233   _next = NULL;
1234 }
1235 
1236 void BreakpointInfo::set(methodOop method) {
1237 #ifdef ASSERT
1238   {
1239     Bytecodes::Code code = (Bytecodes::Code) *method->bcp_from(_bci);
1240     if (code == Bytecodes::_breakpoint)
1241       code = method->orig_bytecode_at(_bci);
1242     assert(orig_bytecode() == code, "original bytecode must be the same");
1243   }
1244 #endif
1245   *method->bcp_from(_bci) = Bytecodes::_breakpoint;
1246   method->incr_number_of_breakpoints();
1247   SystemDictionary::notice_modification();
1248   {
1249     // Deoptimize all dependents on this method
1250     Thread *thread = Thread::current();
1251     HandleMark hm(thread);
1252     methodHandle mh(thread, method);
1253     Universe::flush_dependents_on_method(mh);
1254   }
1255 }
1256 
1257 void BreakpointInfo::clear(methodOop method) {
1258   *method->bcp_from(_bci) = orig_bytecode();
1259   assert(method->number_of_breakpoints() > 0, "must not go negative");
1260   method->decr_number_of_breakpoints();
1261 }