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