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