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