1 /*
2 * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "asm/assembler.inline.hpp"
26 #include "cds/cdsConfig.hpp"
27 #include "code/codeCache.hpp"
28 #include "code/compiledIC.hpp"
29 #include "code/dependencies.hpp"
30 #include "code/nativeInst.hpp"
31 #include "code/nmethod.inline.hpp"
32 #include "code/scopeDesc.hpp"
33 #include "compiler/abstractCompiler.hpp"
34 #include "compiler/compilationLog.hpp"
35 #include "compiler/compileBroker.hpp"
36 #include "compiler/compileLog.hpp"
37 #include "compiler/compilerDirectives.hpp"
38 #include "compiler/compilerOracle.hpp"
39 #include "compiler/compileTask.hpp"
40 #include "compiler/directivesParser.hpp"
41 #include "compiler/disassembler.hpp"
42 #include "compiler/oopMap.inline.hpp"
43 #include "gc/shared/barrierSet.hpp"
44 #include "gc/shared/barrierSetNMethod.hpp"
45 #include "gc/shared/classUnloadingContext.hpp"
46 #include "gc/shared/collectedHeap.hpp"
47 #include "interpreter/bytecode.inline.hpp"
48 #include "jvm.h"
49 #include "logging/log.hpp"
50 #include "logging/logStream.hpp"
51 #include "memory/allocation.inline.hpp"
52 #include "memory/resourceArea.hpp"
53 #include "memory/universe.hpp"
54 #include "oops/access.inline.hpp"
55 #include "oops/klass.inline.hpp"
56 #include "oops/method.inline.hpp"
57 #include "oops/methodData.hpp"
58 #include "oops/oop.inline.hpp"
59 #include "oops/weakHandle.inline.hpp"
60 #include "prims/jvmtiImpl.hpp"
61 #include "prims/jvmtiThreadState.hpp"
62 #include "prims/methodHandles.hpp"
63 #include "runtime/atomicAccess.hpp"
64 #include "runtime/continuation.hpp"
65 #include "runtime/deoptimization.hpp"
66 #include "runtime/flags/flagSetting.hpp"
67 #include "runtime/frame.inline.hpp"
68 #include "runtime/handles.inline.hpp"
69 #include "runtime/icache.hpp"
70 #include "runtime/jniHandles.inline.hpp"
71 #include "runtime/orderAccess.hpp"
72 #include "runtime/os.hpp"
73 #include "runtime/safepointVerifiers.hpp"
74 #include "runtime/serviceThread.hpp"
75 #include "runtime/sharedRuntime.hpp"
76 #include "runtime/signature.hpp"
77 #include "runtime/threadWXSetters.inline.hpp"
78 #include "runtime/vmThread.hpp"
79 #include "utilities/align.hpp"
80 #include "utilities/copy.hpp"
81 #include "utilities/dtrace.hpp"
82 #include "utilities/events.hpp"
83 #include "utilities/globalDefinitions.hpp"
84 #include "utilities/hashTable.hpp"
85 #include "utilities/xmlstream.hpp"
86 #if INCLUDE_JVMCI
87 #include "jvmci/jvmciRuntime.hpp"
88 #endif
89
90 #ifdef DTRACE_ENABLED
91
92 // Only bother with this argument setup if dtrace is available
93
94 #define DTRACE_METHOD_UNLOAD_PROBE(method) \
95 { \
96 Method* m = (method); \
97 if (m != nullptr) { \
98 Symbol* klass_name = m->klass_name(); \
99 Symbol* name = m->name(); \
100 Symbol* signature = m->signature(); \
101 HOTSPOT_COMPILED_METHOD_UNLOAD( \
102 (char *) klass_name->bytes(), klass_name->utf8_length(), \
103 (char *) name->bytes(), name->utf8_length(), \
104 (char *) signature->bytes(), signature->utf8_length()); \
105 } \
106 }
107
108 #else // ndef DTRACE_ENABLED
109
110 #define DTRACE_METHOD_UNLOAD_PROBE(method)
111
112 #endif
113
114 // Cast from int value to narrow type
115 #define CHECKED_CAST(result, T, thing) \
116 result = static_cast<T>(thing); \
117 guarantee(static_cast<int>(result) == thing, "failed: %d != %d", static_cast<int>(result), thing);
118
119 //---------------------------------------------------------------------------------
120 // NMethod statistics
121 // They are printed under various flags, including:
122 // PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.
123 // (In the latter two cases, they like other stats are printed to the log only.)
124
125 #ifndef PRODUCT
126 // These variables are put into one block to reduce relocations
127 // and make it simpler to print from the debugger.
128 struct java_nmethod_stats_struct {
129 uint nmethod_count;
130 uint total_nm_size;
131 uint total_immut_size;
132 uint total_mut_size;
133 uint relocation_size;
134 uint consts_size;
135 uint insts_size;
136 uint stub_size;
137 uint oops_size;
138 uint metadata_size;
139 uint dependencies_size;
140 uint nul_chk_table_size;
141 uint handler_table_size;
142 uint scopes_pcs_size;
143 uint scopes_data_size;
144 #if INCLUDE_JVMCI
145 uint speculations_size;
146 uint jvmci_data_size;
147 #endif
148
149 void note_nmethod(nmethod* nm) {
150 nmethod_count += 1;
151 total_nm_size += nm->size();
152 total_immut_size += nm->immutable_data_size();
153 total_mut_size += nm->mutable_data_size();
154 relocation_size += nm->relocation_size();
155 consts_size += nm->consts_size();
156 insts_size += nm->insts_size();
157 stub_size += nm->stub_size();
158 oops_size += nm->oops_size();
159 metadata_size += nm->metadata_size();
160 scopes_data_size += nm->scopes_data_size();
161 scopes_pcs_size += nm->scopes_pcs_size();
162 dependencies_size += nm->dependencies_size();
163 handler_table_size += nm->handler_table_size();
164 nul_chk_table_size += nm->nul_chk_table_size();
165 #if INCLUDE_JVMCI
166 speculations_size += nm->speculations_size();
167 jvmci_data_size += nm->jvmci_data_size();
168 #endif
169 }
170 void print_nmethod_stats(const char* name) {
171 if (nmethod_count == 0) return;
172 tty->print_cr("Statistics for %u bytecoded nmethods for %s:", nmethod_count, name);
173 uint total_size = total_nm_size + total_immut_size + total_mut_size;
174 if (total_nm_size != 0) {
175 tty->print_cr(" total size = %u (100%%)", total_size);
176 tty->print_cr(" in CodeCache = %u (%f%%)", total_nm_size, (total_nm_size * 100.0f)/total_size);
177 }
178 uint header_size = (uint)(nmethod_count * sizeof(nmethod));
179 if (nmethod_count != 0) {
180 tty->print_cr(" header = %u (%f%%)", header_size, (header_size * 100.0f)/total_nm_size);
181 }
182 if (consts_size != 0) {
183 tty->print_cr(" constants = %u (%f%%)", consts_size, (consts_size * 100.0f)/total_nm_size);
184 }
185 if (insts_size != 0) {
186 tty->print_cr(" main code = %u (%f%%)", insts_size, (insts_size * 100.0f)/total_nm_size);
187 }
188 if (stub_size != 0) {
189 tty->print_cr(" stub code = %u (%f%%)", stub_size, (stub_size * 100.0f)/total_nm_size);
190 }
191 if (oops_size != 0) {
192 tty->print_cr(" oops = %u (%f%%)", oops_size, (oops_size * 100.0f)/total_nm_size);
193 }
194 if (total_mut_size != 0) {
195 tty->print_cr(" mutable data = %u (%f%%)", total_mut_size, (total_mut_size * 100.0f)/total_size);
196 }
197 if (relocation_size != 0) {
198 tty->print_cr(" relocation = %u (%f%%)", relocation_size, (relocation_size * 100.0f)/total_mut_size);
199 }
200 if (metadata_size != 0) {
201 tty->print_cr(" metadata = %u (%f%%)", metadata_size, (metadata_size * 100.0f)/total_mut_size);
202 }
203 #if INCLUDE_JVMCI
204 if (jvmci_data_size != 0) {
205 tty->print_cr(" JVMCI data = %u (%f%%)", jvmci_data_size, (jvmci_data_size * 100.0f)/total_mut_size);
206 }
207 #endif
208 if (total_immut_size != 0) {
209 tty->print_cr(" immutable data = %u (%f%%)", total_immut_size, (total_immut_size * 100.0f)/total_size);
210 }
211 if (dependencies_size != 0) {
212 tty->print_cr(" dependencies = %u (%f%%)", dependencies_size, (dependencies_size * 100.0f)/total_immut_size);
213 }
214 if (nul_chk_table_size != 0) {
215 tty->print_cr(" nul chk table = %u (%f%%)", nul_chk_table_size, (nul_chk_table_size * 100.0f)/total_immut_size);
216 }
217 if (handler_table_size != 0) {
218 tty->print_cr(" handler table = %u (%f%%)", handler_table_size, (handler_table_size * 100.0f)/total_immut_size);
219 }
220 if (scopes_pcs_size != 0) {
221 tty->print_cr(" scopes pcs = %u (%f%%)", scopes_pcs_size, (scopes_pcs_size * 100.0f)/total_immut_size);
222 }
223 if (scopes_data_size != 0) {
224 tty->print_cr(" scopes data = %u (%f%%)", scopes_data_size, (scopes_data_size * 100.0f)/total_immut_size);
225 }
226 #if INCLUDE_JVMCI
227 if (speculations_size != 0) {
228 tty->print_cr(" speculations = %u (%f%%)", speculations_size, (speculations_size * 100.0f)/total_immut_size);
229 }
230 #endif
231 }
232 };
233
234 struct native_nmethod_stats_struct {
235 uint native_nmethod_count;
236 uint native_total_size;
237 uint native_relocation_size;
238 uint native_insts_size;
239 uint native_oops_size;
240 uint native_metadata_size;
241 void note_native_nmethod(nmethod* nm) {
242 native_nmethod_count += 1;
243 native_total_size += nm->size();
244 native_relocation_size += nm->relocation_size();
245 native_insts_size += nm->insts_size();
246 native_oops_size += nm->oops_size();
247 native_metadata_size += nm->metadata_size();
248 }
249 void print_native_nmethod_stats() {
250 if (native_nmethod_count == 0) return;
251 tty->print_cr("Statistics for %u native nmethods:", native_nmethod_count);
252 if (native_total_size != 0) tty->print_cr(" N. total size = %u", native_total_size);
253 if (native_relocation_size != 0) tty->print_cr(" N. relocation = %u", native_relocation_size);
254 if (native_insts_size != 0) tty->print_cr(" N. main code = %u", native_insts_size);
255 if (native_oops_size != 0) tty->print_cr(" N. oops = %u", native_oops_size);
256 if (native_metadata_size != 0) tty->print_cr(" N. metadata = %u", native_metadata_size);
257 }
258 };
259
260 struct pc_nmethod_stats_struct {
261 uint pc_desc_init; // number of initialization of cache (= number of caches)
262 uint pc_desc_queries; // queries to nmethod::find_pc_desc
263 uint pc_desc_approx; // number of those which have approximate true
264 uint pc_desc_repeats; // number of _pc_descs[0] hits
265 uint pc_desc_hits; // number of LRU cache hits
266 uint pc_desc_tests; // total number of PcDesc examinations
267 uint pc_desc_searches; // total number of quasi-binary search steps
268 uint pc_desc_adds; // number of LUR cache insertions
269
270 void print_pc_stats() {
271 tty->print_cr("PcDesc Statistics: %u queries, %.2f comparisons per query",
272 pc_desc_queries,
273 (double)(pc_desc_tests + pc_desc_searches)
274 / pc_desc_queries);
275 tty->print_cr(" caches=%d queries=%u/%u, hits=%u+%u, tests=%u+%u, adds=%u",
276 pc_desc_init,
277 pc_desc_queries, pc_desc_approx,
278 pc_desc_repeats, pc_desc_hits,
279 pc_desc_tests, pc_desc_searches, pc_desc_adds);
280 }
281 };
282
283 #ifdef COMPILER1
284 static java_nmethod_stats_struct c1_java_nmethod_stats;
285 #endif
286 #ifdef COMPILER2
287 static java_nmethod_stats_struct c2_java_nmethod_stats;
288 #endif
289 #if INCLUDE_JVMCI
290 static java_nmethod_stats_struct jvmci_java_nmethod_stats;
291 #endif
292 static java_nmethod_stats_struct unknown_java_nmethod_stats;
293
294 static native_nmethod_stats_struct native_nmethod_stats;
295 static pc_nmethod_stats_struct pc_nmethod_stats;
296
297 static void note_java_nmethod(nmethod* nm) {
298 #ifdef COMPILER1
299 if (nm->is_compiled_by_c1()) {
300 c1_java_nmethod_stats.note_nmethod(nm);
301 } else
302 #endif
303 #ifdef COMPILER2
304 if (nm->is_compiled_by_c2()) {
305 c2_java_nmethod_stats.note_nmethod(nm);
306 } else
307 #endif
308 #if INCLUDE_JVMCI
309 if (nm->is_compiled_by_jvmci()) {
310 jvmci_java_nmethod_stats.note_nmethod(nm);
311 } else
312 #endif
313 {
314 unknown_java_nmethod_stats.note_nmethod(nm);
315 }
316 }
317 #endif // !PRODUCT
318
319 //---------------------------------------------------------------------------------
320
321
322 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {
323 assert(pc != nullptr, "Must be non null");
324 assert(exception.not_null(), "Must be non null");
325 assert(handler != nullptr, "Must be non null");
326
327 _count = 0;
328 _exception_type = exception->klass();
329 _next = nullptr;
330 _purge_list_next = nullptr;
331
332 add_address_and_handler(pc,handler);
333 }
334
335
336 address ExceptionCache::match(Handle exception, address pc) {
337 assert(pc != nullptr,"Must be non null");
338 assert(exception.not_null(),"Must be non null");
339 if (exception->klass() == exception_type()) {
340 return (test_address(pc));
341 }
342
343 return nullptr;
344 }
345
346
347 bool ExceptionCache::match_exception_with_space(Handle exception) {
348 assert(exception.not_null(),"Must be non null");
349 if (exception->klass() == exception_type() && count() < cache_size) {
350 return true;
351 }
352 return false;
353 }
354
355
356 address ExceptionCache::test_address(address addr) {
357 int limit = count();
358 for (int i = 0; i < limit; i++) {
359 if (pc_at(i) == addr) {
360 return handler_at(i);
361 }
362 }
363 return nullptr;
364 }
365
366
367 bool ExceptionCache::add_address_and_handler(address addr, address handler) {
368 if (test_address(addr) == handler) return true;
369
370 int index = count();
371 if (index < cache_size) {
372 set_pc_at(index, addr);
373 set_handler_at(index, handler);
374 increment_count();
375 return true;
376 }
377 return false;
378 }
379
380 ExceptionCache* ExceptionCache::next() {
381 return AtomicAccess::load(&_next);
382 }
383
384 void ExceptionCache::set_next(ExceptionCache *ec) {
385 AtomicAccess::store(&_next, ec);
386 }
387
388 //-----------------------------------------------------------------------------
389
390
391 // Helper used by both find_pc_desc methods.
392 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {
393 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests);
394 if (!approximate) {
395 return pc->pc_offset() == pc_offset;
396 } else {
397 // Do not look before the sentinel
398 assert(pc_offset > PcDesc::lower_offset_limit, "illegal pc_offset");
399 return pc_offset <= pc->pc_offset() && (pc-1)->pc_offset() < pc_offset;
400 }
401 }
402
403 void PcDescCache::init_to(PcDesc* initial_pc_desc) {
404 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_init);
405 // initialize the cache by filling it with benign (non-null) values
406 assert(initial_pc_desc != nullptr && initial_pc_desc->pc_offset() == PcDesc::lower_offset_limit,
407 "must start with a sentinel");
408 for (int i = 0; i < cache_size; i++) {
409 _pc_descs[i] = initial_pc_desc;
410 }
411 }
412
413 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {
414 // Note: one might think that caching the most recently
415 // read value separately would be a win, but one would be
416 // wrong. When many threads are updating it, the cache
417 // line it's in would bounce between caches, negating
418 // any benefit.
419
420 // In order to prevent race conditions do not load cache elements
421 // repeatedly, but use a local copy:
422 PcDesc* res;
423
424 // Step one: Check the most recently added value.
425 res = _pc_descs[0];
426 assert(res != nullptr, "PcDesc cache should be initialized already");
427
428 // Approximate only here since PcDescContainer::find_pc_desc() checked for exact case.
429 if (approximate && match_desc(res, pc_offset, approximate)) {
430 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats);
431 return res;
432 }
433
434 // Step two: Check the rest of the LRU cache.
435 for (int i = 1; i < cache_size; ++i) {
436 res = _pc_descs[i];
437 if (res->pc_offset() < 0) break; // optimization: skip empty cache
438 if (match_desc(res, pc_offset, approximate)) {
439 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits);
440 return res;
441 }
442 }
443
444 // Report failure.
445 return nullptr;
446 }
447
448 void PcDescCache::add_pc_desc(PcDesc* pc_desc) {
449 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds);
450 // Update the LRU cache by shifting pc_desc forward.
451 for (int i = 0; i < cache_size; i++) {
452 PcDesc* next = _pc_descs[i];
453 _pc_descs[i] = pc_desc;
454 pc_desc = next;
455 }
456 }
457
458 // adjust pcs_size so that it is a multiple of both oopSize and
459 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple
460 // of oopSize, then 2*sizeof(PcDesc) is)
461 static int adjust_pcs_size(int pcs_size) {
462 int nsize = align_up(pcs_size, oopSize);
463 if ((nsize % sizeof(PcDesc)) != 0) {
464 nsize = pcs_size + sizeof(PcDesc);
465 }
466 assert((nsize % oopSize) == 0, "correct alignment");
467 return nsize;
468 }
469
470 // Returns a string version of the method state.
471 const char* nmethod::state() const {
472 int state = get_state();
473 switch (state) {
474 case not_installed:
475 return "not installed";
476 case in_use:
477 return "in use";
478 case not_entrant:
479 return "not_entrant";
480 default:
481 fatal("unexpected method state: %d", state);
482 return nullptr;
483 }
484 }
485
486 void nmethod::set_deoptimized_done() {
487 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
488 if (_deoptimization_status != deoptimize_done) { // can't go backwards
489 AtomicAccess::store(&_deoptimization_status, deoptimize_done);
490 }
491 }
492
493 ExceptionCache* nmethod::exception_cache_acquire() const {
494 return AtomicAccess::load_acquire(&_exception_cache);
495 }
496
497 void nmethod::add_exception_cache_entry(ExceptionCache* new_entry) {
498 assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock");
499 assert(new_entry != nullptr,"Must be non null");
500 assert(new_entry->next() == nullptr, "Must be null");
501
502 for (;;) {
503 ExceptionCache *ec = exception_cache();
504 if (ec != nullptr) {
505 Klass* ex_klass = ec->exception_type();
506 if (!ex_klass->is_loader_alive()) {
507 // We must guarantee that entries are not inserted with new next pointer
508 // edges to ExceptionCache entries with dead klasses, due to bad interactions
509 // with concurrent ExceptionCache cleanup. Therefore, the inserts roll
510 // the head pointer forward to the first live ExceptionCache, so that the new
511 // next pointers always point at live ExceptionCaches, that are not removed due
512 // to concurrent ExceptionCache cleanup.
513 ExceptionCache* next = ec->next();
514 if (AtomicAccess::cmpxchg(&_exception_cache, ec, next) == ec) {
515 CodeCache::release_exception_cache(ec);
516 }
517 continue;
518 }
519 ec = exception_cache();
520 if (ec != nullptr) {
521 new_entry->set_next(ec);
522 }
523 }
524 if (AtomicAccess::cmpxchg(&_exception_cache, ec, new_entry) == ec) {
525 return;
526 }
527 }
528 }
529
530 void nmethod::clean_exception_cache() {
531 // For each nmethod, only a single thread may call this cleanup function
532 // at the same time, whether called in STW cleanup or concurrent cleanup.
533 // Note that if the GC is processing exception cache cleaning in a concurrent phase,
534 // then a single writer may contend with cleaning up the head pointer to the
535 // first ExceptionCache node that has a Klass* that is alive. That is fine,
536 // as long as there is no concurrent cleanup of next pointers from concurrent writers.
537 // And the concurrent writers do not clean up next pointers, only the head.
538 // Also note that concurrent readers will walk through Klass* pointers that are not
539 // alive. That does not cause ABA problems, because Klass* is deleted after
540 // a handshake with all threads, after all stale ExceptionCaches have been
541 // unlinked. That is also when the CodeCache::exception_cache_purge_list()
542 // is deleted, with all ExceptionCache entries that were cleaned concurrently.
543 // That similarly implies that CAS operations on ExceptionCache entries do not
544 // suffer from ABA problems as unlinking and deletion is separated by a global
545 // handshake operation.
546 ExceptionCache* prev = nullptr;
547 ExceptionCache* curr = exception_cache_acquire();
548
549 while (curr != nullptr) {
550 ExceptionCache* next = curr->next();
551
552 if (!curr->exception_type()->is_loader_alive()) {
553 if (prev == nullptr) {
554 // Try to clean head; this is contended by concurrent inserts, that
555 // both lazily clean the head, and insert entries at the head. If
556 // the CAS fails, the operation is restarted.
557 if (AtomicAccess::cmpxchg(&_exception_cache, curr, next) != curr) {
558 prev = nullptr;
559 curr = exception_cache_acquire();
560 continue;
561 }
562 } else {
563 // It is impossible to during cleanup connect the next pointer to
564 // an ExceptionCache that has not been published before a safepoint
565 // prior to the cleanup. Therefore, release is not required.
566 prev->set_next(next);
567 }
568 // prev stays the same.
569
570 CodeCache::release_exception_cache(curr);
571 } else {
572 prev = curr;
573 }
574
575 curr = next;
576 }
577 }
578
579 // public method for accessing the exception cache
580 // These are the public access methods.
581 address nmethod::handler_for_exception_and_pc(Handle exception, address pc) {
582 // We never grab a lock to read the exception cache, so we may
583 // have false negatives. This is okay, as it can only happen during
584 // the first few exception lookups for a given nmethod.
585 ExceptionCache* ec = exception_cache_acquire();
586 while (ec != nullptr) {
587 address ret_val;
588 if ((ret_val = ec->match(exception,pc)) != nullptr) {
589 return ret_val;
590 }
591 ec = ec->next();
592 }
593 return nullptr;
594 }
595
596 void nmethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
597 // There are potential race conditions during exception cache updates, so we
598 // must own the ExceptionCache_lock before doing ANY modifications. Because
599 // we don't lock during reads, it is possible to have several threads attempt
600 // to update the cache with the same data. We need to check for already inserted
601 // copies of the current data before adding it.
602
603 MutexLocker ml(ExceptionCache_lock);
604 ExceptionCache* target_entry = exception_cache_entry_for_exception(exception);
605
606 if (target_entry == nullptr || !target_entry->add_address_and_handler(pc,handler)) {
607 target_entry = new ExceptionCache(exception,pc,handler);
608 add_exception_cache_entry(target_entry);
609 }
610 }
611
612 // private method for handling exception cache
613 // These methods are private, and used to manipulate the exception cache
614 // directly.
615 ExceptionCache* nmethod::exception_cache_entry_for_exception(Handle exception) {
616 ExceptionCache* ec = exception_cache_acquire();
617 while (ec != nullptr) {
618 if (ec->match_exception_with_space(exception)) {
619 return ec;
620 }
621 ec = ec->next();
622 }
623 return nullptr;
624 }
625
626 bool nmethod::is_at_poll_return(address pc) {
627 RelocIterator iter(this, pc, pc+1);
628 while (iter.next()) {
629 if (iter.type() == relocInfo::poll_return_type)
630 return true;
631 }
632 return false;
633 }
634
635
636 bool nmethod::is_at_poll_or_poll_return(address pc) {
637 RelocIterator iter(this, pc, pc+1);
638 while (iter.next()) {
639 relocInfo::relocType t = iter.type();
640 if (t == relocInfo::poll_return_type || t == relocInfo::poll_type)
641 return true;
642 }
643 return false;
644 }
645
646 void nmethod::verify_oop_relocations() {
647 // Ensure sure that the code matches the current oop values
648 RelocIterator iter(this, nullptr, nullptr);
649 while (iter.next()) {
650 if (iter.type() == relocInfo::oop_type) {
651 oop_Relocation* reloc = iter.oop_reloc();
652 if (!reloc->oop_is_immediate()) {
653 reloc->verify_oop_relocation();
654 }
655 }
656 }
657 }
658
659
660 ScopeDesc* nmethod::scope_desc_at(address pc) {
661 PcDesc* pd = pc_desc_at(pc);
662 guarantee(pd != nullptr, "scope must be present");
663 return new ScopeDesc(this, pd);
664 }
665
666 ScopeDesc* nmethod::scope_desc_near(address pc) {
667 PcDesc* pd = pc_desc_near(pc);
668 guarantee(pd != nullptr, "scope must be present");
669 return new ScopeDesc(this, pd);
670 }
671
672 address nmethod::oops_reloc_begin() const {
673 // If the method is not entrant then a JMP is plastered over the
674 // first few bytes. If an oop in the old code was there, that oop
675 // should not get GC'd. Skip the first few bytes of oops on
676 // not-entrant methods.
677 if (frame_complete_offset() != CodeOffsets::frame_never_safe &&
678 code_begin() + frame_complete_offset() >
679 verified_entry_point() + NativeJump::instruction_size)
680 {
681 // If we have a frame_complete_offset after the native jump, then there
682 // is no point trying to look for oops before that. This is a requirement
683 // for being allowed to scan oops concurrently.
684 return code_begin() + frame_complete_offset();
685 }
686
687 address low_boundary = verified_entry_point();
688 return low_boundary;
689 }
690
691 // Method that knows how to preserve outgoing arguments at call. This method must be
692 // called with a frame corresponding to a Java invoke
693 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
694 if (method() == nullptr) {
695 return;
696 }
697
698 // handle the case of an anchor explicitly set in continuation code that doesn't have a callee
699 JavaThread* thread = reg_map->thread();
700 if ((thread->has_last_Java_frame() && fr.sp() == thread->last_Java_sp())
701 JVMTI_ONLY(|| (method()->is_continuation_enter_intrinsic() && thread->on_monitor_waited_event()))) {
702 return;
703 }
704
705 if (!method()->is_native()) {
706 address pc = fr.pc();
707 bool has_receiver, has_appendix;
708 Symbol* signature;
709
710 // The method attached by JIT-compilers should be used, if present.
711 // Bytecode can be inaccurate in such case.
712 Method* callee = attached_method_before_pc(pc);
713 if (callee != nullptr) {
714 has_receiver = !(callee->access_flags().is_static());
715 has_appendix = false;
716 signature = callee->signature();
717
718 // If inline types are passed as fields, use the extended signature
719 // which contains the types of all (oop) fields of the inline type.
720 if (is_compiled_by_c2() && callee->has_scalarized_args()) {
721 const GrowableArray<SigEntry>* sig = callee->adapter()->get_sig_cc();
722 assert(sig != nullptr, "sig should never be null");
723 TempNewSymbol tmp_sig = SigEntry::create_symbol(sig);
724 has_receiver = false; // The extended signature contains the receiver type
725 fr.oops_compiled_arguments_do(tmp_sig, has_receiver, has_appendix, reg_map, f);
726 return;
727 }
728 } else {
729 SimpleScopeDesc ssd(this, pc);
730
731 Bytecode_invoke call(methodHandle(Thread::current(), ssd.method()), ssd.bci());
732 has_receiver = call.has_receiver();
733 has_appendix = call.has_appendix();
734 signature = call.signature();
735 }
736
737 fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
738 } else if (method()->is_continuation_enter_intrinsic()) {
739 // This method only calls Continuation.enter()
740 Symbol* signature = vmSymbols::continuationEnter_signature();
741 fr.oops_compiled_arguments_do(signature, false, false, reg_map, f);
742 }
743 }
744
745 Method* nmethod::attached_method(address call_instr) {
746 assert(code_contains(call_instr), "not part of the nmethod");
747 RelocIterator iter(this, call_instr, call_instr + 1);
748 while (iter.next()) {
749 if (iter.addr() == call_instr) {
750 switch(iter.type()) {
751 case relocInfo::static_call_type: return iter.static_call_reloc()->method_value();
752 case relocInfo::opt_virtual_call_type: return iter.opt_virtual_call_reloc()->method_value();
753 case relocInfo::virtual_call_type: return iter.virtual_call_reloc()->method_value();
754 default: break;
755 }
756 }
757 }
758 return nullptr; // not found
759 }
760
761 Method* nmethod::attached_method_before_pc(address pc) {
762 if (NativeCall::is_call_before(pc)) {
763 NativeCall* ncall = nativeCall_before(pc);
764 return attached_method(ncall->instruction_address());
765 }
766 return nullptr; // not a call
767 }
768
769 void nmethod::clear_inline_caches() {
770 assert(SafepointSynchronize::is_at_safepoint() || (NMethodState_lock->owned_by_self() && is_not_installed()), "clearing of IC's only allowed at safepoint or when not installed");
771 RelocIterator iter(this);
772 while (iter.next()) {
773 iter.reloc()->clear_inline_cache();
774 }
775 }
776
777 #ifdef ASSERT
778 // Check class_loader is alive for this bit of metadata.
779 class CheckClass : public MetadataClosure {
780 void do_metadata(Metadata* md) {
781 Klass* klass = nullptr;
782 if (md->is_klass()) {
783 klass = ((Klass*)md);
784 } else if (md->is_method()) {
785 klass = ((Method*)md)->method_holder();
786 } else if (md->is_methodData()) {
787 klass = ((MethodData*)md)->method()->method_holder();
788 } else if (md->is_methodCounters()) {
789 klass = ((MethodCounters*)md)->method()->method_holder();
790 } else {
791 md->print();
792 ShouldNotReachHere();
793 }
794 assert(klass->is_loader_alive(), "must be alive");
795 }
796 };
797 #endif // ASSERT
798
799 // Clean references to unloaded nmethods at addr from this one, which is not unloaded.
800 template <typename CallsiteT>
801 static void clean_if_nmethod_is_unloaded(CallsiteT* callsite, bool clean_all) {
802 CodeBlob* cb = CodeCache::find_blob(callsite->destination());
803 if (!cb->is_nmethod()) {
804 return;
805 }
806 nmethod* nm = cb->as_nmethod();
807 if (clean_all || !nm->is_in_use() || nm->is_unloading() || nm->method()->code() != nm) {
808 callsite->set_to_clean();
809 }
810 }
811
812 // Cleans caches in nmethods that point to either classes that are unloaded
813 // or nmethods that are unloaded.
814 //
815 // Can be called either in parallel by G1 currently or after all
816 // nmethods are unloaded. Return postponed=true in the parallel case for
817 // inline caches found that point to nmethods that are not yet visited during
818 // the do_unloading walk.
819 void nmethod::unload_nmethod_caches(bool unloading_occurred) {
820 ResourceMark rm;
821
822 // Exception cache only needs to be called if unloading occurred
823 if (unloading_occurred) {
824 clean_exception_cache();
825 }
826
827 cleanup_inline_caches_impl(unloading_occurred, false);
828
829 #ifdef ASSERT
830 // Check that the metadata embedded in the nmethod is alive
831 CheckClass check_class;
832 metadata_do(&check_class);
833 #endif
834 }
835
836 void nmethod::run_nmethod_entry_barrier() {
837 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
838 if (bs_nm != nullptr) {
839 // We want to keep an invariant that nmethods found through iterations of a Thread's
840 // nmethods found in safepoints have gone through an entry barrier and are not armed.
841 // By calling this nmethod entry barrier, it plays along and acts
842 // like any other nmethod found on the stack of a thread (fewer surprises).
843 nmethod* nm = this;
844 bool alive = bs_nm->nmethod_entry_barrier(nm);
845 assert(alive, "should be alive");
846 }
847 }
848
849 // Only called by whitebox test
850 void nmethod::cleanup_inline_caches_whitebox() {
851 assert_locked_or_safepoint(CodeCache_lock);
852 CompiledICLocker ic_locker(this);
853 cleanup_inline_caches_impl(false /* unloading_occurred */, true /* clean_all */);
854 }
855
856 address* nmethod::orig_pc_addr(const frame* fr) {
857 return (address*) ((address)fr->unextended_sp() + orig_pc_offset());
858 }
859
860 // Called to clean up after class unloading for live nmethods
861 void nmethod::cleanup_inline_caches_impl(bool unloading_occurred, bool clean_all) {
862 assert(CompiledICLocker::is_safe(this), "mt unsafe call");
863 ResourceMark rm;
864
865 // Find all calls in an nmethod and clear the ones that point to bad nmethods.
866 RelocIterator iter(this, oops_reloc_begin());
867 bool is_in_static_stub = false;
868 while(iter.next()) {
869
870 switch (iter.type()) {
871
872 case relocInfo::virtual_call_type:
873 if (unloading_occurred) {
874 // If class unloading occurred we first clear ICs where the cached metadata
875 // is referring to an unloaded klass or method.
876 CompiledIC_at(&iter)->clean_metadata();
877 }
878
879 clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), clean_all);
880 break;
881
882 case relocInfo::opt_virtual_call_type:
883 case relocInfo::static_call_type:
884 clean_if_nmethod_is_unloaded(CompiledDirectCall::at(iter.reloc()), clean_all);
885 break;
886
887 case relocInfo::static_stub_type: {
888 is_in_static_stub = true;
889 break;
890 }
891
892 case relocInfo::metadata_type: {
893 // Only the metadata relocations contained in static/opt virtual call stubs
894 // contains the Method* passed to c2i adapters. It is the only metadata
895 // relocation that needs to be walked, as it is the one metadata relocation
896 // that violates the invariant that all metadata relocations have an oop
897 // in the compiled method (due to deferred resolution and code patching).
898
899 // This causes dead metadata to remain in compiled methods that are not
900 // unloading. Unless these slippery metadata relocations of the static
901 // stubs are at least cleared, subsequent class redefinition operations
902 // will access potentially free memory, and JavaThread execution
903 // concurrent to class unloading may call c2i adapters with dead methods.
904 if (!is_in_static_stub) {
905 // The first metadata relocation after a static stub relocation is the
906 // metadata relocation of the static stub used to pass the Method* to
907 // c2i adapters.
908 continue;
909 }
910 is_in_static_stub = false;
911 if (is_unloading()) {
912 // If the nmethod itself is dying, then it may point at dead metadata.
913 // Nobody should follow that metadata; it is strictly unsafe.
914 continue;
915 }
916 metadata_Relocation* r = iter.metadata_reloc();
917 Metadata* md = r->metadata_value();
918 if (md != nullptr && md->is_method()) {
919 Method* method = static_cast<Method*>(md);
920 if (!method->method_holder()->is_loader_alive()) {
921 AtomicAccess::store(r->metadata_addr(), (Method*)nullptr);
922
923 if (!r->metadata_is_immediate()) {
924 r->fix_metadata_relocation();
925 }
926 }
927 }
928 break;
929 }
930
931 default:
932 break;
933 }
934 }
935 }
936
937 address nmethod::continuation_for_implicit_exception(address pc, bool for_div0_check) {
938 // Exception happened outside inline-cache check code => we are inside
939 // an active nmethod => use cpc to determine a return address
940 int exception_offset = int(pc - code_begin());
941 int cont_offset = ImplicitExceptionTable(this).continuation_offset( exception_offset );
942 #ifdef ASSERT
943 if (cont_offset == 0) {
944 Thread* thread = Thread::current();
945 ResourceMark rm(thread);
946 CodeBlob* cb = CodeCache::find_blob(pc);
947 assert(cb != nullptr && cb == this, "");
948
949 // Keep tty output consistent. To avoid ttyLocker, we buffer in stream, and print all at once.
950 stringStream ss;
951 ss.print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc));
952 print_on(&ss);
953 // Buffering to a stringStream, disable internal buffering so it's not done twice.
954 method()->print_codes_on(&ss, 0, false);
955 print_code_on(&ss);
956 print_pcs_on(&ss);
957 tty->print("%s", ss.as_string()); // print all at once
958 }
959 #endif
960 if (cont_offset == 0) {
961 // Let the normal error handling report the exception
962 return nullptr;
963 }
964 if (cont_offset == exception_offset) {
965 #if INCLUDE_JVMCI
966 Deoptimization::DeoptReason deopt_reason = for_div0_check ? Deoptimization::Reason_div0_check : Deoptimization::Reason_null_check;
967 JavaThread *thread = JavaThread::current();
968 thread->set_jvmci_implicit_exception_pc(pc);
969 thread->set_pending_deoptimization(Deoptimization::make_trap_request(deopt_reason,
970 Deoptimization::Action_reinterpret));
971 return (SharedRuntime::deopt_blob()->implicit_exception_uncommon_trap());
972 #else
973 ShouldNotReachHere();
974 #endif
975 }
976 return code_begin() + cont_offset;
977 }
978
979 class HasEvolDependency : public MetadataClosure {
980 bool _has_evol_dependency;
981 public:
982 HasEvolDependency() : _has_evol_dependency(false) {}
983 void do_metadata(Metadata* md) {
984 if (md->is_method()) {
985 Method* method = (Method*)md;
986 if (method->is_old()) {
987 _has_evol_dependency = true;
988 }
989 }
990 }
991 bool has_evol_dependency() const { return _has_evol_dependency; }
992 };
993
994 bool nmethod::has_evol_metadata() {
995 // Check the metadata in relocIter and CompiledIC and also deoptimize
996 // any nmethod that has reference to old methods.
997 HasEvolDependency check_evol;
998 metadata_do(&check_evol);
999 if (check_evol.has_evol_dependency() && log_is_enabled(Debug, redefine, class, nmethod)) {
1000 ResourceMark rm;
1001 log_debug(redefine, class, nmethod)
1002 ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on in nmethod metadata",
1003 _method->method_holder()->external_name(),
1004 _method->name()->as_C_string(),
1005 _method->signature()->as_C_string(),
1006 compile_id());
1007 }
1008 return check_evol.has_evol_dependency();
1009 }
1010
1011 int nmethod::total_size() const {
1012 return
1013 consts_size() +
1014 insts_size() +
1015 stub_size() +
1016 scopes_data_size() +
1017 scopes_pcs_size() +
1018 handler_table_size() +
1019 nul_chk_table_size();
1020 }
1021
1022 const char* nmethod::compile_kind() const {
1023 if (is_osr_method()) return "osr";
1024 if (method() != nullptr && is_native_method()) {
1025 if (method()->is_continuation_native_intrinsic()) {
1026 return "cnt";
1027 }
1028 return "c2n";
1029 }
1030 return nullptr;
1031 }
1032
1033 const char* nmethod::compiler_name() const {
1034 return compilertype2name(_compiler_type);
1035 }
1036
1037 #ifdef ASSERT
1038 class CheckForOopsClosure : public OopClosure {
1039 bool _found_oop = false;
1040 public:
1041 virtual void do_oop(oop* o) { _found_oop = true; }
1042 virtual void do_oop(narrowOop* o) { _found_oop = true; }
1043 bool found_oop() { return _found_oop; }
1044 };
1045 class CheckForMetadataClosure : public MetadataClosure {
1046 bool _found_metadata = false;
1047 Metadata* _ignore = nullptr;
1048 public:
1049 CheckForMetadataClosure(Metadata* ignore) : _ignore(ignore) {}
1050 virtual void do_metadata(Metadata* md) { if (md != _ignore) _found_metadata = true; }
1051 bool found_metadata() { return _found_metadata; }
1052 };
1053
1054 static void assert_no_oops_or_metadata(nmethod* nm) {
1055 if (nm == nullptr) return;
1056 assert(nm->oop_maps() == nullptr, "expectation");
1057
1058 CheckForOopsClosure cfo;
1059 nm->oops_do(&cfo);
1060 assert(!cfo.found_oop(), "no oops allowed");
1061
1062 // We allow an exception for the own Method, but require its class to be permanent.
1063 Method* own_method = nm->method();
1064 CheckForMetadataClosure cfm(/* ignore reference to own Method */ own_method);
1065 nm->metadata_do(&cfm);
1066 assert(!cfm.found_metadata(), "no metadata allowed");
1067
1068 assert(own_method->method_holder()->class_loader_data()->is_permanent_class_loader_data(),
1069 "Method's class needs to be permanent");
1070 }
1071 #endif
1072
1073 static int required_mutable_data_size(CodeBuffer* code_buffer,
1074 int jvmci_data_size = 0) {
1075 return align_up(code_buffer->total_relocation_size(), oopSize) +
1076 align_up(code_buffer->total_metadata_size(), oopSize) +
1077 align_up(jvmci_data_size, oopSize);
1078 }
1079
1080 nmethod* nmethod::new_native_nmethod(const methodHandle& method,
1081 int compile_id,
1082 CodeBuffer *code_buffer,
1083 int vep_offset,
1084 int frame_complete,
1085 int frame_size,
1086 ByteSize basic_lock_owner_sp_offset,
1087 ByteSize basic_lock_sp_offset,
1088 OopMapSet* oop_maps,
1089 int exception_handler) {
1090 code_buffer->finalize_oop_references(method);
1091 // create nmethod
1092 nmethod* nm = nullptr;
1093 int native_nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod));
1094 {
1095 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1096
1097 CodeOffsets offsets;
1098 offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
1099 offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
1100 if (exception_handler != -1) {
1101 offsets.set_value(CodeOffsets::Exceptions, exception_handler);
1102 }
1103
1104 int mutable_data_size = required_mutable_data_size(code_buffer);
1105
1106 // MH intrinsics are dispatch stubs which are compatible with NonNMethod space.
1107 // IsUnloadingBehaviour::is_unloading needs to handle them separately.
1108 bool allow_NonNMethod_space = method->can_be_allocated_in_NonNMethod_space();
1109 nm = new (native_nmethod_size, allow_NonNMethod_space)
1110 nmethod(method(), compiler_none, native_nmethod_size,
1111 compile_id, &offsets,
1112 code_buffer, frame_size,
1113 basic_lock_owner_sp_offset,
1114 basic_lock_sp_offset,
1115 oop_maps, mutable_data_size);
1116 DEBUG_ONLY( if (allow_NonNMethod_space) assert_no_oops_or_metadata(nm); )
1117 NOT_PRODUCT(if (nm != nullptr) native_nmethod_stats.note_native_nmethod(nm));
1118 }
1119
1120 if (nm != nullptr) {
1121 // verify nmethod
1122 DEBUG_ONLY(nm->verify();) // might block
1123
1124 nm->log_new_nmethod();
1125 }
1126 return nm;
1127 }
1128
1129 nmethod* nmethod::new_nmethod(const methodHandle& method,
1130 int compile_id,
1131 int entry_bci,
1132 CodeOffsets* offsets,
1133 int orig_pc_offset,
1134 DebugInformationRecorder* debug_info,
1135 Dependencies* dependencies,
1136 CodeBuffer* code_buffer, int frame_size,
1137 OopMapSet* oop_maps,
1138 ExceptionHandlerTable* handler_table,
1139 ImplicitExceptionTable* nul_chk_table,
1140 AbstractCompiler* compiler,
1141 CompLevel comp_level
1142 #if INCLUDE_JVMCI
1143 , char* speculations,
1144 int speculations_len,
1145 JVMCINMethodData* jvmci_data
1146 #endif
1147 )
1148 {
1149 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
1150 code_buffer->finalize_oop_references(method);
1151 // create nmethod
1152 nmethod* nm = nullptr;
1153 int nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod));
1154
1155 int immutable_data_size =
1156 adjust_pcs_size(debug_info->pcs_size())
1157 + align_up((int)dependencies->size_in_bytes(), oopSize)
1158 + align_up(handler_table->size_in_bytes() , oopSize)
1159 + align_up(nul_chk_table->size_in_bytes() , oopSize)
1160 #if INCLUDE_JVMCI
1161 + align_up(speculations_len , oopSize)
1162 #endif
1163 + align_up(debug_info->data_size() , oopSize);
1164
1165 // First, allocate space for immutable data in C heap.
1166 address immutable_data = nullptr;
1167 if (immutable_data_size > 0) {
1168 immutable_data_size += ImmutableDataRefCountSize;
1169 immutable_data = (address)os::malloc(immutable_data_size, mtCode);
1170 if (immutable_data == nullptr) {
1171 vm_exit_out_of_memory(immutable_data_size, OOM_MALLOC_ERROR, "nmethod: no space for immutable data");
1172 return nullptr;
1173 }
1174 }
1175
1176 int mutable_data_size = required_mutable_data_size(code_buffer
1177 JVMCI_ONLY(COMMA (compiler->is_jvmci() ? jvmci_data->size() : 0)));
1178
1179 {
1180 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1181
1182 nm = new (nmethod_size, comp_level)
1183 nmethod(method(), compiler->type(), nmethod_size, immutable_data_size, mutable_data_size,
1184 compile_id, entry_bci, immutable_data, offsets, orig_pc_offset,
1185 debug_info, dependencies, code_buffer, frame_size, oop_maps,
1186 handler_table, nul_chk_table, compiler, comp_level
1187 #if INCLUDE_JVMCI
1188 , speculations,
1189 speculations_len,
1190 jvmci_data
1191 #endif
1192 );
1193
1194 if (nm != nullptr) {
1195 // To make dependency checking during class loading fast, record
1196 // the nmethod dependencies in the classes it is dependent on.
1197 // This allows the dependency checking code to simply walk the
1198 // class hierarchy above the loaded class, checking only nmethods
1199 // which are dependent on those classes. The slow way is to
1200 // check every nmethod for dependencies which makes it linear in
1201 // the number of methods compiled. For applications with a lot
1202 // classes the slow way is too slow.
1203 for (Dependencies::DepStream deps(nm); deps.next(); ) {
1204 if (deps.type() == Dependencies::call_site_target_value) {
1205 // CallSite dependencies are managed on per-CallSite instance basis.
1206 oop call_site = deps.argument_oop(0);
1207 MethodHandles::add_dependent_nmethod(call_site, nm);
1208 } else {
1209 InstanceKlass* ik = deps.context_type();
1210 if (ik == nullptr) {
1211 continue; // ignore things like evol_method
1212 }
1213 // record this nmethod as dependent on this klass
1214 ik->add_dependent_nmethod(nm);
1215 }
1216 }
1217 NOT_PRODUCT(if (nm != nullptr) note_java_nmethod(nm));
1218 }
1219 }
1220 // Do verification and logging outside CodeCache_lock.
1221 if (nm != nullptr) {
1222 // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
1223 DEBUG_ONLY(nm->verify();)
1224 nm->log_new_nmethod();
1225 }
1226 return nm;
1227 }
1228
1229 // Fill in default values for various fields
1230 void nmethod::init_defaults(CodeBuffer *code_buffer, CodeOffsets* offsets) {
1231 // avoid uninitialized fields, even for short time periods
1232 _exception_cache = nullptr;
1233 _gc_data = nullptr;
1234 _oops_do_mark_link = nullptr;
1235 _compiled_ic_data = nullptr;
1236
1237 _is_unloading_state = 0;
1238 _state = not_installed;
1239
1240 _has_unsafe_access = 0;
1241 _has_wide_vectors = 0;
1242 _has_monitors = 0;
1243 _has_scoped_access = 0;
1244 _has_flushed_dependencies = 0;
1245 _is_unlinked = 0;
1246 _load_reported = 0; // jvmti state
1247
1248 _deoptimization_status = not_marked;
1249
1250 // SECT_CONSTS is first in code buffer so the offset should be 0.
1251 int consts_offset = code_buffer->total_offset_of(code_buffer->consts());
1252 assert(consts_offset == 0, "const_offset: %d", consts_offset);
1253
1254 _stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs());
1255
1256 CHECKED_CAST(_entry_offset, uint16_t, (offsets->value(CodeOffsets::Entry)));
1257 CHECKED_CAST(_verified_entry_offset, uint16_t, (offsets->value(CodeOffsets::Verified_Entry)));
1258
1259 _inline_entry_offset = _entry_offset;
1260 _verified_inline_entry_offset = _verified_entry_offset;
1261 _verified_inline_ro_entry_offset = _verified_entry_offset;
1262
1263 _skipped_instructions_size = code_buffer->total_skipped_instructions_size();
1264 }
1265
1266 // Post initialization
1267 void nmethod::post_init() {
1268 clear_unloading_state();
1269
1270 finalize_relocations();
1271
1272 // Flush generated code
1273 ICache::invalidate_range(code_begin(), code_size());
1274
1275 Universe::heap()->register_nmethod(this);
1276 DEBUG_ONLY(Universe::heap()->verify_nmethod(this));
1277
1278 CodeCache::commit(this);
1279 }
1280
1281 // For native wrappers
1282 nmethod::nmethod(
1283 Method* method,
1284 CompilerType type,
1285 int nmethod_size,
1286 int compile_id,
1287 CodeOffsets* offsets,
1288 CodeBuffer* code_buffer,
1289 int frame_size,
1290 ByteSize basic_lock_owner_sp_offset,
1291 ByteSize basic_lock_sp_offset,
1292 OopMapSet* oop_maps,
1293 int mutable_data_size)
1294 : CodeBlob("native nmethod", CodeBlobKind::Nmethod, code_buffer, nmethod_size, sizeof(nmethod),
1295 offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, mutable_data_size),
1296 _deoptimization_generation(0),
1297 _gc_epoch(CodeCache::gc_epoch()),
1298 _method(method),
1299 _native_receiver_sp_offset(basic_lock_owner_sp_offset),
1300 _native_basic_lock_sp_offset(basic_lock_sp_offset)
1301 {
1302 {
1303 DEBUG_ONLY(NoSafepointVerifier nsv;)
1304 assert_locked_or_safepoint(CodeCache_lock);
1305 assert(!method->has_scalarized_args(), "scalarized native wrappers not supported yet");
1306 init_defaults(code_buffer, offsets);
1307
1308 _osr_entry_point = nullptr;
1309 _pc_desc_container = nullptr;
1310 _entry_bci = InvocationEntryBci;
1311 _compile_id = compile_id;
1312 _comp_level = CompLevel_none;
1313 _compiler_type = type;
1314 _orig_pc_offset = 0;
1315 _num_stack_arg_slots = 0;
1316
1317 if (offsets->value(CodeOffsets::Exceptions) != -1) {
1318 // Continuation enter intrinsic
1319 _exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions);
1320 } else {
1321 _exception_offset = 0;
1322 }
1323 // Native wrappers do not have deopt handlers. Make the values
1324 // something that will never match a pc like the nmethod vtable entry
1325 _deopt_handler_entry_offset = 0;
1326 _unwind_handler_offset = 0;
1327
1328 int metadata_size = align_up(code_buffer->total_metadata_size(), wordSize);
1329 JVMCI_ONLY( _metadata_size = metadata_size; )
1330 assert(_mutable_data_size == _relocation_size + metadata_size,
1331 "wrong mutable data size: %d != %d + %d",
1332 _mutable_data_size, _relocation_size, metadata_size);
1333
1334 // native wrapper does not have read-only data but we need unique not null address
1335 _immutable_data = blob_end();
1336 _immutable_data_size = 0;
1337 _nul_chk_table_offset = 0;
1338 _handler_table_offset = 0;
1339 _scopes_pcs_offset = 0;
1340 _scopes_data_offset = 0;
1341 #if INCLUDE_JVMCI
1342 _speculations_offset = 0;
1343 #endif
1344 _immutable_data_ref_count_offset = 0;
1345
1346 code_buffer->copy_code_and_locs_to(this);
1347 code_buffer->copy_values_to(this);
1348
1349 post_init();
1350 }
1351
1352 if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {
1353 ttyLocker ttyl; // keep the following output all in one block
1354 // This output goes directly to the tty, not the compiler log.
1355 // To enable tools to match it up with the compilation activity,
1356 // be sure to tag this tty output with the compile ID.
1357 if (xtty != nullptr) {
1358 xtty->begin_head("print_native_nmethod");
1359 xtty->method(_method);
1360 xtty->stamp();
1361 xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
1362 }
1363 // Print the header part, then print the requested information.
1364 // This is both handled in decode2(), called via print_code() -> decode()
1365 if (PrintNativeNMethods) {
1366 tty->print_cr("-------------------------- Assembly (native nmethod) ---------------------------");
1367 print_code();
1368 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1369 #if defined(SUPPORT_DATA_STRUCTS)
1370 if (AbstractDisassembler::show_structs()) {
1371 if (oop_maps != nullptr) {
1372 tty->print("oop maps:"); // oop_maps->print_on(tty) outputs a cr() at the beginning
1373 oop_maps->print_on(tty);
1374 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1375 }
1376 }
1377 #endif
1378 } else {
1379 print(); // print the header part only.
1380 }
1381 #if defined(SUPPORT_DATA_STRUCTS)
1382 if (AbstractDisassembler::show_structs()) {
1383 if (PrintRelocations) {
1384 print_relocations();
1385 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1386 }
1387 }
1388 #endif
1389 if (xtty != nullptr) {
1390 xtty->tail("print_native_nmethod");
1391 }
1392 }
1393 }
1394
1395
1396 nmethod::nmethod(const nmethod &nm) : CodeBlob(nm._name, nm._kind, nm._size, nm._header_size)
1397 {
1398
1399 if (nm._oop_maps != nullptr) {
1400 _oop_maps = nm._oop_maps->clone();
1401 } else {
1402 _oop_maps = nullptr;
1403 }
1404
1405 _size = nm._size;
1406 _relocation_size = nm._relocation_size;
1407 _content_offset = nm._content_offset;
1408 _code_offset = nm._code_offset;
1409 _data_offset = nm._data_offset;
1410 _frame_size = nm._frame_size;
1411
1412 S390_ONLY( _ctable_offset = nm._ctable_offset; )
1413
1414 _header_size = nm._header_size;
1415 _frame_complete_offset = nm._frame_complete_offset;
1416
1417 _kind = nm._kind;
1418
1419 _caller_must_gc_arguments = nm._caller_must_gc_arguments;
1420
1421 #ifndef PRODUCT
1422 _asm_remarks.share(nm._asm_remarks);
1423 _dbg_strings.share(nm._dbg_strings);
1424 #endif
1425
1426 // Allocate memory and copy mutable data to C heap
1427 _mutable_data_size = nm._mutable_data_size;
1428 if (_mutable_data_size > 0) {
1429 _mutable_data = (address)os::malloc(_mutable_data_size, mtCode);
1430 if (_mutable_data == nullptr) {
1431 vm_exit_out_of_memory(_mutable_data_size, OOM_MALLOC_ERROR, "nmethod: no space for mutable data");
1432 }
1433 memcpy(mutable_data_begin(), nm.mutable_data_begin(), nm.mutable_data_size());
1434 } else {
1435 _mutable_data = nullptr;
1436 }
1437
1438 _deoptimization_generation = 0;
1439 _gc_epoch = CodeCache::gc_epoch();
1440 _method = nm._method;
1441 _osr_link = nullptr;
1442
1443 _exception_cache = nullptr;
1444 _gc_data = nullptr;
1445 _oops_do_mark_nmethods = nullptr;
1446 _oops_do_mark_link = nullptr;
1447 _compiled_ic_data = nullptr;
1448
1449 // Relocate the OSR entry point from nm to the new nmethod.
1450 if (nm._osr_entry_point == nullptr) {
1451 _osr_entry_point = nullptr;
1452 } else {
1453 address new_addr = nm._osr_entry_point - (address) &nm + (address) this;
1454 assert(new_addr >= code_begin() && new_addr < code_end(),
1455 "relocated address must be within code bounds");
1456 _osr_entry_point = new_addr;
1457 }
1458 _entry_offset = nm._entry_offset;
1459 _verified_entry_offset = nm._verified_entry_offset;
1460 _inline_entry_offset = nm._inline_entry_offset;
1461 _verified_inline_entry_offset = nm._verified_inline_entry_offset;
1462 _verified_inline_ro_entry_offset = nm._verified_inline_ro_entry_offset;
1463
1464 _entry_bci = nm._entry_bci;
1465 _immutable_data_size = nm._immutable_data_size;
1466
1467 _skipped_instructions_size = nm._skipped_instructions_size;
1468 _stub_offset = nm._stub_offset;
1469 _exception_offset = nm._exception_offset;
1470 _deopt_handler_entry_offset = nm._deopt_handler_entry_offset;
1471 _unwind_handler_offset = nm._unwind_handler_offset;
1472 _num_stack_arg_slots = nm._num_stack_arg_slots;
1473 #if INCLUDE_JVMCI
1474 _metadata_size = nm._metadata_size;
1475 #endif
1476 _nul_chk_table_offset = nm._nul_chk_table_offset;
1477 _handler_table_offset = nm._handler_table_offset;
1478 _scopes_pcs_offset = nm._scopes_pcs_offset;
1479 _scopes_data_offset = nm._scopes_data_offset;
1480 #if INCLUDE_JVMCI
1481 _speculations_offset = nm._speculations_offset;
1482 #endif
1483 _immutable_data_ref_count_offset = nm._immutable_data_ref_count_offset;
1484
1485 // Increment number of references to immutable data to share it between nmethods
1486 if (_immutable_data_size > 0) {
1487 _immutable_data = nm._immutable_data;
1488 inc_immutable_data_ref_count();
1489 } else {
1490 _immutable_data = blob_end();
1491 }
1492
1493 _orig_pc_offset = nm._orig_pc_offset;
1494 _compile_id = nm._compile_id;
1495 _comp_level = nm._comp_level;
1496 _compiler_type = nm._compiler_type;
1497 _is_unloading_state = nm._is_unloading_state;
1498 _state = not_installed;
1499
1500 _has_unsafe_access = nm._has_unsafe_access;
1501 _has_wide_vectors = nm._has_wide_vectors;
1502 _has_monitors = nm._has_monitors;
1503 _has_scoped_access = nm._has_scoped_access;
1504 _has_flushed_dependencies = nm._has_flushed_dependencies;
1505 _is_unlinked = nm._is_unlinked;
1506 _load_reported = nm._load_reported;
1507
1508 _deoptimization_status = nm._deoptimization_status;
1509
1510 if (nm._pc_desc_container != nullptr) {
1511 _pc_desc_container = new PcDescContainer(scopes_pcs_begin());
1512 } else {
1513 _pc_desc_container = nullptr;
1514 }
1515
1516 // Copy nmethod contents excluding header
1517 // - Constant part (doubles, longs and floats used in nmethod)
1518 // - Code part:
1519 // - Code body
1520 // - Exception handler
1521 // - Stub code
1522 // - OOP table
1523 memcpy(consts_begin(), nm.consts_begin(), nm.data_end() - nm.consts_begin());
1524
1525 // Fix relocation
1526 RelocIterator iter(this);
1527 CodeBuffer src(&nm);
1528 CodeBuffer dst(this);
1529 while (iter.next()) {
1530 #ifdef USE_TRAMPOLINE_STUB_FIX_OWNER
1531 // After an nmethod is moved, some direct call sites may end up out of range.
1532 // CallRelocation::fix_relocation_after_move() assumes the target is always
1533 // reachable and does not check branch range. Calling it without range checks
1534 // could cause us to write an offset too large for the instruction.
1535 //
1536 // If a call site has a trampoline, we skip the normal call relocation. The
1537 // associated trampoline_stub_Relocation will handle the call and the
1538 // trampoline, including range checks and updating the branch as needed.
1539 //
1540 // If no trampoline exists, we can assume the call target is always
1541 // reachable and therefore within direct branch range, so calling
1542 // CallRelocation::fix_relocation_after_move() is safe.
1543 if (iter.reloc()->is_call()) {
1544 address trampoline = trampoline_stub_Relocation::get_trampoline_for(iter.reloc()->addr(), this);
1545 if (trampoline != nullptr) {
1546 continue;
1547 }
1548 }
1549 #endif
1550
1551 iter.reloc()->fix_relocation_after_move(&src, &dst);
1552 }
1553
1554 {
1555 MutexLocker ml(NMethodState_lock, Mutex::_no_safepoint_check_flag);
1556 clear_inline_caches();
1557 }
1558
1559 post_init();
1560 }
1561
1562 nmethod* nmethod::relocate(CodeBlobType code_blob_type) {
1563 assert(NMethodRelocation, "must enable use of function");
1564
1565 // Locks required to be held by caller to ensure the nmethod
1566 // is not modified or purged from code cache during relocation
1567 assert_lock_strong(CodeCache_lock);
1568 assert_lock_strong(Compile_lock);
1569 assert(CompiledICLocker::is_safe(this), "mt unsafe call");
1570
1571 if (!is_relocatable()) {
1572 return nullptr;
1573 }
1574
1575 run_nmethod_entry_barrier();
1576 nmethod* nm_copy = new (size(), code_blob_type) nmethod(*this);
1577
1578 if (nm_copy == nullptr) {
1579 return nullptr;
1580 }
1581
1582 // To make dependency checking during class loading fast, record
1583 // the nmethod dependencies in the classes it is dependent on.
1584 // This allows the dependency checking code to simply walk the
1585 // class hierarchy above the loaded class, checking only nmethods
1586 // which are dependent on those classes. The slow way is to
1587 // check every nmethod for dependencies which makes it linear in
1588 // the number of methods compiled. For applications with a lot
1589 // classes the slow way is too slow.
1590 for (Dependencies::DepStream deps(nm_copy); deps.next(); ) {
1591 if (deps.type() == Dependencies::call_site_target_value) {
1592 // CallSite dependencies are managed on per-CallSite instance basis.
1593 oop call_site = deps.argument_oop(0);
1594 MethodHandles::add_dependent_nmethod(call_site, nm_copy);
1595 } else {
1596 InstanceKlass* ik = deps.context_type();
1597 if (ik == nullptr) {
1598 continue; // ignore things like evol_method
1599 }
1600 // record this nmethod as dependent on this klass
1601 ik->add_dependent_nmethod(nm_copy);
1602 }
1603 }
1604
1605 MutexLocker ml_NMethodState_lock(NMethodState_lock, Mutex::_no_safepoint_check_flag);
1606
1607 // Verify the nm we copied from is still valid
1608 if (!is_marked_for_deoptimization() && is_in_use()) {
1609 assert(method() != nullptr && method()->code() == this, "should be if is in use");
1610
1611 // Attempt to start using the copy
1612 if (nm_copy->make_in_use()) {
1613 methodHandle mh(Thread::current(), nm_copy->method());
1614 nm_copy->method()->set_code(mh, nm_copy);
1615
1616 make_not_entrant(InvalidationReason::RELOCATED);
1617
1618 nm_copy->post_compiled_method_load_event();
1619
1620 nm_copy->log_relocated_nmethod(this);
1621
1622 return nm_copy;
1623 }
1624 }
1625
1626 nm_copy->make_not_used();
1627
1628 return nullptr;
1629 }
1630
1631 bool nmethod::is_relocatable() {
1632 if (!is_java_method()) {
1633 return false;
1634 }
1635
1636 if (!is_in_use()) {
1637 return false;
1638 }
1639
1640 if (is_osr_method()) {
1641 return false;
1642 }
1643
1644 if (is_marked_for_deoptimization()) {
1645 return false;
1646 }
1647
1648 #if INCLUDE_JVMCI
1649 if (jvmci_nmethod_data() != nullptr && jvmci_nmethod_data()->has_mirror()) {
1650 return false;
1651 }
1652 #endif
1653
1654 if (is_unloading()) {
1655 return false;
1656 }
1657
1658 if (has_evol_metadata()) {
1659 return false;
1660 }
1661
1662 return true;
1663 }
1664
1665 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () {
1666 return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level));
1667 }
1668
1669 void* nmethod::operator new(size_t size, int nmethod_size, CodeBlobType code_blob_type) throw () {
1670 return CodeCache::allocate(nmethod_size, code_blob_type);
1671 }
1672
1673 void* nmethod::operator new(size_t size, int nmethod_size, bool allow_NonNMethod_space) throw () {
1674 // Try MethodNonProfiled and MethodProfiled.
1675 void* return_value = CodeCache::allocate(nmethod_size, CodeBlobType::MethodNonProfiled);
1676 if (return_value != nullptr || !allow_NonNMethod_space) return return_value;
1677 // Try NonNMethod or give up.
1678 return CodeCache::allocate(nmethod_size, CodeBlobType::NonNMethod);
1679 }
1680
1681 // For normal JIT compiled code
1682 nmethod::nmethod(
1683 Method* method,
1684 CompilerType type,
1685 int nmethod_size,
1686 int immutable_data_size,
1687 int mutable_data_size,
1688 int compile_id,
1689 int entry_bci,
1690 address immutable_data,
1691 CodeOffsets* offsets,
1692 int orig_pc_offset,
1693 DebugInformationRecorder* debug_info,
1694 Dependencies* dependencies,
1695 CodeBuffer *code_buffer,
1696 int frame_size,
1697 OopMapSet* oop_maps,
1698 ExceptionHandlerTable* handler_table,
1699 ImplicitExceptionTable* nul_chk_table,
1700 AbstractCompiler* compiler,
1701 CompLevel comp_level
1702 #if INCLUDE_JVMCI
1703 , char* speculations,
1704 int speculations_len,
1705 JVMCINMethodData* jvmci_data
1706 #endif
1707 )
1708 : CodeBlob("nmethod", CodeBlobKind::Nmethod, code_buffer, nmethod_size, sizeof(nmethod),
1709 offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, mutable_data_size),
1710 _deoptimization_generation(0),
1711 _gc_epoch(CodeCache::gc_epoch()),
1712 _method(method),
1713 _osr_link(nullptr)
1714 {
1715 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
1716 {
1717 DEBUG_ONLY(NoSafepointVerifier nsv;)
1718 assert_locked_or_safepoint(CodeCache_lock);
1719
1720 init_defaults(code_buffer, offsets);
1721
1722 _osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry);
1723 _entry_bci = entry_bci;
1724 _compile_id = compile_id;
1725 _comp_level = comp_level;
1726 _compiler_type = type;
1727 _orig_pc_offset = orig_pc_offset;
1728
1729 _num_stack_arg_slots = entry_bci != InvocationEntryBci ? 0 : _method->constMethod()->num_stack_arg_slots();
1730
1731 set_ctable_begin(header_begin() + content_offset());
1732
1733 #if INCLUDE_JVMCI
1734 if (compiler->is_jvmci()) {
1735 // JVMCI might not produce any stub sections
1736 if (offsets->value(CodeOffsets::Exceptions) != -1) {
1737 _exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions);
1738 } else {
1739 _exception_offset = -1;
1740 }
1741 if (offsets->value(CodeOffsets::Deopt) != -1) {
1742 _deopt_handler_entry_offset = code_offset() + offsets->value(CodeOffsets::Deopt);
1743 } else {
1744 _deopt_handler_entry_offset = -1;
1745 }
1746 } else
1747 #endif
1748 {
1749 // Exception handler and deopt handler are in the stub section
1750 assert(offsets->value(CodeOffsets::Deopt ) != -1, "must be set");
1751
1752 bool has_exception_handler = (offsets->value(CodeOffsets::Exceptions) != -1);
1753 assert(has_exception_handler == (compiler->type() != compiler_c2),
1754 "C2 compiler doesn't provide exception handler stub code.");
1755 if (has_exception_handler) {
1756 _exception_offset = _stub_offset + offsets->value(CodeOffsets::Exceptions);
1757 } else {
1758 _exception_offset = -1;
1759 }
1760
1761 _deopt_handler_entry_offset = _stub_offset + offsets->value(CodeOffsets::Deopt);
1762 }
1763 if (offsets->value(CodeOffsets::UnwindHandler) != -1) {
1764 // C1 generates UnwindHandler at the end of instructions section.
1765 // Calculate positive offset as distance between the start of stubs section
1766 // (which is also the end of instructions section) and the start of the handler.
1767 int unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler);
1768 CHECKED_CAST(_unwind_handler_offset, int16_t, (_stub_offset - unwind_handler_offset));
1769 } else {
1770 _unwind_handler_offset = -1;
1771 }
1772
1773 int metadata_size = align_up(code_buffer->total_metadata_size(), wordSize);
1774 JVMCI_ONLY( _metadata_size = metadata_size; )
1775 int jvmci_data_size = 0 JVMCI_ONLY( + align_up(compiler->is_jvmci() ? jvmci_data->size() : 0, oopSize));
1776 if (offsets->value(CodeOffsets::Inline_Entry) != CodeOffsets::no_such_entry_point) {
1777 CHECKED_CAST(_inline_entry_offset , uint16_t, offsets->value(CodeOffsets::Inline_Entry));
1778 }
1779 if (offsets->value(CodeOffsets::Verified_Inline_Entry) != CodeOffsets::no_such_entry_point) {
1780 CHECKED_CAST(_verified_inline_entry_offset , uint16_t, offsets->value(CodeOffsets::Verified_Inline_Entry));
1781 }
1782 if (offsets->value(CodeOffsets::Verified_Inline_Entry_RO) != CodeOffsets::no_such_entry_point) {
1783 CHECKED_CAST(_verified_inline_ro_entry_offset, uint16_t, offsets->value(CodeOffsets::Verified_Inline_Entry_RO));
1784 }
1785
1786 assert(_mutable_data_size == _relocation_size + metadata_size + jvmci_data_size,
1787 "wrong mutable data size: %d != %d + %d + %d",
1788 _mutable_data_size, _relocation_size, metadata_size, jvmci_data_size);
1789 assert(nmethod_size == data_end() - header_begin(), "wrong nmethod size: %d != %d",
1790 nmethod_size, (int)(code_end() - header_begin()));
1791
1792 _immutable_data_size = immutable_data_size;
1793 if (immutable_data_size > 0) {
1794 assert(immutable_data != nullptr, "required");
1795 _immutable_data = immutable_data;
1796 } else {
1797 // We need unique not null address
1798 _immutable_data = blob_end();
1799 }
1800 CHECKED_CAST(_nul_chk_table_offset, uint16_t, (align_up((int)dependencies->size_in_bytes(), oopSize)));
1801 CHECKED_CAST(_handler_table_offset, uint16_t, (_nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize)));
1802 _scopes_pcs_offset = _handler_table_offset + align_up(handler_table->size_in_bytes(), oopSize);
1803 _scopes_data_offset = _scopes_pcs_offset + adjust_pcs_size(debug_info->pcs_size());
1804
1805 #if INCLUDE_JVMCI
1806 _speculations_offset = _scopes_data_offset + align_up(debug_info->data_size(), oopSize);
1807 _immutable_data_ref_count_offset = _speculations_offset + align_up(speculations_len, oopSize);
1808 #else
1809 _immutable_data_ref_count_offset = _scopes_data_offset + align_up(debug_info->data_size(), oopSize);
1810 #endif
1811 DEBUG_ONLY( int immutable_data_end_offset = _immutable_data_ref_count_offset + ImmutableDataRefCountSize; )
1812 assert(immutable_data_end_offset <= immutable_data_size, "wrong read-only data size: %d > %d",
1813 immutable_data_end_offset, immutable_data_size);
1814
1815 // Copy code and relocation info
1816 code_buffer->copy_code_and_locs_to(this);
1817 // Copy oops and metadata
1818 code_buffer->copy_values_to(this);
1819 dependencies->copy_to(this);
1820 // Copy PcDesc and ScopeDesc data
1821 debug_info->copy_to(this);
1822
1823 // Create cache after PcDesc data is copied - it will be used to initialize cache
1824 _pc_desc_container = new PcDescContainer(scopes_pcs_begin());
1825
1826 #if INCLUDE_JVMCI
1827 if (compiler->is_jvmci()) {
1828 // Initialize the JVMCINMethodData object inlined into nm
1829 jvmci_nmethod_data()->copy(jvmci_data);
1830 }
1831 #endif
1832
1833 // Copy contents of ExceptionHandlerTable to nmethod
1834 handler_table->copy_to(this);
1835 nul_chk_table->copy_to(this);
1836
1837 #if INCLUDE_JVMCI
1838 // Copy speculations to nmethod
1839 if (speculations_size() != 0) {
1840 memcpy(speculations_begin(), speculations, speculations_len);
1841 }
1842 #endif
1843 init_immutable_data_ref_count();
1844
1845 post_init();
1846
1847 // we use the information of entry points to find out if a method is
1848 // static or non static
1849 assert(compiler->is_c2() || compiler->is_jvmci() ||
1850 _method->is_static() == (entry_point() == verified_entry_point()),
1851 " entry points must be same for static methods and vice versa");
1852 }
1853 }
1854
1855 // Print a short set of xml attributes to identify this nmethod. The
1856 // output should be embedded in some other element.
1857 void nmethod::log_identity(xmlStream* log) const {
1858 log->print(" compile_id='%d'", compile_id());
1859 const char* nm_kind = compile_kind();
1860 if (nm_kind != nullptr) log->print(" compile_kind='%s'", nm_kind);
1861 log->print(" compiler='%s'", compiler_name());
1862 if (TieredCompilation) {
1863 log->print(" level='%d'", comp_level());
1864 }
1865 #if INCLUDE_JVMCI
1866 if (jvmci_nmethod_data() != nullptr) {
1867 const char* jvmci_name = jvmci_nmethod_data()->name();
1868 if (jvmci_name != nullptr) {
1869 log->print(" jvmci_mirror_name='");
1870 log->text("%s", jvmci_name);
1871 log->print("'");
1872 }
1873 }
1874 #endif
1875 }
1876
1877
1878 #define LOG_OFFSET(log, name) \
1879 if (p2i(name##_end()) - p2i(name##_begin())) \
1880 log->print(" " XSTR(name) "_offset='%zd'" , \
1881 p2i(name##_begin()) - p2i(this))
1882
1883
1884 void nmethod::log_new_nmethod() const {
1885 if (LogCompilation && xtty != nullptr) {
1886 ttyLocker ttyl;
1887 xtty->begin_elem("nmethod");
1888 log_identity(xtty);
1889 xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size());
1890 xtty->print(" address='" INTPTR_FORMAT "'", p2i(this));
1891
1892 LOG_OFFSET(xtty, relocation);
1893 LOG_OFFSET(xtty, consts);
1894 LOG_OFFSET(xtty, insts);
1895 LOG_OFFSET(xtty, stub);
1896 LOG_OFFSET(xtty, scopes_data);
1897 LOG_OFFSET(xtty, scopes_pcs);
1898 LOG_OFFSET(xtty, dependencies);
1899 LOG_OFFSET(xtty, handler_table);
1900 LOG_OFFSET(xtty, nul_chk_table);
1901 LOG_OFFSET(xtty, oops);
1902 LOG_OFFSET(xtty, metadata);
1903
1904 xtty->method(method());
1905 xtty->stamp();
1906 xtty->end_elem();
1907 }
1908 }
1909
1910
1911 void nmethod::log_relocated_nmethod(nmethod* original) const {
1912 if (LogCompilation && xtty != nullptr) {
1913 ttyLocker ttyl;
1914 xtty->begin_elem("relocated nmethod");
1915 log_identity(xtty);
1916 xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size());
1917
1918 const char* original_code_heap_name = CodeCache::get_code_heap_name(CodeCache::get_code_blob_type(original));
1919 xtty->print(" original_address='" INTPTR_FORMAT "'", p2i(original));
1920 xtty->print(" original_code_heap='%s'", original_code_heap_name);
1921
1922 const char* new_code_heap_name = CodeCache::get_code_heap_name(CodeCache::get_code_blob_type(this));
1923 xtty->print(" new_address='" INTPTR_FORMAT "'", p2i(this));
1924 xtty->print(" new_code_heap='%s'", new_code_heap_name);
1925
1926 LOG_OFFSET(xtty, relocation);
1927 LOG_OFFSET(xtty, consts);
1928 LOG_OFFSET(xtty, insts);
1929 LOG_OFFSET(xtty, stub);
1930 LOG_OFFSET(xtty, scopes_data);
1931 LOG_OFFSET(xtty, scopes_pcs);
1932 LOG_OFFSET(xtty, dependencies);
1933 LOG_OFFSET(xtty, handler_table);
1934 LOG_OFFSET(xtty, nul_chk_table);
1935 LOG_OFFSET(xtty, oops);
1936 LOG_OFFSET(xtty, metadata);
1937
1938 xtty->method(method());
1939 xtty->stamp();
1940 xtty->end_elem();
1941 }
1942 }
1943
1944 #undef LOG_OFFSET
1945
1946
1947 // Print out more verbose output usually for a newly created nmethod.
1948 void nmethod::print_on_with_msg(outputStream* st, const char* msg) const {
1949 if (st != nullptr) {
1950 ttyLocker ttyl;
1951 if (WizardMode) {
1952 CompileTask::print(st, this, msg, /*short_form:*/ true);
1953 st->print_cr(" (" INTPTR_FORMAT ")", p2i(this));
1954 } else {
1955 CompileTask::print(st, this, msg, /*short_form:*/ false);
1956 }
1957 }
1958 }
1959
1960 void nmethod::maybe_print_nmethod(const DirectiveSet* directive) {
1961 bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption;
1962 if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {
1963 print_nmethod(printnmethods);
1964 }
1965 }
1966
1967 void nmethod::print_nmethod(bool printmethod) {
1968 ttyLocker ttyl; // keep the following output all in one block
1969 if (xtty != nullptr) {
1970 xtty->begin_head("print_nmethod");
1971 log_identity(xtty);
1972 xtty->stamp();
1973 xtty->end_head();
1974 }
1975 // Print the header part, then print the requested information.
1976 // This is both handled in decode2().
1977 if (printmethod) {
1978 ResourceMark m;
1979 if (is_compiled_by_c1()) {
1980 tty->cr();
1981 tty->print_cr("============================= C1-compiled nmethod ==============================");
1982 }
1983 if (is_compiled_by_jvmci()) {
1984 tty->cr();
1985 tty->print_cr("=========================== JVMCI-compiled nmethod =============================");
1986 }
1987 tty->print_cr("----------------------------------- Assembly -----------------------------------");
1988 decode2(tty);
1989 #if defined(SUPPORT_DATA_STRUCTS)
1990 if (AbstractDisassembler::show_structs()) {
1991 // Print the oops from the underlying CodeBlob as well.
1992 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1993 print_oops(tty);
1994 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1995 print_metadata(tty);
1996 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1997 print_pcs_on(tty);
1998 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1999 if (oop_maps() != nullptr) {
2000 tty->print("oop maps:"); // oop_maps()->print_on(tty) outputs a cr() at the beginning
2001 oop_maps()->print_on(tty);
2002 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2003 }
2004 }
2005 #endif
2006 } else {
2007 print(); // print the header part only.
2008 }
2009
2010 #if defined(SUPPORT_DATA_STRUCTS)
2011 if (AbstractDisassembler::show_structs()) {
2012 methodHandle mh(Thread::current(), _method);
2013 if (printmethod || PrintDebugInfo || CompilerOracle::has_option(mh, CompileCommandEnum::PrintDebugInfo)) {
2014 print_scopes();
2015 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2016 }
2017 if (printmethod || PrintRelocations || CompilerOracle::has_option(mh, CompileCommandEnum::PrintRelocations)) {
2018 print_relocations();
2019 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2020 }
2021 if (printmethod || PrintDependencies || CompilerOracle::has_option(mh, CompileCommandEnum::PrintDependencies)) {
2022 print_dependencies_on(tty);
2023 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2024 }
2025 if (printmethod || PrintExceptionHandlers) {
2026 print_handler_table();
2027 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2028 print_nul_chk_table();
2029 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2030 }
2031
2032 if (printmethod) {
2033 print_recorded_oops();
2034 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2035 print_recorded_metadata();
2036 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2037 }
2038 }
2039 #endif
2040
2041 if (xtty != nullptr) {
2042 xtty->tail("print_nmethod");
2043 }
2044 }
2045
2046
2047 // Promote one word from an assembly-time handle to a live embedded oop.
2048 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {
2049 if (handle == nullptr ||
2050 // As a special case, IC oops are initialized to 1 or -1.
2051 handle == (jobject) Universe::non_oop_word()) {
2052 *(void**)dest = handle;
2053 } else {
2054 *dest = JNIHandles::resolve_non_null(handle);
2055 }
2056 }
2057
2058
2059 // Have to have the same name because it's called by a template
2060 void nmethod::copy_values(GrowableArray<jobject>* array) {
2061 int length = array->length();
2062 assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");
2063 oop* dest = oops_begin();
2064 for (int index = 0 ; index < length; index++) {
2065 initialize_immediate_oop(&dest[index], array->at(index));
2066 }
2067
2068 // Now we can fix up all the oops in the code. We need to do this
2069 // in the code because the assembler uses jobjects as placeholders.
2070 // The code and relocations have already been initialized by the
2071 // CodeBlob constructor, so it is valid even at this early point to
2072 // iterate over relocations and patch the code.
2073 fix_oop_relocations(/*initialize_immediates=*/ true);
2074 }
2075
2076 void nmethod::copy_values(GrowableArray<Metadata*>* array) {
2077 int length = array->length();
2078 assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough");
2079 Metadata** dest = metadata_begin();
2080 for (int index = 0 ; index < length; index++) {
2081 dest[index] = array->at(index);
2082 }
2083 }
2084
2085 bool nmethod::fix_oop_relocations(bool initialize_immediates) {
2086 // re-patch all oop-bearing instructions, just in case some oops moved
2087 RelocIterator iter(this);
2088 bool modified_code = false;
2089 while (iter.next()) {
2090 if (iter.type() == relocInfo::oop_type) {
2091 oop_Relocation* reloc = iter.oop_reloc();
2092 if (!reloc->oop_is_immediate()) {
2093 // Refresh the oop-related bits of this instruction.
2094 reloc->set_value(reloc->value());
2095 modified_code = true;
2096 } else if (initialize_immediates) {
2097 oop* dest = reloc->oop_addr();
2098 jobject obj = *reinterpret_cast<jobject*>(dest);
2099 initialize_immediate_oop(dest, obj);
2100 }
2101 } else if (iter.type() == relocInfo::metadata_type) {
2102 metadata_Relocation* reloc = iter.metadata_reloc();
2103 reloc->fix_metadata_relocation();
2104 modified_code |= !reloc->metadata_is_immediate();
2105 }
2106 }
2107 return modified_code;
2108 }
2109
2110 void nmethod::fix_oop_relocations() {
2111 ICacheInvalidationContext icic;
2112 fix_oop_relocations(&icic);
2113 }
2114
2115 void nmethod::fix_oop_relocations(ICacheInvalidationContext* icic) {
2116 assert(icic != nullptr, "must provide context to track if code was modified");
2117 bool modified_code = fix_oop_relocations(/*initialize_immediates=*/ false);
2118 if (modified_code) {
2119 icic->set_has_modified_code();
2120 }
2121 }
2122
2123 static void install_post_call_nop_displacement(nmethod* nm, address pc) {
2124 NativePostCallNop* nop = nativePostCallNop_at((address) pc);
2125 intptr_t cbaddr = (intptr_t) nm;
2126 intptr_t offset = ((intptr_t) pc) - cbaddr;
2127
2128 int oopmap_slot = nm->oop_maps()->find_slot_for_offset(int((intptr_t) pc - (intptr_t) nm->code_begin()));
2129 if (oopmap_slot < 0) { // this can happen at asynchronous (non-safepoint) stackwalks
2130 log_debug(codecache)("failed to find oopmap for cb: " INTPTR_FORMAT " offset: %d", cbaddr, (int) offset);
2131 } else if (!nop->patch(oopmap_slot, offset)) {
2132 log_debug(codecache)("failed to encode %d %d", oopmap_slot, (int) offset);
2133 }
2134 }
2135
2136 void nmethod::finalize_relocations() {
2137 NoSafepointVerifier nsv;
2138
2139 GrowableArray<NativeMovConstReg*> virtual_call_data;
2140
2141 // Make sure that post call nops fill in nmethod offsets eagerly so
2142 // we don't have to race with deoptimization
2143 RelocIterator iter(this);
2144 while (iter.next()) {
2145 if (iter.type() == relocInfo::virtual_call_type) {
2146 virtual_call_Relocation* r = iter.virtual_call_reloc();
2147 NativeMovConstReg* value = nativeMovConstReg_at(r->cached_value());
2148 virtual_call_data.append(value);
2149 } else if (iter.type() == relocInfo::post_call_nop_type) {
2150 post_call_nop_Relocation* const reloc = iter.post_call_nop_reloc();
2151 address pc = reloc->addr();
2152 install_post_call_nop_displacement(this, pc);
2153 }
2154 }
2155
2156 if (virtual_call_data.length() > 0) {
2157 // We allocate a block of CompiledICData per nmethod so the GC can purge this faster.
2158 _compiled_ic_data = new CompiledICData[virtual_call_data.length()];
2159 CompiledICData* next_data = _compiled_ic_data;
2160
2161 for (NativeMovConstReg* value : virtual_call_data) {
2162 value->set_data((intptr_t)next_data);
2163 next_data++;
2164 }
2165 }
2166 }
2167
2168 void nmethod::make_deoptimized() {
2169 if (!Continuations::enabled()) {
2170 // Don't deopt this again.
2171 set_deoptimized_done();
2172 return;
2173 }
2174
2175 assert(method() == nullptr || can_be_deoptimized(), "");
2176
2177 CompiledICLocker ml(this);
2178 assert(CompiledICLocker::is_safe(this), "mt unsafe call");
2179
2180 // If post call nops have been already patched, we can just bail-out.
2181 if (has_been_deoptimized()) {
2182 return;
2183 }
2184
2185 ResourceMark rm;
2186 RelocIterator iter(this, oops_reloc_begin());
2187
2188 // Assume there will be some calls to make deoptimized.
2189 MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
2190
2191 while (iter.next()) {
2192
2193 switch (iter.type()) {
2194 case relocInfo::virtual_call_type: {
2195 CompiledIC *ic = CompiledIC_at(&iter);
2196 address pc = ic->end_of_call();
2197 NativePostCallNop* nop = nativePostCallNop_at(pc);
2198 if (nop != nullptr) {
2199 nop->make_deopt();
2200 }
2201 assert(NativeDeoptInstruction::is_deopt_at(pc), "check");
2202 break;
2203 }
2204 case relocInfo::static_call_type:
2205 case relocInfo::opt_virtual_call_type: {
2206 CompiledDirectCall *csc = CompiledDirectCall::at(iter.reloc());
2207 address pc = csc->end_of_call();
2208 NativePostCallNop* nop = nativePostCallNop_at(pc);
2209 //tty->print_cr(" - static pc %p", pc);
2210 if (nop != nullptr) {
2211 nop->make_deopt();
2212 }
2213 // We can't assert here, there are some calls to stubs / runtime
2214 // that have reloc data and doesn't have a post call NOP.
2215 //assert(NativeDeoptInstruction::is_deopt_at(pc), "check");
2216 break;
2217 }
2218 default:
2219 break;
2220 }
2221 }
2222 // Don't deopt this again.
2223 set_deoptimized_done();
2224 }
2225
2226 void nmethod::verify_clean_inline_caches() {
2227 assert(CompiledICLocker::is_safe(this), "mt unsafe call");
2228
2229 ResourceMark rm;
2230 RelocIterator iter(this, oops_reloc_begin());
2231 while(iter.next()) {
2232 switch(iter.type()) {
2233 case relocInfo::virtual_call_type: {
2234 CompiledIC *ic = CompiledIC_at(&iter);
2235 CodeBlob *cb = CodeCache::find_blob(ic->destination());
2236 assert(cb != nullptr, "destination not in CodeBlob?");
2237 nmethod* nm = cb->as_nmethod_or_null();
2238 if (nm != nullptr) {
2239 // Verify that inline caches pointing to bad nmethods are clean
2240 if (!nm->is_in_use() || nm->is_unloading()) {
2241 assert(ic->is_clean(), "IC should be clean");
2242 }
2243 }
2244 break;
2245 }
2246 case relocInfo::static_call_type:
2247 case relocInfo::opt_virtual_call_type: {
2248 CompiledDirectCall *cdc = CompiledDirectCall::at(iter.reloc());
2249 CodeBlob *cb = CodeCache::find_blob(cdc->destination());
2250 assert(cb != nullptr, "destination not in CodeBlob?");
2251 nmethod* nm = cb->as_nmethod_or_null();
2252 if (nm != nullptr) {
2253 // Verify that inline caches pointing to bad nmethods are clean
2254 if (!nm->is_in_use() || nm->is_unloading() || nm->method()->code() != nm) {
2255 assert(cdc->is_clean(), "IC should be clean");
2256 }
2257 }
2258 break;
2259 }
2260 default:
2261 break;
2262 }
2263 }
2264 }
2265
2266 void nmethod::mark_as_maybe_on_stack() {
2267 MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
2268 AtomicAccess::store(&_gc_epoch, CodeCache::gc_epoch());
2269 }
2270
2271 bool nmethod::is_maybe_on_stack() {
2272 // If the condition below is true, it means that the nmethod was found to
2273 // be alive the previous completed marking cycle.
2274 return AtomicAccess::load(&_gc_epoch) >= CodeCache::previous_completed_gc_marking_cycle();
2275 }
2276
2277 void nmethod::inc_decompile_count() {
2278 if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return;
2279 // Could be gated by ProfileTraps, but do not bother...
2280 #if INCLUDE_JVMCI
2281 if (jvmci_skip_profile_deopt()) {
2282 return;
2283 }
2284 #endif
2285 Method* m = method();
2286 if (m == nullptr) return;
2287 MethodData* mdo = m->method_data();
2288 if (mdo == nullptr) return;
2289 // There is a benign race here. See comments in methodData.hpp.
2290 mdo->inc_decompile_count();
2291 }
2292
2293 bool nmethod::try_transition(signed char new_state_int) {
2294 signed char new_state = new_state_int;
2295 assert_lock_strong(NMethodState_lock);
2296 signed char old_state = _state;
2297 if (old_state >= new_state) {
2298 // Ensure monotonicity of transitions.
2299 return false;
2300 }
2301 AtomicAccess::store(&_state, new_state);
2302 return true;
2303 }
2304
2305 void nmethod::invalidate_osr_method() {
2306 assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
2307 // Remove from list of active nmethods
2308 if (method() != nullptr) {
2309 method()->method_holder()->remove_osr_nmethod(this);
2310 }
2311 }
2312
2313 void nmethod::log_state_change(InvalidationReason invalidation_reason) const {
2314 if (LogCompilation) {
2315 if (xtty != nullptr) {
2316 ttyLocker ttyl; // keep the following output all in one block
2317 xtty->begin_elem("make_not_entrant thread='%zu' reason='%s'",
2318 os::current_thread_id(), invalidation_reason_to_string(invalidation_reason));
2319 log_identity(xtty);
2320 xtty->stamp();
2321 xtty->end_elem();
2322 }
2323 }
2324
2325 ResourceMark rm;
2326 stringStream ss(NEW_RESOURCE_ARRAY(char, 256), 256);
2327 ss.print("made not entrant: %s", invalidation_reason_to_string(invalidation_reason));
2328
2329 CompileTask::print_ul(this, ss.freeze());
2330 if (PrintCompilation) {
2331 print_on_with_msg(tty, ss.freeze());
2332 }
2333 }
2334
2335 void nmethod::unlink_from_method() {
2336 if (method() != nullptr) {
2337 method()->unlink_code(this);
2338 }
2339 }
2340
2341 // Invalidate code
2342 bool nmethod::make_not_entrant(InvalidationReason invalidation_reason) {
2343 // This can be called while the system is already at a safepoint which is ok
2344 NoSafepointVerifier nsv;
2345
2346 if (is_unloading()) {
2347 // If the nmethod is unloading, then it is already not entrant through
2348 // the nmethod entry barriers. No need to do anything; GC will unload it.
2349 return false;
2350 }
2351
2352 if (AtomicAccess::load(&_state) == not_entrant) {
2353 // Avoid taking the lock if already in required state.
2354 // This is safe from races because the state is an end-state,
2355 // which the nmethod cannot back out of once entered.
2356 // No need for fencing either.
2357 return false;
2358 }
2359
2360 MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
2361
2362 {
2363 // Enter critical section. Does not block for safepoint.
2364 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
2365
2366 if (AtomicAccess::load(&_state) == not_entrant) {
2367 // another thread already performed this transition so nothing
2368 // to do, but return false to indicate this.
2369 return false;
2370 }
2371
2372 if (is_osr_method()) {
2373 // This logic is equivalent to the logic below for patching the
2374 // verified entry point of regular methods.
2375 // this effectively makes the osr nmethod not entrant
2376 invalidate_osr_method();
2377 } else {
2378 // The caller can be calling the method statically or through an inline
2379 // cache call.
2380 BarrierSet::barrier_set()->barrier_set_nmethod()->make_not_entrant(this);
2381 }
2382
2383 if (update_recompile_counts()) {
2384 // Mark the method as decompiled.
2385 inc_decompile_count();
2386 }
2387
2388 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2389 if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) {
2390 // If nmethod entry barriers are not supported, we won't mark
2391 // nmethods as on-stack when they become on-stack. So we
2392 // degrade to a less accurate flushing strategy, for now.
2393 mark_as_maybe_on_stack();
2394 }
2395
2396 // Change state
2397 bool success = try_transition(not_entrant);
2398 assert(success, "Transition can't fail");
2399
2400 // Log the transition once
2401 log_state_change(invalidation_reason);
2402
2403 // Remove nmethod from method.
2404 unlink_from_method();
2405
2406 } // leave critical region under NMethodState_lock
2407
2408 #if INCLUDE_JVMCI
2409 // Invalidate can't occur while holding the NMethodState_lock
2410 JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
2411 if (nmethod_data != nullptr) {
2412 nmethod_data->invalidate_nmethod_mirror(this, invalidation_reason);
2413 }
2414 #endif
2415
2416 #ifdef ASSERT
2417 if (is_osr_method() && method() != nullptr) {
2418 // Make sure osr nmethod is invalidated, i.e. not on the list
2419 bool found = method()->method_holder()->remove_osr_nmethod(this);
2420 assert(!found, "osr nmethod should have been invalidated");
2421 }
2422 #endif
2423
2424 return true;
2425 }
2426
2427 // For concurrent GCs, there must be a handshake between unlink and flush
2428 void nmethod::unlink() {
2429 if (is_unlinked()) {
2430 // Already unlinked.
2431 return;
2432 }
2433
2434 flush_dependencies();
2435
2436 // unlink_from_method will take the NMethodState_lock.
2437 // In this case we don't strictly need it when unlinking nmethods from
2438 // the Method, because it is only concurrently unlinked by
2439 // the entry barrier, which acquires the per nmethod lock.
2440 unlink_from_method();
2441
2442 if (is_osr_method()) {
2443 invalidate_osr_method();
2444 }
2445
2446 #if INCLUDE_JVMCI
2447 // Clear the link between this nmethod and a HotSpotNmethod mirror
2448 JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
2449 if (nmethod_data != nullptr) {
2450 nmethod_data->invalidate_nmethod_mirror(this, is_cold() ?
2451 nmethod::InvalidationReason::UNLOADING_COLD :
2452 nmethod::InvalidationReason::UNLOADING);
2453 }
2454 #endif
2455
2456 // Post before flushing as jmethodID is being used
2457 post_compiled_method_unload();
2458
2459 // Register for flushing when it is safe. For concurrent class unloading,
2460 // that would be after the unloading handshake, and for STW class unloading
2461 // that would be when getting back to the VM thread.
2462 ClassUnloadingContext::context()->register_unlinked_nmethod(this);
2463 }
2464
2465 void nmethod::purge(bool unregister_nmethod) {
2466
2467 MutexLocker ml(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2468
2469 // completely deallocate this method
2470 Events::log_nmethod_flush(Thread::current(), "flushing %s nmethod " INTPTR_FORMAT, is_osr_method() ? "osr" : "", p2i(this));
2471
2472 LogTarget(Debug, codecache) lt;
2473 if (lt.is_enabled()) {
2474 ResourceMark rm;
2475 LogStream ls(lt);
2476 const char* method_name = method()->name()->as_C_string();
2477 const size_t codecache_capacity = CodeCache::capacity()/1024;
2478 const size_t codecache_free_space = CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024;
2479 ls.print("Flushing nmethod %6d/" INTPTR_FORMAT ", level=%d, osr=%d, cold=%d, epoch=" UINT64_FORMAT ", cold_count=" UINT64_FORMAT ". "
2480 "Cache capacity: %zuKb, free space: %zuKb. method %s (%s)",
2481 _compile_id, p2i(this), _comp_level, is_osr_method(), is_cold(), _gc_epoch, CodeCache::cold_gc_count(),
2482 codecache_capacity, codecache_free_space, method_name, compiler_name());
2483 }
2484
2485 // We need to deallocate any ExceptionCache data.
2486 // Note that we do not need to grab the nmethod lock for this, it
2487 // better be thread safe if we're disposing of it!
2488 ExceptionCache* ec = exception_cache();
2489 while(ec != nullptr) {
2490 ExceptionCache* next = ec->next();
2491 delete ec;
2492 ec = next;
2493 }
2494 if (_pc_desc_container != nullptr) {
2495 delete _pc_desc_container;
2496 }
2497 delete[] _compiled_ic_data;
2498
2499 if (_immutable_data != blob_end()) {
2500 // Free memory if this was the last nmethod referencing immutable data
2501 if (dec_immutable_data_ref_count() == 0) {
2502 os::free(_immutable_data);
2503 }
2504
2505 _immutable_data = blob_end(); // Valid not null address
2506 }
2507
2508 if (unregister_nmethod) {
2509 Universe::heap()->unregister_nmethod(this);
2510 }
2511 CodeCache::unregister_old_nmethod(this);
2512
2513 JVMCI_ONLY( _metadata_size = 0; )
2514 CodeBlob::purge();
2515 }
2516
2517 oop nmethod::oop_at(int index) const {
2518 if (index == 0) {
2519 return nullptr;
2520 }
2521
2522 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2523 return bs_nm->oop_load_no_keepalive(this, index);
2524 }
2525
2526 oop nmethod::oop_at_phantom(int index) const {
2527 if (index == 0) {
2528 return nullptr;
2529 }
2530
2531 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2532 return bs_nm->oop_load_phantom(this, index);
2533 }
2534
2535 //
2536 // Notify all classes this nmethod is dependent on that it is no
2537 // longer dependent.
2538
2539 void nmethod::flush_dependencies() {
2540 if (!has_flushed_dependencies()) {
2541 set_has_flushed_dependencies(true);
2542 for (Dependencies::DepStream deps(this); deps.next(); ) {
2543 if (deps.type() == Dependencies::call_site_target_value) {
2544 // CallSite dependencies are managed on per-CallSite instance basis.
2545 oop call_site = deps.argument_oop(0);
2546 MethodHandles::clean_dependency_context(call_site);
2547 } else {
2548 InstanceKlass* ik = deps.context_type();
2549 if (ik == nullptr) {
2550 continue; // ignore things like evol_method
2551 }
2552 // During GC liveness of dependee determines class that needs to be updated.
2553 // The GC may clean dependency contexts concurrently and in parallel.
2554 ik->clean_dependency_context();
2555 }
2556 }
2557 }
2558 }
2559
2560 void nmethod::post_compiled_method(CompileTask* task) {
2561 task->mark_success();
2562 task->set_nm_content_size(content_size());
2563 task->set_nm_insts_size(insts_size());
2564 task->set_nm_total_size(total_size());
2565
2566 // JVMTI -- compiled method notification (must be done outside lock)
2567 post_compiled_method_load_event();
2568
2569 if (CompilationLog::log() != nullptr) {
2570 CompilationLog::log()->log_nmethod(JavaThread::current(), this);
2571 }
2572
2573 const DirectiveSet* directive = task->directive();
2574 maybe_print_nmethod(directive);
2575 }
2576
2577 #if INCLUDE_CDS
2578 static GrowableArrayCHeap<nmethod*, mtClassShared>* _delayed_compiled_method_load_events = nullptr;
2579
2580 void nmethod::add_delayed_compiled_method_load_event(nmethod* nm) {
2581 precond(CDSConfig::is_using_aot_linked_classes());
2582 precond(!ServiceThread::has_started());
2583
2584 // We are still in single threaded stage of VM bootstrap. No need to lock.
2585 if (_delayed_compiled_method_load_events == nullptr) {
2586 _delayed_compiled_method_load_events = new GrowableArrayCHeap<nmethod*, mtClassShared>();
2587 }
2588 _delayed_compiled_method_load_events->append(nm);
2589 }
2590
2591 void nmethod::post_delayed_compiled_method_load_events() {
2592 precond(ServiceThread::has_started());
2593 if (_delayed_compiled_method_load_events != nullptr) {
2594 for (int i = 0; i < _delayed_compiled_method_load_events->length(); i++) {
2595 nmethod* nm = _delayed_compiled_method_load_events->at(i);
2596 nm->post_compiled_method_load_event();
2597 }
2598 delete _delayed_compiled_method_load_events;
2599 _delayed_compiled_method_load_events = nullptr;
2600 }
2601 }
2602 #endif
2603
2604 // ------------------------------------------------------------------
2605 // post_compiled_method_load_event
2606 // new method for install_code() path
2607 // Transfer information from compilation to jvmti
2608 void nmethod::post_compiled_method_load_event(JvmtiThreadState* state) {
2609 #if INCLUDE_CDS
2610 if (!ServiceThread::has_started()) {
2611 // With AOT-linked classes, we could compile wrappers for native methods before the
2612 // ServiceThread has been started, so we must delay the events to be posted later.
2613 assert(state == nullptr, "must be");
2614 add_delayed_compiled_method_load_event(this);
2615 return;
2616 }
2617 #endif
2618
2619 // This is a bad time for a safepoint. We don't want
2620 // this nmethod to get unloaded while we're queueing the event.
2621 NoSafepointVerifier nsv;
2622
2623 Method* m = method();
2624 HOTSPOT_COMPILED_METHOD_LOAD(
2625 (char *) m->klass_name()->bytes(),
2626 m->klass_name()->utf8_length(),
2627 (char *) m->name()->bytes(),
2628 m->name()->utf8_length(),
2629 (char *) m->signature()->bytes(),
2630 m->signature()->utf8_length(),
2631 insts_begin(), insts_size());
2632
2633
2634 if (JvmtiExport::should_post_compiled_method_load()) {
2635 // Only post unload events if load events are found.
2636 set_load_reported();
2637 // If a JavaThread hasn't been passed in, let the Service thread
2638 // (which is a real Java thread) post the event
2639 JvmtiDeferredEvent event = JvmtiDeferredEvent::compiled_method_load_event(this);
2640 if (state == nullptr) {
2641 // Execute any barrier code for this nmethod as if it's called, since
2642 // keeping it alive looks like stack walking.
2643 run_nmethod_entry_barrier();
2644 ServiceThread::enqueue_deferred_event(&event);
2645 } else {
2646 // This enters the nmethod barrier outside in the caller.
2647 state->enqueue_event(&event);
2648 }
2649 }
2650 }
2651
2652 void nmethod::post_compiled_method_unload() {
2653 assert(_method != nullptr, "just checking");
2654 DTRACE_METHOD_UNLOAD_PROBE(method());
2655
2656 // If a JVMTI agent has enabled the CompiledMethodUnload event then
2657 // post the event. The Method* will not be valid when this is freed.
2658
2659 // Don't bother posting the unload if the load event wasn't posted.
2660 if (load_reported() && JvmtiExport::should_post_compiled_method_unload()) {
2661 JvmtiDeferredEvent event =
2662 JvmtiDeferredEvent::compiled_method_unload_event(
2663 method()->jmethod_id(), insts_begin());
2664 ServiceThread::enqueue_deferred_event(&event);
2665 }
2666 }
2667
2668 // Iterate over metadata calling this function. Used by RedefineClasses
2669 void nmethod::metadata_do(MetadataClosure* f) {
2670 {
2671 // Visit all immediate references that are embedded in the instruction stream.
2672 RelocIterator iter(this, oops_reloc_begin());
2673 while (iter.next()) {
2674 if (iter.type() == relocInfo::metadata_type) {
2675 metadata_Relocation* r = iter.metadata_reloc();
2676 // In this metadata, we must only follow those metadatas directly embedded in
2677 // the code. Other metadatas (oop_index>0) are seen as part of
2678 // the metadata section below.
2679 assert(1 == (r->metadata_is_immediate()) +
2680 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
2681 "metadata must be found in exactly one place");
2682 if (r->metadata_is_immediate() && r->metadata_value() != nullptr) {
2683 Metadata* md = r->metadata_value();
2684 if (md != _method) f->do_metadata(md);
2685 }
2686 } else if (iter.type() == relocInfo::virtual_call_type) {
2687 // Check compiledIC holders associated with this nmethod
2688 ResourceMark rm;
2689 CompiledIC *ic = CompiledIC_at(&iter);
2690 ic->metadata_do(f);
2691 }
2692 }
2693 }
2694
2695 // Visit the metadata section
2696 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2697 if (*p == Universe::non_oop_word() || *p == nullptr) continue; // skip non-oops
2698 Metadata* md = *p;
2699 f->do_metadata(md);
2700 }
2701
2702 // Visit metadata not embedded in the other places.
2703 if (_method != nullptr) f->do_metadata(_method);
2704 }
2705
2706 // Heuristic for nuking nmethods even though their oops are live.
2707 // Main purpose is to reduce code cache pressure and get rid of
2708 // nmethods that don't seem to be all that relevant any longer.
2709 bool nmethod::is_cold() {
2710 if (!MethodFlushing || is_not_installed()) {
2711 // No heuristic unloading at all
2712 return false;
2713 }
2714
2715 if (!is_maybe_on_stack() && is_not_entrant()) {
2716 // Not entrant nmethods that are not on any stack can just
2717 // be removed
2718 return true;
2719 }
2720
2721 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2722 if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) {
2723 // On platforms that don't support nmethod entry barriers, we can't
2724 // trust the temporal aspect of the gc epochs. So we can't detect
2725 // cold nmethods on such platforms.
2726 return false;
2727 }
2728
2729 if (!UseCodeCacheFlushing) {
2730 // Bail out if we don't heuristically remove nmethods
2731 return false;
2732 }
2733
2734 // Other code can be phased out more gradually after N GCs
2735 return CodeCache::previous_completed_gc_marking_cycle() > _gc_epoch + 2 * CodeCache::cold_gc_count();
2736 }
2737
2738 // The _is_unloading_state encodes a tuple comprising the unloading cycle
2739 // and the result of IsUnloadingBehaviour::is_unloading() for that cycle.
2740 // This is the bit layout of the _is_unloading_state byte: 00000CCU
2741 // CC refers to the cycle, which has 2 bits, and U refers to the result of
2742 // IsUnloadingBehaviour::is_unloading() for that unloading cycle.
2743
2744 class IsUnloadingState: public AllStatic {
2745 static const uint8_t _is_unloading_mask = 1;
2746 static const uint8_t _is_unloading_shift = 0;
2747 static const uint8_t _unloading_cycle_mask = 6;
2748 static const uint8_t _unloading_cycle_shift = 1;
2749
2750 static uint8_t set_is_unloading(uint8_t state, bool value) {
2751 state &= (uint8_t)~_is_unloading_mask;
2752 if (value) {
2753 state |= 1 << _is_unloading_shift;
2754 }
2755 assert(is_unloading(state) == value, "unexpected unloading cycle overflow");
2756 return state;
2757 }
2758
2759 static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) {
2760 state &= (uint8_t)~_unloading_cycle_mask;
2761 state |= (uint8_t)(value << _unloading_cycle_shift);
2762 assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow");
2763 return state;
2764 }
2765
2766 public:
2767 static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; }
2768 static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; }
2769
2770 static uint8_t create(bool is_unloading, uint8_t unloading_cycle) {
2771 uint8_t state = 0;
2772 state = set_is_unloading(state, is_unloading);
2773 state = set_unloading_cycle(state, unloading_cycle);
2774 return state;
2775 }
2776 };
2777
2778 bool nmethod::is_unloading() {
2779 uint8_t state = AtomicAccess::load(&_is_unloading_state);
2780 bool state_is_unloading = IsUnloadingState::is_unloading(state);
2781 if (state_is_unloading) {
2782 return true;
2783 }
2784 uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state);
2785 uint8_t current_cycle = CodeCache::unloading_cycle();
2786 if (state_unloading_cycle == current_cycle) {
2787 return false;
2788 }
2789
2790 // The IsUnloadingBehaviour is responsible for calculating if the nmethod
2791 // should be unloaded. This can be either because there is a dead oop,
2792 // or because is_cold() heuristically determines it is time to unload.
2793 state_unloading_cycle = current_cycle;
2794 state_is_unloading = IsUnloadingBehaviour::is_unloading(this);
2795 uint8_t new_state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle);
2796
2797 MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
2798
2799 // Note that if an nmethod has dead oops, everyone will agree that the
2800 // nmethod is_unloading. However, the is_cold heuristics can yield
2801 // different outcomes, so we guard the computed result with a CAS
2802 // to ensure all threads have a shared view of whether an nmethod
2803 // is_unloading or not.
2804 uint8_t found_state = AtomicAccess::cmpxchg(&_is_unloading_state, state, new_state, memory_order_relaxed);
2805
2806 if (found_state == state) {
2807 // First to change state, we win
2808 return state_is_unloading;
2809 } else {
2810 // State already set, so use it
2811 return IsUnloadingState::is_unloading(found_state);
2812 }
2813 }
2814
2815 void nmethod::clear_unloading_state() {
2816 uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle());
2817 AtomicAccess::store(&_is_unloading_state, state);
2818 }
2819
2820
2821 // This is called at the end of the strong tracing/marking phase of a
2822 // GC to unload an nmethod if it contains otherwise unreachable
2823 // oops or is heuristically found to be not important.
2824 void nmethod::do_unloading(bool unloading_occurred) {
2825 // Make sure the oop's ready to receive visitors
2826 if (is_unloading()) {
2827 unlink();
2828 } else {
2829 unload_nmethod_caches(unloading_occurred);
2830 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2831 if (bs_nm != nullptr) {
2832 bs_nm->disarm(this);
2833 }
2834 }
2835 }
2836
2837 void nmethod::oops_do(OopClosure* f) {
2838 // Prevent extra code cache walk for platforms that don't have immediate oops.
2839 if (relocInfo::mustIterateImmediateOopsInCode()) {
2840 RelocIterator iter(this, oops_reloc_begin());
2841
2842 while (iter.next()) {
2843 if (iter.type() == relocInfo::oop_type ) {
2844 oop_Relocation* r = iter.oop_reloc();
2845 // In this loop, we must only follow those oops directly embedded in
2846 // the code. Other oops (oop_index>0) are seen as part of scopes_oops.
2847 assert(1 == (r->oop_is_immediate()) +
2848 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2849 "oop must be found in exactly one place");
2850 if (r->oop_is_immediate() && r->oop_value() != nullptr) {
2851 f->do_oop(r->oop_addr());
2852 }
2853 }
2854 }
2855 }
2856
2857 // Scopes
2858 // This includes oop constants not inlined in the code stream.
2859 for (oop* p = oops_begin(); p < oops_end(); p++) {
2860 if (*p == Universe::non_oop_word()) continue; // skip non-oops
2861 f->do_oop(p);
2862 }
2863 }
2864
2865 void nmethod::follow_nmethod(OopIterateClosure* cl) {
2866 // Process oops in the nmethod
2867 oops_do(cl);
2868
2869 // CodeCache unloading support
2870 mark_as_maybe_on_stack();
2871
2872 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2873 bs_nm->disarm(this);
2874
2875 // There's an assumption made that this function is not used by GCs that
2876 // relocate objects, and therefore we don't call fix_oop_relocations.
2877 }
2878
2879 nmethod* volatile nmethod::_oops_do_mark_nmethods;
2880
2881 void nmethod::oops_do_log_change(const char* state) {
2882 LogTarget(Trace, gc, nmethod) lt;
2883 if (lt.is_enabled()) {
2884 LogStream ls(lt);
2885 CompileTask::print(&ls, this, state, true /* short_form */);
2886 }
2887 }
2888
2889 bool nmethod::oops_do_try_claim() {
2890 if (oops_do_try_claim_weak_request()) {
2891 nmethod* result = oops_do_try_add_to_list_as_weak_done();
2892 assert(result == nullptr, "adding to global list as weak done must always succeed.");
2893 return true;
2894 }
2895 return false;
2896 }
2897
2898 bool nmethod::oops_do_try_claim_weak_request() {
2899 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2900
2901 if ((_oops_do_mark_link == nullptr) &&
2902 (AtomicAccess::replace_if_null(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag)))) {
2903 oops_do_log_change("oops_do, mark weak request");
2904 return true;
2905 }
2906 return false;
2907 }
2908
2909 void nmethod::oops_do_set_strong_done(nmethod* old_head) {
2910 _oops_do_mark_link = mark_link(old_head, claim_strong_done_tag);
2911 }
2912
2913 nmethod::oops_do_mark_link* nmethod::oops_do_try_claim_strong_done() {
2914 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2915
2916 oops_do_mark_link* old_next = AtomicAccess::cmpxchg(&_oops_do_mark_link, mark_link(nullptr, claim_weak_request_tag), mark_link(this, claim_strong_done_tag));
2917 if (old_next == nullptr) {
2918 oops_do_log_change("oops_do, mark strong done");
2919 }
2920 return old_next;
2921 }
2922
2923 nmethod::oops_do_mark_link* nmethod::oops_do_try_add_strong_request(nmethod::oops_do_mark_link* next) {
2924 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2925 assert(next == mark_link(this, claim_weak_request_tag), "Should be claimed as weak");
2926
2927 oops_do_mark_link* old_next = AtomicAccess::cmpxchg(&_oops_do_mark_link, next, mark_link(this, claim_strong_request_tag));
2928 if (old_next == next) {
2929 oops_do_log_change("oops_do, mark strong request");
2930 }
2931 return old_next;
2932 }
2933
2934 bool nmethod::oops_do_try_claim_weak_done_as_strong_done(nmethod::oops_do_mark_link* next) {
2935 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2936 assert(extract_state(next) == claim_weak_done_tag, "Should be claimed as weak done");
2937
2938 oops_do_mark_link* old_next = AtomicAccess::cmpxchg(&_oops_do_mark_link, next, mark_link(extract_nmethod(next), claim_strong_done_tag));
2939 if (old_next == next) {
2940 oops_do_log_change("oops_do, mark weak done -> mark strong done");
2941 return true;
2942 }
2943 return false;
2944 }
2945
2946 nmethod* nmethod::oops_do_try_add_to_list_as_weak_done() {
2947 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2948
2949 assert(extract_state(_oops_do_mark_link) == claim_weak_request_tag ||
2950 extract_state(_oops_do_mark_link) == claim_strong_request_tag,
2951 "must be but is nmethod " PTR_FORMAT " %u", p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));
2952
2953 nmethod* old_head = AtomicAccess::xchg(&_oops_do_mark_nmethods, this);
2954 // Self-loop if needed.
2955 if (old_head == nullptr) {
2956 old_head = this;
2957 }
2958 // Try to install end of list and weak done tag.
2959 if (AtomicAccess::cmpxchg(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag), mark_link(old_head, claim_weak_done_tag)) == mark_link(this, claim_weak_request_tag)) {
2960 oops_do_log_change("oops_do, mark weak done");
2961 return nullptr;
2962 } else {
2963 return old_head;
2964 }
2965 }
2966
2967 void nmethod::oops_do_add_to_list_as_strong_done() {
2968 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2969
2970 nmethod* old_head = AtomicAccess::xchg(&_oops_do_mark_nmethods, this);
2971 // Self-loop if needed.
2972 if (old_head == nullptr) {
2973 old_head = this;
2974 }
2975 assert(_oops_do_mark_link == mark_link(this, claim_strong_done_tag), "must be but is nmethod " PTR_FORMAT " state %u",
2976 p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));
2977
2978 oops_do_set_strong_done(old_head);
2979 }
2980
2981 void nmethod::oops_do_process_weak(OopsDoProcessor* p) {
2982 if (!oops_do_try_claim_weak_request()) {
2983 // Failed to claim for weak processing.
2984 oops_do_log_change("oops_do, mark weak request fail");
2985 return;
2986 }
2987
2988 p->do_regular_processing(this);
2989
2990 nmethod* old_head = oops_do_try_add_to_list_as_weak_done();
2991 if (old_head == nullptr) {
2992 return;
2993 }
2994 oops_do_log_change("oops_do, mark weak done fail");
2995 // Adding to global list failed, another thread added a strong request.
2996 assert(extract_state(_oops_do_mark_link) == claim_strong_request_tag,
2997 "must be but is %u", extract_state(_oops_do_mark_link));
2998
2999 oops_do_log_change("oops_do, mark weak request -> mark strong done");
3000
3001 oops_do_set_strong_done(old_head);
3002 // Do missing strong processing.
3003 p->do_remaining_strong_processing(this);
3004 }
3005
3006 void nmethod::oops_do_process_strong(OopsDoProcessor* p) {
3007 oops_do_mark_link* next_raw = oops_do_try_claim_strong_done();
3008 if (next_raw == nullptr) {
3009 p->do_regular_processing(this);
3010 oops_do_add_to_list_as_strong_done();
3011 return;
3012 }
3013 // Claim failed. Figure out why and handle it.
3014 if (oops_do_has_weak_request(next_raw)) {
3015 oops_do_mark_link* old = next_raw;
3016 // Claim failed because being weak processed (state == "weak request").
3017 // Try to request deferred strong processing.
3018 next_raw = oops_do_try_add_strong_request(old);
3019 if (next_raw == old) {
3020 // Successfully requested deferred strong processing.
3021 return;
3022 }
3023 // Failed because of a concurrent transition. No longer in "weak request" state.
3024 }
3025 if (oops_do_has_any_strong_state(next_raw)) {
3026 // Already claimed for strong processing or requested for such.
3027 return;
3028 }
3029 if (oops_do_try_claim_weak_done_as_strong_done(next_raw)) {
3030 // Successfully claimed "weak done" as "strong done". Do the missing marking.
3031 p->do_remaining_strong_processing(this);
3032 return;
3033 }
3034 // Claim failed, some other thread got it.
3035 }
3036
3037 void nmethod::oops_do_marking_prologue() {
3038 assert_at_safepoint();
3039
3040 log_trace(gc, nmethod)("oops_do_marking_prologue");
3041 assert(_oops_do_mark_nmethods == nullptr, "must be empty");
3042 }
3043
3044 void nmethod::oops_do_marking_epilogue() {
3045 assert_at_safepoint();
3046
3047 nmethod* next = _oops_do_mark_nmethods;
3048 _oops_do_mark_nmethods = nullptr;
3049 if (next != nullptr) {
3050 nmethod* cur;
3051 do {
3052 cur = next;
3053 next = extract_nmethod(cur->_oops_do_mark_link);
3054 cur->_oops_do_mark_link = nullptr;
3055 DEBUG_ONLY(cur->verify_oop_relocations());
3056
3057 LogTarget(Trace, gc, nmethod) lt;
3058 if (lt.is_enabled()) {
3059 LogStream ls(lt);
3060 CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true);
3061 }
3062 // End if self-loop has been detected.
3063 } while (cur != next);
3064 }
3065 log_trace(gc, nmethod)("oops_do_marking_epilogue");
3066 }
3067
3068 inline bool includes(void* p, void* from, void* to) {
3069 return from <= p && p < to;
3070 }
3071
3072
3073 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
3074 assert(count >= 2, "must be sentinel values, at least");
3075
3076 #ifdef ASSERT
3077 // must be sorted and unique; we do a binary search in find_pc_desc()
3078 int prev_offset = pcs[0].pc_offset();
3079 assert(prev_offset == PcDesc::lower_offset_limit,
3080 "must start with a sentinel");
3081 for (int i = 1; i < count; i++) {
3082 int this_offset = pcs[i].pc_offset();
3083 assert(this_offset > prev_offset, "offsets must be sorted");
3084 prev_offset = this_offset;
3085 }
3086 assert(prev_offset == PcDesc::upper_offset_limit,
3087 "must end with a sentinel");
3088 #endif //ASSERT
3089
3090 int size = count * sizeof(PcDesc);
3091 assert(scopes_pcs_size() >= size, "oob");
3092 memcpy(scopes_pcs_begin(), pcs, size);
3093
3094 // Adjust the final sentinel downward.
3095 PcDesc* last_pc = &scopes_pcs_begin()[count-1];
3096 assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
3097 last_pc->set_pc_offset(content_size() + 1);
3098 for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
3099 // Fill any rounding gaps with copies of the last record.
3100 last_pc[1] = last_pc[0];
3101 }
3102 // The following assert could fail if sizeof(PcDesc) is not
3103 // an integral multiple of oopSize (the rounding term).
3104 // If it fails, change the logic to always allocate a multiple
3105 // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
3106 assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
3107 }
3108
3109 void nmethod::copy_scopes_data(u_char* buffer, int size) {
3110 assert(scopes_data_size() >= size, "oob");
3111 memcpy(scopes_data_begin(), buffer, size);
3112 }
3113
3114 #ifdef ASSERT
3115 static PcDesc* linear_search(int pc_offset, bool approximate, PcDesc* lower, PcDesc* upper) {
3116 PcDesc* res = nullptr;
3117 assert(lower != nullptr && lower->pc_offset() == PcDesc::lower_offset_limit,
3118 "must start with a sentinel");
3119 // lower + 1 to exclude initial sentinel
3120 for (PcDesc* p = lower + 1; p < upper; p++) {
3121 NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests); // don't count this call to match_desc
3122 if (match_desc(p, pc_offset, approximate)) {
3123 if (res == nullptr) {
3124 res = p;
3125 } else {
3126 res = (PcDesc*) badAddress;
3127 }
3128 }
3129 }
3130 return res;
3131 }
3132 #endif
3133
3134
3135 #ifndef PRODUCT
3136 // Version of method to collect statistic
3137 PcDesc* PcDescContainer::find_pc_desc(address pc, bool approximate, address code_begin,
3138 PcDesc* lower, PcDesc* upper) {
3139 ++pc_nmethod_stats.pc_desc_queries;
3140 if (approximate) ++pc_nmethod_stats.pc_desc_approx;
3141
3142 PcDesc* desc = _pc_desc_cache.last_pc_desc();
3143 assert(desc != nullptr, "PcDesc cache should be initialized already");
3144 if (desc->pc_offset() == (pc - code_begin)) {
3145 // Cached value matched
3146 ++pc_nmethod_stats.pc_desc_tests;
3147 ++pc_nmethod_stats.pc_desc_repeats;
3148 return desc;
3149 }
3150 return find_pc_desc_internal(pc, approximate, code_begin, lower, upper);
3151 }
3152 #endif
3153
3154 // Finds a PcDesc with real-pc equal to "pc"
3155 PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, address code_begin,
3156 PcDesc* lower_incl, PcDesc* upper_incl) {
3157 if ((pc < code_begin) ||
3158 (pc - code_begin) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
3159 return nullptr; // PC is wildly out of range
3160 }
3161 int pc_offset = (int) (pc - code_begin);
3162
3163 // Check the PcDesc cache if it contains the desired PcDesc
3164 // (This as an almost 100% hit rate.)
3165 PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
3166 if (res != nullptr) {
3167 assert(res == linear_search(pc_offset, approximate, lower_incl, upper_incl), "cache ok");
3168 return res;
3169 }
3170
3171 // Fallback algorithm: quasi-linear search for the PcDesc
3172 // Find the last pc_offset less than the given offset.
3173 // The successor must be the required match, if there is a match at all.
3174 // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
3175 PcDesc* lower = lower_incl; // this is initial sentinel
3176 PcDesc* upper = upper_incl - 1; // exclude final sentinel
3177 if (lower >= upper) return nullptr; // no PcDescs at all
3178
3179 #define assert_LU_OK \
3180 /* invariant on lower..upper during the following search: */ \
3181 assert(lower->pc_offset() < pc_offset, "sanity"); \
3182 assert(upper->pc_offset() >= pc_offset, "sanity")
3183 assert_LU_OK;
3184
3185 // Use the last successful return as a split point.
3186 PcDesc* mid = _pc_desc_cache.last_pc_desc();
3187 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
3188 if (mid->pc_offset() < pc_offset) {
3189 lower = mid;
3190 } else {
3191 upper = mid;
3192 }
3193
3194 // Take giant steps at first (4096, then 256, then 16, then 1)
3195 const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ DEBUG_ONLY(-1);
3196 const int RADIX = (1 << LOG2_RADIX);
3197 for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
3198 while ((mid = lower + step) < upper) {
3199 assert_LU_OK;
3200 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
3201 if (mid->pc_offset() < pc_offset) {
3202 lower = mid;
3203 } else {
3204 upper = mid;
3205 break;
3206 }
3207 }
3208 assert_LU_OK;
3209 }
3210
3211 // Sneak up on the value with a linear search of length ~16.
3212 while (true) {
3213 assert_LU_OK;
3214 mid = lower + 1;
3215 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
3216 if (mid->pc_offset() < pc_offset) {
3217 lower = mid;
3218 } else {
3219 upper = mid;
3220 break;
3221 }
3222 }
3223 #undef assert_LU_OK
3224
3225 if (match_desc(upper, pc_offset, approximate)) {
3226 assert(upper == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch");
3227 if (!Thread::current_in_asgct()) {
3228 // we don't want to modify the cache if we're in ASGCT
3229 // which is typically called in a signal handler
3230 _pc_desc_cache.add_pc_desc(upper);
3231 }
3232 return upper;
3233 } else {
3234 assert(nullptr == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch");
3235 return nullptr;
3236 }
3237 }
3238
3239 bool nmethod::check_dependency_on(DepChange& changes) {
3240 // What has happened:
3241 // 1) a new class dependee has been added
3242 // 2) dependee and all its super classes have been marked
3243 bool found_check = false; // set true if we are upset
3244 for (Dependencies::DepStream deps(this); deps.next(); ) {
3245 // Evaluate only relevant dependencies.
3246 if (deps.spot_check_dependency_at(changes) != nullptr) {
3247 found_check = true;
3248 NOT_DEBUG(break);
3249 }
3250 }
3251 return found_check;
3252 }
3253
3254 // Called from mark_for_deoptimization, when dependee is invalidated.
3255 bool nmethod::is_dependent_on_method(Method* dependee) {
3256 for (Dependencies::DepStream deps(this); deps.next(); ) {
3257 if (Dependencies::has_method_dep(deps.type())) {
3258 Method* method = deps.method_argument(0);
3259 if (method == dependee) return true;
3260 }
3261 }
3262 return false;
3263 }
3264
3265 void nmethod_init() {
3266 // make sure you didn't forget to adjust the filler fields
3267 assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
3268 }
3269
3270 // -----------------------------------------------------------------------------
3271 // Verification
3272
3273 class VerifyOopsClosure: public OopClosure {
3274 nmethod* _nm;
3275 bool _ok;
3276 public:
3277 VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
3278 bool ok() { return _ok; }
3279 virtual void do_oop(oop* p) {
3280 if (oopDesc::is_oop_or_null(*p)) return;
3281 // Print diagnostic information before calling print_nmethod().
3282 // Assertions therein might prevent call from returning.
3283 tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
3284 p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));
3285 if (_ok) {
3286 _nm->print_nmethod(true);
3287 _ok = false;
3288 }
3289 }
3290 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
3291 };
3292
3293 class VerifyMetadataClosure: public MetadataClosure {
3294 public:
3295 void do_metadata(Metadata* md) {
3296 if (md->is_method()) {
3297 Method* method = (Method*)md;
3298 assert(!method->is_old(), "Should not be installing old methods");
3299 }
3300 }
3301 };
3302
3303
3304 void nmethod::verify() {
3305 if (is_not_entrant())
3306 return;
3307
3308 // assert(oopDesc::is_oop(method()), "must be valid");
3309
3310 ResourceMark rm;
3311
3312 if (!CodeCache::contains(this)) {
3313 fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this));
3314 }
3315
3316 if(is_native_method() )
3317 return;
3318
3319 nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
3320 if (nm != this) {
3321 fatal("find_nmethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this));
3322 }
3323
3324 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3325 if (! p->verify(this)) {
3326 tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this));
3327 }
3328 }
3329
3330 #ifdef ASSERT
3331 #if INCLUDE_JVMCI
3332 {
3333 // Verify that implicit exceptions that deoptimize have a PcDesc and OopMap
3334 ImmutableOopMapSet* oms = oop_maps();
3335 ImplicitExceptionTable implicit_table(this);
3336 for (uint i = 0; i < implicit_table.len(); i++) {
3337 int exec_offset = (int) implicit_table.get_exec_offset(i);
3338 if (implicit_table.get_exec_offset(i) == implicit_table.get_cont_offset(i)) {
3339 assert(pc_desc_at(code_begin() + exec_offset) != nullptr, "missing PcDesc");
3340 bool found = false;
3341 for (int i = 0, imax = oms->count(); i < imax; i++) {
3342 if (oms->pair_at(i)->pc_offset() == exec_offset) {
3343 found = true;
3344 break;
3345 }
3346 }
3347 assert(found, "missing oopmap");
3348 }
3349 }
3350 }
3351 #endif
3352 #endif
3353
3354 VerifyOopsClosure voc(this);
3355 oops_do(&voc);
3356 assert(voc.ok(), "embedded oops must be OK");
3357 Universe::heap()->verify_nmethod(this);
3358
3359 assert(_oops_do_mark_link == nullptr, "_oops_do_mark_link for %s should be nullptr but is " PTR_FORMAT,
3360 nm->method()->external_name(), p2i(_oops_do_mark_link));
3361 verify_scopes();
3362
3363 CompiledICLocker nm_verify(this);
3364 VerifyMetadataClosure vmc;
3365 metadata_do(&vmc);
3366 }
3367
3368
3369 void nmethod::verify_interrupt_point(address call_site, bool is_inline_cache) {
3370
3371 // Verify IC only when nmethod installation is finished.
3372 if (!is_not_installed()) {
3373 if (CompiledICLocker::is_safe(this)) {
3374 if (is_inline_cache) {
3375 CompiledIC_at(this, call_site);
3376 } else {
3377 CompiledDirectCall::at(call_site);
3378 }
3379 } else {
3380 CompiledICLocker ml_verify(this);
3381 if (is_inline_cache) {
3382 CompiledIC_at(this, call_site);
3383 } else {
3384 CompiledDirectCall::at(call_site);
3385 }
3386 }
3387 }
3388
3389 HandleMark hm(Thread::current());
3390
3391 PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
3392 assert(pd != nullptr, "PcDesc must exist");
3393 for (ScopeDesc* sd = new ScopeDesc(this, pd);
3394 !sd->is_top(); sd = sd->sender()) {
3395 sd->verify();
3396 }
3397 }
3398
3399 void nmethod::verify_scopes() {
3400 if( !method() ) return; // Runtime stubs have no scope
3401 if (method()->is_native()) return; // Ignore stub methods.
3402 // iterate through all interrupt point
3403 // and verify the debug information is valid.
3404 RelocIterator iter(this);
3405 while (iter.next()) {
3406 address stub = nullptr;
3407 switch (iter.type()) {
3408 case relocInfo::virtual_call_type:
3409 verify_interrupt_point(iter.addr(), true /* is_inline_cache */);
3410 break;
3411 case relocInfo::opt_virtual_call_type:
3412 stub = iter.opt_virtual_call_reloc()->static_stub();
3413 verify_interrupt_point(iter.addr(), false /* is_inline_cache */);
3414 break;
3415 case relocInfo::static_call_type:
3416 stub = iter.static_call_reloc()->static_stub();
3417 verify_interrupt_point(iter.addr(), false /* is_inline_cache */);
3418 break;
3419 case relocInfo::runtime_call_type:
3420 case relocInfo::runtime_call_w_cp_type: {
3421 address destination = iter.reloc()->value();
3422 // Right now there is no way to find out which entries support
3423 // an interrupt point. It would be nice if we had this
3424 // information in a table.
3425 break;
3426 }
3427 default:
3428 break;
3429 }
3430 assert(stub == nullptr || stub_contains(stub), "static call stub outside stub section");
3431 }
3432 }
3433
3434
3435 // -----------------------------------------------------------------------------
3436 // Printing operations
3437
3438 void nmethod::print_on_impl(outputStream* st) const {
3439 ResourceMark rm;
3440
3441 st->print("Compiled method ");
3442
3443 if (is_compiled_by_c1()) {
3444 st->print("(c1) ");
3445 } else if (is_compiled_by_c2()) {
3446 st->print("(c2) ");
3447 } else if (is_compiled_by_jvmci()) {
3448 st->print("(JVMCI) ");
3449 } else {
3450 st->print("(n/a) ");
3451 }
3452
3453 print_on_with_msg(st, nullptr);
3454
3455 if (WizardMode) {
3456 st->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this));
3457 st->print(" for method " INTPTR_FORMAT , p2i(method()));
3458 st->print(" { ");
3459 st->print_cr("%s ", state());
3460 st->print_cr("}:");
3461 }
3462 if (size () > 0) st->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3463 p2i(this),
3464 p2i(this) + size(),
3465 size());
3466 if (consts_size () > 0) st->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3467 p2i(consts_begin()),
3468 p2i(consts_end()),
3469 consts_size());
3470 if (insts_size () > 0) st->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3471 p2i(insts_begin()),
3472 p2i(insts_end()),
3473 insts_size());
3474 if (stub_size () > 0) st->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3475 p2i(stub_begin()),
3476 p2i(stub_end()),
3477 stub_size());
3478 if (oops_size () > 0) st->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3479 p2i(oops_begin()),
3480 p2i(oops_end()),
3481 oops_size());
3482 if (mutable_data_size() > 0) st->print_cr(" mutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3483 p2i(mutable_data_begin()),
3484 p2i(mutable_data_end()),
3485 mutable_data_size());
3486 if (relocation_size() > 0) st->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3487 p2i(relocation_begin()),
3488 p2i(relocation_end()),
3489 relocation_size());
3490 if (metadata_size () > 0) st->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3491 p2i(metadata_begin()),
3492 p2i(metadata_end()),
3493 metadata_size());
3494 #if INCLUDE_JVMCI
3495 if (jvmci_data_size () > 0) st->print_cr(" JVMCI data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3496 p2i(jvmci_data_begin()),
3497 p2i(jvmci_data_end()),
3498 jvmci_data_size());
3499 #endif
3500 if (immutable_data_size() > 0) st->print_cr(" immutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3501 p2i(immutable_data_begin()),
3502 p2i(immutable_data_end()),
3503 immutable_data_size());
3504 if (dependencies_size () > 0) st->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3505 p2i(dependencies_begin()),
3506 p2i(dependencies_end()),
3507 dependencies_size());
3508 if (nul_chk_table_size() > 0) st->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3509 p2i(nul_chk_table_begin()),
3510 p2i(nul_chk_table_end()),
3511 nul_chk_table_size());
3512 if (handler_table_size() > 0) st->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3513 p2i(handler_table_begin()),
3514 p2i(handler_table_end()),
3515 handler_table_size());
3516 if (scopes_pcs_size () > 0) st->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3517 p2i(scopes_pcs_begin()),
3518 p2i(scopes_pcs_end()),
3519 scopes_pcs_size());
3520 if (scopes_data_size () > 0) st->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3521 p2i(scopes_data_begin()),
3522 p2i(scopes_data_end()),
3523 scopes_data_size());
3524 #if INCLUDE_JVMCI
3525 if (speculations_size () > 0) st->print_cr(" speculations [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3526 p2i(speculations_begin()),
3527 p2i(speculations_end()),
3528 speculations_size());
3529 #endif
3530 }
3531
3532 void nmethod::print_code() {
3533 ResourceMark m;
3534 ttyLocker ttyl;
3535 // Call the specialized decode method of this class.
3536 decode(tty);
3537 }
3538
3539 #ifndef PRODUCT // called InstanceKlass methods are available only then. Declared as PRODUCT_RETURN
3540
3541 void nmethod::print_dependencies_on(outputStream* out) {
3542 ResourceMark rm;
3543 stringStream st;
3544 st.print_cr("Dependencies:");
3545 for (Dependencies::DepStream deps(this); deps.next(); ) {
3546 deps.print_dependency(&st);
3547 InstanceKlass* ctxk = deps.context_type();
3548 if (ctxk != nullptr) {
3549 if (ctxk->is_dependent_nmethod(this)) {
3550 st.print_cr(" [nmethod<=klass]%s", ctxk->external_name());
3551 }
3552 }
3553 deps.log_dependency(); // put it into the xml log also
3554 }
3555 out->print_raw(st.as_string());
3556 }
3557 #endif
3558
3559 #if defined(SUPPORT_DATA_STRUCTS)
3560
3561 // Print the oops from the underlying CodeBlob.
3562 void nmethod::print_oops(outputStream* st) {
3563 ResourceMark m;
3564 st->print("Oops:");
3565 if (oops_begin() < oops_end()) {
3566 st->cr();
3567 for (oop* p = oops_begin(); p < oops_end(); p++) {
3568 Disassembler::print_location((unsigned char*)p, (unsigned char*)oops_begin(), (unsigned char*)oops_end(), st, true, false);
3569 st->print(PTR_FORMAT " ", *((uintptr_t*)p));
3570 if (Universe::contains_non_oop_word(p)) {
3571 st->print_cr("NON_OOP");
3572 continue; // skip non-oops
3573 }
3574 if (*p == nullptr) {
3575 st->print_cr("nullptr-oop");
3576 continue; // skip non-oops
3577 }
3578 (*p)->print_value_on(st);
3579 st->cr();
3580 }
3581 } else {
3582 st->print_cr(" <list empty>");
3583 }
3584 }
3585
3586 // Print metadata pool.
3587 void nmethod::print_metadata(outputStream* st) {
3588 ResourceMark m;
3589 st->print("Metadata:");
3590 if (metadata_begin() < metadata_end()) {
3591 st->cr();
3592 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
3593 Disassembler::print_location((unsigned char*)p, (unsigned char*)metadata_begin(), (unsigned char*)metadata_end(), st, true, false);
3594 st->print(PTR_FORMAT " ", *((uintptr_t*)p));
3595 if (*p && *p != Universe::non_oop_word()) {
3596 (*p)->print_value_on(st);
3597 }
3598 st->cr();
3599 }
3600 } else {
3601 st->print_cr(" <list empty>");
3602 }
3603 }
3604
3605 #ifndef PRODUCT // ScopeDesc::print_on() is available only then. Declared as PRODUCT_RETURN
3606 void nmethod::print_scopes_on(outputStream* st) {
3607 // Find the first pc desc for all scopes in the code and print it.
3608 ResourceMark rm;
3609 st->print("scopes:");
3610 if (scopes_pcs_begin() < scopes_pcs_end()) {
3611 st->cr();
3612 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3613 if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
3614 continue;
3615
3616 ScopeDesc* sd = scope_desc_at(p->real_pc(this));
3617 while (sd != nullptr) {
3618 sd->print_on(st, p); // print output ends with a newline
3619 sd = sd->sender();
3620 }
3621 }
3622 } else {
3623 st->print_cr(" <list empty>");
3624 }
3625 }
3626 #endif
3627
3628 #ifndef PRODUCT // RelocIterator does support printing only then.
3629 void nmethod::print_relocations() {
3630 ResourceMark m; // in case methods get printed via the debugger
3631 tty->print_cr("relocations:");
3632 RelocIterator iter(this);
3633 iter.print_on(tty);
3634 }
3635 #endif
3636
3637 void nmethod::print_pcs_on(outputStream* st) {
3638 ResourceMark m; // in case methods get printed via debugger
3639 st->print("pc-bytecode offsets:");
3640 if (scopes_pcs_begin() < scopes_pcs_end()) {
3641 st->cr();
3642 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3643 p->print_on(st, this); // print output ends with a newline
3644 }
3645 } else {
3646 st->print_cr(" <list empty>");
3647 }
3648 }
3649
3650 void nmethod::print_handler_table() {
3651 ExceptionHandlerTable(this).print(code_begin());
3652 }
3653
3654 void nmethod::print_nul_chk_table() {
3655 ImplicitExceptionTable(this).print(code_begin());
3656 }
3657
3658 void nmethod::print_recorded_oop(int log_n, int i) {
3659 void* value;
3660
3661 if (i == 0) {
3662 value = nullptr;
3663 } else {
3664 // Be careful around non-oop words. Don't create an oop
3665 // with that value, or it will assert in verification code.
3666 if (Universe::contains_non_oop_word(oop_addr_at(i))) {
3667 value = Universe::non_oop_word();
3668 } else {
3669 value = oop_at(i);
3670 }
3671 }
3672
3673 tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(value));
3674
3675 if (value == Universe::non_oop_word()) {
3676 tty->print("non-oop word");
3677 } else {
3678 if (value == nullptr) {
3679 tty->print("nullptr-oop");
3680 } else {
3681 oop_at(i)->print_value_on(tty);
3682 }
3683 }
3684
3685 tty->cr();
3686 }
3687
3688 void nmethod::print_recorded_oops() {
3689 const int n = oops_count();
3690 const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
3691 tty->print("Recorded oops:");
3692 if (n > 0) {
3693 tty->cr();
3694 for (int i = 0; i < n; i++) {
3695 print_recorded_oop(log_n, i);
3696 }
3697 } else {
3698 tty->print_cr(" <list empty>");
3699 }
3700 }
3701
3702 void nmethod::print_recorded_metadata() {
3703 const int n = metadata_count();
3704 const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
3705 tty->print("Recorded metadata:");
3706 if (n > 0) {
3707 tty->cr();
3708 for (int i = 0; i < n; i++) {
3709 Metadata* m = metadata_at(i);
3710 tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(m));
3711 if (m == (Metadata*)Universe::non_oop_word()) {
3712 tty->print("non-metadata word");
3713 } else if (m == nullptr) {
3714 tty->print("nullptr-oop");
3715 } else {
3716 Metadata::print_value_on_maybe_null(tty, m);
3717 }
3718 tty->cr();
3719 }
3720 } else {
3721 tty->print_cr(" <list empty>");
3722 }
3723 }
3724 #endif
3725
3726 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
3727
3728 void nmethod::print_constant_pool(outputStream* st) {
3729 //-----------------------------------
3730 //---< Print the constant pool >---
3731 //-----------------------------------
3732 int consts_size = this->consts_size();
3733 if ( consts_size > 0 ) {
3734 unsigned char* cstart = this->consts_begin();
3735 unsigned char* cp = cstart;
3736 unsigned char* cend = cp + consts_size;
3737 unsigned int bytes_per_line = 4;
3738 unsigned int CP_alignment = 8;
3739 unsigned int n;
3740
3741 st->cr();
3742
3743 //---< print CP header to make clear what's printed >---
3744 if( ((uintptr_t)cp&(CP_alignment-1)) == 0 ) {
3745 n = bytes_per_line;
3746 st->print_cr("[Constant Pool]");
3747 Disassembler::print_location(cp, cstart, cend, st, true, true);
3748 Disassembler::print_hexdata(cp, n, st, true);
3749 st->cr();
3750 } else {
3751 n = (int)((uintptr_t)cp & (bytes_per_line-1));
3752 st->print_cr("[Constant Pool (unaligned)]");
3753 }
3754
3755 //---< print CP contents, bytes_per_line at a time >---
3756 while (cp < cend) {
3757 Disassembler::print_location(cp, cstart, cend, st, true, false);
3758 Disassembler::print_hexdata(cp, n, st, false);
3759 cp += n;
3760 n = bytes_per_line;
3761 st->cr();
3762 }
3763
3764 //---< Show potential alignment gap between constant pool and code >---
3765 cend = code_begin();
3766 if( cp < cend ) {
3767 n = 4;
3768 st->print_cr("[Code entry alignment]");
3769 while (cp < cend) {
3770 Disassembler::print_location(cp, cstart, cend, st, false, false);
3771 cp += n;
3772 st->cr();
3773 }
3774 }
3775 } else {
3776 st->print_cr("[Constant Pool (empty)]");
3777 }
3778 st->cr();
3779 }
3780
3781 #endif
3782
3783 // Disassemble this nmethod.
3784 // Print additional debug information, if requested. This could be code
3785 // comments, block comments, profiling counters, etc.
3786 // The undisassembled format is useful no disassembler library is available.
3787 // The resulting hex dump (with markers) can be disassembled later, or on
3788 // another system, when/where a disassembler library is available.
3789 void nmethod::decode2(outputStream* ost) const {
3790
3791 // Called from frame::back_trace_with_decode without ResourceMark.
3792 ResourceMark rm;
3793
3794 // Make sure we have a valid stream to print on.
3795 outputStream* st = ost ? ost : tty;
3796
3797 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) && ! defined(SUPPORT_ASSEMBLY)
3798 const bool use_compressed_format = true;
3799 const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
3800 AbstractDisassembler::show_block_comment());
3801 #else
3802 const bool use_compressed_format = Disassembler::is_abstract();
3803 const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
3804 AbstractDisassembler::show_block_comment());
3805 #endif
3806
3807 st->cr();
3808 this->print_on(st);
3809 st->cr();
3810
3811 #if defined(SUPPORT_ASSEMBLY)
3812 //----------------------------------
3813 //---< Print real disassembly >---
3814 //----------------------------------
3815 if (! use_compressed_format) {
3816 st->print_cr("[Disassembly]");
3817 Disassembler::decode(const_cast<nmethod*>(this), st);
3818 st->bol();
3819 st->print_cr("[/Disassembly]");
3820 return;
3821 }
3822 #endif
3823
3824 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3825
3826 // Compressed undisassembled disassembly format.
3827 // The following status values are defined/supported:
3828 // = 0 - currently at bol() position, nothing printed yet on current line.
3829 // = 1 - currently at position after print_location().
3830 // > 1 - in the midst of printing instruction stream bytes.
3831 int compressed_format_idx = 0;
3832 int code_comment_column = 0;
3833 const int instr_maxlen = Assembler::instr_maxlen();
3834 const uint tabspacing = 8;
3835 unsigned char* start = this->code_begin();
3836 unsigned char* p = this->code_begin();
3837 unsigned char* end = this->code_end();
3838 unsigned char* pss = p; // start of a code section (used for offsets)
3839
3840 if ((start == nullptr) || (end == nullptr)) {
3841 st->print_cr("PrintAssembly not possible due to uninitialized section pointers");
3842 return;
3843 }
3844 #endif
3845
3846 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3847 //---< plain abstract disassembly, no comments or anything, just section headers >---
3848 if (use_compressed_format && ! compressed_with_comments) {
3849 const_cast<nmethod*>(this)->print_constant_pool(st);
3850
3851 st->bol();
3852 st->cr();
3853 st->print_cr("Loading hsdis library failed, undisassembled code is shown in MachCode section");
3854 //---< Open the output (Marker for post-mortem disassembler) >---
3855 st->print_cr("[MachCode]");
3856 const char* header = nullptr;
3857 address p0 = p;
3858 while (p < end) {
3859 address pp = p;
3860 while ((p < end) && (header == nullptr)) {
3861 header = nmethod_section_label(p);
3862 pp = p;
3863 p += Assembler::instr_len(p);
3864 }
3865 if (pp > p0) {
3866 AbstractDisassembler::decode_range_abstract(p0, pp, start, end, st, Assembler::instr_maxlen());
3867 p0 = pp;
3868 p = pp;
3869 header = nullptr;
3870 } else if (header != nullptr) {
3871 st->bol();
3872 st->print_cr("%s", header);
3873 header = nullptr;
3874 }
3875 }
3876 //---< Close the output (Marker for post-mortem disassembler) >---
3877 st->bol();
3878 st->print_cr("[/MachCode]");
3879 return;
3880 }
3881 #endif
3882
3883 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3884 //---< abstract disassembly with comments and section headers merged in >---
3885 if (compressed_with_comments) {
3886 const_cast<nmethod*>(this)->print_constant_pool(st);
3887
3888 st->bol();
3889 st->cr();
3890 st->print_cr("Loading hsdis library failed, undisassembled code is shown in MachCode section");
3891 //---< Open the output (Marker for post-mortem disassembler) >---
3892 st->print_cr("[MachCode]");
3893 while ((p < end) && (p != nullptr)) {
3894 const int instruction_size_in_bytes = Assembler::instr_len(p);
3895
3896 //---< Block comments for nmethod. Interrupts instruction stream, if any. >---
3897 // Outputs a bol() before and a cr() after, but only if a comment is printed.
3898 // Prints nmethod_section_label as well.
3899 if (AbstractDisassembler::show_block_comment()) {
3900 print_block_comment(st, p);
3901 if (st->position() == 0) {
3902 compressed_format_idx = 0;
3903 }
3904 }
3905
3906 //---< New location information after line break >---
3907 if (compressed_format_idx == 0) {
3908 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
3909 compressed_format_idx = 1;
3910 }
3911
3912 //---< Code comment for current instruction. Address range [p..(p+len)) >---
3913 unsigned char* p_end = p + (ssize_t)instruction_size_in_bytes;
3914 S390_ONLY(if (p_end > end) p_end = end;) // avoid getting past the end
3915
3916 if (AbstractDisassembler::show_comment() && const_cast<nmethod*>(this)->has_code_comment(p, p_end)) {
3917 //---< interrupt instruction byte stream for code comment >---
3918 if (compressed_format_idx > 1) {
3919 st->cr(); // interrupt byte stream
3920 st->cr(); // add an empty line
3921 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
3922 }
3923 const_cast<nmethod*>(this)->print_code_comment_on(st, code_comment_column, p, p_end );
3924 st->bol();
3925 compressed_format_idx = 0;
3926 }
3927
3928 //---< New location information after line break >---
3929 if (compressed_format_idx == 0) {
3930 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
3931 compressed_format_idx = 1;
3932 }
3933
3934 //---< Nicely align instructions for readability >---
3935 if (compressed_format_idx > 1) {
3936 Disassembler::print_delimiter(st);
3937 }
3938
3939 //---< Now, finally, print the actual instruction bytes >---
3940 unsigned char* p0 = p;
3941 p = Disassembler::decode_instruction_abstract(p, st, instruction_size_in_bytes, instr_maxlen);
3942 compressed_format_idx += (int)(p - p0);
3943
3944 if (Disassembler::start_newline(compressed_format_idx-1)) {
3945 st->cr();
3946 compressed_format_idx = 0;
3947 }
3948 }
3949 //---< Close the output (Marker for post-mortem disassembler) >---
3950 st->bol();
3951 st->print_cr("[/MachCode]");
3952 return;
3953 }
3954 #endif
3955 }
3956
3957 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
3958
3959 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
3960 RelocIterator iter(this, begin, end);
3961 bool have_one = false;
3962 while (iter.next()) {
3963 have_one = true;
3964 switch (iter.type()) {
3965 case relocInfo::none: {
3966 // Skip it and check next
3967 break;
3968 }
3969 case relocInfo::oop_type: {
3970 // Get a non-resizable resource-allocated stringStream.
3971 // Our callees make use of (nested) ResourceMarks.
3972 stringStream st(NEW_RESOURCE_ARRAY(char, 1024), 1024);
3973 oop_Relocation* r = iter.oop_reloc();
3974 oop obj = r->oop_value();
3975 st.print("oop(");
3976 if (obj == nullptr) st.print("nullptr");
3977 else obj->print_value_on(&st);
3978 st.print(")");
3979 return st.as_string();
3980 }
3981 case relocInfo::metadata_type: {
3982 stringStream st;
3983 metadata_Relocation* r = iter.metadata_reloc();
3984 Metadata* obj = r->metadata_value();
3985 st.print("metadata(");
3986 if (obj == nullptr) st.print("nullptr");
3987 else obj->print_value_on(&st);
3988 st.print(")");
3989 return st.as_string();
3990 }
3991 case relocInfo::runtime_call_type:
3992 case relocInfo::runtime_call_w_cp_type: {
3993 stringStream st;
3994 st.print("runtime_call");
3995 CallRelocation* r = (CallRelocation*)iter.reloc();
3996 address dest = r->destination();
3997 if (StubRoutines::contains(dest)) {
3998 StubCodeDesc* desc = StubCodeDesc::desc_for(dest);
3999 if (desc == nullptr) {
4000 desc = StubCodeDesc::desc_for(dest + frame::pc_return_offset);
4001 }
4002 if (desc != nullptr) {
4003 st.print(" Stub::%s", desc->name());
4004 return st.as_string();
4005 }
4006 }
4007 CodeBlob* cb = CodeCache::find_blob(dest);
4008 if (cb != nullptr) {
4009 st.print(" %s", cb->name());
4010 } else {
4011 ResourceMark rm;
4012 const int buflen = 1024;
4013 char* buf = NEW_RESOURCE_ARRAY(char, buflen);
4014 int offset;
4015 if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {
4016 st.print(" %s", buf);
4017 if (offset != 0) {
4018 st.print("+%d", offset);
4019 }
4020 }
4021 }
4022 return st.as_string();
4023 }
4024 case relocInfo::virtual_call_type: {
4025 stringStream st;
4026 st.print_raw("virtual_call");
4027 virtual_call_Relocation* r = iter.virtual_call_reloc();
4028 Method* m = r->method_value();
4029 if (m != nullptr) {
4030 assert(m->is_method(), "");
4031 m->print_short_name(&st);
4032 }
4033 return st.as_string();
4034 }
4035 case relocInfo::opt_virtual_call_type: {
4036 stringStream st;
4037 st.print_raw("optimized virtual_call");
4038 opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc();
4039 Method* m = r->method_value();
4040 if (m != nullptr) {
4041 assert(m->is_method(), "");
4042 m->print_short_name(&st);
4043 }
4044 return st.as_string();
4045 }
4046 case relocInfo::static_call_type: {
4047 stringStream st;
4048 st.print_raw("static_call");
4049 static_call_Relocation* r = iter.static_call_reloc();
4050 Method* m = r->method_value();
4051 if (m != nullptr) {
4052 assert(m->is_method(), "");
4053 m->print_short_name(&st);
4054 }
4055 return st.as_string();
4056 }
4057 case relocInfo::static_stub_type: return "static_stub";
4058 case relocInfo::external_word_type: return "external_word";
4059 case relocInfo::internal_word_type: return "internal_word";
4060 case relocInfo::section_word_type: return "section_word";
4061 case relocInfo::poll_type: return "poll";
4062 case relocInfo::poll_return_type: return "poll_return";
4063 case relocInfo::trampoline_stub_type: return "trampoline_stub";
4064 case relocInfo::entry_guard_type: return "entry_guard";
4065 case relocInfo::post_call_nop_type: return "post_call_nop";
4066 case relocInfo::barrier_type: {
4067 barrier_Relocation* const reloc = iter.barrier_reloc();
4068 stringStream st;
4069 st.print("barrier format=%d", reloc->format());
4070 return st.as_string();
4071 }
4072
4073 case relocInfo::type_mask: return "type_bit_mask";
4074
4075 default: {
4076 stringStream st;
4077 st.print("unknown relocInfo=%d", (int) iter.type());
4078 return st.as_string();
4079 }
4080 }
4081 }
4082 return have_one ? "other" : nullptr;
4083 }
4084
4085 // Return the last scope in (begin..end]
4086 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
4087 PcDesc* p = pc_desc_near(begin+1);
4088 if (p != nullptr && p->real_pc(this) <= end) {
4089 return new ScopeDesc(this, p);
4090 }
4091 return nullptr;
4092 }
4093
4094 const char* nmethod::nmethod_section_label(address pos) const {
4095 const char* label = nullptr;
4096 if (pos == code_begin()) label = "[Instructions begin]";
4097 if (pos == entry_point()) label = "[Entry Point]";
4098 if (pos == inline_entry_point()) label = "[Inline Entry Point]";
4099 if (pos == verified_entry_point()) label = "[Verified Entry Point]";
4100 if (pos == verified_inline_entry_point()) label = "[Verified Inline Entry Point]";
4101 if (pos == verified_inline_ro_entry_point()) label = "[Verified Inline Entry Point (RO)]";
4102 if (pos == consts_begin() && pos != insts_begin()) label = "[Constants]";
4103 // Check stub_code before checking exception_handler or deopt_handler.
4104 if (pos == this->stub_begin()) label = "[Stub Code]";
4105 if (JVMCI_ONLY(_exception_offset >= 0 &&) pos == exception_begin()) label = "[Exception Handler]";
4106 if (JVMCI_ONLY(_deopt_handler_entry_offset != -1 &&) pos == deopt_handler_entry()) label = "[Deopt Handler Entry Point]";
4107 return label;
4108 }
4109
4110 static int maybe_print_entry_label(outputStream* stream, address pos, address entry, const char* label) {
4111 if (pos == entry) {
4112 stream->bol();
4113 stream->print_cr("%s", label);
4114 return 1;
4115 } else {
4116 return 0;
4117 }
4118 }
4119
4120 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels) const {
4121 if (print_section_labels) {
4122 int n = 0;
4123 // Multiple entry points may be at the same position. Print them all.
4124 n += maybe_print_entry_label(stream, block_begin, entry_point(), "[Entry Point]");
4125 n += maybe_print_entry_label(stream, block_begin, inline_entry_point(), "[Inline Entry Point]");
4126 n += maybe_print_entry_label(stream, block_begin, verified_entry_point(), "[Verified Entry Point]");
4127 n += maybe_print_entry_label(stream, block_begin, verified_inline_entry_point(), "[Verified Inline Entry Point]");
4128 n += maybe_print_entry_label(stream, block_begin, verified_inline_ro_entry_point(), "[Verified Inline Entry Point (RO)]");
4129 if (n == 0) {
4130 const char* label = nmethod_section_label(block_begin);
4131 if (label != nullptr) {
4132 stream->bol();
4133 stream->print_cr("%s", label);
4134 }
4135 }
4136 }
4137
4138 Method* m = method();
4139 if (m == nullptr || is_osr_method()) {
4140 return;
4141 }
4142
4143 // Print the name of the method (only once)
4144 address low = MIN3(entry_point(),
4145 verified_entry_point(),
4146 inline_entry_point());
4147 // The verified inline entry point and verified inline RO entry point are not always
4148 // used. When they are unused. CodeOffsets::Verified_Inline_Entry(_RO) is -1. Hence,
4149 // the calculated entry point is smaller than the block they are offsetting into.
4150 if (verified_inline_entry_point() >= block_begin) {
4151 low = MIN2(low, verified_inline_entry_point());
4152 }
4153 if (verified_inline_ro_entry_point() >= block_begin) {
4154 low = MIN2(low, verified_inline_ro_entry_point());
4155 }
4156 assert(low != nullptr, "sanity");
4157 if (block_begin == low) {
4158 stream->print(" # ");
4159 m->print_value_on(stream);
4160 stream->cr();
4161 }
4162
4163 // Print the arguments for the 3 types of verified entry points
4164 CompiledEntrySignature ces(m);
4165 ces.compute_calling_conventions(false);
4166 const GrowableArray<SigEntry>* sig_cc;
4167 const VMRegPair* regs;
4168 if (block_begin == verified_entry_point()) {
4169 sig_cc = ces.sig_cc();
4170 regs = ces.regs_cc();
4171 } else if (block_begin == verified_inline_entry_point()) {
4172 sig_cc = ces.sig();
4173 regs = ces.regs();
4174 } else if (block_begin == verified_inline_ro_entry_point()) {
4175 sig_cc = ces.sig_cc_ro();
4176 regs = ces.regs_cc_ro();
4177 } else {
4178 return;
4179 }
4180
4181 bool has_this = !m->is_static();
4182 if (ces.has_inline_recv() && block_begin == verified_entry_point()) {
4183 // <this> argument is scalarized for verified_entry_point()
4184 has_this = false;
4185 }
4186 const char* spname = "sp"; // make arch-specific?
4187 int stack_slot_offset = this->frame_size() * wordSize;
4188 int tab1 = 14, tab2 = 24;
4189 int sig_index = 0;
4190 int arg_index = has_this ? -1 : 0;
4191 bool did_old_sp = false;
4192 for (ExtendedSignature sig = ExtendedSignature(sig_cc, SigEntryFilter()); !sig.at_end(); ++sig) {
4193 bool at_this = (arg_index == -1);
4194 bool at_old_sp = false;
4195 BasicType t = (*sig)._bt;
4196 if (at_this) {
4197 stream->print(" # this: ");
4198 } else {
4199 stream->print(" # parm%d: ", arg_index);
4200 }
4201 stream->move_to(tab1);
4202 VMReg fst = regs[sig_index].first();
4203 VMReg snd = regs[sig_index].second();
4204 if (fst->is_reg()) {
4205 stream->print("%s", fst->name());
4206 if (snd->is_valid()) {
4207 stream->print(":%s", snd->name());
4208 }
4209 } else if (fst->is_stack()) {
4210 int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
4211 if (offset == stack_slot_offset) at_old_sp = true;
4212 stream->print("[%s+0x%x]", spname, offset);
4213 } else {
4214 stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
4215 }
4216 stream->print(" ");
4217 stream->move_to(tab2);
4218 stream->print("= ");
4219 if (at_this) {
4220 m->method_holder()->print_value_on(stream);
4221 } else {
4222 bool did_name = false;
4223 if (is_reference_type(t) && !(*sig)._vt_oop) {
4224 Symbol* name = (*sig)._name;
4225 name->print_value_on(stream);
4226 did_name = true;
4227 }
4228 if (!did_name)
4229 stream->print("%s", type2name(t));
4230 if ((*sig)._null_marker) {
4231 stream->print(" (null marker)");
4232 }
4233 if ((*sig)._vt_oop) {
4234 stream->print(" (VT OOP)");
4235 }
4236 }
4237 if (at_old_sp) {
4238 stream->print(" (%s of caller)", spname);
4239 did_old_sp = true;
4240 }
4241 stream->cr();
4242 sig_index += type2size[t];
4243 arg_index += 1;
4244 }
4245 if (!did_old_sp) {
4246 stream->print(" # ");
4247 stream->move_to(tab1);
4248 stream->print("[%s+0x%x]", spname, stack_slot_offset);
4249 stream->print(" (%s of caller)", spname);
4250 stream->cr();
4251 }
4252 }
4253
4254 // Returns whether this nmethod has code comments.
4255 bool nmethod::has_code_comment(address begin, address end) {
4256 // scopes?
4257 ScopeDesc* sd = scope_desc_in(begin, end);
4258 if (sd != nullptr) return true;
4259
4260 // relocations?
4261 const char* str = reloc_string_for(begin, end);
4262 if (str != nullptr) return true;
4263
4264 // implicit exceptions?
4265 int cont_offset = ImplicitExceptionTable(this).continuation_offset((uint)(begin - code_begin()));
4266 if (cont_offset != 0) return true;
4267
4268 return false;
4269 }
4270
4271 void nmethod::print_code_comment_on(outputStream* st, int column, address begin, address end) {
4272 ImplicitExceptionTable implicit_table(this);
4273 int pc_offset = (int)(begin - code_begin());
4274 int cont_offset = implicit_table.continuation_offset(pc_offset);
4275 bool oop_map_required = false;
4276 if (cont_offset != 0) {
4277 st->move_to(column, 6, 0);
4278 if (pc_offset == cont_offset) {
4279 st->print("; implicit exception: deoptimizes");
4280 oop_map_required = true;
4281 } else {
4282 st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));
4283 }
4284 }
4285
4286 // Find an oopmap in (begin, end]. We use the odd half-closed
4287 // interval so that oop maps and scope descs which are tied to the
4288 // byte after a call are printed with the call itself. OopMaps
4289 // associated with implicit exceptions are printed with the implicit
4290 // instruction.
4291 address base = code_begin();
4292 ImmutableOopMapSet* oms = oop_maps();
4293 if (oms != nullptr) {
4294 for (int i = 0, imax = oms->count(); i < imax; i++) {
4295 const ImmutableOopMapPair* pair = oms->pair_at(i);
4296 const ImmutableOopMap* om = pair->get_from(oms);
4297 address pc = base + pair->pc_offset();
4298 if (pc >= begin) {
4299 #if INCLUDE_JVMCI
4300 bool is_implicit_deopt = implicit_table.continuation_offset(pair->pc_offset()) == (uint) pair->pc_offset();
4301 #else
4302 bool is_implicit_deopt = false;
4303 #endif
4304 if (is_implicit_deopt ? pc == begin : pc > begin && pc <= end) {
4305 st->move_to(column, 6, 0);
4306 st->print("; ");
4307 om->print_on(st);
4308 oop_map_required = false;
4309 }
4310 }
4311 if (pc > end) {
4312 break;
4313 }
4314 }
4315 }
4316 assert(!oop_map_required, "missed oopmap");
4317
4318 Thread* thread = Thread::current();
4319
4320 // Print any debug info present at this pc.
4321 ScopeDesc* sd = scope_desc_in(begin, end);
4322 if (sd != nullptr) {
4323 st->move_to(column, 6, 0);
4324 if (sd->bci() == SynchronizationEntryBCI) {
4325 st->print(";*synchronization entry");
4326 } else if (sd->bci() == AfterBci) {
4327 st->print(";* method exit (unlocked if synchronized)");
4328 } else if (sd->bci() == UnwindBci) {
4329 st->print(";* unwind (locked if synchronized)");
4330 } else if (sd->bci() == AfterExceptionBci) {
4331 st->print(";* unwind (unlocked if synchronized)");
4332 } else if (sd->bci() == UnknownBci) {
4333 st->print(";* unknown");
4334 } else if (sd->bci() == InvalidFrameStateBci) {
4335 st->print(";* invalid frame state");
4336 } else {
4337 if (sd->method() == nullptr) {
4338 st->print("method is nullptr");
4339 } else if (sd->method()->is_native()) {
4340 st->print("method is native");
4341 } else {
4342 Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
4343 st->print(";*%s", Bytecodes::name(bc));
4344 switch (bc) {
4345 case Bytecodes::_invokevirtual:
4346 case Bytecodes::_invokespecial:
4347 case Bytecodes::_invokestatic:
4348 case Bytecodes::_invokeinterface:
4349 {
4350 Bytecode_invoke invoke(methodHandle(thread, sd->method()), sd->bci());
4351 st->print(" ");
4352 if (invoke.name() != nullptr)
4353 invoke.name()->print_symbol_on(st);
4354 else
4355 st->print("<UNKNOWN>");
4356 break;
4357 }
4358 case Bytecodes::_getfield:
4359 case Bytecodes::_putfield:
4360 case Bytecodes::_getstatic:
4361 case Bytecodes::_putstatic:
4362 {
4363 Bytecode_field field(methodHandle(thread, sd->method()), sd->bci());
4364 st->print(" ");
4365 if (field.name() != nullptr)
4366 field.name()->print_symbol_on(st);
4367 else
4368 st->print("<UNKNOWN>");
4369 }
4370 default:
4371 break;
4372 }
4373 }
4374 st->print(" {reexecute=%d rethrow=%d return_oop=%d return_scalarized=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop(), sd->return_scalarized());
4375 }
4376
4377 // Print all scopes
4378 for (;sd != nullptr; sd = sd->sender()) {
4379 st->move_to(column, 6, 0);
4380 st->print("; -");
4381 if (sd->should_reexecute()) {
4382 st->print(" (reexecute)");
4383 }
4384 if (sd->method() == nullptr) {
4385 st->print("method is nullptr");
4386 } else {
4387 sd->method()->print_short_name(st);
4388 }
4389 int lineno = sd->method()->line_number_from_bci(sd->bci());
4390 if (lineno != -1) {
4391 st->print("@%d (line %d)", sd->bci(), lineno);
4392 } else {
4393 st->print("@%d", sd->bci());
4394 }
4395 st->cr();
4396 }
4397 }
4398
4399 // Print relocation information
4400 // Prevent memory leak: allocating without ResourceMark.
4401 ResourceMark rm;
4402 const char* str = reloc_string_for(begin, end);
4403 if (str != nullptr) {
4404 if (sd != nullptr) st->cr();
4405 st->move_to(column, 6, 0);
4406 st->print("; {%s}", str);
4407 }
4408 }
4409
4410 #endif
4411
4412 address nmethod::call_instruction_address(address pc) const {
4413 if (NativeCall::is_call_before(pc)) {
4414 NativeCall *ncall = nativeCall_before(pc);
4415 return ncall->instruction_address();
4416 }
4417 return nullptr;
4418 }
4419
4420 void nmethod::print_value_on_impl(outputStream* st) const {
4421 st->print_cr("nmethod");
4422 #if defined(SUPPORT_DATA_STRUCTS)
4423 print_on_with_msg(st, nullptr);
4424 #endif
4425 }
4426
4427 void nmethod::print_code_snippet(outputStream* st, address addr) const {
4428 if (entry_point() <= addr && addr < code_end()) {
4429 // Pointing into the nmethod's code. Try to disassemble some instructions around addr.
4430 // Determine conservative start and end points.
4431 address start;
4432 if (frame_complete_offset() != CodeOffsets::frame_never_safe &&
4433 addr >= code_begin() + frame_complete_offset()) {
4434 start = code_begin() + frame_complete_offset();
4435 } else {
4436 start = (addr < verified_entry_point()) ? entry_point() : verified_entry_point();
4437 }
4438 address start_for_hex_dump = start; // We can choose a different starting point for hex dump, below.
4439 address end = code_end();
4440
4441 // Try using relocations to find closer instruction start and end points.
4442 // (Some platforms have variable length instructions and can only
4443 // disassemble correctly at instruction start addresses.)
4444 RelocIterator iter((nmethod*)this, start);
4445 while (iter.next() && iter.addr() < addr) { // find relocation before addr
4446 // Note: There's a relocation which doesn't point to an instruction start:
4447 // ZBarrierRelocationFormatStoreGoodAfterMov with ZGC on x86_64
4448 // We could detect and skip it, but hex dump is still usable when
4449 // disassembler produces garbage in such a very rare case.
4450 start = iter.addr();
4451 // We want at least 64 Bytes ahead in hex dump.
4452 if (iter.addr() <= (addr - 64)) start_for_hex_dump = iter.addr();
4453 }
4454 if (iter.has_current()) {
4455 if (iter.addr() == addr) iter.next(); // find relocation after addr
4456 if (iter.has_current()) end = iter.addr();
4457 }
4458
4459 // Always print hex. Disassembler may still have problems when hitting an incorrect instruction start.
4460 os::print_hex_dump(st, start_for_hex_dump, end, 1, /* print_ascii=*/false);
4461 if (!Disassembler::is_abstract()) {
4462 Disassembler::decode(start, end, st);
4463 }
4464 }
4465 }
4466
4467 #ifndef PRODUCT
4468
4469 void nmethod::print_calls(outputStream* st) {
4470 RelocIterator iter(this);
4471 while (iter.next()) {
4472 switch (iter.type()) {
4473 case relocInfo::virtual_call_type: {
4474 CompiledICLocker ml_verify(this);
4475 CompiledIC_at(&iter)->print();
4476 break;
4477 }
4478 case relocInfo::static_call_type:
4479 case relocInfo::opt_virtual_call_type:
4480 st->print_cr("Direct call at " INTPTR_FORMAT, p2i(iter.reloc()->addr()));
4481 CompiledDirectCall::at(iter.reloc())->print();
4482 break;
4483 default:
4484 break;
4485 }
4486 }
4487 }
4488
4489 void nmethod::print_statistics() {
4490 ttyLocker ttyl;
4491 if (xtty != nullptr) xtty->head("statistics type='nmethod'");
4492 native_nmethod_stats.print_native_nmethod_stats();
4493 #ifdef COMPILER1
4494 c1_java_nmethod_stats.print_nmethod_stats("C1");
4495 #endif
4496 #ifdef COMPILER2
4497 c2_java_nmethod_stats.print_nmethod_stats("C2");
4498 #endif
4499 #if INCLUDE_JVMCI
4500 jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");
4501 #endif
4502 unknown_java_nmethod_stats.print_nmethod_stats("Unknown");
4503 DebugInformationRecorder::print_statistics();
4504 pc_nmethod_stats.print_pc_stats();
4505 Dependencies::print_statistics();
4506 ExternalsRecorder::print_statistics();
4507 if (xtty != nullptr) xtty->tail("statistics");
4508 }
4509
4510 #endif // !PRODUCT
4511
4512 #if INCLUDE_JVMCI
4513 void nmethod::update_speculation(JavaThread* thread) {
4514 jlong speculation = thread->pending_failed_speculation();
4515 if (speculation != 0) {
4516 guarantee(jvmci_nmethod_data() != nullptr, "failed speculation in nmethod without failed speculation list");
4517 jvmci_nmethod_data()->add_failed_speculation(this, speculation);
4518 thread->set_pending_failed_speculation(0);
4519 }
4520 }
4521
4522 const char* nmethod::jvmci_name() {
4523 if (jvmci_nmethod_data() != nullptr) {
4524 return jvmci_nmethod_data()->name();
4525 }
4526 return nullptr;
4527 }
4528
4529 bool nmethod::jvmci_skip_profile_deopt() const {
4530 return jvmci_nmethod_data() != nullptr && !jvmci_nmethod_data()->profile_deopt();
4531 }
4532 #endif