1 /*
   2  * Copyright (c) 1997, 2012, 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/systemDictionary.hpp"
  27 #include "code/debugInfoRec.hpp"
  28 #include "gc_interface/collectedHeap.inline.hpp"
  29 #include "interpreter/bytecodeStream.hpp"
  30 #include "interpreter/bytecodeTracer.hpp"
  31 #include "interpreter/bytecodes.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "interpreter/oopMapCache.hpp"
  34 #include "memory/gcLocker.hpp"
  35 #include "memory/generation.hpp"
  36 #include "memory/oopFactory.hpp"
  37 #include "oops/klassOop.hpp"
  38 #include "oops/methodDataOop.hpp"
  39 #include "oops/methodOop.hpp"
  40 #include "oops/oop.inline.hpp"
  41 #include "oops/symbol.hpp"
  42 #include "prims/jvmtiExport.hpp"
  43 #include "prims/methodHandleWalk.hpp"
  44 #include "prims/nativeLookup.hpp"
  45 #include "runtime/arguments.hpp"
  46 #include "runtime/compilationPolicy.hpp"
  47 #include "runtime/frame.inline.hpp"
  48 #include "runtime/handles.inline.hpp"
  49 #include "runtime/relocator.hpp"
  50 #include "runtime/sharedRuntime.hpp"
  51 #include "runtime/signature.hpp"
  52 #include "utilities/quickSort.hpp"
  53 #include "utilities/xmlstream.hpp"
  54 
  55 
  56 // Implementation of methodOopDesc
  57 
  58 address methodOopDesc::get_i2c_entry() {
  59   assert(_adapter != NULL, "must have");
  60   return _adapter->get_i2c_entry();
  61 }
  62 
  63 address methodOopDesc::get_c2i_entry() {
  64   assert(_adapter != NULL, "must have");
  65   return _adapter->get_c2i_entry();
  66 }
  67 
  68 address methodOopDesc::get_c2i_unverified_entry() {
  69   assert(_adapter != NULL, "must have");
  70   return _adapter->get_c2i_unverified_entry();
  71 }
  72 
  73 char* methodOopDesc::name_and_sig_as_C_string() const {
  74   return name_and_sig_as_C_string(Klass::cast(constants()->pool_holder()), name(), signature());
  75 }
  76 
  77 char* methodOopDesc::name_and_sig_as_C_string(char* buf, int size) const {
  78   return name_and_sig_as_C_string(Klass::cast(constants()->pool_holder()), name(), signature(), buf, size);
  79 }
  80 
  81 char* methodOopDesc::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature) {
  82   const char* klass_name = klass->external_name();
  83   int klass_name_len  = (int)strlen(klass_name);
  84   int method_name_len = method_name->utf8_length();
  85   int len             = klass_name_len + 1 + method_name_len + signature->utf8_length();
  86   char* dest          = NEW_RESOURCE_ARRAY(char, len + 1);
  87   strcpy(dest, klass_name);
  88   dest[klass_name_len] = '.';
  89   strcpy(&dest[klass_name_len + 1], method_name->as_C_string());
  90   strcpy(&dest[klass_name_len + 1 + method_name_len], signature->as_C_string());
  91   dest[len] = 0;
  92   return dest;
  93 }
  94 
  95 char* methodOopDesc::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature, char* buf, int size) {
  96   Symbol* klass_name = klass->name();
  97   klass_name->as_klass_external_name(buf, size);
  98   int len = (int)strlen(buf);
  99 
 100   if (len < size - 1) {
 101     buf[len++] = '.';
 102 
 103     method_name->as_C_string(&(buf[len]), size - len);
 104     len = (int)strlen(buf);
 105 
 106     signature->as_C_string(&(buf[len]), size - len);
 107   }
 108 
 109   return buf;
 110 }
 111 
 112 int  methodOopDesc::fast_exception_handler_bci_for(KlassHandle ex_klass, int throw_bci, TRAPS) {
 113   // exception table holds quadruple entries of the form (beg_bci, end_bci, handler_bci, klass_index)
 114   // access exception table
 115   ExceptionTable table(this);
 116   int length = table.length();
 117   // iterate through all entries sequentially
 118   constantPoolHandle pool(THREAD, constants());
 119   for (int i = 0; i < length; i ++) {
 120     //reacquire the table in case a GC happened
 121     ExceptionTable table(this);
 122     int beg_bci = table.start_pc(i);
 123     int end_bci = table.end_pc(i);
 124     assert(beg_bci <= end_bci, "inconsistent exception table");
 125     if (beg_bci <= throw_bci && throw_bci < end_bci) {
 126       // exception handler bci range covers throw_bci => investigate further
 127       int handler_bci = table.handler_pc(i);
 128       int klass_index = table.catch_type_index(i);
 129       if (klass_index == 0) {
 130         return handler_bci;
 131       } else if (ex_klass.is_null()) {
 132         return handler_bci;
 133       } else {
 134         // we know the exception class => get the constraint class
 135         // this may require loading of the constraint class; if verification
 136         // fails or some other exception occurs, return handler_bci
 137         klassOop k = pool->klass_at(klass_index, CHECK_(handler_bci));
 138         KlassHandle klass = KlassHandle(THREAD, k);
 139         assert(klass.not_null(), "klass not loaded");
 140         if (ex_klass->is_subtype_of(klass())) {
 141           return handler_bci;
 142         }
 143       }
 144     }
 145   }
 146 
 147   return -1;
 148 }
 149 
 150 void methodOopDesc::mask_for(int bci, InterpreterOopMap* mask) {
 151 
 152   Thread* myThread    = Thread::current();
 153   methodHandle h_this(myThread, this);
 154 #ifdef ASSERT
 155   bool has_capability = myThread->is_VM_thread() ||
 156                         myThread->is_ConcurrentGC_thread() ||
 157                         myThread->is_GC_task_thread();
 158 
 159   if (!has_capability) {
 160     if (!VerifyStack && !VerifyLastFrame) {
 161       // verify stack calls this outside VM thread
 162       warning("oopmap should only be accessed by the "
 163               "VM, GC task or CMS threads (or during debugging)");
 164       InterpreterOopMap local_mask;
 165       instanceKlass::cast(method_holder())->mask_for(h_this, bci, &local_mask);
 166       local_mask.print();
 167     }
 168   }
 169 #endif
 170   instanceKlass::cast(method_holder())->mask_for(h_this, bci, mask);
 171   return;
 172 }
 173 
 174 
 175 int methodOopDesc::bci_from(address bcp) const {
 176   assert(is_native() && bcp == code_base() || contains(bcp) || is_error_reported(),
 177          err_msg("bcp doesn't belong to this method: bcp: " INTPTR_FORMAT ", method: %s", bcp, name_and_sig_as_C_string()));
 178   return bcp - code_base();
 179 }
 180 
 181 
 182 // Return (int)bcx if it appears to be a valid BCI.
 183 // Return bci_from((address)bcx) if it appears to be a valid BCP.
 184 // Return -1 otherwise.
 185 // Used by profiling code, when invalid data is a possibility.
 186 // The caller is responsible for validating the methodOop itself.
 187 int methodOopDesc::validate_bci_from_bcx(intptr_t bcx) const {
 188   // keep bci as -1 if not a valid bci
 189   int bci = -1;
 190   if (bcx == 0 || (address)bcx == code_base()) {
 191     // code_size() may return 0 and we allow 0 here
 192     // the method may be native
 193     bci = 0;
 194   } else if (frame::is_bci(bcx)) {
 195     if (bcx < code_size()) {
 196       bci = (int)bcx;
 197     }
 198   } else if (contains((address)bcx)) {
 199     bci = (address)bcx - code_base();
 200   }
 201   // Assert that if we have dodged any asserts, bci is negative.
 202   assert(bci == -1 || bci == bci_from(bcp_from(bci)), "sane bci if >=0");
 203   return bci;
 204 }
 205 
 206 address methodOopDesc::bcp_from(int bci) const {
 207   assert((is_native() && bci == 0)  || (!is_native() && 0 <= bci && bci < code_size()), "illegal bci");
 208   address bcp = code_base() + bci;
 209   assert(is_native() && bcp == code_base() || contains(bcp), "bcp doesn't belong to this method");
 210   return bcp;
 211 }
 212 
 213 
 214 int methodOopDesc::object_size(bool is_native) {
 215   // If native, then include pointers for native_function and signature_handler
 216   int extra_bytes = (is_native) ? 2*sizeof(address*) : 0;
 217   int extra_words = align_size_up(extra_bytes, BytesPerWord) / BytesPerWord;
 218   return align_object_size(header_size() + extra_words);
 219 }
 220 
 221 
 222 Symbol* methodOopDesc::klass_name() const {
 223   klassOop k = method_holder();
 224   assert(k->is_klass(), "must be klass");
 225   instanceKlass* ik = (instanceKlass*) k->klass_part();
 226   return ik->name();
 227 }
 228 
 229 
 230 void methodOopDesc::set_interpreter_kind() {
 231   int kind = Interpreter::method_kind(methodOop(this));
 232   assert(kind != Interpreter::invalid,
 233          "interpreter entry must be valid");
 234   set_interpreter_kind(kind);
 235 }
 236 
 237 
 238 // Attempt to return method oop to original state.  Clear any pointers
 239 // (to objects outside the shared spaces).  We won't be able to predict
 240 // where they should point in a new JVM.  Further initialize some
 241 // entries now in order allow them to be write protected later.
 242 
 243 void methodOopDesc::remove_unshareable_info() {
 244   unlink_method();
 245   set_interpreter_kind();
 246 }
 247 
 248 
 249 bool methodOopDesc::was_executed_more_than(int n) {
 250   // Invocation counter is reset when the methodOop is compiled.
 251   // If the method has compiled code we therefore assume it has
 252   // be excuted more than n times.
 253   if (is_accessor() || is_empty_method() || (code() != NULL)) {
 254     // interpreter doesn't bump invocation counter of trivial methods
 255     // compiler does not bump invocation counter of compiled methods
 256     return true;
 257   }
 258   else if (_invocation_counter.carry() || (method_data() != NULL && method_data()->invocation_counter()->carry())) {
 259     // The carry bit is set when the counter overflows and causes
 260     // a compilation to occur.  We don't know how many times
 261     // the counter has been reset, so we simply assume it has
 262     // been executed more than n times.
 263     return true;
 264   } else {
 265     return invocation_count() > n;
 266   }
 267 }
 268 
 269 #ifndef PRODUCT
 270 void methodOopDesc::print_invocation_count() {
 271   if (is_static()) tty->print("static ");
 272   if (is_final()) tty->print("final ");
 273   if (is_synchronized()) tty->print("synchronized ");
 274   if (is_native()) tty->print("native ");
 275   method_holder()->klass_part()->name()->print_symbol_on(tty);
 276   tty->print(".");
 277   name()->print_symbol_on(tty);
 278   signature()->print_symbol_on(tty);
 279 
 280   if (WizardMode) {
 281     // dump the size of the byte codes
 282     tty->print(" {%d}", code_size());
 283   }
 284   tty->cr();
 285 
 286   tty->print_cr ("  interpreter_invocation_count: %8d ", interpreter_invocation_count());
 287   tty->print_cr ("  invocation_counter:           %8d ", invocation_count());
 288   tty->print_cr ("  backedge_counter:             %8d ", backedge_count());
 289   if (CountCompiledCalls) {
 290     tty->print_cr ("  compiled_invocation_count: %8d ", compiled_invocation_count());
 291   }
 292 
 293 }
 294 #endif
 295 
 296 // Build a methodDataOop object to hold information about this method
 297 // collected in the interpreter.
 298 void methodOopDesc::build_interpreter_method_data(methodHandle method, TRAPS) {
 299   // Do not profile method if current thread holds the pending list lock,
 300   // which avoids deadlock for acquiring the MethodData_lock.
 301   if (instanceRefKlass::owns_pending_list_lock((JavaThread*)THREAD)) {
 302     return;
 303   }
 304 
 305   // Grab a lock here to prevent multiple
 306   // methodDataOops from being created.
 307   MutexLocker ml(MethodData_lock, THREAD);
 308   if (method->method_data() == NULL) {
 309     methodDataOop method_data = oopFactory::new_methodData(method, CHECK);
 310     method->set_method_data(method_data);
 311     if (PrintMethodData && (Verbose || WizardMode)) {
 312       ResourceMark rm(THREAD);
 313       tty->print("build_interpreter_method_data for ");
 314       method->print_name(tty);
 315       tty->cr();
 316       // At the end of the run, the MDO, full of data, will be dumped.
 317     }
 318   }
 319 }
 320 
 321 void methodOopDesc::cleanup_inline_caches() {
 322   // The current system doesn't use inline caches in the interpreter
 323   // => nothing to do (keep this method around for future use)
 324 }
 325 
 326 
 327 int methodOopDesc::extra_stack_words() {
 328   // not an inline function, to avoid a header dependency on Interpreter
 329   return extra_stack_entries() * Interpreter::stackElementSize;
 330 }
 331 
 332 
 333 void methodOopDesc::compute_size_of_parameters(Thread *thread) {
 334   ArgumentSizeComputer asc(signature());
 335   set_size_of_parameters(asc.size() + (is_static() ? 0 : 1));
 336 }
 337 
 338 #ifdef CC_INTERP
 339 void methodOopDesc::set_result_index(BasicType type)          {
 340   _result_index = Interpreter::BasicType_as_index(type);
 341 }
 342 #endif
 343 
 344 BasicType methodOopDesc::result_type() const {
 345   ResultTypeFinder rtf(signature());
 346   return rtf.type();
 347 }
 348 
 349 
 350 bool methodOopDesc::is_empty_method() const {
 351   return  code_size() == 1
 352       && *code_base() == Bytecodes::_return;
 353 }
 354 
 355 
 356 bool methodOopDesc::is_vanilla_constructor() const {
 357   // Returns true if this method is a vanilla constructor, i.e. an "<init>" "()V" method
 358   // which only calls the superclass vanilla constructor and possibly does stores of
 359   // zero constants to local fields:
 360   //
 361   //   aload_0
 362   //   invokespecial
 363   //   indexbyte1
 364   //   indexbyte2
 365   //
 366   // followed by an (optional) sequence of:
 367   //
 368   //   aload_0
 369   //   aconst_null / iconst_0 / fconst_0 / dconst_0
 370   //   putfield
 371   //   indexbyte1
 372   //   indexbyte2
 373   //
 374   // followed by:
 375   //
 376   //   return
 377 
 378   assert(name() == vmSymbols::object_initializer_name(),    "Should only be called for default constructors");
 379   assert(signature() == vmSymbols::void_method_signature(), "Should only be called for default constructors");
 380   int size = code_size();
 381   // Check if size match
 382   if (size == 0 || size % 5 != 0) return false;
 383   address cb = code_base();
 384   int last = size - 1;
 385   if (cb[0] != Bytecodes::_aload_0 || cb[1] != Bytecodes::_invokespecial || cb[last] != Bytecodes::_return) {
 386     // Does not call superclass default constructor
 387     return false;
 388   }
 389   // Check optional sequence
 390   for (int i = 4; i < last; i += 5) {
 391     if (cb[i] != Bytecodes::_aload_0) return false;
 392     if (!Bytecodes::is_zero_const(Bytecodes::cast(cb[i+1]))) return false;
 393     if (cb[i+2] != Bytecodes::_putfield) return false;
 394   }
 395   return true;
 396 }
 397 
 398 
 399 bool methodOopDesc::compute_has_loops_flag() {
 400   BytecodeStream bcs(methodOop(this));
 401   Bytecodes::Code bc;
 402 
 403   while ((bc = bcs.next()) >= 0) {
 404     switch( bc ) {
 405       case Bytecodes::_ifeq:
 406       case Bytecodes::_ifnull:
 407       case Bytecodes::_iflt:
 408       case Bytecodes::_ifle:
 409       case Bytecodes::_ifne:
 410       case Bytecodes::_ifnonnull:
 411       case Bytecodes::_ifgt:
 412       case Bytecodes::_ifge:
 413       case Bytecodes::_if_icmpeq:
 414       case Bytecodes::_if_icmpne:
 415       case Bytecodes::_if_icmplt:
 416       case Bytecodes::_if_icmpgt:
 417       case Bytecodes::_if_icmple:
 418       case Bytecodes::_if_icmpge:
 419       case Bytecodes::_if_acmpeq:
 420       case Bytecodes::_if_acmpne:
 421       case Bytecodes::_goto:
 422       case Bytecodes::_jsr:
 423         if( bcs.dest() < bcs.next_bci() ) _access_flags.set_has_loops();
 424         break;
 425 
 426       case Bytecodes::_goto_w:
 427       case Bytecodes::_jsr_w:
 428         if( bcs.dest_w() < bcs.next_bci() ) _access_flags.set_has_loops();
 429         break;
 430     }
 431   }
 432   _access_flags.set_loops_flag_init();
 433   return _access_flags.has_loops();
 434 }
 435 
 436 
 437 bool methodOopDesc::is_final_method() const {
 438   // %%% Should return true for private methods also,
 439   // since there is no way to override them.
 440   return is_final() || Klass::cast(method_holder())->is_final();
 441 }
 442 
 443 
 444 bool methodOopDesc::is_strict_method() const {
 445   return is_strict();
 446 }
 447 
 448 
 449 bool methodOopDesc::can_be_statically_bound() const {
 450   if (is_final_method())  return true;
 451   return vtable_index() == nonvirtual_vtable_index;
 452 }
 453 
 454 
 455 bool methodOopDesc::is_accessor() const {
 456   if (code_size() != 5) return false;
 457   if (size_of_parameters() != 1) return false;
 458   if (java_code_at(0) != Bytecodes::_aload_0 ) return false;
 459   if (java_code_at(1) != Bytecodes::_getfield) return false;
 460   if (java_code_at(4) != Bytecodes::_areturn &&
 461       java_code_at(4) != Bytecodes::_ireturn ) return false;
 462   return true;
 463 }
 464 
 465 
 466 bool methodOopDesc::is_initializer() const {
 467   return name() == vmSymbols::object_initializer_name() || is_static_initializer();
 468 }
 469 
 470 bool methodOopDesc::has_valid_initializer_flags() const {
 471   return (is_static() ||
 472           instanceKlass::cast(method_holder())->major_version() < 51);
 473 }
 474 
 475 bool methodOopDesc::is_static_initializer() const {
 476   // For classfiles version 51 or greater, ensure that the clinit method is
 477   // static.  Non-static methods with the name "<clinit>" are not static
 478   // initializers. (older classfiles exempted for backward compatibility)
 479   return name() == vmSymbols::class_initializer_name() &&
 480          has_valid_initializer_flags();
 481 }
 482 
 483 
 484 objArrayHandle methodOopDesc::resolved_checked_exceptions_impl(methodOop this_oop, TRAPS) {
 485   int length = this_oop->checked_exceptions_length();
 486   if (length == 0) {  // common case
 487     return objArrayHandle(THREAD, Universe::the_empty_class_klass_array());
 488   } else {
 489     methodHandle h_this(THREAD, this_oop);
 490     objArrayOop m_oop = oopFactory::new_objArray(SystemDictionary::Class_klass(), length, CHECK_(objArrayHandle()));
 491     objArrayHandle mirrors (THREAD, m_oop);
 492     for (int i = 0; i < length; i++) {
 493       CheckedExceptionElement* table = h_this->checked_exceptions_start(); // recompute on each iteration, not gc safe
 494       klassOop k = h_this->constants()->klass_at(table[i].class_cp_index, CHECK_(objArrayHandle()));
 495       assert(Klass::cast(k)->is_subclass_of(SystemDictionary::Throwable_klass()), "invalid exception class");
 496       mirrors->obj_at_put(i, Klass::cast(k)->java_mirror());
 497     }
 498     return mirrors;
 499   }
 500 };
 501 
 502 
 503 int methodOopDesc::line_number_from_bci(int bci) const {
 504   if (bci == SynchronizationEntryBCI) bci = 0;
 505   assert(bci == 0 || 0 <= bci && bci < code_size(), "illegal bci");
 506   int best_bci  =  0;
 507   int best_line = -1;
 508 
 509   if (has_linenumber_table()) {
 510     // The line numbers are a short array of 2-tuples [start_pc, line_number].
 511     // Not necessarily sorted and not necessarily one-to-one.
 512     CompressedLineNumberReadStream stream(compressed_linenumber_table());
 513     while (stream.read_pair()) {
 514       if (stream.bci() == bci) {
 515         // perfect match
 516         return stream.line();
 517       } else {
 518         // update best_bci/line
 519         if (stream.bci() < bci && stream.bci() >= best_bci) {
 520           best_bci  = stream.bci();
 521           best_line = stream.line();
 522         }
 523       }
 524     }
 525   }
 526   return best_line;
 527 }
 528 
 529 
 530 bool methodOopDesc::is_klass_loaded_by_klass_index(int klass_index) const {
 531   if( constants()->tag_at(klass_index).is_unresolved_klass() ) {
 532     Thread *thread = Thread::current();
 533     Symbol* klass_name = constants()->klass_name_at(klass_index);
 534     Handle loader(thread, instanceKlass::cast(method_holder())->class_loader());
 535     Handle prot  (thread, Klass::cast(method_holder())->protection_domain());
 536     return SystemDictionary::find(klass_name, loader, prot, thread) != NULL;
 537   } else {
 538     return true;
 539   }
 540 }
 541 
 542 
 543 bool methodOopDesc::is_klass_loaded(int refinfo_index, bool must_be_resolved) const {
 544   int klass_index = constants()->klass_ref_index_at(refinfo_index);
 545   if (must_be_resolved) {
 546     // Make sure klass is resolved in constantpool.
 547     if (constants()->tag_at(klass_index).is_unresolved_klass()) return false;
 548   }
 549   return is_klass_loaded_by_klass_index(klass_index);
 550 }
 551 
 552 
 553 void methodOopDesc::set_native_function(address function, bool post_event_flag) {
 554   assert(function != NULL, "use clear_native_function to unregister natives");
 555   address* native_function = native_function_addr();
 556 
 557   // We can see racers trying to place the same native function into place. Once
 558   // is plenty.
 559   address current = *native_function;
 560   if (current == function) return;
 561   if (post_event_flag && JvmtiExport::should_post_native_method_bind() &&
 562       function != NULL) {
 563     // native_method_throw_unsatisfied_link_error_entry() should only
 564     // be passed when post_event_flag is false.
 565     assert(function !=
 566       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 567       "post_event_flag mis-match");
 568 
 569     // post the bind event, and possible change the bind function
 570     JvmtiExport::post_native_method_bind(this, &function);
 571   }
 572   *native_function = function;
 573   // This function can be called more than once. We must make sure that we always
 574   // use the latest registered method -> check if a stub already has been generated.
 575   // If so, we have to make it not_entrant.
 576   nmethod* nm = code(); // Put it into local variable to guard against concurrent updates
 577   if (nm != NULL) {
 578     nm->make_not_entrant();
 579   }
 580 }
 581 
 582 
 583 bool methodOopDesc::has_native_function() const {
 584   address func = native_function();
 585   return (func != NULL && func != SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
 586 }
 587 
 588 
 589 void methodOopDesc::clear_native_function() {
 590   set_native_function(
 591     SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 592     !native_bind_event_is_interesting);
 593   clear_code();
 594 }
 595 
 596 address methodOopDesc::critical_native_function() {
 597   methodHandle mh(this);
 598   return NativeLookup::lookup_critical_entry(mh);
 599 }
 600 
 601 
 602 void methodOopDesc::set_signature_handler(address handler) {
 603   address* signature_handler =  signature_handler_addr();
 604   *signature_handler = handler;
 605 }
 606 
 607 
 608 bool methodOopDesc::is_not_compilable(int comp_level) const {
 609   if (is_method_handle_invoke()) {
 610     // compilers must recognize this method specially, or not at all
 611     return true;
 612   }
 613   if (number_of_breakpoints() > 0) {
 614     return true;
 615   }
 616   if (comp_level == CompLevel_any) {
 617     return is_not_c1_compilable() || is_not_c2_compilable();
 618   }
 619   if (is_c1_compile(comp_level)) {
 620     return is_not_c1_compilable();
 621   }
 622   if (is_c2_compile(comp_level)) {
 623     return is_not_c2_compilable();
 624   }
 625   return false;
 626 }
 627 
 628 // call this when compiler finds that this method is not compilable
 629 void methodOopDesc::set_not_compilable(int comp_level, bool report) {
 630   if (PrintCompilation && report) {
 631     ttyLocker ttyl;
 632     tty->print("made not compilable ");
 633     this->print_short_name(tty);
 634     int size = this->code_size();
 635     if (size > 0)
 636       tty->print(" (%d bytes)", size);
 637     tty->cr();
 638   }
 639   if ((TraceDeoptimization || LogCompilation) && (xtty != NULL)) {
 640     ttyLocker ttyl;
 641     xtty->begin_elem("make_not_compilable thread='%d'", (int) os::current_thread_id());
 642     xtty->method(methodOop(this));
 643     xtty->stamp();
 644     xtty->end_elem();
 645   }
 646   if (comp_level == CompLevel_all) {
 647     set_not_c1_compilable();
 648     set_not_c2_compilable();
 649   } else {
 650     if (is_c1_compile(comp_level)) {
 651       set_not_c1_compilable();
 652     } else
 653       if (is_c2_compile(comp_level)) {
 654         set_not_c2_compilable();
 655       }
 656   }
 657   CompilationPolicy::policy()->disable_compilation(this);
 658 }
 659 
 660 // Revert to using the interpreter and clear out the nmethod
 661 void methodOopDesc::clear_code() {
 662 
 663   // this may be NULL if c2i adapters have not been made yet
 664   // Only should happen at allocate time.
 665   if (_adapter == NULL) {
 666     _from_compiled_entry    = NULL;
 667   } else {
 668     _from_compiled_entry    = _adapter->get_c2i_entry();
 669   }
 670   OrderAccess::storestore();
 671   _from_interpreted_entry = _i2i_entry;
 672   OrderAccess::storestore();
 673   _code = NULL;
 674 }
 675 
 676 // Called by class data sharing to remove any entry points (which are not shared)
 677 void methodOopDesc::unlink_method() {
 678   _code = NULL;
 679   _i2i_entry = NULL;
 680   _from_interpreted_entry = NULL;
 681   if (is_native()) {
 682     *native_function_addr() = NULL;
 683     set_signature_handler(NULL);
 684   }
 685   NOT_PRODUCT(set_compiled_invocation_count(0);)
 686   invocation_counter()->reset();
 687   backedge_counter()->reset();
 688   _adapter = NULL;
 689   _from_compiled_entry = NULL;
 690   assert(_method_data == NULL, "unexpected method data?");
 691   set_method_data(NULL);
 692   set_interpreter_throwout_count(0);
 693   set_interpreter_invocation_count(0);
 694 }
 695 
 696 // Called when the method_holder is getting linked. Setup entrypoints so the method
 697 // is ready to be called from interpreter, compiler, and vtables.
 698 void methodOopDesc::link_method(methodHandle h_method, TRAPS) {
 699   // If the code cache is full, we may reenter this function for the
 700   // leftover methods that weren't linked.
 701   if (_i2i_entry != NULL) return;
 702 
 703   assert(_adapter == NULL, "init'd to NULL" );
 704   assert( _code == NULL, "nothing compiled yet" );
 705 
 706   // Setup interpreter entrypoint
 707   assert(this == h_method(), "wrong h_method()" );
 708   address entry = Interpreter::entry_for_method(h_method);
 709   assert(entry != NULL, "interpreter entry must be non-null");
 710   // Sets both _i2i_entry and _from_interpreted_entry
 711   set_interpreter_entry(entry);
 712   if (is_native() && !is_method_handle_invoke()) {
 713     set_native_function(
 714       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 715       !native_bind_event_is_interesting);
 716   }
 717 
 718   // Setup compiler entrypoint.  This is made eagerly, so we do not need
 719   // special handling of vtables.  An alternative is to make adapters more
 720   // lazily by calling make_adapter() from from_compiled_entry() for the
 721   // normal calls.  For vtable calls life gets more complicated.  When a
 722   // call-site goes mega-morphic we need adapters in all methods which can be
 723   // called from the vtable.  We need adapters on such methods that get loaded
 724   // later.  Ditto for mega-morphic itable calls.  If this proves to be a
 725   // problem we'll make these lazily later.
 726   (void) make_adapters(h_method, CHECK);
 727 
 728   // ONLY USE the h_method now as make_adapter may have blocked
 729 
 730 }
 731 
 732 address methodOopDesc::make_adapters(methodHandle mh, TRAPS) {
 733   // Adapters for compiled code are made eagerly here.  They are fairly
 734   // small (generally < 100 bytes) and quick to make (and cached and shared)
 735   // so making them eagerly shouldn't be too expensive.
 736   AdapterHandlerEntry* adapter = AdapterHandlerLibrary::get_adapter(mh);
 737   if (adapter == NULL ) {
 738     THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(), "out of space in CodeCache for adapters");
 739   }
 740 
 741   mh->set_adapter_entry(adapter);
 742   mh->_from_compiled_entry = adapter->get_c2i_entry();
 743   return adapter->get_c2i_entry();
 744 }
 745 
 746 // The verified_code_entry() must be called when a invoke is resolved
 747 // on this method.
 748 
 749 // It returns the compiled code entry point, after asserting not null.
 750 // This function is called after potential safepoints so that nmethod
 751 // or adapter that it points to is still live and valid.
 752 // This function must not hit a safepoint!
 753 address methodOopDesc::verified_code_entry() {
 754   debug_only(No_Safepoint_Verifier nsv;)
 755   nmethod *code = (nmethod *)OrderAccess::load_ptr_acquire(&_code);
 756   if (code == NULL && UseCodeCacheFlushing) {
 757     nmethod *saved_code = CodeCache::find_and_remove_saved_code(this);
 758     if (saved_code != NULL) {
 759       methodHandle method(this);
 760       assert( ! saved_code->is_osr_method(), "should not get here for osr" );
 761       set_code( method, saved_code );
 762     }
 763   }
 764 
 765   assert(_from_compiled_entry != NULL, "must be set");
 766   return _from_compiled_entry;
 767 }
 768 
 769 // Check that if an nmethod ref exists, it has a backlink to this or no backlink at all
 770 // (could be racing a deopt).
 771 // Not inline to avoid circular ref.
 772 bool methodOopDesc::check_code() const {
 773   // cached in a register or local.  There's a race on the value of the field.
 774   nmethod *code = (nmethod *)OrderAccess::load_ptr_acquire(&_code);
 775   return code == NULL || (code->method() == NULL) || (code->method() == (methodOop)this && !code->is_osr_method());
 776 }
 777 
 778 // Install compiled code.  Instantly it can execute.
 779 void methodOopDesc::set_code(methodHandle mh, nmethod *code) {
 780   assert( code, "use clear_code to remove code" );
 781   assert( mh->check_code(), "" );
 782 
 783   guarantee(mh->adapter() != NULL, "Adapter blob must already exist!");
 784 
 785   // These writes must happen in this order, because the interpreter will
 786   // directly jump to from_interpreted_entry which jumps to an i2c adapter
 787   // which jumps to _from_compiled_entry.
 788   mh->_code = code;             // Assign before allowing compiled code to exec
 789 
 790   int comp_level = code->comp_level();
 791   // In theory there could be a race here. In practice it is unlikely
 792   // and not worth worrying about.
 793   if (comp_level > mh->highest_comp_level()) {
 794     mh->set_highest_comp_level(comp_level);
 795   }
 796 
 797   OrderAccess::storestore();
 798 #ifdef SHARK
 799   mh->_from_interpreted_entry = code->insts_begin();
 800 #else
 801   mh->_from_compiled_entry = code->verified_entry_point();
 802   OrderAccess::storestore();
 803   // Instantly compiled code can execute.
 804   mh->_from_interpreted_entry = mh->get_i2c_entry();
 805 #endif // SHARK
 806 
 807 }
 808 
 809 
 810 bool methodOopDesc::is_overridden_in(klassOop k) const {
 811   instanceKlass* ik = instanceKlass::cast(k);
 812 
 813   if (ik->is_interface()) return false;
 814 
 815   // If method is an interface, we skip it - except if it
 816   // is a miranda method
 817   if (instanceKlass::cast(method_holder())->is_interface()) {
 818     // Check that method is not a miranda method
 819     if (ik->lookup_method(name(), signature()) == NULL) {
 820       // No implementation exist - so miranda method
 821       return false;
 822     }
 823     return true;
 824   }
 825 
 826   assert(ik->is_subclass_of(method_holder()), "should be subklass");
 827   assert(ik->vtable() != NULL, "vtable should exist");
 828   if (vtable_index() == nonvirtual_vtable_index) {
 829     return false;
 830   } else {
 831     methodOop vt_m = ik->method_at_vtable(vtable_index());
 832     return vt_m != methodOop(this);
 833   }
 834 }
 835 
 836 
 837 // give advice about whether this methodOop should be cached or not
 838 bool methodOopDesc::should_not_be_cached() const {
 839   if (is_old()) {
 840     // This method has been redefined. It is either EMCP or obsolete
 841     // and we don't want to cache it because that would pin the method
 842     // down and prevent it from being collectible if and when it
 843     // finishes executing.
 844     return true;
 845   }
 846 
 847   if (mark()->should_not_be_cached()) {
 848     // It is either not safe or not a good idea to cache this
 849     // method at this time because of the state of the embedded
 850     // markOop. See markOop.cpp for the gory details.
 851     return true;
 852   }
 853 
 854   // caching this method should be just fine
 855   return false;
 856 }
 857 
 858 bool methodOopDesc::is_method_handle_invoke_name(vmSymbols::SID name_sid) {
 859   switch (name_sid) {
 860   case vmSymbols::VM_SYMBOL_ENUM_NAME(invokeExact_name):
 861   case vmSymbols::VM_SYMBOL_ENUM_NAME(invoke_name):
 862     return true;
 863   }
 864   if (AllowInvokeGeneric
 865       && name_sid == vmSymbols::VM_SYMBOL_ENUM_NAME(invokeGeneric_name))
 866     return true;
 867   return false;
 868 }
 869 
 870 // Constant pool structure for invoke methods:
 871 enum {
 872   _imcp_invoke_name = 1,        // utf8: 'invokeExact' or 'invokeGeneric'
 873   _imcp_invoke_signature,       // utf8: (variable Symbol*)
 874   _imcp_method_type_value,      // string: (variable java/lang/invoke/MethodType, sic)
 875   _imcp_limit
 876 };
 877 
 878 oop methodOopDesc::method_handle_type() const {
 879   if (!is_method_handle_invoke()) { assert(false, "caller resp."); return NULL; }
 880   oop mt = constants()->resolved_string_at(_imcp_method_type_value);
 881   assert(mt->klass() == SystemDictionary::MethodType_klass(), "");
 882   return mt;
 883 }
 884 
 885 jint* methodOopDesc::method_type_offsets_chain() {
 886   static jint pchase[] = { -1, -1, -1, -1 };
 887   if (pchase[0] == -1) {
 888     jint step0 = in_bytes(const_offset());
 889     jint step1 = in_bytes(constMethodOopDesc::constants_offset());
 890     jint step2 = (constantPoolOopDesc::header_size() + _imcp_method_type_value) * HeapWordSize;
 891     // do this in reverse to avoid races:
 892     OrderAccess::release_store(&pchase[2], step2);
 893     OrderAccess::release_store(&pchase[1], step1);
 894     OrderAccess::release_store(&pchase[0], step0);
 895   }
 896   return pchase;
 897 }
 898 
 899 //------------------------------------------------------------------------------
 900 // methodOopDesc::is_method_handle_adapter
 901 //
 902 // Tests if this method is an internal adapter frame from the
 903 // MethodHandleCompiler.
 904 // Must be consistent with MethodHandleCompiler::get_method_oop().
 905 bool methodOopDesc::is_method_handle_adapter() const {
 906   if (is_synthetic() &&
 907       !is_native() &&   // has code from MethodHandleCompiler
 908       is_method_handle_invoke_name(name()) &&
 909       MethodHandleCompiler::klass_is_method_handle_adapter_holder(method_holder())) {
 910     assert(!is_method_handle_invoke(), "disjoint");
 911     return true;
 912   } else {
 913     return false;
 914   }
 915 }
 916 
 917 methodHandle methodOopDesc::make_invoke_method(KlassHandle holder,
 918                                                Symbol* name,
 919                                                Symbol* signature,
 920                                                Handle method_type, TRAPS) {
 921   ResourceMark rm;
 922   methodHandle empty;
 923 
 924   assert(holder() == SystemDictionary::MethodHandle_klass(),
 925          "must be a JSR 292 magic type");
 926 
 927   if (TraceMethodHandles) {
 928     tty->print("Creating invoke method for ");
 929     signature->print_value();
 930     tty->cr();
 931   }
 932 
 933   // invariant:   cp->symbol_at_put is preceded by a refcount increment (more usually a lookup)
 934   name->increment_refcount();
 935   signature->increment_refcount();
 936 
 937   // record non-BCP method types in the constant pool
 938   GrowableArray<KlassHandle>* extra_klasses = NULL;
 939   for (int i = -1, len = java_lang_invoke_MethodType::ptype_count(method_type()); i < len; i++) {
 940     oop ptype = (i == -1
 941                  ? java_lang_invoke_MethodType::rtype(method_type())
 942                  : java_lang_invoke_MethodType::ptype(method_type(), i));
 943     klassOop klass = check_non_bcp_klass(java_lang_Class::as_klassOop(ptype));
 944     if (klass != NULL) {
 945       if (extra_klasses == NULL)
 946         extra_klasses = new GrowableArray<KlassHandle>(len+1);
 947       bool dup = false;
 948       for (int j = 0; j < extra_klasses->length(); j++) {
 949         if (extra_klasses->at(j) == klass) { dup = true; break; }
 950       }
 951       if (!dup)
 952         extra_klasses->append(KlassHandle(THREAD, klass));
 953     }
 954   }
 955 
 956   int extra_klass_count = (extra_klasses == NULL ? 0 : extra_klasses->length());
 957   int cp_length = _imcp_limit + extra_klass_count;
 958   constantPoolHandle cp;
 959   {
 960     constantPoolOop cp_oop = oopFactory::new_constantPool(cp_length, IsSafeConc, CHECK_(empty));
 961     cp = constantPoolHandle(THREAD, cp_oop);
 962   }
 963   cp->symbol_at_put(_imcp_invoke_name,       name);
 964   cp->symbol_at_put(_imcp_invoke_signature,  signature);
 965   cp->string_at_put(_imcp_method_type_value, Universe::the_null_string());
 966   for (int j = 0; j < extra_klass_count; j++) {
 967     KlassHandle klass = extra_klasses->at(j);
 968     cp->klass_at_put(_imcp_limit + j, klass());
 969   }
 970   cp->set_preresolution();
 971   cp->set_pool_holder(holder());
 972 
 973   // set up the fancy stuff:
 974   cp->pseudo_string_at_put(_imcp_method_type_value, method_type());
 975   methodHandle m;
 976   {
 977     int flags_bits = (JVM_MH_INVOKE_BITS | JVM_ACC_PUBLIC | JVM_ACC_FINAL);
 978     methodOop m_oop = oopFactory::new_method(0, accessFlags_from(flags_bits),
 979                                              0, 0, 0, 0, IsSafeConc, CHECK_(empty));
 980     m = methodHandle(THREAD, m_oop);
 981   }
 982   m->set_constants(cp());
 983   m->set_name_index(_imcp_invoke_name);
 984   m->set_signature_index(_imcp_invoke_signature);
 985   assert(is_method_handle_invoke_name(m->name()), "");
 986   assert(m->signature() == signature, "");
 987   assert(m->is_method_handle_invoke(), "");
 988 #ifdef CC_INTERP
 989   ResultTypeFinder rtf(signature);
 990   m->set_result_index(rtf.type());
 991 #endif
 992   m->compute_size_of_parameters(THREAD);
 993   m->init_intrinsic_id();
 994   assert(m->intrinsic_id() == vmIntrinsics::_invokeExact ||
 995          m->intrinsic_id() == vmIntrinsics::_invokeGeneric, "must be an invoker");
 996 
 997   // Finally, set up its entry points.
 998   assert(m->method_handle_type() == method_type(), "");
 999   assert(m->can_be_statically_bound(), "");
1000   m->set_vtable_index(methodOopDesc::nonvirtual_vtable_index);
1001   m->link_method(m, CHECK_(empty));
1002 
1003 #ifdef ASSERT
1004   // Make sure the pointer chase works.
1005   address p = (address) m();
1006   for (jint* pchase = method_type_offsets_chain(); (*pchase) != -1; pchase++) {
1007     p = *(address*)(p + (*pchase));
1008   }
1009   assert((oop)p == method_type(), "pointer chase is correct");
1010 #endif
1011 
1012   if (TraceMethodHandles && (Verbose || WizardMode))
1013     m->print_on(tty);
1014 
1015   return m;
1016 }
1017 
1018 klassOop methodOopDesc::check_non_bcp_klass(klassOop klass) {
1019   if (klass != NULL && Klass::cast(klass)->class_loader() != NULL) {
1020     if (Klass::cast(klass)->oop_is_objArray())
1021       klass = objArrayKlass::cast(klass)->bottom_klass();
1022     return klass;
1023   }
1024   return NULL;
1025 }
1026 
1027 
1028 methodHandle methodOopDesc:: clone_with_new_data(methodHandle m, u_char* new_code, int new_code_length,
1029                                                 u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS) {
1030   // Code below does not work for native methods - they should never get rewritten anyway
1031   assert(!m->is_native(), "cannot rewrite native methods");
1032   // Allocate new methodOop
1033   AccessFlags flags = m->access_flags();
1034   int checked_exceptions_len = m->checked_exceptions_length();
1035   int localvariable_len = m->localvariable_table_length();
1036   int exception_table_len = m->exception_table_length();
1037   // Allocate newm_oop with the is_conc_safe parameter set
1038   // to IsUnsafeConc to indicate that newm_oop is not yet
1039   // safe for concurrent processing by a GC.
1040   methodOop newm_oop = oopFactory::new_method(new_code_length,
1041                                               flags,
1042                                               new_compressed_linenumber_size,
1043                                               localvariable_len,
1044                                               exception_table_len,
1045                                               checked_exceptions_len,
1046                                               IsUnsafeConc,
1047                                               CHECK_(methodHandle()));
1048   methodHandle newm (THREAD, newm_oop);
1049   NOT_PRODUCT(int nmsz = newm->is_parsable() ? newm->size() : -1;)
1050   int new_method_size = newm->method_size();
1051   // Create a shallow copy of methodOopDesc part, but be careful to preserve the new constMethodOop
1052   constMethodOop newcm = newm->constMethod();
1053   NOT_PRODUCT(int ncmsz = newcm->is_parsable() ? newcm->size() : -1;)
1054   int new_const_method_size = newm->constMethod()->object_size();
1055 
1056   memcpy(newm(), m(), sizeof(methodOopDesc));
1057   // Create shallow copy of constMethodOopDesc, but be careful to preserve the methodOop
1058   // is_conc_safe is set to false because that is the value of
1059   // is_conc_safe initialzied into newcm and the copy should
1060   // not overwrite that value.  During the window during which it is
1061   // tagged as unsafe, some extra work could be needed during precleaning
1062   // or concurrent marking but those phases will be correct.  Setting and
1063   // resetting is done in preference to a careful copying into newcm to
1064   // avoid having to know the precise layout of a constMethodOop.
1065   m->constMethod()->set_is_conc_safe(oopDesc::IsUnsafeConc);
1066   assert(m->constMethod()->is_parsable(), "Should remain parsable");
1067 
1068   // NOTE: this is a reachable object that transiently signals "conc_unsafe"
1069   // However, no allocations are done during this window
1070   // during which it is tagged conc_unsafe, so we are assured that any concurrent
1071   // thread will not wait forever for the object to revert to "conc_safe".
1072   // Further, any such conc_unsafe object will indicate a stable size
1073   // through the transition.
1074   memcpy(newcm, m->constMethod(), sizeof(constMethodOopDesc));
1075   m->constMethod()->set_is_conc_safe(oopDesc::IsSafeConc);
1076   assert(m->constMethod()->is_parsable(), "Should remain parsable");
1077 
1078   // Reset correct method/const method, method size, and parameter info
1079   newm->set_constMethod(newcm);
1080   newm->constMethod()->set_code_size(new_code_length);
1081   newm->constMethod()->set_constMethod_size(new_const_method_size);
1082   newm->set_method_size(new_method_size);
1083   assert(newm->code_size() == new_code_length, "check");
1084   assert(newm->checked_exceptions_length() == checked_exceptions_len, "check");
1085   assert(newm->localvariable_table_length() == localvariable_len, "check");
1086   // Copy new byte codes
1087   memcpy(newm->code_base(), new_code, new_code_length);
1088   // Copy line number table
1089   if (new_compressed_linenumber_size > 0) {
1090     memcpy(newm->compressed_linenumber_table(),
1091            new_compressed_linenumber_table,
1092            new_compressed_linenumber_size);
1093   }
1094   // Copy checked_exceptions
1095   if (checked_exceptions_len > 0) {
1096     memcpy(newm->checked_exceptions_start(),
1097            m->checked_exceptions_start(),
1098            checked_exceptions_len * sizeof(CheckedExceptionElement));
1099   }
1100   // Copy local variable number table
1101   if (localvariable_len > 0) {
1102     memcpy(newm->localvariable_table_start(),
1103            m->localvariable_table_start(),
1104            localvariable_len * sizeof(LocalVariableTableElement));
1105   }
1106 
1107   // Only set is_conc_safe to true when changes to newcm are
1108   // complete.
1109   assert(!newm->is_parsable()  || nmsz  < 0 || newm->size()  == nmsz,  "newm->size()  inconsistency");
1110   assert(!newcm->is_parsable() || ncmsz < 0 || newcm->size() == ncmsz, "newcm->size() inconsistency");
1111   newcm->set_is_conc_safe(true);
1112   return newm;
1113 }
1114 
1115 vmSymbols::SID methodOopDesc::klass_id_for_intrinsics(klassOop holder) {
1116   // if loader is not the default loader (i.e., != NULL), we can't know the intrinsics
1117   // because we are not loading from core libraries
1118   if (instanceKlass::cast(holder)->class_loader() != NULL)
1119     return vmSymbols::NO_SID;   // regardless of name, no intrinsics here
1120 
1121   // see if the klass name is well-known:
1122   Symbol* klass_name = instanceKlass::cast(holder)->name();
1123   return vmSymbols::find_sid(klass_name);
1124 }
1125 
1126 void methodOopDesc::init_intrinsic_id() {
1127   assert(_intrinsic_id == vmIntrinsics::_none, "do this just once");
1128   const uintptr_t max_id_uint = right_n_bits((int)(sizeof(_intrinsic_id) * BitsPerByte));
1129   assert((uintptr_t)vmIntrinsics::ID_LIMIT <= max_id_uint, "else fix size");
1130   assert(intrinsic_id_size_in_bytes() == sizeof(_intrinsic_id), "");
1131 
1132   // the klass name is well-known:
1133   vmSymbols::SID klass_id = klass_id_for_intrinsics(method_holder());
1134   assert(klass_id != vmSymbols::NO_SID, "caller responsibility");
1135 
1136   // ditto for method and signature:
1137   vmSymbols::SID  name_id = vmSymbols::find_sid(name());
1138   if (name_id == vmSymbols::NO_SID)  return;
1139   vmSymbols::SID   sig_id = vmSymbols::find_sid(signature());
1140   if (klass_id != vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1141       && sig_id == vmSymbols::NO_SID)  return;
1142   jshort flags = access_flags().as_short();
1143 
1144   vmIntrinsics::ID id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
1145   if (id != vmIntrinsics::_none) {
1146     set_intrinsic_id(id);
1147     return;
1148   }
1149 
1150   // A few slightly irregular cases:
1151   switch (klass_id) {
1152   case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_StrictMath):
1153     // Second chance: check in regular Math.
1154     switch (name_id) {
1155     case vmSymbols::VM_SYMBOL_ENUM_NAME(min_name):
1156     case vmSymbols::VM_SYMBOL_ENUM_NAME(max_name):
1157     case vmSymbols::VM_SYMBOL_ENUM_NAME(sqrt_name):
1158       // pretend it is the corresponding method in the non-strict class:
1159       klass_id = vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_Math);
1160       id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
1161       break;
1162     }
1163     break;
1164 
1165   // Signature-polymorphic methods: MethodHandle.invoke*, InvokeDynamic.*.
1166   case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle):
1167     if (is_static() || !is_native())  break;
1168     switch (name_id) {
1169     case vmSymbols::VM_SYMBOL_ENUM_NAME(invokeGeneric_name):
1170       if (!AllowInvokeGeneric)  break;
1171     case vmSymbols::VM_SYMBOL_ENUM_NAME(invoke_name):
1172       id = vmIntrinsics::_invokeGeneric;
1173       break;
1174     case vmSymbols::VM_SYMBOL_ENUM_NAME(invokeExact_name):
1175       id = vmIntrinsics::_invokeExact;
1176       break;
1177     }
1178     break;
1179   case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_InvokeDynamic):
1180     if (!is_static() || !is_native())  break;
1181     id = vmIntrinsics::_invokeDynamic;
1182     break;
1183   }
1184 
1185   if (id != vmIntrinsics::_none) {
1186     // Set up its iid.  It is an alias method.
1187     set_intrinsic_id(id);
1188     return;
1189   }
1190 }
1191 
1192 // These two methods are static since a GC may move the methodOopDesc
1193 bool methodOopDesc::load_signature_classes(methodHandle m, TRAPS) {
1194   bool sig_is_loaded = true;
1195   Handle class_loader(THREAD, instanceKlass::cast(m->method_holder())->class_loader());
1196   Handle protection_domain(THREAD, Klass::cast(m->method_holder())->protection_domain());
1197   ResourceMark rm(THREAD);
1198   Symbol*  signature = m->signature();
1199   for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
1200     if (ss.is_object()) {
1201       Symbol* sym = ss.as_symbol(CHECK_(false));
1202       Symbol*  name  = sym;
1203       klassOop klass = SystemDictionary::resolve_or_null(name, class_loader,
1204                                              protection_domain, THREAD);
1205       // We are loading classes eagerly. If a ClassNotFoundException or
1206       // a LinkageError was generated, be sure to ignore it.
1207       if (HAS_PENDING_EXCEPTION) {
1208         if (PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass()) ||
1209             PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
1210           CLEAR_PENDING_EXCEPTION;
1211         } else {
1212           return false;
1213         }
1214       }
1215       if( klass == NULL) { sig_is_loaded = false; }
1216     }
1217   }
1218   return sig_is_loaded;
1219 }
1220 
1221 bool methodOopDesc::has_unloaded_classes_in_signature(methodHandle m, TRAPS) {
1222   Handle class_loader(THREAD, instanceKlass::cast(m->method_holder())->class_loader());
1223   Handle protection_domain(THREAD, Klass::cast(m->method_holder())->protection_domain());
1224   ResourceMark rm(THREAD);
1225   Symbol*  signature = m->signature();
1226   for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
1227     if (ss.type() == T_OBJECT) {
1228       Symbol* name = ss.as_symbol_or_null();
1229       if (name == NULL) return true;
1230       klassOop klass = SystemDictionary::find(name, class_loader, protection_domain, THREAD);
1231       if (klass == NULL) return true;
1232     }
1233   }
1234   return false;
1235 }
1236 
1237 // Exposed so field engineers can debug VM
1238 void methodOopDesc::print_short_name(outputStream* st) {
1239   ResourceMark rm;
1240 #ifdef PRODUCT
1241   st->print(" %s::", method_holder()->klass_part()->external_name());
1242 #else
1243   st->print(" %s::", method_holder()->klass_part()->internal_name());
1244 #endif
1245   name()->print_symbol_on(st);
1246   if (WizardMode) signature()->print_symbol_on(st);
1247 }
1248 
1249 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
1250 static void reorder_based_on_method_index(objArrayOop methods,
1251                                           objArrayOop annotations,
1252                                           GrowableArray<oop>* temp_array) {
1253   if (annotations == NULL) {
1254     return;
1255   }
1256 
1257   int length = methods->length();
1258   int i;
1259   // Copy to temp array
1260   temp_array->clear();
1261   for (i = 0; i < length; i++) {
1262     temp_array->append(annotations->obj_at(i));
1263   }
1264 
1265   // Copy back using old method indices
1266   for (i = 0; i < length; i++) {
1267     methodOop m = (methodOop) methods->obj_at(i);
1268     annotations->obj_at_put(i, temp_array->at(m->method_idnum()));
1269   }
1270 }
1271 
1272 // Comparer for sorting an object array containing
1273 // methodOops.
1274 // Used non-template method_comparator methods since
1275 // Visual Studio 2003 compiler generates incorrect
1276 // optimized code for it.
1277 static int method_comparator_narrowOop(narrowOop a, narrowOop b) {
1278   methodOop m = (methodOop)oopDesc::decode_heap_oop_not_null(a);
1279   methodOop n = (methodOop)oopDesc::decode_heap_oop_not_null(b);
1280   return m->name()->fast_compare(n->name());
1281 }
1282 static int method_comparator_oop(oop a, oop b) {
1283   methodOop m = (methodOop)a;
1284   methodOop n = (methodOop)b;
1285   return m->name()->fast_compare(n->name());
1286 }
1287 
1288 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
1289 void methodOopDesc::sort_methods(objArrayOop methods,
1290                                  objArrayOop methods_annotations,
1291                                  objArrayOop methods_parameter_annotations,
1292                                  objArrayOop methods_default_annotations,
1293                                  bool idempotent) {
1294   int length = methods->length();
1295   if (length > 1) {
1296     bool do_annotations = false;
1297     if (methods_annotations != NULL ||
1298         methods_parameter_annotations != NULL ||
1299         methods_default_annotations != NULL) {
1300       do_annotations = true;
1301     }
1302     if (do_annotations) {
1303       // Remember current method ordering so we can reorder annotations
1304       for (int i = 0; i < length; i++) {
1305         methodOop m = (methodOop) methods->obj_at(i);
1306         m->set_method_idnum(i);
1307       }
1308     }
1309     {
1310       No_Safepoint_Verifier nsv;
1311       if (UseCompressedOops) {
1312         QuickSort::sort<narrowOop>((narrowOop*)(methods->base()), length, method_comparator_narrowOop, idempotent);
1313       } else {
1314         QuickSort::sort<oop>((oop*)(methods->base()), length, method_comparator_oop, idempotent);
1315       }
1316       if (UseConcMarkSweepGC) {
1317         // For CMS we need to dirty the cards for the array
1318         BarrierSet* bs = Universe::heap()->barrier_set();
1319         assert(bs->has_write_ref_array_opt(), "Barrier set must have ref array opt");
1320         bs->write_ref_array(methods->base(), length);
1321       }
1322     }
1323 
1324     // Sort annotations if necessary
1325     assert(methods_annotations == NULL           || methods_annotations->length() == methods->length(), "");
1326     assert(methods_parameter_annotations == NULL || methods_parameter_annotations->length() == methods->length(), "");
1327     assert(methods_default_annotations == NULL   || methods_default_annotations->length() == methods->length(), "");
1328     if (do_annotations) {
1329       ResourceMark rm;
1330       // Allocate temporary storage
1331       GrowableArray<oop>* temp_array = new GrowableArray<oop>(length);
1332       reorder_based_on_method_index(methods, methods_annotations, temp_array);
1333       reorder_based_on_method_index(methods, methods_parameter_annotations, temp_array);
1334       reorder_based_on_method_index(methods, methods_default_annotations, temp_array);
1335     }
1336 
1337     // Reset method ordering
1338     for (int i = 0; i < length; i++) {
1339       methodOop m = (methodOop) methods->obj_at(i);
1340       m->set_method_idnum(i);
1341     }
1342   }
1343 }
1344 
1345 
1346 //-----------------------------------------------------------------------------------
1347 // Non-product code
1348 
1349 #ifndef PRODUCT
1350 class SignatureTypePrinter : public SignatureTypeNames {
1351  private:
1352   outputStream* _st;
1353   bool _use_separator;
1354 
1355   void type_name(const char* name) {
1356     if (_use_separator) _st->print(", ");
1357     _st->print(name);
1358     _use_separator = true;
1359   }
1360 
1361  public:
1362   SignatureTypePrinter(Symbol* signature, outputStream* st) : SignatureTypeNames(signature) {
1363     _st = st;
1364     _use_separator = false;
1365   }
1366 
1367   void print_parameters()              { _use_separator = false; iterate_parameters(); }
1368   void print_returntype()              { _use_separator = false; iterate_returntype(); }
1369 };
1370 
1371 
1372 void methodOopDesc::print_name(outputStream* st) {
1373   Thread *thread = Thread::current();
1374   ResourceMark rm(thread);
1375   SignatureTypePrinter sig(signature(), st);
1376   st->print("%s ", is_static() ? "static" : "virtual");
1377   sig.print_returntype();
1378   st->print(" %s.", method_holder()->klass_part()->internal_name());
1379   name()->print_symbol_on(st);
1380   st->print("(");
1381   sig.print_parameters();
1382   st->print(")");
1383 }
1384 
1385 
1386 void methodOopDesc::print_codes_on(outputStream* st) const {
1387   print_codes_on(0, code_size(), st);
1388 }
1389 
1390 void methodOopDesc::print_codes_on(int from, int to, outputStream* st) const {
1391   Thread *thread = Thread::current();
1392   ResourceMark rm(thread);
1393   methodHandle mh (thread, (methodOop)this);
1394   BytecodeStream s(mh);
1395   s.set_interval(from, to);
1396   BytecodeTracer::set_closure(BytecodeTracer::std_closure());
1397   while (s.next() >= 0) BytecodeTracer::trace(mh, s.bcp(), st);
1398 }
1399 #endif // not PRODUCT
1400 
1401 
1402 // Simple compression of line number tables. We use a regular compressed stream, except that we compress deltas
1403 // between (bci,line) pairs since they are smaller. If (bci delta, line delta) fits in (5-bit unsigned, 3-bit unsigned)
1404 // we save it as one byte, otherwise we write a 0xFF escape character and use regular compression. 0x0 is used
1405 // as end-of-stream terminator.
1406 
1407 void CompressedLineNumberWriteStream::write_pair_regular(int bci_delta, int line_delta) {
1408   // bci and line number does not compress into single byte.
1409   // Write out escape character and use regular compression for bci and line number.
1410   write_byte((jubyte)0xFF);
1411   write_signed_int(bci_delta);
1412   write_signed_int(line_delta);
1413 }
1414 
1415 // See comment in methodOop.hpp which explains why this exists.
1416 #if defined(_M_AMD64) && _MSC_VER >= 1400
1417 #pragma optimize("", off)
1418 void CompressedLineNumberWriteStream::write_pair(int bci, int line) {
1419   write_pair_inline(bci, line);
1420 }
1421 #pragma optimize("", on)
1422 #endif
1423 
1424 CompressedLineNumberReadStream::CompressedLineNumberReadStream(u_char* buffer) : CompressedReadStream(buffer) {
1425   _bci = 0;
1426   _line = 0;
1427 };
1428 
1429 
1430 bool CompressedLineNumberReadStream::read_pair() {
1431   jubyte next = read_byte();
1432   // Check for terminator
1433   if (next == 0) return false;
1434   if (next == 0xFF) {
1435     // Escape character, regular compression used
1436     _bci  += read_signed_int();
1437     _line += read_signed_int();
1438   } else {
1439     // Single byte compression used
1440     _bci  += next >> 3;
1441     _line += next & 0x7;
1442   }
1443   return true;
1444 }
1445 
1446 
1447 Bytecodes::Code methodOopDesc::orig_bytecode_at(int bci) const {
1448   BreakpointInfo* bp = instanceKlass::cast(method_holder())->breakpoints();
1449   for (; bp != NULL; bp = bp->next()) {
1450     if (bp->match(this, bci)) {
1451       return bp->orig_bytecode();
1452     }
1453   }
1454   ShouldNotReachHere();
1455   return Bytecodes::_shouldnotreachhere;
1456 }
1457 
1458 void methodOopDesc::set_orig_bytecode_at(int bci, Bytecodes::Code code) {
1459   assert(code != Bytecodes::_breakpoint, "cannot patch breakpoints this way");
1460   BreakpointInfo* bp = instanceKlass::cast(method_holder())->breakpoints();
1461   for (; bp != NULL; bp = bp->next()) {
1462     if (bp->match(this, bci)) {
1463       bp->set_orig_bytecode(code);
1464       // and continue, in case there is more than one
1465     }
1466   }
1467 }
1468 
1469 void methodOopDesc::set_breakpoint(int bci) {
1470   instanceKlass* ik = instanceKlass::cast(method_holder());
1471   BreakpointInfo *bp = new BreakpointInfo(this, bci);
1472   bp->set_next(ik->breakpoints());
1473   ik->set_breakpoints(bp);
1474   // do this last:
1475   bp->set(this);
1476 }
1477 
1478 static void clear_matches(methodOop m, int bci) {
1479   instanceKlass* ik = instanceKlass::cast(m->method_holder());
1480   BreakpointInfo* prev_bp = NULL;
1481   BreakpointInfo* next_bp;
1482   for (BreakpointInfo* bp = ik->breakpoints(); bp != NULL; bp = next_bp) {
1483     next_bp = bp->next();
1484     // bci value of -1 is used to delete all breakpoints in method m (ex: clear_all_breakpoint).
1485     if (bci >= 0 ? bp->match(m, bci) : bp->match(m)) {
1486       // do this first:
1487       bp->clear(m);
1488       // unhook it
1489       if (prev_bp != NULL)
1490         prev_bp->set_next(next_bp);
1491       else
1492         ik->set_breakpoints(next_bp);
1493       delete bp;
1494       // When class is redefined JVMTI sets breakpoint in all versions of EMCP methods
1495       // at same location. So we have multiple matching (method_index and bci)
1496       // BreakpointInfo nodes in BreakpointInfo list. We should just delete one
1497       // breakpoint for clear_breakpoint request and keep all other method versions
1498       // BreakpointInfo for future clear_breakpoint request.
1499       // bcivalue of -1 is used to clear all breakpoints (see clear_all_breakpoints)
1500       // which is being called when class is unloaded. We delete all the Breakpoint
1501       // information for all versions of method. We may not correctly restore the original
1502       // bytecode in all method versions, but that is ok. Because the class is being unloaded
1503       // so these methods won't be used anymore.
1504       if (bci >= 0) {
1505         break;
1506       }
1507     } else {
1508       // This one is a keeper.
1509       prev_bp = bp;
1510     }
1511   }
1512 }
1513 
1514 void methodOopDesc::clear_breakpoint(int bci) {
1515   assert(bci >= 0, "");
1516   clear_matches(this, bci);
1517 }
1518 
1519 void methodOopDesc::clear_all_breakpoints() {
1520   clear_matches(this, -1);
1521 }
1522 
1523 
1524 int methodOopDesc::invocation_count() {
1525   if (TieredCompilation) {
1526     const methodDataOop mdo = method_data();
1527     if (invocation_counter()->carry() || ((mdo != NULL) ? mdo->invocation_counter()->carry() : false)) {
1528       return InvocationCounter::count_limit;
1529     } else {
1530       return invocation_counter()->count() + ((mdo != NULL) ? mdo->invocation_counter()->count() : 0);
1531     }
1532   } else {
1533     return invocation_counter()->count();
1534   }
1535 }
1536 
1537 int methodOopDesc::backedge_count() {
1538   if (TieredCompilation) {
1539     const methodDataOop mdo = method_data();
1540     if (backedge_counter()->carry() || ((mdo != NULL) ? mdo->backedge_counter()->carry() : false)) {
1541       return InvocationCounter::count_limit;
1542     } else {
1543       return backedge_counter()->count() + ((mdo != NULL) ? mdo->backedge_counter()->count() : 0);
1544     }
1545   } else {
1546     return backedge_counter()->count();
1547   }
1548 }
1549 
1550 int methodOopDesc::highest_comp_level() const {
1551   methodDataOop mdo = method_data();
1552   if (mdo != NULL) {
1553     return mdo->highest_comp_level();
1554   } else {
1555     return CompLevel_none;
1556   }
1557 }
1558 
1559 int methodOopDesc::highest_osr_comp_level() const {
1560   methodDataOop mdo = method_data();
1561   if (mdo != NULL) {
1562     return mdo->highest_osr_comp_level();
1563   } else {
1564     return CompLevel_none;
1565   }
1566 }
1567 
1568 void methodOopDesc::set_highest_comp_level(int level) {
1569   methodDataOop mdo = method_data();
1570   if (mdo != NULL) {
1571     mdo->set_highest_comp_level(level);
1572   }
1573 }
1574 
1575 void methodOopDesc::set_highest_osr_comp_level(int level) {
1576   methodDataOop mdo = method_data();
1577   if (mdo != NULL) {
1578     mdo->set_highest_osr_comp_level(level);
1579   }
1580 }
1581 
1582 BreakpointInfo::BreakpointInfo(methodOop m, int bci) {
1583   _bci = bci;
1584   _name_index = m->name_index();
1585   _signature_index = m->signature_index();
1586   _orig_bytecode = (Bytecodes::Code) *m->bcp_from(_bci);
1587   if (_orig_bytecode == Bytecodes::_breakpoint)
1588     _orig_bytecode = m->orig_bytecode_at(_bci);
1589   _next = NULL;
1590 }
1591 
1592 void BreakpointInfo::set(methodOop method) {
1593 #ifdef ASSERT
1594   {
1595     Bytecodes::Code code = (Bytecodes::Code) *method->bcp_from(_bci);
1596     if (code == Bytecodes::_breakpoint)
1597       code = method->orig_bytecode_at(_bci);
1598     assert(orig_bytecode() == code, "original bytecode must be the same");
1599   }
1600 #endif
1601   *method->bcp_from(_bci) = Bytecodes::_breakpoint;
1602   method->incr_number_of_breakpoints();
1603   SystemDictionary::notice_modification();
1604   {
1605     // Deoptimize all dependents on this method
1606     Thread *thread = Thread::current();
1607     HandleMark hm(thread);
1608     methodHandle mh(thread, method);
1609     Universe::flush_dependents_on_method(mh);
1610   }
1611 }
1612 
1613 void BreakpointInfo::clear(methodOop method) {
1614   *method->bcp_from(_bci) = orig_bytecode();
1615   assert(method->number_of_breakpoints() > 0, "must not go negative");
1616   method->decr_number_of_breakpoints();
1617 }