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