1 /*
   2  * Copyright (c) 1997, 2024, 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_CODE_NMETHOD_HPP
  26 #define SHARE_CODE_NMETHOD_HPP
  27 
  28 #include "code/codeBlob.hpp"
  29 #include "code/pcDesc.hpp"
  30 #include "oops/metadata.hpp"
  31 #include "oops/method.hpp"
  32 
  33 class AbstractCompiler;
  34 class CompiledDirectCall;
  35 class CompiledIC;
  36 class CompiledICData;
  37 class CompileTask;
  38 class DepChange;
  39 class Dependencies;
  40 class DirectiveSet;
  41 class DebugInformationRecorder;
  42 class ExceptionHandlerTable;
  43 class ImplicitExceptionTable;
  44 class JvmtiThreadState;
  45 class MetadataClosure;
  46 class NativeCallWrapper;
  47 class OopIterateClosure;
  48 class SCCEntry;
  49 class ScopeDesc;
  50 class xmlStream;
  51 
  52 // This class is used internally by nmethods, to cache
  53 // exception/pc/handler information.
  54 
  55 class ExceptionCache : public CHeapObj<mtCode> {
  56   friend class VMStructs;
  57  private:
  58   enum { cache_size = 16 };
  59   Klass*   _exception_type;
  60   address  _pc[cache_size];
  61   address  _handler[cache_size];
  62   volatile int _count;
  63   ExceptionCache* volatile _next;
  64   ExceptionCache* _purge_list_next;
  65 
  66   inline address pc_at(int index);
  67   void set_pc_at(int index, address a)      { assert(index >= 0 && index < cache_size,""); _pc[index] = a; }
  68 
  69   inline address handler_at(int index);
  70   void set_handler_at(int index, address a) { assert(index >= 0 && index < cache_size,""); _handler[index] = a; }
  71 
  72   inline int count();
  73   // increment_count is only called under lock, but there may be concurrent readers.
  74   void increment_count();
  75 
  76  public:
  77 
  78   ExceptionCache(Handle exception, address pc, address handler);
  79 
  80   Klass*    exception_type()                { return _exception_type; }
  81   ExceptionCache* next();
  82   void      set_next(ExceptionCache *ec);
  83   ExceptionCache* purge_list_next()                 { return _purge_list_next; }
  84   void      set_purge_list_next(ExceptionCache *ec) { _purge_list_next = ec; }
  85 
  86   address match(Handle exception, address pc);
  87   bool    match_exception_with_space(Handle exception) ;
  88   address test_address(address addr);
  89   bool    add_address_and_handler(address addr, address handler) ;
  90 };
  91 
  92 // cache pc descs found in earlier inquiries
  93 class PcDescCache {
  94   friend class VMStructs;
  95  private:
  96   enum { cache_size = 4 };
  97   // The array elements MUST be volatile! Several threads may modify
  98   // and read from the cache concurrently. find_pc_desc_internal has
  99   // returned wrong results. C++ compiler (namely xlC12) may duplicate
 100   // C++ field accesses if the elements are not volatile.
 101   typedef PcDesc* PcDescPtr;
 102   volatile PcDescPtr _pc_descs[cache_size]; // last cache_size pc_descs found
 103  public:
 104   PcDescCache() { debug_only(_pc_descs[0] = nullptr); }
 105   void    init_to(PcDesc* initial_pc_desc);
 106   PcDesc* find_pc_desc(int pc_offset, bool approximate);
 107   void    add_pc_desc(PcDesc* pc_desc);
 108   PcDesc* last_pc_desc() { return _pc_descs[0]; }
 109 };
 110 
 111 class PcDescContainer : public CHeapObj<mtCode> {
 112 private:
 113   PcDescCache _pc_desc_cache;
 114 public:
 115   PcDescContainer(PcDesc* initial_pc_desc) { _pc_desc_cache.init_to(initial_pc_desc); }
 116 
 117   PcDesc* find_pc_desc_internal(address pc, bool approximate, address code_begin,
 118                                 PcDesc* lower, PcDesc* upper);
 119 
 120   PcDesc* find_pc_desc(address pc, bool approximate, address code_begin, PcDesc* lower, PcDesc* upper)
 121 #ifdef PRODUCT
 122   {
 123     PcDesc* desc = _pc_desc_cache.last_pc_desc();
 124     assert(desc != nullptr, "PcDesc cache should be initialized already");
 125     if (desc->pc_offset() == (pc - code_begin)) {
 126       // Cached value matched
 127       return desc;
 128     }
 129     return find_pc_desc_internal(pc, approximate, code_begin, lower, upper);
 130   }
 131 #endif
 132   ;
 133 };
 134 
 135 // nmethods (native methods) are the compiled code versions of Java methods.
 136 //
 137 // An nmethod contains:
 138 //  - header                 (the nmethod structure)
 139 //  [Relocation]
 140 //  - relocation information
 141 //  - constant part          (doubles, longs and floats used in nmethod)
 142 //  - oop table
 143 //  [Code]
 144 //  - code body
 145 //  - exception handler
 146 //  - stub code
 147 //  [Debugging information]
 148 //  - oop array
 149 //  - data array
 150 //  - pcs
 151 //  [Exception handler table]
 152 //  - handler entry point array
 153 //  [Implicit Null Pointer exception table]
 154 //  - implicit null table array
 155 //  [Speculations]
 156 //  - encoded speculations array
 157 //  [JVMCINMethodData]
 158 //  - meta data for JVMCI compiled nmethod
 159 
 160 #if INCLUDE_JVMCI
 161 class FailedSpeculation;
 162 class JVMCINMethodData;
 163 #endif
 164 
 165 class nmethod : public CodeBlob {
 166   friend class VMStructs;
 167   friend class JVMCIVMStructs;
 168   friend class CodeCache;  // scavengable oops
 169   friend class JVMCINMethodData;
 170   friend class DeoptimizationScope;
 171 
 172  private:
 173 
 174   // Used to track in which deoptimize handshake this method will be deoptimized.
 175   uint64_t  _deoptimization_generation;
 176 
 177   uint64_t  _gc_epoch;
 178 
 179   // Profiling counter used to figure out the hottest nmethods to record into CDS
 180   volatile uint64_t _method_profiling_count;
 181 
 182   Method*   _method;
 183 
 184   // To reduce header size union fields which usages do not overlap.
 185   union {
 186     // To support simple linked-list chaining of nmethods:
 187     nmethod*  _osr_link; // from InstanceKlass::osr_nmethods_head
 188     struct {
 189       // These are used for compiled synchronized native methods to
 190       // locate the owner and stack slot for the BasicLock. They are
 191       // needed because there is no debug information for compiled native
 192       // wrappers and the oop maps are insufficient to allow
 193       // frame::retrieve_receiver() to work. Currently they are expected
 194       // to be byte offsets from the Java stack pointer for maximum code
 195       // sharing between platforms. JVMTI's GetLocalInstance() uses these
 196       // offsets to find the receiver for non-static native wrapper frames.
 197       ByteSize _native_receiver_sp_offset;
 198       ByteSize _native_basic_lock_sp_offset;
 199     };
 200   };
 201 
 202   // nmethod's read-only data
 203   address _immutable_data;
 204 
 205   PcDescContainer* _pc_desc_container;
 206   ExceptionCache* volatile _exception_cache;
 207 
 208   void* _gc_data;
 209 
 210   struct oops_do_mark_link; // Opaque data type.
 211   static nmethod*    volatile _oops_do_mark_nmethods;
 212   oops_do_mark_link* volatile _oops_do_mark_link;
 213 
 214   CompiledICData* _compiled_ic_data;
 215 
 216   // offsets for entry points
 217   address  _osr_entry_point;       // entry point for on stack replacement
 218   uint16_t _entry_offset;          // entry point with class check
 219   uint16_t _verified_entry_offset; // entry point without class check
 220   int      _entry_bci;             // != InvocationEntryBci if this nmethod is an on-stack replacement method
 221   int      _immutable_data_size;
 222 
 223   // _consts_offset == _content_offset because SECT_CONSTS is first in code buffer
 224 
 225   int _skipped_instructions_size;
 226 
 227   int _stub_offset;
 228 
 229   // Offsets for different stubs section parts
 230   int _exception_offset;
 231   // All deoptee's will resume execution at this location described by
 232   // this offset.
 233   int _deopt_handler_offset;
 234   // All deoptee's at a MethodHandle call site will resume execution
 235   // at this location described by this offset.
 236   int _deopt_mh_handler_offset;
 237   // Offset (from insts_end) of the unwind handler if it exists
 238   int16_t  _unwind_handler_offset;
 239   // Number of arguments passed on the stack
 240   uint16_t _num_stack_arg_slots;
 241 
 242   // Offsets in mutable data section
 243   // _oops_offset == _data_offset,  offset where embedded oop table begins (inside data)
 244   uint16_t _metadata_offset; // embedded meta data table
 245 #if INCLUDE_JVMCI
 246   uint16_t _jvmci_data_offset;
 247 #endif
 248 
 249   // Offset in immutable data section
 250   // _dependencies_offset == 0
 251   uint16_t _nul_chk_table_offset;
 252   uint16_t _handler_table_offset; // This table could be big in C1 code
 253   int      _scopes_pcs_offset;
 254   int      _scopes_data_offset;
 255 #if INCLUDE_JVMCI
 256   int      _speculations_offset;
 257 #endif
 258 
 259   // location in frame (offset for sp) that deopt can store the original
 260   // pc during a deopt.
 261   int _orig_pc_offset;
 262 
 263   int          _compile_id;            // which compilation made this nmethod
 264   CompLevel    _comp_level;            // compilation level (s1)
 265   CompilerType _compiler_type;         // which compiler made this nmethod (u1)
 266 
 267   SCCEntry* _scc_entry;
 268 
 269   bool _used; // has this nmethod ever been invoked?
 270 
 271   // Local state used to keep track of whether unloading is happening or not
 272   volatile uint8_t _is_unloading_state;
 273 
 274   // Protected by NMethodState_lock
 275   volatile signed char _state;         // {not_installed, in_use, not_entrant}
 276 
 277   // set during construction
 278   uint8_t _has_unsafe_access:1,        // May fault due to unsafe access.
 279           _has_method_handle_invokes:1,// Has this method MethodHandle invokes?
 280           _has_wide_vectors:1,         // Preserve wide vectors at safepoints
 281           _has_monitors:1,             // Fastpath monitor detection for continuations
 282           _has_flushed_dependencies:1, // Used for maintenance of dependencies (under CodeCache_lock)
 283           _is_unlinked:1,              // mark during class unloading
 284           _load_reported:1,            // used by jvmti to track if an event has been posted for this nmethod
 285           _preloaded:1,
 286           _has_clinit_barriers:1;
 287 
 288   enum DeoptimizationStatus : u1 {
 289     not_marked,
 290     deoptimize,
 291     deoptimize_noupdate,
 292     deoptimize_done
 293   };
 294 
 295   volatile DeoptimizationStatus _deoptimization_status; // Used for stack deoptimization
 296 
 297   DeoptimizationStatus deoptimization_status() const {
 298     return Atomic::load(&_deoptimization_status);
 299   }
 300 
 301   // Initialize fields to their default values
 302   void init_defaults(CodeBuffer *code_buffer, CodeOffsets* offsets);
 303 
 304   // Post initialization
 305   void post_init();
 306 
 307   // For native wrappers
 308   nmethod(Method* method,
 309           CompilerType type,
 310           int nmethod_size,
 311           int compile_id,
 312           CodeOffsets* offsets,
 313           CodeBuffer *code_buffer,
 314           int frame_size,
 315           ByteSize basic_lock_owner_sp_offset, /* synchronized natives only */
 316           ByteSize basic_lock_sp_offset,       /* synchronized natives only */
 317           OopMapSet* oop_maps);
 318 
 319   // For normal JIT compiled code
 320   nmethod(Method* method,
 321           CompilerType type,
 322           int nmethod_size,
 323           int immutable_data_size,
 324           int compile_id,
 325           int entry_bci,
 326           address immutable_data,
 327           CodeOffsets* offsets,
 328           int orig_pc_offset,
 329           DebugInformationRecorder *recorder,
 330           Dependencies* dependencies,
 331           CodeBuffer *code_buffer,
 332           int frame_size,
 333           OopMapSet* oop_maps,
 334           ExceptionHandlerTable* handler_table,
 335           ImplicitExceptionTable* nul_chk_table,
 336           AbstractCompiler* compiler,
 337           CompLevel comp_level
 338           , SCCEntry* scc_entry
 339 #if INCLUDE_JVMCI
 340           , char* speculations = nullptr,
 341           int speculations_len = 0,
 342           JVMCINMethodData* jvmci_data = nullptr
 343 #endif
 344           );
 345 
 346   // helper methods
 347   void* operator new(size_t size, int nmethod_size, int comp_level) throw();
 348 
 349   // For method handle intrinsics: Try MethodNonProfiled, MethodProfiled and NonNMethod.
 350   // Attention: Only allow NonNMethod space for special nmethods which don't need to be
 351   // findable by nmethod iterators! In particular, they must not contain oops!
 352   void* operator new(size_t size, int nmethod_size, bool allow_NonNMethod_space) throw();
 353 
 354   const char* reloc_string_for(u_char* begin, u_char* end);
 355 
 356   bool try_transition(signed char new_state);
 357 
 358   // Returns true if this thread changed the state of the nmethod or
 359   // false if another thread performed the transition.
 360   bool make_entrant() { Unimplemented(); return false; }
 361   void inc_decompile_count();
 362 
 363   // Inform external interfaces that a compiled method has been unloaded
 364   void post_compiled_method_unload();
 365 
 366   PcDesc* find_pc_desc(address pc, bool approximate) {
 367     if (_pc_desc_container == nullptr) return nullptr; // native method
 368     return _pc_desc_container->find_pc_desc(pc, approximate, code_begin(), scopes_pcs_begin(), scopes_pcs_end());
 369   }
 370 
 371   // STW two-phase nmethod root processing helpers.
 372   //
 373   // When determining liveness of a given nmethod to do code cache unloading,
 374   // some collectors need to do different things depending on whether the nmethods
 375   // need to absolutely be kept alive during root processing; "strong"ly reachable
 376   // nmethods are known to be kept alive at root processing, but the liveness of
 377   // "weak"ly reachable ones is to be determined later.
 378   //
 379   // We want to allow strong and weak processing of nmethods by different threads
 380   // at the same time without heavy synchronization. Additional constraints are
 381   // to make sure that every nmethod is processed a minimal amount of time, and
 382   // nmethods themselves are always iterated at most once at a particular time.
 383   //
 384   // Note that strong processing work must be a superset of weak processing work
 385   // for this code to work.
 386   //
 387   // We store state and claim information in the _oops_do_mark_link member, using
 388   // the two LSBs for the state and the remaining upper bits for linking together
 389   // nmethods that were already visited.
 390   // The last element is self-looped, i.e. points to itself to avoid some special
 391   // "end-of-list" sentinel value.
 392   //
 393   // _oops_do_mark_link special values:
 394   //
 395   //   _oops_do_mark_link == nullptr: the nmethod has not been visited at all yet, i.e.
 396   //      is Unclaimed.
 397   //
 398   // For other values, its lowest two bits indicate the following states of the nmethod:
 399   //
 400   //   weak_request (WR): the nmethod has been claimed by a thread for weak processing
 401   //   weak_done (WD): weak processing has been completed for this nmethod.
 402   //   strong_request (SR): the nmethod has been found to need strong processing while
 403   //       being weak processed.
 404   //   strong_done (SD): strong processing has been completed for this nmethod .
 405   //
 406   // The following shows the _only_ possible progressions of the _oops_do_mark_link
 407   // pointer.
 408   //
 409   // Given
 410   //   N as the nmethod
 411   //   X the current next value of _oops_do_mark_link
 412   //
 413   // Unclaimed (C)-> N|WR (C)-> X|WD: the nmethod has been processed weakly by
 414   //   a single thread.
 415   // Unclaimed (C)-> N|WR (C)-> X|WD (O)-> X|SD: after weak processing has been
 416   //   completed (as above) another thread found that the nmethod needs strong
 417   //   processing after all.
 418   // Unclaimed (C)-> N|WR (O)-> N|SR (C)-> X|SD: during weak processing another
 419   //   thread finds that the nmethod needs strong processing, marks it as such and
 420   //   terminates. The original thread completes strong processing.
 421   // Unclaimed (C)-> N|SD (C)-> X|SD: the nmethod has been processed strongly from
 422   //   the beginning by a single thread.
 423   //
 424   // "|" describes the concatenation of bits in _oops_do_mark_link.
 425   //
 426   // The diagram also describes the threads responsible for changing the nmethod to
 427   // the next state by marking the _transition_ with (C) and (O), which mean "current"
 428   // and "other" thread respectively.
 429   //
 430 
 431   // States used for claiming nmethods during root processing.
 432   static const uint claim_weak_request_tag = 0;
 433   static const uint claim_weak_done_tag = 1;
 434   static const uint claim_strong_request_tag = 2;
 435   static const uint claim_strong_done_tag = 3;
 436 
 437   static oops_do_mark_link* mark_link(nmethod* nm, uint tag) {
 438     assert(tag <= claim_strong_done_tag, "invalid tag %u", tag);
 439     assert(is_aligned(nm, 4), "nmethod pointer must have zero lower two LSB");
 440     return (oops_do_mark_link*)(((uintptr_t)nm & ~0x3) | tag);
 441   }
 442 
 443   static uint extract_state(oops_do_mark_link* link) {
 444     return (uint)((uintptr_t)link & 0x3);
 445   }
 446 
 447   static nmethod* extract_nmethod(oops_do_mark_link* link) {
 448     return (nmethod*)((uintptr_t)link & ~0x3);
 449   }
 450 
 451   void oops_do_log_change(const char* state);
 452 
 453   static bool oops_do_has_weak_request(oops_do_mark_link* next) {
 454     return extract_state(next) == claim_weak_request_tag;
 455   }
 456 
 457   static bool oops_do_has_any_strong_state(oops_do_mark_link* next) {
 458     return extract_state(next) >= claim_strong_request_tag;
 459   }
 460 
 461   // Attempt Unclaimed -> N|WR transition. Returns true if successful.
 462   bool oops_do_try_claim_weak_request();
 463 
 464   // Attempt Unclaimed -> N|SD transition. Returns the current link.
 465   oops_do_mark_link* oops_do_try_claim_strong_done();
 466   // Attempt N|WR -> X|WD transition. Returns nullptr if successful, X otherwise.
 467   nmethod* oops_do_try_add_to_list_as_weak_done();
 468 
 469   // Attempt X|WD -> N|SR transition. Returns the current link.
 470   oops_do_mark_link* oops_do_try_add_strong_request(oops_do_mark_link* next);
 471   // Attempt X|WD -> X|SD transition. Returns true if successful.
 472   bool oops_do_try_claim_weak_done_as_strong_done(oops_do_mark_link* next);
 473 
 474   // Do the N|SD -> X|SD transition.
 475   void oops_do_add_to_list_as_strong_done();
 476 
 477   // Sets this nmethod as strongly claimed (as part of N|SD -> X|SD and N|SR -> X|SD
 478   // transitions).
 479   void oops_do_set_strong_done(nmethod* old_head);
 480 
 481 public:
 482   // create nmethod with entry_bci
 483   static nmethod* new_nmethod(const methodHandle& method,
 484                               int compile_id,
 485                               int entry_bci,
 486                               CodeOffsets* offsets,
 487                               int orig_pc_offset,
 488                               DebugInformationRecorder* recorder,
 489                               Dependencies* dependencies,
 490                               CodeBuffer *code_buffer,
 491                               int frame_size,
 492                               OopMapSet* oop_maps,
 493                               ExceptionHandlerTable* handler_table,
 494                               ImplicitExceptionTable* nul_chk_table,
 495                               AbstractCompiler* compiler,
 496                               CompLevel comp_level
 497                               , SCCEntry* scc_entry
 498 #if INCLUDE_JVMCI
 499                               , char* speculations = nullptr,
 500                               int speculations_len = 0,
 501                               JVMCINMethodData* jvmci_data = nullptr
 502 #endif
 503   );
 504 
 505   static nmethod* new_native_nmethod(const methodHandle& method,
 506                                      int compile_id,
 507                                      CodeBuffer *code_buffer,
 508                                      int vep_offset,
 509                                      int frame_complete,
 510                                      int frame_size,
 511                                      ByteSize receiver_sp_offset,
 512                                      ByteSize basic_lock_sp_offset,
 513                                      OopMapSet* oop_maps,
 514                                      int exception_handler = -1);
 515 
 516   Method* method       () const { return _method; }
 517   bool is_native_method() const { return _method != nullptr && _method->is_native(); }
 518   bool is_java_method  () const { return _method != nullptr && !_method->is_native(); }
 519   bool is_osr_method   () const { return _entry_bci != InvocationEntryBci; }
 520 
 521   // Compiler task identification.  Note that all OSR methods
 522   // are numbered in an independent sequence if CICountOSR is true,
 523   // and native method wrappers are also numbered independently if
 524   // CICountNative is true.
 525   int compile_id() const { return _compile_id; }
 526   const char* compile_kind() const;
 527 
 528   inline bool  is_compiled_by_c1   () const { return _compiler_type == compiler_c1; }
 529   inline bool  is_compiled_by_c2   () const { return _compiler_type == compiler_c2; }
 530   inline bool  is_compiled_by_jvmci() const { return _compiler_type == compiler_jvmci; }
 531   CompilerType compiler_type       () const { return _compiler_type; }
 532   const char*  compiler_name       () const;
 533 
 534   // boundaries for different parts
 535   address consts_begin          () const { return           content_begin(); }
 536   address consts_end            () const { return           code_begin()   ; }
 537   address insts_begin           () const { return           code_begin()   ; }
 538   address insts_end             () const { return           header_begin() + _stub_offset             ; }
 539   address stub_begin            () const { return           header_begin() + _stub_offset             ; }
 540   address stub_end              () const { return           data_begin()   ; }
 541   address exception_begin       () const { return           header_begin() + _exception_offset        ; }
 542   address deopt_handler_begin   () const { return           header_begin() + _deopt_handler_offset    ; }
 543   address deopt_mh_handler_begin() const { return           header_begin() + _deopt_mh_handler_offset ; }
 544   address unwind_handler_begin  () const { return _unwind_handler_offset != -1 ? (insts_end() - _unwind_handler_offset) : nullptr; }
 545 
 546   // mutable data
 547   oop*    oops_begin            () const { return (oop*)        data_begin(); }
 548   oop*    oops_end              () const { return (oop*)       (data_begin() + _metadata_offset)      ; }
 549   Metadata** metadata_begin     () const { return (Metadata**) (data_begin() + _metadata_offset)      ; }
 550 #if INCLUDE_JVMCI
 551   Metadata** metadata_end       () const { return (Metadata**) (data_begin() + _jvmci_data_offset)    ; }
 552   address jvmci_data_begin      () const { return               data_begin() + _jvmci_data_offset     ; }
 553   address jvmci_data_end        () const { return               data_end(); }
 554 #else
 555   Metadata** metadata_end       () const { return (Metadata**)  data_end(); }
 556 #endif
 557 
 558   // immutable data
 559   address immutable_data_begin  () const { return           _immutable_data; }
 560   address immutable_data_end    () const { return           _immutable_data + _immutable_data_size ; }
 561   address dependencies_begin    () const { return           _immutable_data; }
 562   address dependencies_end      () const { return           _immutable_data + _nul_chk_table_offset; }
 563   address nul_chk_table_begin   () const { return           _immutable_data + _nul_chk_table_offset; }
 564   address nul_chk_table_end     () const { return           _immutable_data + _handler_table_offset; }
 565   address handler_table_begin   () const { return           _immutable_data + _handler_table_offset; }
 566   address handler_table_end     () const { return           _immutable_data + _scopes_pcs_offset   ; }
 567   PcDesc* scopes_pcs_begin      () const { return (PcDesc*)(_immutable_data + _scopes_pcs_offset)  ; }
 568   PcDesc* scopes_pcs_end        () const { return (PcDesc*)(_immutable_data + _scopes_data_offset) ; }
 569   address scopes_data_begin     () const { return           _immutable_data + _scopes_data_offset  ; }
 570 
 571 #if INCLUDE_JVMCI
 572   address scopes_data_end       () const { return           _immutable_data + _speculations_offset ; }
 573   address speculations_begin    () const { return           _immutable_data + _speculations_offset ; }
 574   address speculations_end      () const { return            immutable_data_end(); }
 575 #else
 576   address scopes_data_end       () const { return            immutable_data_end(); }
 577 #endif
 578 
 579   // Sizes
 580   int immutable_data_size() const { return _immutable_data_size; }
 581   int consts_size        () const { return int(          consts_end       () -           consts_begin       ()); }
 582   int insts_size         () const { return int(          insts_end        () -           insts_begin        ()); }
 583   int stub_size          () const { return int(          stub_end         () -           stub_begin         ()); }
 584   int oops_size          () const { return int((address) oops_end         () - (address) oops_begin         ()); }
 585   int metadata_size      () const { return int((address) metadata_end     () - (address) metadata_begin     ()); }
 586   int scopes_data_size   () const { return int(          scopes_data_end  () -           scopes_data_begin  ()); }
 587   int scopes_pcs_size    () const { return int((intptr_t)scopes_pcs_end   () - (intptr_t)scopes_pcs_begin   ()); }
 588   int dependencies_size  () const { return int(          dependencies_end () -           dependencies_begin ()); }
 589   int handler_table_size () const { return int(          handler_table_end() -           handler_table_begin()); }
 590   int nul_chk_table_size () const { return int(          nul_chk_table_end() -           nul_chk_table_begin()); }
 591 #if INCLUDE_JVMCI
 592   int speculations_size  () const { return int(          speculations_end () -           speculations_begin ()); }
 593   int jvmci_data_size    () const { return int(          jvmci_data_end   () -           jvmci_data_begin   ()); }
 594 #endif
 595 
 596   int     oops_count() const { assert(oops_size() % oopSize == 0, "");  return (oops_size() / oopSize) + 1; }
 597   int metadata_count() const { assert(metadata_size() % wordSize == 0, ""); return (metadata_size() / wordSize) + 1; }
 598 
 599   int skipped_instructions_size () const { return _skipped_instructions_size; }
 600   int total_size() const;
 601 
 602   // Containment
 603   bool consts_contains         (address addr) const { return consts_begin       () <= addr && addr < consts_end       (); }
 604   // Returns true if a given address is in the 'insts' section. The method
 605   // insts_contains_inclusive() is end-inclusive.
 606   bool insts_contains          (address addr) const { return insts_begin        () <= addr && addr < insts_end        (); }
 607   bool insts_contains_inclusive(address addr) const { return insts_begin        () <= addr && addr <= insts_end       (); }
 608   bool stub_contains           (address addr) const { return stub_begin         () <= addr && addr < stub_end         (); }
 609   bool oops_contains           (oop*    addr) const { return oops_begin         () <= addr && addr < oops_end         (); }
 610   bool metadata_contains       (Metadata** addr) const { return metadata_begin  () <= addr && addr < metadata_end     (); }
 611   bool scopes_data_contains    (address addr) const { return scopes_data_begin  () <= addr && addr < scopes_data_end  (); }
 612   bool scopes_pcs_contains     (PcDesc* addr) const { return scopes_pcs_begin   () <= addr && addr < scopes_pcs_end   (); }
 613   bool handler_table_contains  (address addr) const { return handler_table_begin() <= addr && addr < handler_table_end(); }
 614   bool nul_chk_table_contains  (address addr) const { return nul_chk_table_begin() <= addr && addr < nul_chk_table_end(); }
 615 
 616   // entry points
 617   address entry_point() const          { return code_begin() + _entry_offset;          } // normal entry point
 618   address verified_entry_point() const { return code_begin() + _verified_entry_offset; } // if klass is correct
 619 
 620   enum : signed char { not_installed = -1, // in construction, only the owner doing the construction is
 621                                            // allowed to advance state
 622                        in_use        = 0,  // executable nmethod
 623                        not_entrant   = 1   // marked for deoptimization but activations may still exist
 624   };
 625 
 626   // flag accessing and manipulation
 627   bool is_not_installed() const        { return _state == not_installed; }
 628   bool is_in_use() const               { return _state <= in_use; }
 629   bool is_not_entrant() const          { return _state == not_entrant; }
 630   int  get_state() const               { return _state; }
 631 
 632   void clear_unloading_state();
 633   // Heuristically deduce an nmethod isn't worth keeping around
 634   bool is_cold();
 635   bool is_unloading();
 636   void do_unloading(bool unloading_occurred);
 637 
 638   void inc_method_profiling_count();
 639   uint64_t method_profiling_count();
 640 
 641   bool make_in_use() {
 642     return try_transition(in_use);
 643   }
 644   // Make the nmethod non entrant. The nmethod will continue to be
 645   // alive.  It is used when an uncommon trap happens.  Returns true
 646   // if this thread changed the state of the nmethod or false if
 647   // another thread performed the transition.
 648   bool  make_not_entrant(bool make_not_entrant = true);
 649   bool  make_not_used() { return make_not_entrant(false); }
 650 
 651   bool  is_marked_for_deoptimization() const { return deoptimization_status() != not_marked; }
 652   bool  has_been_deoptimized() const { return deoptimization_status() == deoptimize_done; }
 653   void  set_deoptimized_done();
 654 
 655   bool update_recompile_counts() const {
 656     // Update recompile counts when either the update is explicitly requested (deoptimize)
 657     // or the nmethod is not marked for deoptimization at all (not_marked).
 658     // The latter happens during uncommon traps when deoptimized nmethod is made not entrant.
 659     DeoptimizationStatus status = deoptimization_status();
 660     return status != deoptimize_noupdate && status != deoptimize_done;
 661   }
 662 
 663   // tells whether frames described by this nmethod can be deoptimized
 664   // note: native wrappers cannot be deoptimized.
 665   bool can_be_deoptimized() const { return is_java_method(); }
 666 
 667   bool has_dependencies()                         { return dependencies_size() != 0; }
 668   void print_dependencies_on(outputStream* out) PRODUCT_RETURN;
 669   void flush_dependencies();
 670 
 671   template<typename T>
 672   T* gc_data() const                              { return reinterpret_cast<T*>(_gc_data); }
 673   template<typename T>
 674   void set_gc_data(T* gc_data)                    { _gc_data = reinterpret_cast<void*>(gc_data); }
 675 
 676   bool  has_unsafe_access() const                 { return _has_unsafe_access; }
 677   void  set_has_unsafe_access(bool z)             { _has_unsafe_access = z; }
 678 
 679   bool  has_monitors() const                      { return _has_monitors; }
 680   void  set_has_monitors(bool z)                  { _has_monitors = z; }
 681 
 682   bool  has_method_handle_invokes() const         { return _has_method_handle_invokes; }
 683   void  set_has_method_handle_invokes(bool z)     { _has_method_handle_invokes = z; }
 684 
 685   bool  has_wide_vectors() const                  { return _has_wide_vectors; }
 686   void  set_has_wide_vectors(bool z)              { _has_wide_vectors = z; }
 687 
 688   bool  has_clinit_barriers() const               { return _has_clinit_barriers; }
 689   void  set_has_clinit_barriers(bool z)           { _has_clinit_barriers = z; }
 690 
 691   bool  preloaded() const                         { return _preloaded; }
 692   void  set_preloaded(bool z)                     { _preloaded = z; }
 693 
 694   bool  has_flushed_dependencies() const          { return _has_flushed_dependencies; }
 695   void  set_has_flushed_dependencies(bool z)      {
 696     assert(!has_flushed_dependencies(), "should only happen once");
 697     _has_flushed_dependencies = z;
 698   }
 699 
 700   bool  is_unlinked() const                       { return _is_unlinked; }
 701   void  set_is_unlinked()                         {
 702      assert(!_is_unlinked, "already unlinked");
 703       _is_unlinked = true;
 704   }
 705 
 706   int   comp_level() const                        { return _comp_level; }
 707 
 708   // Support for oops in scopes and relocs:
 709   // Note: index 0 is reserved for null.
 710   oop   oop_at(int index) const;
 711   oop   oop_at_phantom(int index) const; // phantom reference
 712   oop*  oop_addr_at(int index) const {  // for GC
 713     // relocation indexes are biased by 1 (because 0 is reserved)
 714     assert(index > 0 && index <= oops_count(), "must be a valid non-zero index");
 715     return &oops_begin()[index - 1];
 716   }
 717 
 718   // Support for meta data in scopes and relocs:
 719   // Note: index 0 is reserved for null.
 720   Metadata*   metadata_at(int index) const      { return index == 0 ? nullptr: *metadata_addr_at(index); }
 721   Metadata**  metadata_addr_at(int index) const {  // for GC
 722     // relocation indexes are biased by 1 (because 0 is reserved)
 723     assert(index > 0 && index <= metadata_count(), "must be a valid non-zero index");
 724     return &metadata_begin()[index - 1];
 725   }
 726 
 727   void copy_values(GrowableArray<jobject>* oops);
 728   void copy_values(GrowableArray<Metadata*>* metadata);
 729   void copy_values(GrowableArray<address>* metadata) {} // Nothing to do
 730 
 731   // Relocation support
 732 private:
 733   void fix_oop_relocations(address begin, address end, bool initialize_immediates);
 734   inline void initialize_immediate_oop(oop* dest, jobject handle);
 735 
 736 protected:
 737   address oops_reloc_begin() const;
 738 
 739 public:
 740   void fix_oop_relocations(address begin, address end) { fix_oop_relocations(begin, end, false); }
 741   void fix_oop_relocations()                           { fix_oop_relocations(nullptr, nullptr, false); }
 742 
 743   bool is_at_poll_return(address pc);
 744   bool is_at_poll_or_poll_return(address pc);
 745 
 746 protected:
 747   // Exception cache support
 748   // Note: _exception_cache may be read and cleaned concurrently.
 749   ExceptionCache* exception_cache() const         { return _exception_cache; }
 750   ExceptionCache* exception_cache_acquire() const;
 751 
 752 public:
 753   address handler_for_exception_and_pc(Handle exception, address pc);
 754   void add_handler_for_exception_and_pc(Handle exception, address pc, address handler);
 755   void clean_exception_cache();
 756 
 757   void add_exception_cache_entry(ExceptionCache* new_entry);
 758   ExceptionCache* exception_cache_entry_for_exception(Handle exception);
 759 
 760 
 761   // MethodHandle
 762   bool is_method_handle_return(address return_pc);
 763   // Deopt
 764   // Return true is the PC is one would expect if the frame is being deopted.
 765   inline bool is_deopt_pc(address pc);
 766   inline bool is_deopt_mh_entry(address pc);
 767   inline bool is_deopt_entry(address pc);
 768 
 769   // Accessor/mutator for the original pc of a frame before a frame was deopted.
 770   address get_original_pc(const frame* fr) { return *orig_pc_addr(fr); }
 771   void    set_original_pc(const frame* fr, address pc) { *orig_pc_addr(fr) = pc; }
 772 
 773   const char* state() const;
 774 
 775   bool inlinecache_check_contains(address addr) const {
 776     return (addr >= code_begin() && addr < verified_entry_point());
 777   }
 778 
 779   void preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f);
 780 
 781   // implicit exceptions support
 782   address continuation_for_implicit_div0_exception(address pc) { return continuation_for_implicit_exception(pc, true); }
 783   address continuation_for_implicit_null_exception(address pc) { return continuation_for_implicit_exception(pc, false); }
 784 
 785   // Inline cache support for class unloading and nmethod unloading
 786  private:
 787   void cleanup_inline_caches_impl(bool unloading_occurred, bool clean_all);
 788 
 789   address continuation_for_implicit_exception(address pc, bool for_div0_check);
 790 
 791  public:
 792   // Serial version used by whitebox test
 793   void cleanup_inline_caches_whitebox();
 794 
 795   void clear_inline_caches();
 796 
 797   // Execute nmethod barrier code, as if entering through nmethod call.
 798   void run_nmethod_entry_barrier();
 799 
 800   void verify_oop_relocations();
 801 
 802   bool has_evol_metadata();
 803 
 804   Method* attached_method(address call_pc);
 805   Method* attached_method_before_pc(address pc);
 806 
 807   // GC unloading support
 808   // Cleans unloaded klasses and unloaded nmethods in inline caches
 809 
 810   void unload_nmethod_caches(bool class_unloading_occurred);
 811 
 812   void unlink_from_method();
 813 
 814   // On-stack replacement support
 815   int      osr_entry_bci()    const { assert(is_osr_method(), "wrong kind of nmethod"); return _entry_bci; }
 816   address  osr_entry()        const { assert(is_osr_method(), "wrong kind of nmethod"); return _osr_entry_point; }
 817   nmethod* osr_link()         const { return _osr_link; }
 818   void     set_osr_link(nmethod *n) { _osr_link = n; }
 819   void     invalidate_osr_method();
 820 
 821   int num_stack_arg_slots(bool rounded = true) const {
 822     return rounded ? align_up(_num_stack_arg_slots, 2) : _num_stack_arg_slots;
 823   }
 824 
 825   // Verify calls to dead methods have been cleaned.
 826   void verify_clean_inline_caches();
 827 
 828   // Unlink this nmethod from the system
 829   void unlink();
 830 
 831   // Deallocate this nmethod - called by the GC
 832   void purge(bool unregister_nmethod);
 833 
 834   // See comment at definition of _last_seen_on_stack
 835   void mark_as_maybe_on_stack();
 836   bool is_maybe_on_stack();
 837 
 838   // Evolution support. We make old (discarded) compiled methods point to new Method*s.
 839   void set_method(Method* method) { _method = method; }
 840 
 841 #if INCLUDE_JVMCI
 842   // Gets the JVMCI name of this nmethod.
 843   const char* jvmci_name();
 844 
 845   // Records the pending failed speculation in the
 846   // JVMCI speculation log associated with this nmethod.
 847   void update_speculation(JavaThread* thread);
 848 
 849   // Gets the data specific to a JVMCI compiled method.
 850   // This returns a non-nullptr value iff this nmethod was
 851   // compiled by the JVMCI compiler.
 852   JVMCINMethodData* jvmci_nmethod_data() const {
 853     return jvmci_data_size() == 0 ? nullptr : (JVMCINMethodData*) jvmci_data_begin();
 854   }
 855 #endif
 856 
 857   void oops_do(OopClosure* f) { oops_do(f, false); }
 858   void oops_do(OopClosure* f, bool allow_dead);
 859 
 860   // All-in-one claiming of nmethods: returns true if the caller successfully claimed that
 861   // nmethod.
 862   bool oops_do_try_claim();
 863 
 864   // Loom support for following nmethods on the stack
 865   void follow_nmethod(OopIterateClosure* cl);
 866 
 867   // Class containing callbacks for the oops_do_process_weak/strong() methods
 868   // below.
 869   class OopsDoProcessor {
 870   public:
 871     // Process the oops of the given nmethod based on whether it has been called
 872     // in a weak or strong processing context, i.e. apply either weak or strong
 873     // work on it.
 874     virtual void do_regular_processing(nmethod* nm) = 0;
 875     // Assuming that the oops of the given nmethod has already been its weak
 876     // processing applied, apply the remaining strong processing part.
 877     virtual void do_remaining_strong_processing(nmethod* nm) = 0;
 878   };
 879 
 880   // The following two methods do the work corresponding to weak/strong nmethod
 881   // processing.
 882   void oops_do_process_weak(OopsDoProcessor* p);
 883   void oops_do_process_strong(OopsDoProcessor* p);
 884 
 885   static void oops_do_marking_prologue();
 886   static void oops_do_marking_epilogue();
 887 
 888  private:
 889   ScopeDesc* scope_desc_in(address begin, address end);
 890 
 891   address* orig_pc_addr(const frame* fr);
 892 
 893   // used by jvmti to track if the load events has been reported
 894   bool  load_reported() const                     { return _load_reported; }
 895   void  set_load_reported()                       { _load_reported = true; }
 896 
 897  public:
 898   // ScopeDesc retrieval operation
 899   PcDesc* pc_desc_at(address pc)   { return find_pc_desc(pc, false); }
 900   // pc_desc_near returns the first PcDesc at or after the given pc.
 901   PcDesc* pc_desc_near(address pc) { return find_pc_desc(pc, true); }
 902 
 903   // ScopeDesc for an instruction
 904   ScopeDesc* scope_desc_at(address pc);
 905   ScopeDesc* scope_desc_near(address pc);
 906 
 907   // copying of debugging information
 908   void copy_scopes_pcs(PcDesc* pcs, int count);
 909   void copy_scopes_data(address buffer, int size);
 910 
 911   int orig_pc_offset() { return _orig_pc_offset; }
 912 
 913   SCCEntry* scc_entry() const { return _scc_entry; }
 914   bool is_scc() const { return scc_entry() != nullptr; }
 915 
 916   bool     used() const { return _used; }
 917   void set_used()       { _used = true; }
 918 
 919   // Post successful compilation
 920   void post_compiled_method(CompileTask* task);
 921 
 922   // jvmti support:
 923   void post_compiled_method_load_event(JvmtiThreadState* state = nullptr);
 924 
 925   // verify operations
 926   void verify() override;
 927   void verify_scopes();
 928   void verify_interrupt_point(address interrupt_point, bool is_inline_cache);
 929 
 930   // Disassemble this nmethod with additional debug information, e.g. information about blocks.
 931   void decode2(outputStream* st) const;
 932   void print_constant_pool(outputStream* st);
 933 
 934   // Avoid hiding of parent's 'decode(outputStream*)' method.
 935   void decode(outputStream* st) const { decode2(st); } // just delegate here.
 936 
 937   // printing support
 938   void print()                 const override;
 939   void print(outputStream* st) const;
 940   void print_code();
 941 
 942 #if defined(SUPPORT_DATA_STRUCTS)
 943   // print output in opt build for disassembler library
 944   void print_relocations_on(outputStream* st)     PRODUCT_RETURN;
 945   void print_pcs_on(outputStream* st);
 946   void print_scopes() { print_scopes_on(tty); }
 947   void print_scopes_on(outputStream* st)          PRODUCT_RETURN;
 948   void print_value_on(outputStream* st) const override;
 949   void print_handler_table();
 950   void print_nul_chk_table();
 951   void print_recorded_oop(int log_n, int index);
 952   void print_recorded_oops();
 953   void print_recorded_metadata();
 954 
 955   void print_oops(outputStream* st);     // oops from the underlying CodeBlob.
 956   void print_metadata(outputStream* st); // metadata in metadata pool.
 957 #else
 958   void print_pcs_on(outputStream* st) { return; }
 959 #endif
 960 
 961   void print_calls(outputStream* st)              PRODUCT_RETURN;
 962   static void print_statistics()                  PRODUCT_RETURN;
 963 
 964   void maybe_print_nmethod(const DirectiveSet* directive);
 965   void print_nmethod(bool print_code);
 966 
 967   // need to re-define this from CodeBlob else the overload hides it
 968   void print_on(outputStream* st) const override { CodeBlob::print_on(st); }
 969   void print_on(outputStream* st, const char* msg) const;
 970 
 971   // Logging
 972   void log_identity(xmlStream* log) const;
 973   void log_new_nmethod() const;
 974   void log_state_change() const;
 975 
 976   // Prints block-level comments, including nmethod specific block labels:
 977   void print_block_comment(outputStream* stream, address block_begin) const override {
 978 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 979     print_nmethod_labels(stream, block_begin);
 980     CodeBlob::print_block_comment(stream, block_begin);
 981 #endif
 982   }
 983 
 984   void print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels=true) const;
 985   const char* nmethod_section_label(address pos) const;
 986 
 987   // returns whether this nmethod has code comments.
 988   bool has_code_comment(address begin, address end);
 989   // Prints a comment for one native instruction (reloc info, pc desc)
 990   void print_code_comment_on(outputStream* st, int column, address begin, address end);
 991 
 992   // tells if this compiled method is dependent on the given changes,
 993   // and the changes have invalidated it
 994   bool check_dependency_on(DepChange& changes);
 995 
 996   // Fast breakpoint support. Tells if this compiled method is
 997   // dependent on the given method. Returns true if this nmethod
 998   // corresponds to the given method as well.
 999   bool is_dependent_on_method(Method* dependee);
1000 
1001   // JVMTI's GetLocalInstance() support
1002   ByteSize native_receiver_sp_offset() {
1003     assert(is_native_method(), "sanity");
1004     return _native_receiver_sp_offset;
1005   }
1006   ByteSize native_basic_lock_sp_offset() {
1007     assert(is_native_method(), "sanity");
1008     return _native_basic_lock_sp_offset;
1009   }
1010 
1011   // support for code generation
1012   static ByteSize osr_entry_point_offset() { return byte_offset_of(nmethod, _osr_entry_point); }
1013   static ByteSize state_offset()           { return byte_offset_of(nmethod, _state); }
1014 
1015   void metadata_do(MetadataClosure* f);
1016 
1017   address call_instruction_address(address pc) const;
1018 
1019   void make_deoptimized();
1020   void finalize_relocations();
1021 };
1022 
1023 #endif // SHARE_CODE_NMETHOD_HPP