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