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 #ifndef SHARE_VM_OOPS_METHODOOP_HPP
  26 #define SHARE_VM_OOPS_METHODOOP_HPP
  27 
  28 #include "classfile/vmSymbols.hpp"
  29 #include "code/compressedStream.hpp"
  30 #include "compiler/oopMap.hpp"
  31 #include "interpreter/invocationCounter.hpp"
  32 #include "oops/annotations.hpp"
  33 #include "oops/constantPool.hpp"
  34 #include "oops/instanceKlass.hpp"
  35 #include "oops/oop.hpp"
  36 #include "oops/typeArrayOop.hpp"
  37 #include "utilities/accessFlags.hpp"
  38 #include "utilities/growableArray.hpp"
  39 
  40 // A Method* represents a Java method.
  41 //
  42 // Memory layout (each line represents a word). Note that most applications load thousands of methods,
  43 // so keeping the size of this structure small has a big impact on footprint.
  44 //
  45 // We put all oops and method_size first for better gc cache locality.
  46 //
  47 // The actual bytecodes are inlined after the end of the Method struct.
  48 //
  49 // There are bits in the access_flags telling whether inlined tables are present.
  50 // Note that accessing the line number and local variable tables is not performance critical at all.
  51 // Accessing the checked exceptions table is used by reflection, so we put that last to make access
  52 // to it fast.
  53 //
  54 // The line number table is compressed and inlined following the byte codes. It is found as the first
  55 // byte following the byte codes. The checked exceptions table and the local variable table are inlined
  56 // after the line number table, and indexed from the end of the method. We do not compress the checked
  57 // exceptions table since the average length is less than 2, and do not bother to compress the local
  58 // variable table either since it is mostly absent.
  59 //
  60 // Note that native_function and signature_handler has to be at fixed offsets (required by the interpreter)
  61 //
  62 // |------------------------------------------------------|
  63 // | header                                               |
  64 // | klass                                                |
  65 // |------------------------------------------------------|
  66 // | ConstMethod*                   (oop)                 |
  67 // |------------------------------------------------------|
  68 // | methodData                     (oop)                 |
  69 // | interp_invocation_count                              |
  70 // |------------------------------------------------------|
  71 // | access_flags                                         |
  72 // | vtable_index                                         |
  73 // |------------------------------------------------------|
  74 // | result_index (C++ interpreter only)                  |
  75 // |------------------------------------------------------|
  76 // | method_size             |   intrinsic_id|   flags    |
  77 // |------------------------------------------------------|
  78 // | throwout_count          |   num_breakpoints          |
  79 // |------------------------------------------------------|
  80 // | invocation_counter                                   |
  81 // | backedge_counter                                     |
  82 // |------------------------------------------------------|
  83 // |           prev_time (tiered only, 64 bit wide)       |
  84 // |                                                      |
  85 // |------------------------------------------------------|
  86 // |                  rate (tiered)                       |
  87 // |------------------------------------------------------|
  88 // | code                           (pointer)             |
  89 // | i2i                            (pointer)             |
  90 // | adapter                        (pointer)             |
  91 // | from_compiled_entry            (pointer)             |
  92 // | from_interpreted_entry         (pointer)             |
  93 // |------------------------------------------------------|
  94 // | native_function       (present only if native)       |
  95 // | signature_handler     (present only if native)       |
  96 // |------------------------------------------------------|
  97 
  98 
  99 class CheckedExceptionElement;
 100 class LocalVariableTableElement;
 101 class AdapterHandlerEntry;
 102 class MethodData;
 103 class ConstMethod;
 104 
 105 class Method : public Metadata {
 106  friend class VMStructs;
 107  private:
 108   ConstMethod*      _constMethod;                // Method read-only data.
 109   MethodData*       _method_data;
 110   int               _interpreter_invocation_count; // Count of times invoked (reused as prev_event_count in tiered)
 111   AccessFlags       _access_flags;               // Access flags
 112   int               _vtable_index;               // vtable index of this method (see VtableIndexFlag)
 113                                                  // note: can have vtables with >2**16 elements (because of inheritance)
 114 #ifdef CC_INTERP
 115   int               _result_index;               // C++ interpreter needs for converting results to/from stack
 116 #endif
 117   u2                _method_size;                // size of this object
 118   u1                _intrinsic_id;               // vmSymbols::intrinsic_id (0 == _none)
 119   u1                _jfr_towrite  : 1,           // Flags
 120                     _force_inline : 1,
 121                     _hidden       : 1,
 122                     _dont_inline  : 1,
 123                                   : 4;
 124   u2                _interpreter_throwout_count; // Count of times method was exited via exception while interpreting
 125   u2                _number_of_breakpoints;      // fullspeed debugging support
 126   InvocationCounter _invocation_counter;         // Incremented before each activation of the method - used to trigger frequency-based optimizations
 127   InvocationCounter _backedge_counter;           // Incremented before each backedge taken - used to trigger frequencey-based optimizations
 128 
 129 #ifdef TIERED
 130   jlong             _prev_time;                   // Previous time the rate was acquired
 131   float             _rate;                        // Events (invocation and backedge counter increments) per millisecond
 132 #endif
 133 
 134 #ifndef PRODUCT
 135   int               _compiled_invocation_count;  // Number of nmethod invocations so far (for perf. debugging)
 136 #endif
 137   // Entry point for calling both from and to the interpreter.
 138   address _i2i_entry;           // All-args-on-stack calling convention
 139   // Adapter blob (i2c/c2i) for this Method*. Set once when method is linked.
 140   AdapterHandlerEntry* _adapter;
 141   // Entry point for calling from compiled code, to compiled code if it exists
 142   // or else the interpreter.
 143   volatile address _from_compiled_entry;        // Cache of: _code ? _code->entry_point() : _adapter->c2i_entry()
 144   // The entry point for calling both from and to compiled code is
 145   // "_code->entry_point()".  Because of tiered compilation and de-opt, this
 146   // field can come and go.  It can transition from NULL to not-null at any
 147   // time (whenever a compile completes).  It can transition from not-null to
 148   // NULL only at safepoints (because of a de-opt).
 149   nmethod* volatile _code;                       // Points to the corresponding piece of native code
 150   volatile address           _from_interpreted_entry; // Cache of _code ? _adapter->i2c_entry() : _i2i_entry
 151 
 152   // Constructor
 153   Method(ConstMethod* xconst, AccessFlags access_flags, int size);
 154  public:
 155 
 156   static Method* allocate(ClassLoaderData* loader_data,
 157                           int byte_code_size,
 158                           AccessFlags access_flags,
 159                           int compressed_line_number_size,
 160                           int localvariable_table_length,
 161                           int exception_table_length,
 162                           int checked_exceptions_length,
 163                           u2 generic_signature_index,
 164                           ConstMethod::MethodType method_type,
 165                           TRAPS);
 166 
 167   // CDS and vtbl checking can create an empty Method to get vtbl pointer.
 168   Method(){}
 169 
 170   // The Method vtable is restored by this call when the Method is in the
 171   // shared archive.  See patch_klass_vtables() in metaspaceShared.cpp for
 172   // all the gory details.  SA, dtrace and pstack helpers distinguish metadata
 173   // by their vtable.
 174   void restore_vtable() { guarantee(is_method(), "vtable restored by this call"); }
 175   bool is_method() const volatile { return true; }
 176 
 177   // accessors for instance variables
 178 
 179   ConstMethod* constMethod() const             { return _constMethod; }
 180   void set_constMethod(ConstMethod* xconst)    { _constMethod = xconst; }
 181 
 182 
 183   static address make_adapters(methodHandle mh, TRAPS);
 184   volatile address from_compiled_entry() const   { return (address)OrderAccess::load_ptr_acquire(&_from_compiled_entry); }
 185   volatile address from_interpreted_entry() const{ return (address)OrderAccess::load_ptr_acquire(&_from_interpreted_entry); }
 186 
 187   // access flag
 188   AccessFlags access_flags() const               { return _access_flags;  }
 189   void set_access_flags(AccessFlags flags)       { _access_flags = flags; }
 190 
 191   // name
 192   Symbol* name() const                           { return constants()->symbol_at(name_index()); }
 193   int name_index() const                         { return constMethod()->name_index();         }
 194   void set_name_index(int index)                 { constMethod()->set_name_index(index);       }
 195 
 196   // signature
 197   Symbol* signature() const                      { return constants()->symbol_at(signature_index()); }
 198   int signature_index() const                    { return constMethod()->signature_index();         }
 199   void set_signature_index(int index)            { constMethod()->set_signature_index(index);       }
 200 
 201   // generics support
 202   Symbol* generic_signature() const              { int idx = generic_signature_index(); return ((idx != 0) ? constants()->symbol_at(idx) : (Symbol*)NULL); }
 203   int generic_signature_index() const            { return constMethod()->generic_signature_index(); }
 204   void set_generic_signature_index(int index)    { constMethod()->set_generic_signature_index(index); }
 205 
 206   // annotations support
 207   AnnotationArray* annotations() const           {
 208     InstanceKlass* ik = method_holder();
 209     if (ik->annotations() == NULL) {
 210       return NULL;
 211     }
 212     return ik->annotations()->get_method_annotations_of(method_idnum());
 213   }
 214   AnnotationArray* parameter_annotations() const {
 215     InstanceKlass* ik = method_holder();
 216     if (ik->annotations() == NULL) {
 217       return NULL;
 218     }
 219     return ik->annotations()->get_method_parameter_annotations_of(method_idnum());
 220   }
 221   AnnotationArray* annotation_default() const    {
 222     InstanceKlass* ik = method_holder();
 223     if (ik->annotations() == NULL) {
 224       return NULL;
 225     }
 226     return ik->annotations()->get_method_default_annotations_of(method_idnum());
 227   }
 228 
 229 #ifdef CC_INTERP
 230   void set_result_index(BasicType type);
 231   int  result_index()                            { return _result_index; }
 232 #endif
 233 
 234   // Helper routine: get klass name + "." + method name + signature as
 235   // C string, for the purpose of providing more useful NoSuchMethodErrors
 236   // and fatal error handling. The string is allocated in resource
 237   // area if a buffer is not provided by the caller.
 238   char* name_and_sig_as_C_string() const;
 239   char* name_and_sig_as_C_string(char* buf, int size) const;
 240 
 241   // Static routine in the situations we don't have a Method*
 242   static char* name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature);
 243   static char* name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature, char* buf, int size);
 244 
 245   Bytecodes::Code java_code_at(int bci) const {
 246     return Bytecodes::java_code_at(this, bcp_from(bci));
 247   }
 248   Bytecodes::Code code_at(int bci) const {
 249     return Bytecodes::code_at(this, bcp_from(bci));
 250   }
 251 
 252   // JVMTI breakpoints
 253   Bytecodes::Code orig_bytecode_at(int bci) const;
 254   void        set_orig_bytecode_at(int bci, Bytecodes::Code code);
 255   void set_breakpoint(int bci);
 256   void clear_breakpoint(int bci);
 257   void clear_all_breakpoints();
 258   // Tracking number of breakpoints, for fullspeed debugging.
 259   // Only mutated by VM thread.
 260   u2   number_of_breakpoints() const             { return _number_of_breakpoints; }
 261   void incr_number_of_breakpoints()              { ++_number_of_breakpoints; }
 262   void decr_number_of_breakpoints()              { --_number_of_breakpoints; }
 263   // Initialization only
 264   void clear_number_of_breakpoints()             { _number_of_breakpoints = 0; }
 265 
 266   // index into InstanceKlass methods() array
 267   // note: also used by jfr
 268   u2 method_idnum() const           { return constMethod()->method_idnum(); }
 269   void set_method_idnum(u2 idnum)   { constMethod()->set_method_idnum(idnum); }
 270 
 271   // code size
 272   int code_size() const                  { return constMethod()->code_size(); }
 273 
 274   // method size
 275   int method_size() const                        { return _method_size; }
 276   void set_method_size(int size) {
 277     assert(0 <= size && size < (1 << 16), "invalid method size");
 278     _method_size = size;
 279   }
 280 
 281   // constant pool for Klass* holding this method
 282   ConstantPool* constants() const              { return constMethod()->constants(); }
 283   void set_constants(ConstantPool* c)          { constMethod()->set_constants(c); }
 284 
 285   // max stack
 286   // return original max stack size for method verification
 287   int  verifier_max_stack() const                { return constMethod()->max_stack(); }
 288   int           max_stack() const                { return constMethod()->max_stack() + extra_stack_entries(); }
 289   void      set_max_stack(int size)              {        constMethod()->set_max_stack(size); }
 290 
 291   // max locals
 292   int  max_locals() const                        { return constMethod()->max_locals(); }
 293   void set_max_locals(int size)                  { constMethod()->set_max_locals(size); }
 294 
 295   int highest_comp_level() const;
 296   void set_highest_comp_level(int level);
 297   int highest_osr_comp_level() const;
 298   void set_highest_osr_comp_level(int level);
 299 
 300   // Count of times method was exited via exception while interpreting
 301   void interpreter_throwout_increment() {
 302     if (_interpreter_throwout_count < 65534) {
 303       _interpreter_throwout_count++;
 304     }
 305   }
 306 
 307   int  interpreter_throwout_count() const        { return _interpreter_throwout_count; }
 308   void set_interpreter_throwout_count(int count) { _interpreter_throwout_count = count; }
 309 
 310   // size of parameters
 311   int  size_of_parameters() const                { return constMethod()->size_of_parameters(); }
 312   void set_size_of_parameters(int size)          { constMethod()->set_size_of_parameters(size); }
 313 
 314   bool has_stackmap_table() const {
 315     return constMethod()->has_stackmap_table();
 316   }
 317 
 318   Array<u1>* stackmap_data() const {
 319     return constMethod()->stackmap_data();
 320   }
 321 
 322   void set_stackmap_data(Array<u1>* sd) {
 323     constMethod()->set_stackmap_data(sd);
 324   }
 325 
 326   // exception handler table
 327   bool has_exception_handler() const
 328                              { return constMethod()->has_exception_handler(); }
 329   int exception_table_length() const
 330                              { return constMethod()->exception_table_length(); }
 331   ExceptionTableElement* exception_table_start() const
 332                              { return constMethod()->exception_table_start(); }
 333 
 334   // Finds the first entry point bci of an exception handler for an
 335   // exception of klass ex_klass thrown at throw_bci. A value of NULL
 336   // for ex_klass indicates that the exception klass is not known; in
 337   // this case it matches any constraint class. Returns -1 if the
 338   // exception cannot be handled in this method. The handler
 339   // constraint classes are loaded if necessary. Note that this may
 340   // throw an exception if loading of the constraint classes causes
 341   // an IllegalAccessError (bugid 4307310) or an OutOfMemoryError.
 342   // If an exception is thrown, returns the bci of the
 343   // exception handler which caused the exception to be thrown, which
 344   // is needed for proper retries. See, for example,
 345   // InterpreterRuntime::exception_handler_for_exception.
 346   int fast_exception_handler_bci_for(KlassHandle ex_klass, int throw_bci, TRAPS);
 347 
 348   // method data access
 349   MethodData* method_data() const              {
 350     return _method_data;
 351   }
 352   void set_method_data(MethodData* data)       {
 353     _method_data = data;
 354   }
 355 
 356   // invocation counter
 357   InvocationCounter* invocation_counter() { return &_invocation_counter; }
 358   InvocationCounter* backedge_counter()   { return &_backedge_counter; }
 359 
 360 #ifdef TIERED
 361   // We are reusing interpreter_invocation_count as a holder for the previous event count!
 362   // We can do that since interpreter_invocation_count is not used in tiered.
 363   int prev_event_count() const                   { return _interpreter_invocation_count;  }
 364   void set_prev_event_count(int count)           { _interpreter_invocation_count = count; }
 365   jlong prev_time() const                        { return _prev_time; }
 366   void set_prev_time(jlong time)                 { _prev_time = time; }
 367   float rate() const                             { return _rate; }
 368   void set_rate(float rate)                      { _rate = rate; }
 369 #endif
 370 
 371   int invocation_count();
 372   int backedge_count();
 373 
 374   bool was_executed_more_than(int n);
 375   bool was_never_executed()                      { return !was_executed_more_than(0); }
 376 
 377   static void build_interpreter_method_data(methodHandle method, TRAPS);
 378 
 379   int interpreter_invocation_count() {
 380     if (TieredCompilation) return invocation_count();
 381     else return _interpreter_invocation_count;
 382   }
 383   void set_interpreter_invocation_count(int count) { _interpreter_invocation_count = count; }
 384   int increment_interpreter_invocation_count() {
 385     if (TieredCompilation) ShouldNotReachHere();
 386     return ++_interpreter_invocation_count;
 387   }
 388 
 389 #ifndef PRODUCT
 390   int  compiled_invocation_count() const         { return _compiled_invocation_count;  }
 391   void set_compiled_invocation_count(int count)  { _compiled_invocation_count = count; }
 392 #endif // not PRODUCT
 393 
 394   // Clear (non-shared space) pointers which could not be relevant
 395   // if this (shared) method were mapped into another JVM.
 396   void remove_unshareable_info();
 397 
 398   // nmethod/verified compiler entry
 399   address verified_code_entry();
 400   bool check_code() const;      // Not inline to avoid circular ref
 401   nmethod* volatile code() const                 { assert( check_code(), "" ); return (nmethod *)OrderAccess::load_ptr_acquire(&_code); }
 402   void clear_code();            // Clear out any compiled code
 403   static void set_code(methodHandle mh, nmethod* code);
 404   void set_adapter_entry(AdapterHandlerEntry* adapter) {  _adapter = adapter; }
 405   address get_i2c_entry();
 406   address get_c2i_entry();
 407   address get_c2i_unverified_entry();
 408   AdapterHandlerEntry* adapter() {  return _adapter; }
 409   // setup entry points
 410   void link_method(methodHandle method, TRAPS);
 411   // clear entry points. Used by sharing code
 412   void unlink_method();
 413 
 414   // vtable index
 415   enum VtableIndexFlag {
 416     // Valid vtable indexes are non-negative (>= 0).
 417     // These few negative values are used as sentinels.
 418     highest_unused_vtable_index_value = -5,
 419     invalid_vtable_index    = -4,  // distinct from any valid vtable index
 420     garbage_vtable_index    = -3,  // not yet linked; no vtable layout yet
 421     nonvirtual_vtable_index = -2   // there is no need for vtable dispatch
 422     // 6330203 Note:  Do not use -1, which was overloaded with many meanings.
 423   };
 424   DEBUG_ONLY(bool valid_vtable_index() const     { return _vtable_index >= nonvirtual_vtable_index; })
 425   int  vtable_index() const                      { assert(valid_vtable_index(), "");
 426                                                    return _vtable_index; }
 427   void set_vtable_index(int index)               { _vtable_index = index; }
 428 
 429   // interpreter entry
 430   address interpreter_entry() const              { return _i2i_entry; }
 431   // Only used when first initialize so we can set _i2i_entry and _from_interpreted_entry
 432   void set_interpreter_entry(address entry)      { _i2i_entry = entry;  _from_interpreted_entry = entry; }
 433   int  interpreter_kind(void) {
 434      return constMethod()->interpreter_kind();
 435   }
 436   void set_interpreter_kind();
 437   void set_interpreter_kind(int kind) {
 438     constMethod()->set_interpreter_kind(kind);
 439   }
 440 
 441   // native function (used for native methods only)
 442   enum {
 443     native_bind_event_is_interesting = true
 444   };
 445   address native_function() const                { return *(native_function_addr()); }
 446   address critical_native_function();
 447 
 448   // Must specify a real function (not NULL).
 449   // Use clear_native_function() to unregister.
 450   void set_native_function(address function, bool post_event_flag);
 451   bool has_native_function() const;
 452   void clear_native_function();
 453 
 454   // signature handler (used for native methods only)
 455   address signature_handler() const              { return *(signature_handler_addr()); }
 456   void set_signature_handler(address handler);
 457 
 458   // Interpreter oopmap support
 459   void mask_for(int bci, InterpreterOopMap* mask);
 460 
 461 #ifndef PRODUCT
 462   // operations on invocation counter
 463   void print_invocation_count();
 464 #endif
 465 
 466   // byte codes
 467   void    set_code(address code)      { return constMethod()->set_code(code); }
 468   address code_base() const           { return constMethod()->code_base(); }
 469   bool    contains(address bcp) const { return constMethod()->contains(bcp); }
 470 
 471   // prints byte codes
 472   void print_codes() const            { print_codes_on(tty); }
 473   void print_codes_on(outputStream* st) const                      PRODUCT_RETURN;
 474   void print_codes_on(int from, int to, outputStream* st) const    PRODUCT_RETURN;
 475 
 476   // checked exceptions
 477   int checked_exceptions_length() const
 478                          { return constMethod()->checked_exceptions_length(); }
 479   CheckedExceptionElement* checked_exceptions_start() const
 480                           { return constMethod()->checked_exceptions_start(); }
 481 
 482   // localvariable table
 483   bool has_localvariable_table() const
 484                           { return constMethod()->has_localvariable_table(); }
 485   int localvariable_table_length() const
 486                         { return constMethod()->localvariable_table_length(); }
 487   LocalVariableTableElement* localvariable_table_start() const
 488                          { return constMethod()->localvariable_table_start(); }
 489 
 490   bool has_linenumber_table() const
 491                               { return constMethod()->has_linenumber_table(); }
 492   u_char* compressed_linenumber_table() const
 493                        { return constMethod()->compressed_linenumber_table(); }
 494 
 495   // method holder (the Klass* holding this method)
 496   InstanceKlass* method_holder() const         { return constants()->pool_holder(); }
 497 
 498   void compute_size_of_parameters(Thread *thread); // word size of parameters (receiver if any + arguments)
 499   Symbol* klass_name() const;                    // returns the name of the method holder
 500   BasicType result_type() const;                 // type of the method result
 501   int result_type_index() const;                 // type index of the method result
 502   bool is_returning_oop() const                  { BasicType r = result_type(); return (r == T_OBJECT || r == T_ARRAY); }
 503   bool is_returning_fp() const                   { BasicType r = result_type(); return (r == T_FLOAT || r == T_DOUBLE); }
 504 
 505   // Checked exceptions thrown by this method (resolved to mirrors)
 506   objArrayHandle resolved_checked_exceptions(TRAPS) { return resolved_checked_exceptions_impl(this, THREAD); }
 507 
 508   // Access flags
 509   bool is_public() const                         { return access_flags().is_public();      }
 510   bool is_private() const                        { return access_flags().is_private();     }
 511   bool is_protected() const                      { return access_flags().is_protected();   }
 512   bool is_package_private() const                { return !is_public() && !is_private() && !is_protected(); }
 513   bool is_static() const                         { return access_flags().is_static();      }
 514   bool is_final() const                          { return access_flags().is_final();       }
 515   bool is_synchronized() const                   { return access_flags().is_synchronized();}
 516   bool is_native() const                         { return access_flags().is_native();      }
 517   bool is_abstract() const                       { return access_flags().is_abstract();    }
 518   bool is_strict() const                         { return access_flags().is_strict();      }
 519   bool is_synthetic() const                      { return access_flags().is_synthetic();   }
 520 
 521   // returns true if contains only return operation
 522   bool is_empty_method() const;
 523 
 524   // returns true if this is a vanilla constructor
 525   bool is_vanilla_constructor() const;
 526 
 527   // checks method and its method holder
 528   bool is_final_method() const;
 529   bool is_strict_method() const;
 530 
 531   // true if method needs no dynamic dispatch (final and/or no vtable entry)
 532   bool can_be_statically_bound() const;
 533 
 534   // returns true if the method has any backward branches.
 535   bool has_loops() {
 536     return access_flags().loops_flag_init() ? access_flags().has_loops() : compute_has_loops_flag();
 537   };
 538 
 539   bool compute_has_loops_flag();
 540 
 541   bool has_jsrs() {
 542     return access_flags().has_jsrs();
 543   };
 544   void set_has_jsrs() {
 545     _access_flags.set_has_jsrs();
 546   }
 547 
 548   // returns true if the method has any monitors.
 549   bool has_monitors() const                      { return is_synchronized() || access_flags().has_monitor_bytecodes(); }
 550   bool has_monitor_bytecodes() const             { return access_flags().has_monitor_bytecodes(); }
 551 
 552   void set_has_monitor_bytecodes()               { _access_flags.set_has_monitor_bytecodes(); }
 553 
 554   // monitor matching. This returns a conservative estimate of whether the monitorenter/monitorexit bytecodes
 555   // propererly nest in the method. It might return false, even though they actually nest properly, since the info.
 556   // has not been computed yet.
 557   bool guaranteed_monitor_matching() const       { return access_flags().is_monitor_matching(); }
 558   void set_guaranteed_monitor_matching()         { _access_flags.set_monitor_matching(); }
 559 
 560   // returns true if the method is an accessor function (setter/getter).
 561   bool is_accessor() const;
 562 
 563   // returns true if the method is an initializer (<init> or <clinit>).
 564   bool is_initializer() const;
 565 
 566   // returns true if the method is static OR if the classfile version < 51
 567   bool has_valid_initializer_flags() const;
 568 
 569   // returns true if the method name is <clinit> and the method has
 570   // valid static initializer flags.
 571   bool is_static_initializer() const;
 572 
 573   // compiled code support
 574   // NOTE: code() is inherently racy as deopt can be clearing code
 575   // simultaneously. Use with caution.
 576   bool has_compiled_code() const                 { return code() != NULL; }
 577 
 578   // sizing
 579   static int header_size()                       { return sizeof(Method)/HeapWordSize; }
 580   static int size(bool is_native);
 581   int size() const                               { return method_size(); }
 582 
 583   // interpreter support
 584   static ByteSize const_offset()                 { return byte_offset_of(Method, _constMethod       ); }
 585   static ByteSize access_flags_offset()          { return byte_offset_of(Method, _access_flags      ); }
 586 #ifdef CC_INTERP
 587   static ByteSize result_index_offset()          { return byte_offset_of(Method, _result_index ); }
 588 #endif /* CC_INTERP */
 589   static ByteSize from_compiled_offset()         { return byte_offset_of(Method, _from_compiled_entry); }
 590   static ByteSize code_offset()                  { return byte_offset_of(Method, _code); }
 591   static ByteSize invocation_counter_offset()    { return byte_offset_of(Method, _invocation_counter); }
 592   static ByteSize backedge_counter_offset()      { return byte_offset_of(Method, _backedge_counter); }
 593   static ByteSize method_data_offset()           {
 594     return byte_offset_of(Method, _method_data);
 595   }
 596   static ByteSize interpreter_invocation_counter_offset() { return byte_offset_of(Method, _interpreter_invocation_count); }
 597 #ifndef PRODUCT
 598   static ByteSize compiled_invocation_counter_offset() { return byte_offset_of(Method, _compiled_invocation_count); }
 599 #endif // not PRODUCT
 600   static ByteSize native_function_offset()       { return in_ByteSize(sizeof(Method));                 }
 601   static ByteSize from_interpreted_offset()      { return byte_offset_of(Method, _from_interpreted_entry ); }
 602   static ByteSize interpreter_entry_offset()     { return byte_offset_of(Method, _i2i_entry ); }
 603   static ByteSize signature_handler_offset()     { return in_ByteSize(sizeof(Method) + wordSize);      }
 604 
 605   // for code generation
 606   static int method_data_offset_in_bytes()       { return offset_of(Method, _method_data); }
 607   static int interpreter_invocation_counter_offset_in_bytes()
 608                                                  { return offset_of(Method, _interpreter_invocation_count); }
 609   static int intrinsic_id_offset_in_bytes()      { return offset_of(Method, _intrinsic_id); }
 610   static int intrinsic_id_size_in_bytes()        { return sizeof(u1); }
 611 
 612   // Static methods that are used to implement member methods where an exposed this pointer
 613   // is needed due to possible GCs
 614   static objArrayHandle resolved_checked_exceptions_impl(Method* this_oop, TRAPS);
 615 
 616   // Returns the byte code index from the byte code pointer
 617   int     bci_from(address bcp) const;
 618   address bcp_from(int     bci) const;
 619   int validate_bci_from_bcx(intptr_t bcx) const;
 620 
 621   // Returns the line number for a bci if debugging information for the method is prowided,
 622   // -1 is returned otherwise.
 623   int line_number_from_bci(int bci) const;
 624 
 625   // Reflection support
 626   bool is_overridden_in(Klass* k) const;
 627 
 628   // JSR 292 support
 629   bool is_method_handle_intrinsic() const;          // MethodHandles::is_signature_polymorphic_intrinsic(intrinsic_id)
 630   bool is_compiled_lambda_form() const;             // intrinsic_id() == vmIntrinsics::_compiledLambdaForm
 631   bool has_member_arg() const;                      // intrinsic_id() == vmIntrinsics::_linkToSpecial, etc.
 632   static methodHandle make_method_handle_intrinsic(vmIntrinsics::ID iid, // _invokeBasic, _linkToVirtual
 633                                                    Symbol* signature, //anything at all
 634                                                    TRAPS);
 635   static Klass* check_non_bcp_klass(Klass* klass);
 636   // these operate only on invoke methods:
 637   // presize interpreter frames for extra interpreter stack entries, if needed
 638   // method handles want to be able to push a few extra values (e.g., a bound receiver), and
 639   // invokedynamic sometimes needs to push a bootstrap method, call site, and arglist,
 640   // all without checking for a stack overflow
 641   static int extra_stack_entries() { return EnableInvokeDynamic ? 2 : 0; }
 642   static int extra_stack_words();  // = extra_stack_entries() * Interpreter::stackElementSize()
 643 
 644   // RedefineClasses() support:
 645   bool is_old() const                               { return access_flags().is_old(); }
 646   void set_is_old()                                 { _access_flags.set_is_old(); }
 647   bool is_obsolete() const                          { return access_flags().is_obsolete(); }
 648   void set_is_obsolete()                            { _access_flags.set_is_obsolete(); }
 649   bool on_stack() const                             { return access_flags().on_stack(); }
 650   void set_on_stack(const bool value);
 651 
 652   // see the definition in Method*.cpp for the gory details
 653   bool should_not_be_cached() const;
 654 
 655   // JVMTI Native method prefixing support:
 656   bool is_prefixed_native() const                   { return access_flags().is_prefixed_native(); }
 657   void set_is_prefixed_native()                     { _access_flags.set_is_prefixed_native(); }
 658 
 659   // Rewriting support
 660   static methodHandle clone_with_new_data(methodHandle m, u_char* new_code, int new_code_length,
 661                                           u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS);
 662 
 663   // jmethodID handling
 664   // Because the useful life-span of a jmethodID cannot be determined,
 665   // once created they are never reclaimed.  The methods to which they refer,
 666   // however, can be GC'ed away if the class is unloaded or if the method is
 667   // made obsolete or deleted -- in these cases, the jmethodID
 668   // refers to NULL (as is the case for any weak reference).
 669   static jmethodID make_jmethod_id(ClassLoaderData* loader_data, Method* mh);
 670   static void destroy_jmethod_id(ClassLoaderData* loader_data, jmethodID mid);
 671 
 672   // Use resolve_jmethod_id() in situations where the caller is expected
 673   // to provide a valid jmethodID; the only sanity checks are in asserts;
 674   // result guaranteed not to be NULL.
 675   inline static Method* resolve_jmethod_id(jmethodID mid) {
 676     assert(mid != NULL, "JNI method id should not be null");
 677     return *((Method**)mid);
 678   }
 679 
 680   // Use checked_resolve_jmethod_id() in situations where the caller
 681   // should provide a valid jmethodID, but might not. NULL is returned
 682   // when the jmethodID does not refer to a valid method.
 683   static Method* checked_resolve_jmethod_id(jmethodID mid);
 684 
 685   static void change_method_associated_with_jmethod_id(jmethodID old_jmid_ptr, Method* new_method);
 686   static bool is_method_id(jmethodID mid);
 687 
 688   // Clear methods
 689   static void clear_jmethod_ids(ClassLoaderData* loader_data);
 690   static void print_jmethod_ids(ClassLoaderData* loader_data, outputStream* out) PRODUCT_RETURN;
 691 
 692   // Get this method's jmethodID -- allocate if it doesn't exist
 693   jmethodID jmethod_id()                            { methodHandle this_h(this);
 694                                                       return InstanceKlass::get_jmethod_id(method_holder(), this_h); }
 695 
 696   // Lookup the jmethodID for this method.  Return NULL if not found.
 697   // NOTE that this function can be called from a signal handler
 698   // (see AsyncGetCallTrace support for Forte Analyzer) and this
 699   // needs to be async-safe. No allocation should be done and
 700   // so handles are not used to avoid deadlock.
 701   jmethodID find_jmethod_id_or_null()               { return method_holder()->jmethod_id_or_null(this); }
 702 
 703   // JNI static invoke cached itable index accessors
 704   int cached_itable_index()                         { return method_holder()->cached_itable_index(method_idnum()); }
 705   void set_cached_itable_index(int index)           { method_holder()->set_cached_itable_index(method_idnum(), index); }
 706 
 707   // Support for inlining of intrinsic methods
 708   vmIntrinsics::ID intrinsic_id() const          { return (vmIntrinsics::ID) _intrinsic_id;           }
 709   void     set_intrinsic_id(vmIntrinsics::ID id) {                           _intrinsic_id = (u1) id; }
 710 
 711   // Helper routines for intrinsic_id() and vmIntrinsics::method().
 712   void init_intrinsic_id();     // updates from _none if a match
 713   static vmSymbols::SID klass_id_for_intrinsics(Klass* holder);
 714 
 715   bool jfr_towrite()                 { return _jfr_towrite; }
 716   void set_jfr_towrite(bool towrite) { _jfr_towrite = towrite; }
 717 
 718   bool     force_inline()       { return _force_inline;     }
 719   void set_force_inline(bool x) {        _force_inline = x; }
 720   bool     dont_inline()        { return _dont_inline;      }
 721   void set_dont_inline(bool x)  {        _dont_inline = x;  }
 722   bool  is_hidden()             { return _hidden;           }
 723   void set_hidden(bool x)       {        _hidden = x;       }
 724   ConstMethod::MethodType method_type() const {
 725       return _constMethod->method_type();
 726   }
 727   bool is_overpass() const { return method_type() == ConstMethod::OVERPASS; }
 728 
 729   // On-stack replacement support
 730   bool has_osr_nmethod(int level, bool match_level) {
 731    return method_holder()->lookup_osr_nmethod(this, InvocationEntryBci, level, match_level) != NULL;
 732   }
 733 
 734   nmethod* lookup_osr_nmethod_for(int bci, int level, bool match_level) {
 735     return method_holder()->lookup_osr_nmethod(this, bci, level, match_level);
 736   }
 737 
 738   // Inline cache support
 739   void cleanup_inline_caches();
 740 
 741   // Find if klass for method is loaded
 742   bool is_klass_loaded_by_klass_index(int klass_index) const;
 743   bool is_klass_loaded(int refinfo_index, bool must_be_resolved = false) const;
 744 
 745   // Indicates whether compilation failed earlier for this method, or
 746   // whether it is not compilable for another reason like having a
 747   // breakpoint set in it.
 748   bool  is_not_compilable(int comp_level = CompLevel_any) const;
 749   void set_not_compilable(int comp_level = CompLevel_all, bool report = true);
 750   void set_not_compilable_quietly(int comp_level = CompLevel_all) {
 751     set_not_compilable(comp_level, false);
 752   }
 753   bool  is_not_osr_compilable(int comp_level = CompLevel_any) const;
 754   void set_not_osr_compilable(int comp_level = CompLevel_all, bool report = true);
 755   void set_not_osr_compilable_quietly(int comp_level = CompLevel_all) {
 756     set_not_osr_compilable(comp_level, false);
 757   }
 758 
 759  private:
 760   void print_made_not_compilable(int comp_level, bool is_osr, bool report);
 761 
 762  public:
 763   bool  is_not_c1_compilable() const          { return access_flags().is_not_c1_compilable(); }
 764   void set_not_c1_compilable()                {       _access_flags.set_not_c1_compilable();  }
 765   bool  is_not_c2_compilable() const          { return access_flags().is_not_c2_compilable(); }
 766   void set_not_c2_compilable()                {       _access_flags.set_not_c2_compilable();  }
 767 
 768   bool  is_not_c1_osr_compilable() const      { return is_not_c1_compilable(); }  // don't waste an accessFlags bit
 769   void set_not_c1_osr_compilable()            {       set_not_c1_compilable(); }  // don't waste an accessFlags bit
 770   bool  is_not_c2_osr_compilable() const      { return access_flags().is_not_c2_osr_compilable(); }
 771   void set_not_c2_osr_compilable()            {       _access_flags.set_not_c2_osr_compilable();  }
 772 
 773   // Background compilation support
 774   bool queued_for_compilation() const  { return access_flags().queued_for_compilation(); }
 775   void set_queued_for_compilation()    { _access_flags.set_queued_for_compilation();     }
 776   void clear_queued_for_compilation()  { _access_flags.clear_queued_for_compilation();   }
 777 
 778   // Resolve all classes in signature, return 'true' if successful
 779   static bool load_signature_classes(methodHandle m, TRAPS);
 780 
 781   // Return if true if not all classes references in signature, including return type, has been loaded
 782   static bool has_unloaded_classes_in_signature(methodHandle m, TRAPS);
 783 
 784   // Printing
 785   void print_short_name(outputStream* st = tty)  /*PRODUCT_RETURN*/; // prints as klassname::methodname; Exposed so field engineers can debug VM
 786   void print_name(outputStream* st = tty)        PRODUCT_RETURN; // prints as "virtual void foo(int)"
 787 
 788   // Helper routine used for method sorting
 789   static void sort_methods(Array<Method*>* methods,
 790                            Array<AnnotationArray*>* methods_annotations,
 791                            Array<AnnotationArray*>* methods_parameter_annotations,
 792                            Array<AnnotationArray*>* methods_default_annotations,
 793                            bool idempotent = false);
 794 
 795   // Deallocation function for redefine classes or if an error occurs
 796   void deallocate_contents(ClassLoaderData* loader_data);
 797 
 798   // Printing
 799 #ifndef PRODUCT
 800   void print_on(outputStream* st) const;
 801 #endif
 802   void print_value_on(outputStream* st) const;
 803 
 804   const char* internal_name() const { return "{method}"; }
 805 
 806   // Check for valid method pointer
 807   bool is_valid_method() const;
 808 
 809   // Verify
 810   void verify() { verify_on(tty); }
 811   void verify_on(outputStream* st);
 812 
 813  private:
 814 
 815   // Inlined elements
 816   address* native_function_addr() const          { assert(is_native(), "must be native"); return (address*) (this+1); }
 817   address* signature_handler_addr() const        { return native_function_addr() + 1; }
 818 };
 819 
 820 
 821 // Utility class for compressing line number tables
 822 
 823 class CompressedLineNumberWriteStream: public CompressedWriteStream {
 824  private:
 825   int _bci;
 826   int _line;
 827  public:
 828   // Constructor
 829   CompressedLineNumberWriteStream(int initial_size) : CompressedWriteStream(initial_size), _bci(0), _line(0) {}
 830   CompressedLineNumberWriteStream(u_char* buffer, int initial_size) : CompressedWriteStream(buffer, initial_size), _bci(0), _line(0) {}
 831 
 832   // Write (bci, line number) pair to stream
 833   void write_pair_regular(int bci_delta, int line_delta);
 834 
 835   inline void write_pair_inline(int bci, int line) {
 836     int bci_delta = bci - _bci;
 837     int line_delta = line - _line;
 838     _bci = bci;
 839     _line = line;
 840     // Skip (0,0) deltas - they do not add information and conflict with terminator.
 841     if (bci_delta == 0 && line_delta == 0) return;
 842     // Check if bci is 5-bit and line number 3-bit unsigned.
 843     if (((bci_delta & ~0x1F) == 0) && ((line_delta & ~0x7) == 0)) {
 844       // Compress into single byte.
 845       jubyte value = ((jubyte) bci_delta << 3) | (jubyte) line_delta;
 846       // Check that value doesn't match escape character.
 847       if (value != 0xFF) {
 848         write_byte(value);
 849         return;
 850       }
 851     }
 852     write_pair_regular(bci_delta, line_delta);
 853   }
 854 
 855 // Windows AMD64 + Apr 2005 PSDK with /O2 generates bad code for write_pair.
 856 // Disabling optimization doesn't work for methods in header files
 857 // so we force it to call through the non-optimized version in the .cpp.
 858 // It's gross, but it's the only way we can ensure that all callers are
 859 // fixed.  _MSC_VER is defined by the windows compiler
 860 #if defined(_M_AMD64) && _MSC_VER >= 1400
 861   void write_pair(int bci, int line);
 862 #else
 863   void write_pair(int bci, int line) { write_pair_inline(bci, line); }
 864 #endif
 865 
 866   // Write end-of-stream marker
 867   void write_terminator()                        { write_byte(0); }
 868 };
 869 
 870 
 871 // Utility class for decompressing line number tables
 872 
 873 class CompressedLineNumberReadStream: public CompressedReadStream {
 874  private:
 875   int _bci;
 876   int _line;
 877  public:
 878   // Constructor
 879   CompressedLineNumberReadStream(u_char* buffer);
 880   // Read (bci, line number) pair from stream. Returns false at end-of-stream.
 881   bool read_pair();
 882   // Accessing bci and line number (after calling read_pair)
 883   int bci() const                               { return _bci; }
 884   int line() const                              { return _line; }
 885 };
 886 
 887 
 888 /// Fast Breakpoints.
 889 
 890 // If this structure gets more complicated (because bpts get numerous),
 891 // move it into its own header.
 892 
 893 // There is presently no provision for concurrent access
 894 // to breakpoint lists, which is only OK for JVMTI because
 895 // breakpoints are written only at safepoints, and are read
 896 // concurrently only outside of safepoints.
 897 
 898 class BreakpointInfo : public CHeapObj<mtClass> {
 899   friend class VMStructs;
 900  private:
 901   Bytecodes::Code  _orig_bytecode;
 902   int              _bci;
 903   u2               _name_index;       // of method
 904   u2               _signature_index;  // of method
 905   BreakpointInfo*  _next;             // simple storage allocation
 906 
 907  public:
 908   BreakpointInfo(Method* m, int bci);
 909 
 910   // accessors
 911   Bytecodes::Code orig_bytecode()                     { return _orig_bytecode; }
 912   void        set_orig_bytecode(Bytecodes::Code code) { _orig_bytecode = code; }
 913   int         bci()                                   { return _bci; }
 914 
 915   BreakpointInfo*          next() const               { return _next; }
 916   void                 set_next(BreakpointInfo* n)    { _next = n; }
 917 
 918   // helps for searchers
 919   bool match(const Method* m, int bci) {
 920     return bci == _bci && match(m);
 921   }
 922 
 923   bool match(const Method* m) {
 924     return _name_index == m->name_index() &&
 925       _signature_index == m->signature_index();
 926   }
 927 
 928   void set(Method* method);
 929   void clear(Method* method);
 930 };
 931 
 932 // Utility class for access exception handlers
 933 class ExceptionTable : public StackObj {
 934  private:
 935   ExceptionTableElement* _table;
 936   u2  _length;
 937 
 938  public:
 939   ExceptionTable(Method* m) {
 940     if (m->has_exception_handler()) {
 941       _table = m->exception_table_start();
 942       _length = m->exception_table_length();
 943     } else {
 944       _table = NULL;
 945       _length = 0;
 946     }
 947   }
 948 
 949   int length() const {
 950     return _length;
 951   }
 952 
 953   u2 start_pc(int idx) const {
 954     assert(idx < _length, "out of bounds");
 955     return _table[idx].start_pc;
 956   }
 957 
 958   void set_start_pc(int idx, u2 value) {
 959     assert(idx < _length, "out of bounds");
 960     _table[idx].start_pc = value;
 961   }
 962 
 963   u2 end_pc(int idx) const {
 964     assert(idx < _length, "out of bounds");
 965     return _table[idx].end_pc;
 966   }
 967 
 968   void set_end_pc(int idx, u2 value) {
 969     assert(idx < _length, "out of bounds");
 970     _table[idx].end_pc = value;
 971   }
 972 
 973   u2 handler_pc(int idx) const {
 974     assert(idx < _length, "out of bounds");
 975     return _table[idx].handler_pc;
 976   }
 977 
 978   void set_handler_pc(int idx, u2 value) {
 979     assert(idx < _length, "out of bounds");
 980     _table[idx].handler_pc = value;
 981   }
 982 
 983   u2 catch_type_index(int idx) const {
 984     assert(idx < _length, "out of bounds");
 985     return _table[idx].catch_type_index;
 986   }
 987 
 988   void set_catch_type_index(int idx, u2 value) {
 989     assert(idx < _length, "out of bounds");
 990     _table[idx].catch_type_index = value;
 991   }
 992 };
 993 
 994 #endif // SHARE_VM_OOPS_METHODOOP_HPP