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_scoped_access:1,        // used by for shared scope closure (scopedMemoryAccess.cpp)
 283           _has_flushed_dependencies:1, // Used for maintenance of dependencies (under CodeCache_lock)
 284           _is_unlinked:1,              // mark during class unloading
 285           _load_reported:1,            // used by jvmti to track if an event has been posted for this nmethod
 286           _preloaded:1,
 287           _has_clinit_barriers:1;
 288 
 289   enum DeoptimizationStatus : u1 {
 290     not_marked,
 291     deoptimize,
 292     deoptimize_noupdate,
 293     deoptimize_done
 294   };
 295 
 296   volatile DeoptimizationStatus _deoptimization_status; // Used for stack deoptimization
 297 
 298   DeoptimizationStatus deoptimization_status() const {
 299     return Atomic::load(&_deoptimization_status);
 300   }
 301 
 302   // Initialize fields to their default values
 303   void init_defaults(CodeBuffer *code_buffer, CodeOffsets* offsets);
 304 
 305   // Post initialization
 306   void post_init();
 307 
 308   // For native wrappers
 309   nmethod(Method* method,
 310           CompilerType type,
 311           int nmethod_size,
 312           int compile_id,
 313           CodeOffsets* offsets,
 314           CodeBuffer *code_buffer,
 315           int frame_size,
 316           ByteSize basic_lock_owner_sp_offset, /* synchronized natives only */
 317           ByteSize basic_lock_sp_offset,       /* synchronized natives only */
 318           OopMapSet* oop_maps);
 319 
 320   // For normal JIT compiled code
 321   nmethod(Method* method,
 322           CompilerType type,
 323           int nmethod_size,
 324           int immutable_data_size,
 325           int compile_id,
 326           int entry_bci,
 327           address immutable_data,
 328           CodeOffsets* offsets,
 329           int orig_pc_offset,
 330           DebugInformationRecorder *recorder,
 331           Dependencies* dependencies,
 332           CodeBuffer *code_buffer,
 333           int frame_size,
 334           OopMapSet* oop_maps,
 335           ExceptionHandlerTable* handler_table,
 336           ImplicitExceptionTable* nul_chk_table,
 337           AbstractCompiler* compiler,
 338           CompLevel comp_level
 339           , SCCEntry* scc_entry
 340 #if INCLUDE_JVMCI
 341           , char* speculations = nullptr,
 342           int speculations_len = 0,
 343           JVMCINMethodData* jvmci_data = nullptr
 344 #endif
 345           );
 346 
 347   // helper methods
 348   void* operator new(size_t size, int nmethod_size, int comp_level) throw();
 349 
 350   // For method handle intrinsics: Try MethodNonProfiled, MethodProfiled and NonNMethod.
 351   // Attention: Only allow NonNMethod space for special nmethods which don't need to be
 352   // findable by nmethod iterators! In particular, they must not contain oops!
 353   void* operator new(size_t size, int nmethod_size, bool allow_NonNMethod_space) throw();
 354 
 355   const char* reloc_string_for(u_char* begin, u_char* end);
 356 
 357   bool try_transition(signed char new_state);
 358 
 359   // Returns true if this thread changed the state of the nmethod or
 360   // false if another thread performed the transition.
 361   bool make_entrant() { Unimplemented(); return false; }
 362   void inc_decompile_count();
 363 
 364   // Inform external interfaces that a compiled method has been unloaded
 365   void post_compiled_method_unload();
 366 
 367   PcDesc* find_pc_desc(address pc, bool approximate) {
 368     if (_pc_desc_container == nullptr) return nullptr; // native method
 369     return _pc_desc_container->find_pc_desc(pc, approximate, code_begin(), scopes_pcs_begin(), scopes_pcs_end());
 370   }
 371 
 372   // STW two-phase nmethod root processing helpers.
 373   //
 374   // When determining liveness of a given nmethod to do code cache unloading,
 375   // some collectors need to do different things depending on whether the nmethods
 376   // need to absolutely be kept alive during root processing; "strong"ly reachable
 377   // nmethods are known to be kept alive at root processing, but the liveness of
 378   // "weak"ly reachable ones is to be determined later.
 379   //
 380   // We want to allow strong and weak processing of nmethods by different threads
 381   // at the same time without heavy synchronization. Additional constraints are
 382   // to make sure that every nmethod is processed a minimal amount of time, and
 383   // nmethods themselves are always iterated at most once at a particular time.
 384   //
 385   // Note that strong processing work must be a superset of weak processing work
 386   // for this code to work.
 387   //
 388   // We store state and claim information in the _oops_do_mark_link member, using
 389   // the two LSBs for the state and the remaining upper bits for linking together
 390   // nmethods that were already visited.
 391   // The last element is self-looped, i.e. points to itself to avoid some special
 392   // "end-of-list" sentinel value.
 393   //
 394   // _oops_do_mark_link special values:
 395   //
 396   //   _oops_do_mark_link == nullptr: the nmethod has not been visited at all yet, i.e.
 397   //      is Unclaimed.
 398   //
 399   // For other values, its lowest two bits indicate the following states of the nmethod:
 400   //
 401   //   weak_request (WR): the nmethod has been claimed by a thread for weak processing
 402   //   weak_done (WD): weak processing has been completed for this nmethod.
 403   //   strong_request (SR): the nmethod has been found to need strong processing while
 404   //       being weak processed.
 405   //   strong_done (SD): strong processing has been completed for this nmethod .
 406   //
 407   // The following shows the _only_ possible progressions of the _oops_do_mark_link
 408   // pointer.
 409   //
 410   // Given
 411   //   N as the nmethod
 412   //   X the current next value of _oops_do_mark_link
 413   //
 414   // Unclaimed (C)-> N|WR (C)-> X|WD: the nmethod has been processed weakly by
 415   //   a single thread.
 416   // Unclaimed (C)-> N|WR (C)-> X|WD (O)-> X|SD: after weak processing has been
 417   //   completed (as above) another thread found that the nmethod needs strong
 418   //   processing after all.
 419   // Unclaimed (C)-> N|WR (O)-> N|SR (C)-> X|SD: during weak processing another
 420   //   thread finds that the nmethod needs strong processing, marks it as such and
 421   //   terminates. The original thread completes strong processing.
 422   // Unclaimed (C)-> N|SD (C)-> X|SD: the nmethod has been processed strongly from
 423   //   the beginning by a single thread.
 424   //
 425   // "|" describes the concatenation of bits in _oops_do_mark_link.
 426   //
 427   // The diagram also describes the threads responsible for changing the nmethod to
 428   // the next state by marking the _transition_ with (C) and (O), which mean "current"
 429   // and "other" thread respectively.
 430   //
 431 
 432   // States used for claiming nmethods during root processing.
 433   static const uint claim_weak_request_tag = 0;
 434   static const uint claim_weak_done_tag = 1;
 435   static const uint claim_strong_request_tag = 2;
 436   static const uint claim_strong_done_tag = 3;
 437 
 438   static oops_do_mark_link* mark_link(nmethod* nm, uint tag) {
 439     assert(tag <= claim_strong_done_tag, "invalid tag %u", tag);
 440     assert(is_aligned(nm, 4), "nmethod pointer must have zero lower two LSB");
 441     return (oops_do_mark_link*)(((uintptr_t)nm & ~0x3) | tag);
 442   }
 443 
 444   static uint extract_state(oops_do_mark_link* link) {
 445     return (uint)((uintptr_t)link & 0x3);
 446   }
 447 
 448   static nmethod* extract_nmethod(oops_do_mark_link* link) {
 449     return (nmethod*)((uintptr_t)link & ~0x3);
 450   }
 451 
 452   void oops_do_log_change(const char* state);
 453 
 454   static bool oops_do_has_weak_request(oops_do_mark_link* next) {
 455     return extract_state(next) == claim_weak_request_tag;
 456   }
 457 
 458   static bool oops_do_has_any_strong_state(oops_do_mark_link* next) {
 459     return extract_state(next) >= claim_strong_request_tag;
 460   }
 461 
 462   // Attempt Unclaimed -> N|WR transition. Returns true if successful.
 463   bool oops_do_try_claim_weak_request();
 464 
 465   // Attempt Unclaimed -> N|SD transition. Returns the current link.
 466   oops_do_mark_link* oops_do_try_claim_strong_done();
 467   // Attempt N|WR -> X|WD transition. Returns nullptr if successful, X otherwise.
 468   nmethod* oops_do_try_add_to_list_as_weak_done();
 469 
 470   // Attempt X|WD -> N|SR transition. Returns the current link.
 471   oops_do_mark_link* oops_do_try_add_strong_request(oops_do_mark_link* next);
 472   // Attempt X|WD -> X|SD transition. Returns true if successful.
 473   bool oops_do_try_claim_weak_done_as_strong_done(oops_do_mark_link* next);
 474 
 475   // Do the N|SD -> X|SD transition.
 476   void oops_do_add_to_list_as_strong_done();
 477 
 478   // Sets this nmethod as strongly claimed (as part of N|SD -> X|SD and N|SR -> X|SD
 479   // transitions).
 480   void oops_do_set_strong_done(nmethod* old_head);
 481 
 482 public:
 483   // create nmethod with entry_bci
 484   static nmethod* new_nmethod(const methodHandle& method,
 485                               int compile_id,
 486                               int entry_bci,
 487                               CodeOffsets* offsets,
 488                               int orig_pc_offset,
 489                               DebugInformationRecorder* recorder,
 490                               Dependencies* dependencies,
 491                               CodeBuffer *code_buffer,
 492                               int frame_size,
 493                               OopMapSet* oop_maps,
 494                               ExceptionHandlerTable* handler_table,
 495                               ImplicitExceptionTable* nul_chk_table,
 496                               AbstractCompiler* compiler,
 497                               CompLevel comp_level
 498                               , SCCEntry* scc_entry
 499 #if INCLUDE_JVMCI
 500                               , char* speculations = nullptr,
 501                               int speculations_len = 0,
 502                               JVMCINMethodData* jvmci_data = nullptr
 503 #endif
 504   );
 505 
 506   static nmethod* new_native_nmethod(const methodHandle& method,
 507                                      int compile_id,
 508                                      CodeBuffer *code_buffer,
 509                                      int vep_offset,
 510                                      int frame_complete,
 511                                      int frame_size,
 512                                      ByteSize receiver_sp_offset,
 513                                      ByteSize basic_lock_sp_offset,
 514                                      OopMapSet* oop_maps,
 515                                      int exception_handler = -1);
 516 
 517   Method* method       () const { return _method; }
 518   bool is_native_method() const { return _method != nullptr && _method->is_native(); }
 519   bool is_java_method  () const { return _method != nullptr && !_method->is_native(); }
 520   bool is_osr_method   () const { return _entry_bci != InvocationEntryBci; }
 521 
 522   // Compiler task identification.  Note that all OSR methods
 523   // are numbered in an independent sequence if CICountOSR is true,
 524   // and native method wrappers are also numbered independently if
 525   // CICountNative is true.
 526   int compile_id() const { return _compile_id; }
 527   const char* compile_kind() const;
 528 
 529   inline bool  is_compiled_by_c1   () const { return _compiler_type == compiler_c1; }
 530   inline bool  is_compiled_by_c2   () const { return _compiler_type == compiler_c2; }
 531   inline bool  is_compiled_by_jvmci() const { return _compiler_type == compiler_jvmci; }
 532   CompilerType compiler_type       () const { return _compiler_type; }
 533   const char*  compiler_name       () const;
 534 
 535   // boundaries for different parts
 536   address consts_begin          () const { return           content_begin(); }
 537   address consts_end            () const { return           code_begin()   ; }
 538   address insts_begin           () const { return           code_begin()   ; }
 539   address insts_end             () const { return           header_begin() + _stub_offset             ; }
 540   address stub_begin            () const { return           header_begin() + _stub_offset             ; }
 541   address stub_end              () const { return           data_begin()   ; }
 542   address exception_begin       () const { return           header_begin() + _exception_offset        ; }
 543   address deopt_handler_begin   () const { return           header_begin() + _deopt_handler_offset    ; }
 544   address deopt_mh_handler_begin() const { return           header_begin() + _deopt_mh_handler_offset ; }
 545   address unwind_handler_begin  () const { return _unwind_handler_offset != -1 ? (insts_end() - _unwind_handler_offset) : nullptr; }
 546 
 547   // mutable data
 548   oop*    oops_begin            () const { return (oop*)        data_begin(); }
 549   oop*    oops_end              () const { return (oop*)       (data_begin() + _metadata_offset)      ; }
 550   Metadata** metadata_begin     () const { return (Metadata**) (data_begin() + _metadata_offset)      ; }
 551 #if INCLUDE_JVMCI
 552   Metadata** metadata_end       () const { return (Metadata**) (data_begin() + _jvmci_data_offset)    ; }
 553   address jvmci_data_begin      () const { return               data_begin() + _jvmci_data_offset     ; }
 554   address jvmci_data_end        () const { return               data_end(); }
 555 #else
 556   Metadata** metadata_end       () const { return (Metadata**)  data_end(); }
 557 #endif
 558 
 559   // immutable data
 560   address immutable_data_begin  () const { return           _immutable_data; }
 561   address immutable_data_end    () const { return           _immutable_data + _immutable_data_size ; }
 562   address dependencies_begin    () const { return           _immutable_data; }
 563   address dependencies_end      () const { return           _immutable_data + _nul_chk_table_offset; }
 564   address nul_chk_table_begin   () const { return           _immutable_data + _nul_chk_table_offset; }
 565   address nul_chk_table_end     () const { return           _immutable_data + _handler_table_offset; }
 566   address handler_table_begin   () const { return           _immutable_data + _handler_table_offset; }
 567   address handler_table_end     () const { return           _immutable_data + _scopes_pcs_offset   ; }
 568   PcDesc* scopes_pcs_begin      () const { return (PcDesc*)(_immutable_data + _scopes_pcs_offset)  ; }
 569   PcDesc* scopes_pcs_end        () const { return (PcDesc*)(_immutable_data + _scopes_data_offset) ; }
 570   address scopes_data_begin     () const { return           _immutable_data + _scopes_data_offset  ; }
 571 
 572 #if INCLUDE_JVMCI
 573   address scopes_data_end       () const { return           _immutable_data + _speculations_offset ; }
 574   address speculations_begin    () const { return           _immutable_data + _speculations_offset ; }
 575   address speculations_end      () const { return            immutable_data_end(); }
 576 #else
 577   address scopes_data_end       () const { return            immutable_data_end(); }
 578 #endif
 579 
 580   // Sizes
 581   int immutable_data_size() const { return _immutable_data_size; }
 582   int consts_size        () const { return int(          consts_end       () -           consts_begin       ()); }
 583   int insts_size         () const { return int(          insts_end        () -           insts_begin        ()); }
 584   int stub_size          () const { return int(          stub_end         () -           stub_begin         ()); }
 585   int oops_size          () const { return int((address) oops_end         () - (address) oops_begin         ()); }
 586   int metadata_size      () const { return int((address) metadata_end     () - (address) metadata_begin     ()); }
 587   int scopes_data_size   () const { return int(          scopes_data_end  () -           scopes_data_begin  ()); }
 588   int scopes_pcs_size    () const { return int((intptr_t)scopes_pcs_end   () - (intptr_t)scopes_pcs_begin   ()); }
 589   int dependencies_size  () const { return int(          dependencies_end () -           dependencies_begin ()); }
 590   int handler_table_size () const { return int(          handler_table_end() -           handler_table_begin()); }
 591   int nul_chk_table_size () const { return int(          nul_chk_table_end() -           nul_chk_table_begin()); }
 592 #if INCLUDE_JVMCI
 593   int speculations_size  () const { return int(          speculations_end () -           speculations_begin ()); }
 594   int jvmci_data_size    () const { return int(          jvmci_data_end   () -           jvmci_data_begin   ()); }
 595 #endif
 596 
 597   int     oops_count() const { assert(oops_size() % oopSize == 0, "");  return (oops_size() / oopSize) + 1; }
 598   int metadata_count() const { assert(metadata_size() % wordSize == 0, ""); return (metadata_size() / wordSize) + 1; }
 599 
 600   int skipped_instructions_size () const { return _skipped_instructions_size; }
 601   int total_size() const;
 602 
 603   // Containment
 604   bool consts_contains         (address addr) const { return consts_begin       () <= addr && addr < consts_end       (); }
 605   // Returns true if a given address is in the 'insts' section. The method
 606   // insts_contains_inclusive() is end-inclusive.
 607   bool insts_contains          (address addr) const { return insts_begin        () <= addr && addr < insts_end        (); }
 608   bool insts_contains_inclusive(address addr) const { return insts_begin        () <= addr && addr <= insts_end       (); }
 609   bool stub_contains           (address addr) const { return stub_begin         () <= addr && addr < stub_end         (); }
 610   bool oops_contains           (oop*    addr) const { return oops_begin         () <= addr && addr < oops_end         (); }
 611   bool metadata_contains       (Metadata** addr) const { return metadata_begin  () <= addr && addr < metadata_end     (); }
 612   bool scopes_data_contains    (address addr) const { return scopes_data_begin  () <= addr && addr < scopes_data_end  (); }
 613   bool scopes_pcs_contains     (PcDesc* addr) const { return scopes_pcs_begin   () <= addr && addr < scopes_pcs_end   (); }
 614   bool handler_table_contains  (address addr) const { return handler_table_begin() <= addr && addr < handler_table_end(); }
 615   bool nul_chk_table_contains  (address addr) const { return nul_chk_table_begin() <= addr && addr < nul_chk_table_end(); }
 616 
 617   // entry points
 618   address entry_point() const          { return code_begin() + _entry_offset;          } // normal entry point
 619   address verified_entry_point() const { return code_begin() + _verified_entry_offset; } // if klass is correct
 620 
 621   enum : signed char { not_installed = -1, // in construction, only the owner doing the construction is
 622                                            // allowed to advance state
 623                        in_use        = 0,  // executable nmethod
 624                        not_entrant   = 1   // marked for deoptimization but activations may still exist
 625   };
 626 
 627   // flag accessing and manipulation
 628   bool is_not_installed() const        { return _state == not_installed; }
 629   bool is_in_use() const               { return _state <= in_use; }
 630   bool is_not_entrant() const          { return _state == not_entrant; }
 631   int  get_state() const               { return _state; }
 632 
 633   void clear_unloading_state();
 634   // Heuristically deduce an nmethod isn't worth keeping around
 635   bool is_cold();
 636   bool is_unloading();
 637   void do_unloading(bool unloading_occurred);
 638 
 639   void inc_method_profiling_count();
 640   uint64_t method_profiling_count();
 641 
 642   bool make_in_use() {
 643     return try_transition(in_use);
 644   }
 645   // Make the nmethod non entrant. The nmethod will continue to be
 646   // alive.  It is used when an uncommon trap happens.  Returns true
 647   // if this thread changed the state of the nmethod or false if
 648   // another thread performed the transition.
 649   bool  make_not_entrant(bool make_not_entrant = true);
 650   bool  make_not_used() { return make_not_entrant(false); }
 651 
 652   bool  is_marked_for_deoptimization() const { return deoptimization_status() != not_marked; }
 653   bool  has_been_deoptimized() const { return deoptimization_status() == deoptimize_done; }
 654   void  set_deoptimized_done();
 655 
 656   bool update_recompile_counts() const {
 657     // Update recompile counts when either the update is explicitly requested (deoptimize)
 658     // or the nmethod is not marked for deoptimization at all (not_marked).
 659     // The latter happens during uncommon traps when deoptimized nmethod is made not entrant.
 660     DeoptimizationStatus status = deoptimization_status();
 661     return status != deoptimize_noupdate && status != deoptimize_done;
 662   }
 663 
 664   // tells whether frames described by this nmethod can be deoptimized
 665   // note: native wrappers cannot be deoptimized.
 666   bool can_be_deoptimized() const { return is_java_method(); }
 667 
 668   bool has_dependencies()                         { return dependencies_size() != 0; }
 669   void print_dependencies_on(outputStream* out) PRODUCT_RETURN;
 670   void flush_dependencies();
 671 
 672   template<typename T>
 673   T* gc_data() const                              { return reinterpret_cast<T*>(_gc_data); }
 674   template<typename T>
 675   void set_gc_data(T* gc_data)                    { _gc_data = reinterpret_cast<void*>(gc_data); }
 676 
 677   bool  has_unsafe_access() const                 { return _has_unsafe_access; }
 678   void  set_has_unsafe_access(bool z)             { _has_unsafe_access = z; }
 679 
 680   bool  has_monitors() const                      { return _has_monitors; }
 681   void  set_has_monitors(bool z)                  { _has_monitors = z; }
 682 
 683   bool  has_scoped_access() const                 { return _has_scoped_access; }
 684   void  set_has_scoped_access(bool z)             { _has_scoped_access = z; }
 685 
 686   bool  has_method_handle_invokes() const         { return _has_method_handle_invokes; }
 687   void  set_has_method_handle_invokes(bool z)     { _has_method_handle_invokes = z; }
 688 
 689   bool  has_wide_vectors() const                  { return _has_wide_vectors; }
 690   void  set_has_wide_vectors(bool z)              { _has_wide_vectors = z; }
 691 
 692   bool  has_clinit_barriers() const               { return _has_clinit_barriers; }
 693   void  set_has_clinit_barriers(bool z)           { _has_clinit_barriers = z; }
 694 
 695   bool  preloaded() const                         { return _preloaded; }
 696   void  set_preloaded(bool z)                     { _preloaded = z; }
 697 
 698   bool  has_flushed_dependencies() const          { return _has_flushed_dependencies; }
 699   void  set_has_flushed_dependencies(bool z)      {
 700     assert(!has_flushed_dependencies(), "should only happen once");
 701     _has_flushed_dependencies = z;
 702   }
 703 
 704   bool  is_unlinked() const                       { return _is_unlinked; }
 705   void  set_is_unlinked()                         {
 706      assert(!_is_unlinked, "already unlinked");
 707       _is_unlinked = true;
 708   }
 709 
 710   int   comp_level() const                        { return _comp_level; }
 711 
 712   // Support for oops in scopes and relocs:
 713   // Note: index 0 is reserved for null.
 714   oop   oop_at(int index) const;
 715   oop   oop_at_phantom(int index) const; // phantom reference
 716   oop*  oop_addr_at(int index) const {  // for GC
 717     // relocation indexes are biased by 1 (because 0 is reserved)
 718     assert(index > 0 && index <= oops_count(), "must be a valid non-zero index");
 719     return &oops_begin()[index - 1];
 720   }
 721 
 722   // Support for meta data in scopes and relocs:
 723   // Note: index 0 is reserved for null.
 724   Metadata*   metadata_at(int index) const      { return index == 0 ? nullptr: *metadata_addr_at(index); }
 725   Metadata**  metadata_addr_at(int index) const {  // for GC
 726     // relocation indexes are biased by 1 (because 0 is reserved)
 727     assert(index > 0 && index <= metadata_count(), "must be a valid non-zero index");
 728     return &metadata_begin()[index - 1];
 729   }
 730 
 731   void copy_values(GrowableArray<jobject>* oops);
 732   void copy_values(GrowableArray<Metadata*>* metadata);
 733   void copy_values(GrowableArray<address>* metadata) {} // Nothing to do
 734 
 735   // Relocation support
 736 private:
 737   void fix_oop_relocations(address begin, address end, bool initialize_immediates);
 738   inline void initialize_immediate_oop(oop* dest, jobject handle);
 739 
 740 protected:
 741   address oops_reloc_begin() const;
 742 
 743 public:
 744   void fix_oop_relocations(address begin, address end) { fix_oop_relocations(begin, end, false); }
 745   void fix_oop_relocations()                           { fix_oop_relocations(nullptr, nullptr, false); }
 746 
 747   bool is_at_poll_return(address pc);
 748   bool is_at_poll_or_poll_return(address pc);
 749 
 750 protected:
 751   // Exception cache support
 752   // Note: _exception_cache may be read and cleaned concurrently.
 753   ExceptionCache* exception_cache() const         { return _exception_cache; }
 754   ExceptionCache* exception_cache_acquire() const;
 755 
 756 public:
 757   address handler_for_exception_and_pc(Handle exception, address pc);
 758   void add_handler_for_exception_and_pc(Handle exception, address pc, address handler);
 759   void clean_exception_cache();
 760 
 761   void add_exception_cache_entry(ExceptionCache* new_entry);
 762   ExceptionCache* exception_cache_entry_for_exception(Handle exception);
 763 
 764 
 765   // MethodHandle
 766   bool is_method_handle_return(address return_pc);
 767   // Deopt
 768   // Return true is the PC is one would expect if the frame is being deopted.
 769   inline bool is_deopt_pc(address pc);
 770   inline bool is_deopt_mh_entry(address pc);
 771   inline bool is_deopt_entry(address pc);
 772 
 773   // Accessor/mutator for the original pc of a frame before a frame was deopted.
 774   address get_original_pc(const frame* fr) { return *orig_pc_addr(fr); }
 775   void    set_original_pc(const frame* fr, address pc) { *orig_pc_addr(fr) = pc; }
 776 
 777   const char* state() const;
 778 
 779   bool inlinecache_check_contains(address addr) const {
 780     return (addr >= code_begin() && addr < verified_entry_point());
 781   }
 782 
 783   void preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f);
 784 
 785   // implicit exceptions support
 786   address continuation_for_implicit_div0_exception(address pc) { return continuation_for_implicit_exception(pc, true); }
 787   address continuation_for_implicit_null_exception(address pc) { return continuation_for_implicit_exception(pc, false); }
 788 
 789   // Inline cache support for class unloading and nmethod unloading
 790  private:
 791   void cleanup_inline_caches_impl(bool unloading_occurred, bool clean_all);
 792 
 793   address continuation_for_implicit_exception(address pc, bool for_div0_check);
 794 
 795  public:
 796   // Serial version used by whitebox test
 797   void cleanup_inline_caches_whitebox();
 798 
 799   void clear_inline_caches();
 800 
 801   // Execute nmethod barrier code, as if entering through nmethod call.
 802   void run_nmethod_entry_barrier();
 803 
 804   void verify_oop_relocations();
 805 
 806   bool has_evol_metadata();
 807 
 808   Method* attached_method(address call_pc);
 809   Method* attached_method_before_pc(address pc);
 810 
 811   // GC unloading support
 812   // Cleans unloaded klasses and unloaded nmethods in inline caches
 813 
 814   void unload_nmethod_caches(bool class_unloading_occurred);
 815 
 816   void unlink_from_method();
 817 
 818   // On-stack replacement support
 819   int      osr_entry_bci()    const { assert(is_osr_method(), "wrong kind of nmethod"); return _entry_bci; }
 820   address  osr_entry()        const { assert(is_osr_method(), "wrong kind of nmethod"); return _osr_entry_point; }
 821   nmethod* osr_link()         const { return _osr_link; }
 822   void     set_osr_link(nmethod *n) { _osr_link = n; }
 823   void     invalidate_osr_method();
 824 
 825   int num_stack_arg_slots(bool rounded = true) const {
 826     return rounded ? align_up(_num_stack_arg_slots, 2) : _num_stack_arg_slots;
 827   }
 828 
 829   // Verify calls to dead methods have been cleaned.
 830   void verify_clean_inline_caches();
 831 
 832   // Unlink this nmethod from the system
 833   void unlink();
 834 
 835   // Deallocate this nmethod - called by the GC
 836   void purge(bool unregister_nmethod);
 837 
 838   // See comment at definition of _last_seen_on_stack
 839   void mark_as_maybe_on_stack();
 840   bool is_maybe_on_stack();
 841 
 842   // Evolution support. We make old (discarded) compiled methods point to new Method*s.
 843   void set_method(Method* method) { _method = method; }
 844 
 845 #if INCLUDE_JVMCI
 846   // Gets the JVMCI name of this nmethod.
 847   const char* jvmci_name();
 848 
 849   // Records the pending failed speculation in the
 850   // JVMCI speculation log associated with this nmethod.
 851   void update_speculation(JavaThread* thread);
 852 
 853   // Gets the data specific to a JVMCI compiled method.
 854   // This returns a non-nullptr value iff this nmethod was
 855   // compiled by the JVMCI compiler.
 856   JVMCINMethodData* jvmci_nmethod_data() const {
 857     return jvmci_data_size() == 0 ? nullptr : (JVMCINMethodData*) jvmci_data_begin();
 858   }
 859 #endif
 860 
 861   void oops_do(OopClosure* f) { oops_do(f, false); }
 862   void oops_do(OopClosure* f, bool allow_dead);
 863 
 864   // All-in-one claiming of nmethods: returns true if the caller successfully claimed that
 865   // nmethod.
 866   bool oops_do_try_claim();
 867 
 868   // Loom support for following nmethods on the stack
 869   void follow_nmethod(OopIterateClosure* cl);
 870 
 871   // Class containing callbacks for the oops_do_process_weak/strong() methods
 872   // below.
 873   class OopsDoProcessor {
 874   public:
 875     // Process the oops of the given nmethod based on whether it has been called
 876     // in a weak or strong processing context, i.e. apply either weak or strong
 877     // work on it.
 878     virtual void do_regular_processing(nmethod* nm) = 0;
 879     // Assuming that the oops of the given nmethod has already been its weak
 880     // processing applied, apply the remaining strong processing part.
 881     virtual void do_remaining_strong_processing(nmethod* nm) = 0;
 882   };
 883 
 884   // The following two methods do the work corresponding to weak/strong nmethod
 885   // processing.
 886   void oops_do_process_weak(OopsDoProcessor* p);
 887   void oops_do_process_strong(OopsDoProcessor* p);
 888 
 889   static void oops_do_marking_prologue();
 890   static void oops_do_marking_epilogue();
 891 
 892  private:
 893   ScopeDesc* scope_desc_in(address begin, address end);
 894 
 895   address* orig_pc_addr(const frame* fr);
 896 
 897   // used by jvmti to track if the load events has been reported
 898   bool  load_reported() const                     { return _load_reported; }
 899   void  set_load_reported()                       { _load_reported = true; }
 900 
 901  public:
 902   // ScopeDesc retrieval operation
 903   PcDesc* pc_desc_at(address pc)   { return find_pc_desc(pc, false); }
 904   // pc_desc_near returns the first PcDesc at or after the given pc.
 905   PcDesc* pc_desc_near(address pc) { return find_pc_desc(pc, true); }
 906 
 907   // ScopeDesc for an instruction
 908   ScopeDesc* scope_desc_at(address pc);
 909   ScopeDesc* scope_desc_near(address pc);
 910 
 911   // copying of debugging information
 912   void copy_scopes_pcs(PcDesc* pcs, int count);
 913   void copy_scopes_data(address buffer, int size);
 914 
 915   int orig_pc_offset() { return _orig_pc_offset; }
 916 
 917   SCCEntry* scc_entry() const { return _scc_entry; }
 918   bool is_scc() const { return scc_entry() != nullptr; }
 919 
 920   bool     used() const { return _used; }
 921   void set_used()       { _used = true; }
 922 
 923   // Post successful compilation
 924   void post_compiled_method(CompileTask* task);
 925 
 926   // jvmti support:
 927   void post_compiled_method_load_event(JvmtiThreadState* state = nullptr);
 928 
 929   // verify operations
 930   void verify() override;
 931   void verify_scopes();
 932   void verify_interrupt_point(address interrupt_point, bool is_inline_cache);
 933 
 934   // Disassemble this nmethod with additional debug information, e.g. information about blocks.
 935   void decode2(outputStream* st) const;
 936   void print_constant_pool(outputStream* st);
 937 
 938   // Avoid hiding of parent's 'decode(outputStream*)' method.
 939   void decode(outputStream* st) const { decode2(st); } // just delegate here.
 940 
 941   // printing support
 942   void print()                 const override;
 943   void print(outputStream* st) const;
 944   void print_code();
 945 
 946 #if defined(SUPPORT_DATA_STRUCTS)
 947   // print output in opt build for disassembler library
 948   void print_relocations_on(outputStream* st)     PRODUCT_RETURN;
 949   void print_pcs_on(outputStream* st);
 950   void print_scopes() { print_scopes_on(tty); }
 951   void print_scopes_on(outputStream* st)          PRODUCT_RETURN;
 952   void print_value_on(outputStream* st) const override;
 953   void print_handler_table();
 954   void print_nul_chk_table();
 955   void print_recorded_oop(int log_n, int index);
 956   void print_recorded_oops();
 957   void print_recorded_metadata();
 958 
 959   void print_oops(outputStream* st);     // oops from the underlying CodeBlob.
 960   void print_metadata(outputStream* st); // metadata in metadata pool.
 961 #else
 962   void print_pcs_on(outputStream* st) { return; }
 963 #endif
 964 
 965   void print_calls(outputStream* st)              PRODUCT_RETURN;
 966   static void print_statistics()                  PRODUCT_RETURN;
 967 
 968   void maybe_print_nmethod(const DirectiveSet* directive);
 969   void print_nmethod(bool print_code);
 970 
 971   // need to re-define this from CodeBlob else the overload hides it
 972   void print_on(outputStream* st) const override { CodeBlob::print_on(st); }
 973   void print_on(outputStream* st, const char* msg) const;
 974 
 975   // Logging
 976   void log_identity(xmlStream* log) const;
 977   void log_new_nmethod() const;
 978   void log_state_change() const;
 979 
 980   // Prints block-level comments, including nmethod specific block labels:
 981   void print_block_comment(outputStream* stream, address block_begin) const override {
 982 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 983     print_nmethod_labels(stream, block_begin);
 984     CodeBlob::print_block_comment(stream, block_begin);
 985 #endif
 986   }
 987 
 988   void print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels=true) const;
 989   const char* nmethod_section_label(address pos) const;
 990 
 991   // returns whether this nmethod has code comments.
 992   bool has_code_comment(address begin, address end);
 993   // Prints a comment for one native instruction (reloc info, pc desc)
 994   void print_code_comment_on(outputStream* st, int column, address begin, address end);
 995 
 996   // tells if this compiled method is dependent on the given changes,
 997   // and the changes have invalidated it
 998   bool check_dependency_on(DepChange& changes);
 999 
1000   // Fast breakpoint support. Tells if this compiled method is
1001   // dependent on the given method. Returns true if this nmethod
1002   // corresponds to the given method as well.
1003   bool is_dependent_on_method(Method* dependee);
1004 
1005   // JVMTI's GetLocalInstance() support
1006   ByteSize native_receiver_sp_offset() {
1007     assert(is_native_method(), "sanity");
1008     return _native_receiver_sp_offset;
1009   }
1010   ByteSize native_basic_lock_sp_offset() {
1011     assert(is_native_method(), "sanity");
1012     return _native_basic_lock_sp_offset;
1013   }
1014 
1015   // support for code generation
1016   static ByteSize osr_entry_point_offset() { return byte_offset_of(nmethod, _osr_entry_point); }
1017   static ByteSize state_offset()           { return byte_offset_of(nmethod, _state); }
1018 
1019   void metadata_do(MetadataClosure* f);
1020 
1021   address call_instruction_address(address pc) const;
1022 
1023   void make_deoptimized();
1024   void finalize_relocations();
1025 };
1026 
1027 #endif // SHARE_CODE_NMETHOD_HPP