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