Thu, 12 Oct 2017 21:27:07 +0800
merge
1 /*
2 * Copyright (c) 1997, 2014, 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 */
25 /*
26 * This file has been modified by Loongson Technology in 2015. These
27 * modifications are Copyright (c) 2015 Loongson Technology, and are made
28 * available on the same license terms set forth above.
29 */
31 #include "precompiled.hpp"
32 #include "code/codeCache.hpp"
33 #include "code/compiledIC.hpp"
34 #include "code/dependencies.hpp"
35 #include "code/nmethod.hpp"
36 #include "code/scopeDesc.hpp"
37 #include "compiler/abstractCompiler.hpp"
38 #include "compiler/compileBroker.hpp"
39 #include "compiler/compileLog.hpp"
40 #include "compiler/compilerOracle.hpp"
41 #include "compiler/disassembler.hpp"
42 #include "interpreter/bytecode.hpp"
43 #include "oops/methodData.hpp"
44 #include "prims/jvmtiRedefineClassesTrace.hpp"
45 #include "prims/jvmtiImpl.hpp"
46 #include "runtime/orderAccess.inline.hpp"
47 #include "runtime/sharedRuntime.hpp"
48 #include "runtime/sweeper.hpp"
49 #include "utilities/dtrace.hpp"
50 #include "utilities/events.hpp"
51 #include "utilities/xmlstream.hpp"
52 #ifdef SHARK
53 #include "shark/sharkCompiler.hpp"
54 #endif
56 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
58 unsigned char nmethod::_global_unloading_clock = 0;
60 #ifdef DTRACE_ENABLED
62 // Only bother with this argument setup if dtrace is available
64 #ifndef USDT2
65 HS_DTRACE_PROBE_DECL8(hotspot, compiled__method__load,
66 const char*, int, const char*, int, const char*, int, void*, size_t);
68 HS_DTRACE_PROBE_DECL6(hotspot, compiled__method__unload,
69 char*, int, char*, int, char*, int);
71 #define DTRACE_METHOD_UNLOAD_PROBE(method) \
72 { \
73 Method* m = (method); \
74 if (m != NULL) { \
75 Symbol* klass_name = m->klass_name(); \
76 Symbol* name = m->name(); \
77 Symbol* signature = m->signature(); \
78 HS_DTRACE_PROBE6(hotspot, compiled__method__unload, \
79 klass_name->bytes(), klass_name->utf8_length(), \
80 name->bytes(), name->utf8_length(), \
81 signature->bytes(), signature->utf8_length()); \
82 } \
83 }
84 #else /* USDT2 */
85 #define DTRACE_METHOD_UNLOAD_PROBE(method) \
86 { \
87 Method* m = (method); \
88 if (m != NULL) { \
89 Symbol* klass_name = m->klass_name(); \
90 Symbol* name = m->name(); \
91 Symbol* signature = m->signature(); \
92 HOTSPOT_COMPILED_METHOD_UNLOAD( \
93 (char *) klass_name->bytes(), klass_name->utf8_length(), \
94 (char *) name->bytes(), name->utf8_length(), \
95 (char *) signature->bytes(), signature->utf8_length()); \
96 } \
97 }
98 #endif /* USDT2 */
100 #else // ndef DTRACE_ENABLED
102 #define DTRACE_METHOD_UNLOAD_PROBE(method)
104 #endif
106 bool nmethod::is_compiled_by_c1() const {
107 if (compiler() == NULL) {
108 return false;
109 }
110 return compiler()->is_c1();
111 }
112 bool nmethod::is_compiled_by_c2() const {
113 if (compiler() == NULL) {
114 return false;
115 }
116 return compiler()->is_c2();
117 }
118 bool nmethod::is_compiled_by_shark() const {
119 if (compiler() == NULL) {
120 return false;
121 }
122 return compiler()->is_shark();
123 }
127 //---------------------------------------------------------------------------------
128 // NMethod statistics
129 // They are printed under various flags, including:
130 // PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.
131 // (In the latter two cases, they like other stats are printed to the log only.)
133 #ifndef PRODUCT
134 // These variables are put into one block to reduce relocations
135 // and make it simpler to print from the debugger.
136 static
137 struct nmethod_stats_struct {
138 int nmethod_count;
139 int total_size;
140 int relocation_size;
141 int consts_size;
142 int insts_size;
143 int stub_size;
144 int scopes_data_size;
145 int scopes_pcs_size;
146 int dependencies_size;
147 int handler_table_size;
148 int nul_chk_table_size;
149 int oops_size;
151 void note_nmethod(nmethod* nm) {
152 nmethod_count += 1;
153 total_size += nm->size();
154 relocation_size += nm->relocation_size();
155 consts_size += nm->consts_size();
156 insts_size += nm->insts_size();
157 stub_size += nm->stub_size();
158 oops_size += nm->oops_size();
159 scopes_data_size += nm->scopes_data_size();
160 scopes_pcs_size += nm->scopes_pcs_size();
161 dependencies_size += nm->dependencies_size();
162 handler_table_size += nm->handler_table_size();
163 nul_chk_table_size += nm->nul_chk_table_size();
164 }
165 void print_nmethod_stats() {
166 if (nmethod_count == 0) return;
167 tty->print_cr("Statistics for %d bytecoded nmethods:", nmethod_count);
168 if (total_size != 0) tty->print_cr(" total in heap = %d", total_size);
169 if (relocation_size != 0) tty->print_cr(" relocation = %d", relocation_size);
170 if (consts_size != 0) tty->print_cr(" constants = %d", consts_size);
171 if (insts_size != 0) tty->print_cr(" main code = %d", insts_size);
172 if (stub_size != 0) tty->print_cr(" stub code = %d", stub_size);
173 if (oops_size != 0) tty->print_cr(" oops = %d", oops_size);
174 if (scopes_data_size != 0) tty->print_cr(" scopes data = %d", scopes_data_size);
175 if (scopes_pcs_size != 0) tty->print_cr(" scopes pcs = %d", scopes_pcs_size);
176 if (dependencies_size != 0) tty->print_cr(" dependencies = %d", dependencies_size);
177 if (handler_table_size != 0) tty->print_cr(" handler table = %d", handler_table_size);
178 if (nul_chk_table_size != 0) tty->print_cr(" nul chk table = %d", nul_chk_table_size);
179 }
181 int native_nmethod_count;
182 int native_total_size;
183 int native_relocation_size;
184 int native_insts_size;
185 int native_oops_size;
186 void note_native_nmethod(nmethod* nm) {
187 native_nmethod_count += 1;
188 native_total_size += nm->size();
189 native_relocation_size += nm->relocation_size();
190 native_insts_size += nm->insts_size();
191 native_oops_size += nm->oops_size();
192 }
193 void print_native_nmethod_stats() {
194 if (native_nmethod_count == 0) return;
195 tty->print_cr("Statistics for %d native nmethods:", native_nmethod_count);
196 if (native_total_size != 0) tty->print_cr(" N. total size = %d", native_total_size);
197 if (native_relocation_size != 0) tty->print_cr(" N. relocation = %d", native_relocation_size);
198 if (native_insts_size != 0) tty->print_cr(" N. main code = %d", native_insts_size);
199 if (native_oops_size != 0) tty->print_cr(" N. oops = %d", native_oops_size);
200 }
202 int pc_desc_resets; // number of resets (= number of caches)
203 int pc_desc_queries; // queries to nmethod::find_pc_desc
204 int pc_desc_approx; // number of those which have approximate true
205 int pc_desc_repeats; // number of _pc_descs[0] hits
206 int pc_desc_hits; // number of LRU cache hits
207 int pc_desc_tests; // total number of PcDesc examinations
208 int pc_desc_searches; // total number of quasi-binary search steps
209 int pc_desc_adds; // number of LUR cache insertions
211 void print_pc_stats() {
212 tty->print_cr("PcDesc Statistics: %d queries, %.2f comparisons per query",
213 pc_desc_queries,
214 (double)(pc_desc_tests + pc_desc_searches)
215 / pc_desc_queries);
216 tty->print_cr(" caches=%d queries=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d",
217 pc_desc_resets,
218 pc_desc_queries, pc_desc_approx,
219 pc_desc_repeats, pc_desc_hits,
220 pc_desc_tests, pc_desc_searches, pc_desc_adds);
221 }
222 } nmethod_stats;
223 #endif //PRODUCT
226 //---------------------------------------------------------------------------------
229 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {
230 assert(pc != NULL, "Must be non null");
231 assert(exception.not_null(), "Must be non null");
232 assert(handler != NULL, "Must be non null");
234 _count = 0;
235 _exception_type = exception->klass();
236 _next = NULL;
238 add_address_and_handler(pc,handler);
239 }
242 address ExceptionCache::match(Handle exception, address pc) {
243 assert(pc != NULL,"Must be non null");
244 assert(exception.not_null(),"Must be non null");
245 if (exception->klass() == exception_type()) {
246 return (test_address(pc));
247 }
249 return NULL;
250 }
253 bool ExceptionCache::match_exception_with_space(Handle exception) {
254 assert(exception.not_null(),"Must be non null");
255 if (exception->klass() == exception_type() && count() < cache_size) {
256 return true;
257 }
258 return false;
259 }
262 address ExceptionCache::test_address(address addr) {
263 for (int i=0; i<count(); i++) {
264 if (pc_at(i) == addr) {
265 return handler_at(i);
266 }
267 }
268 return NULL;
269 }
272 bool ExceptionCache::add_address_and_handler(address addr, address handler) {
273 if (test_address(addr) == handler) return true;
274 if (count() < cache_size) {
275 set_pc_at(count(),addr);
276 set_handler_at(count(), handler);
277 increment_count();
278 return true;
279 }
280 return false;
281 }
284 // private method for handling exception cache
285 // These methods are private, and used to manipulate the exception cache
286 // directly.
287 ExceptionCache* nmethod::exception_cache_entry_for_exception(Handle exception) {
288 ExceptionCache* ec = exception_cache();
289 while (ec != NULL) {
290 if (ec->match_exception_with_space(exception)) {
291 return ec;
292 }
293 ec = ec->next();
294 }
295 return NULL;
296 }
299 //-----------------------------------------------------------------------------
302 // Helper used by both find_pc_desc methods.
303 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {
304 NOT_PRODUCT(++nmethod_stats.pc_desc_tests);
305 if (!approximate)
306 return pc->pc_offset() == pc_offset;
307 else
308 return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset();
309 }
311 void PcDescCache::reset_to(PcDesc* initial_pc_desc) {
312 if (initial_pc_desc == NULL) {
313 _pc_descs[0] = NULL; // native method; no PcDescs at all
314 return;
315 }
316 NOT_PRODUCT(++nmethod_stats.pc_desc_resets);
317 // reset the cache by filling it with benign (non-null) values
318 assert(initial_pc_desc->pc_offset() < 0, "must be sentinel");
319 for (int i = 0; i < cache_size; i++)
320 _pc_descs[i] = initial_pc_desc;
321 }
323 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {
324 NOT_PRODUCT(++nmethod_stats.pc_desc_queries);
325 NOT_PRODUCT(if (approximate) ++nmethod_stats.pc_desc_approx);
327 // Note: one might think that caching the most recently
328 // read value separately would be a win, but one would be
329 // wrong. When many threads are updating it, the cache
330 // line it's in would bounce between caches, negating
331 // any benefit.
333 // In order to prevent race conditions do not load cache elements
334 // repeatedly, but use a local copy:
335 PcDesc* res;
337 // Step one: Check the most recently added value.
338 res = _pc_descs[0];
339 if (res == NULL) return NULL; // native method; no PcDescs at all
340 if (match_desc(res, pc_offset, approximate)) {
341 NOT_PRODUCT(++nmethod_stats.pc_desc_repeats);
342 return res;
343 }
345 // Step two: Check the rest of the LRU cache.
346 for (int i = 1; i < cache_size; ++i) {
347 res = _pc_descs[i];
348 if (res->pc_offset() < 0) break; // optimization: skip empty cache
349 if (match_desc(res, pc_offset, approximate)) {
350 NOT_PRODUCT(++nmethod_stats.pc_desc_hits);
351 return res;
352 }
353 }
355 // Report failure.
356 return NULL;
357 }
359 void PcDescCache::add_pc_desc(PcDesc* pc_desc) {
360 NOT_PRODUCT(++nmethod_stats.pc_desc_adds);
361 // Update the LRU cache by shifting pc_desc forward.
362 for (int i = 0; i < cache_size; i++) {
363 PcDesc* next = _pc_descs[i];
364 _pc_descs[i] = pc_desc;
365 pc_desc = next;
366 }
367 }
369 // adjust pcs_size so that it is a multiple of both oopSize and
370 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple
371 // of oopSize, then 2*sizeof(PcDesc) is)
372 static int adjust_pcs_size(int pcs_size) {
373 int nsize = round_to(pcs_size, oopSize);
374 if ((nsize % sizeof(PcDesc)) != 0) {
375 nsize = pcs_size + sizeof(PcDesc);
376 }
377 assert((nsize % oopSize) == 0, "correct alignment");
378 return nsize;
379 }
381 //-----------------------------------------------------------------------------
384 void nmethod::add_exception_cache_entry(ExceptionCache* new_entry) {
385 assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock");
386 assert(new_entry != NULL,"Must be non null");
387 assert(new_entry->next() == NULL, "Must be null");
389 if (exception_cache() != NULL) {
390 new_entry->set_next(exception_cache());
391 }
392 set_exception_cache(new_entry);
393 }
395 void nmethod::clean_exception_cache(BoolObjectClosure* is_alive) {
396 ExceptionCache* prev = NULL;
397 ExceptionCache* curr = exception_cache();
399 while (curr != NULL) {
400 ExceptionCache* next = curr->next();
402 Klass* ex_klass = curr->exception_type();
403 if (ex_klass != NULL && !ex_klass->is_loader_alive(is_alive)) {
404 if (prev == NULL) {
405 set_exception_cache(next);
406 } else {
407 prev->set_next(next);
408 }
409 delete curr;
410 // prev stays the same.
411 } else {
412 prev = curr;
413 }
415 curr = next;
416 }
417 }
419 // public method for accessing the exception cache
420 // These are the public access methods.
421 address nmethod::handler_for_exception_and_pc(Handle exception, address pc) {
422 // We never grab a lock to read the exception cache, so we may
423 // have false negatives. This is okay, as it can only happen during
424 // the first few exception lookups for a given nmethod.
425 ExceptionCache* ec = exception_cache();
426 while (ec != NULL) {
427 address ret_val;
428 if ((ret_val = ec->match(exception,pc)) != NULL) {
429 return ret_val;
430 }
431 ec = ec->next();
432 }
433 return NULL;
434 }
437 void nmethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
438 // There are potential race conditions during exception cache updates, so we
439 // must own the ExceptionCache_lock before doing ANY modifications. Because
440 // we don't lock during reads, it is possible to have several threads attempt
441 // to update the cache with the same data. We need to check for already inserted
442 // copies of the current data before adding it.
444 MutexLocker ml(ExceptionCache_lock);
445 ExceptionCache* target_entry = exception_cache_entry_for_exception(exception);
447 if (target_entry == NULL || !target_entry->add_address_and_handler(pc,handler)) {
448 target_entry = new ExceptionCache(exception,pc,handler);
449 add_exception_cache_entry(target_entry);
450 }
451 }
454 //-------------end of code for ExceptionCache--------------
457 int nmethod::total_size() const {
458 return
459 consts_size() +
460 insts_size() +
461 stub_size() +
462 scopes_data_size() +
463 scopes_pcs_size() +
464 handler_table_size() +
465 nul_chk_table_size();
466 }
468 const char* nmethod::compile_kind() const {
469 if (is_osr_method()) return "osr";
470 if (method() != NULL && is_native_method()) return "c2n";
471 return NULL;
472 }
474 // Fill in default values for various flag fields
475 void nmethod::init_defaults() {
476 _state = in_use;
477 _unloading_clock = 0;
478 _marked_for_reclamation = 0;
479 _has_flushed_dependencies = 0;
480 _has_unsafe_access = 0;
481 _has_method_handle_invokes = 0;
482 _lazy_critical_native = 0;
483 _has_wide_vectors = 0;
484 _marked_for_deoptimization = 0;
485 _lock_count = 0;
486 _stack_traversal_mark = 0;
487 _unload_reported = false; // jvmti state
489 #ifdef ASSERT
490 _oops_are_stale = false;
491 #endif
493 _oops_do_mark_link = NULL;
494 _jmethod_id = NULL;
495 _osr_link = NULL;
496 if (UseG1GC) {
497 _unloading_next = NULL;
498 } else {
499 _scavenge_root_link = NULL;
500 }
501 _scavenge_root_state = 0;
502 _compiler = NULL;
503 #if INCLUDE_RTM_OPT
504 _rtm_state = NoRTM;
505 #endif
506 #ifdef HAVE_DTRACE_H
507 _trap_offset = 0;
508 #endif // def HAVE_DTRACE_H
509 }
511 nmethod* nmethod::new_native_nmethod(methodHandle method,
512 int compile_id,
513 CodeBuffer *code_buffer,
514 int vep_offset,
515 int frame_complete,
516 int frame_size,
517 ByteSize basic_lock_owner_sp_offset,
518 ByteSize basic_lock_sp_offset,
519 OopMapSet* oop_maps) {
520 code_buffer->finalize_oop_references(method);
521 // create nmethod
522 nmethod* nm = NULL;
523 {
524 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
525 int native_nmethod_size = allocation_size(code_buffer, sizeof(nmethod));
526 CodeOffsets offsets;
527 offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
528 offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
529 nm = new (native_nmethod_size) nmethod(method(), native_nmethod_size,
530 compile_id, &offsets,
531 code_buffer, frame_size,
532 basic_lock_owner_sp_offset,
533 basic_lock_sp_offset, oop_maps);
534 NOT_PRODUCT(if (nm != NULL) nmethod_stats.note_native_nmethod(nm));
535 if (PrintAssembly && nm != NULL) {
536 Disassembler::decode(nm);
537 }
538 }
539 // verify nmethod
540 debug_only(if (nm) nm->verify();) // might block
542 if (nm != NULL) {
543 nm->log_new_nmethod();
544 }
546 return nm;
547 }
549 #ifdef HAVE_DTRACE_H
550 nmethod* nmethod::new_dtrace_nmethod(methodHandle method,
551 CodeBuffer *code_buffer,
552 int vep_offset,
553 int trap_offset,
554 int frame_complete,
555 int frame_size) {
556 code_buffer->finalize_oop_references(method);
557 // create nmethod
558 nmethod* nm = NULL;
559 {
560 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
561 int nmethod_size = allocation_size(code_buffer, sizeof(nmethod));
562 CodeOffsets offsets;
563 offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
564 offsets.set_value(CodeOffsets::Dtrace_trap, trap_offset);
565 offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
567 nm = new (nmethod_size) nmethod(method(), nmethod_size,
568 &offsets, code_buffer, frame_size);
570 NOT_PRODUCT(if (nm != NULL) nmethod_stats.note_nmethod(nm));
571 if (PrintAssembly && nm != NULL) {
572 Disassembler::decode(nm);
573 }
574 }
575 // verify nmethod
576 debug_only(if (nm) nm->verify();) // might block
578 if (nm != NULL) {
579 nm->log_new_nmethod();
580 }
582 return nm;
583 }
585 #endif // def HAVE_DTRACE_H
587 nmethod* nmethod::new_nmethod(methodHandle method,
588 int compile_id,
589 int entry_bci,
590 CodeOffsets* offsets,
591 int orig_pc_offset,
592 DebugInformationRecorder* debug_info,
593 Dependencies* dependencies,
594 CodeBuffer* code_buffer, int frame_size,
595 OopMapSet* oop_maps,
596 ExceptionHandlerTable* handler_table,
597 ImplicitExceptionTable* nul_chk_table,
598 AbstractCompiler* compiler,
599 int comp_level
600 )
601 {
602 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
603 code_buffer->finalize_oop_references(method);
604 // create nmethod
605 nmethod* nm = NULL;
606 { MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
607 int nmethod_size =
608 allocation_size(code_buffer, sizeof(nmethod))
609 + adjust_pcs_size(debug_info->pcs_size())
610 + round_to(dependencies->size_in_bytes() , oopSize)
611 + round_to(handler_table->size_in_bytes(), oopSize)
612 + round_to(nul_chk_table->size_in_bytes(), oopSize)
613 + round_to(debug_info->data_size() , oopSize);
615 nm = new (nmethod_size)
616 nmethod(method(), nmethod_size, compile_id, entry_bci, offsets,
617 orig_pc_offset, debug_info, dependencies, code_buffer, frame_size,
618 oop_maps,
619 handler_table,
620 nul_chk_table,
621 compiler,
622 comp_level);
624 if (nm != NULL) {
625 // To make dependency checking during class loading fast, record
626 // the nmethod dependencies in the classes it is dependent on.
627 // This allows the dependency checking code to simply walk the
628 // class hierarchy above the loaded class, checking only nmethods
629 // which are dependent on those classes. The slow way is to
630 // check every nmethod for dependencies which makes it linear in
631 // the number of methods compiled. For applications with a lot
632 // classes the slow way is too slow.
633 for (Dependencies::DepStream deps(nm); deps.next(); ) {
634 Klass* klass = deps.context_type();
635 if (klass == NULL) {
636 continue; // ignore things like evol_method
637 }
639 // record this nmethod as dependent on this klass
640 InstanceKlass::cast(klass)->add_dependent_nmethod(nm);
641 }
642 NOT_PRODUCT(nmethod_stats.note_nmethod(nm));
643 if (PrintAssembly || CompilerOracle::has_option_string(method, "PrintAssembly")) {
644 Disassembler::decode(nm);
645 }
646 }
647 }
648 // Do verification and logging outside CodeCache_lock.
649 if (nm != NULL) {
650 // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
651 DEBUG_ONLY(nm->verify();)
652 nm->log_new_nmethod();
653 }
654 return nm;
655 }
658 // For native wrappers
659 nmethod::nmethod(
660 Method* method,
661 int nmethod_size,
662 int compile_id,
663 CodeOffsets* offsets,
664 CodeBuffer* code_buffer,
665 int frame_size,
666 ByteSize basic_lock_owner_sp_offset,
667 ByteSize basic_lock_sp_offset,
668 OopMapSet* oop_maps )
669 : CodeBlob("native nmethod", code_buffer, sizeof(nmethod),
670 nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps),
671 _native_receiver_sp_offset(basic_lock_owner_sp_offset),
672 _native_basic_lock_sp_offset(basic_lock_sp_offset)
673 {
674 {
675 debug_only(No_Safepoint_Verifier nsv;)
676 assert_locked_or_safepoint(CodeCache_lock);
678 init_defaults();
679 _method = method;
680 _entry_bci = InvocationEntryBci;
681 // We have no exception handler or deopt handler make the
682 // values something that will never match a pc like the nmethod vtable entry
683 _exception_offset = 0;
684 _deoptimize_offset = 0;
685 _deoptimize_mh_offset = 0;
686 _orig_pc_offset = 0;
688 _consts_offset = data_offset();
689 _stub_offset = data_offset();
690 _oops_offset = data_offset();
691 _metadata_offset = _oops_offset + round_to(code_buffer->total_oop_size(), oopSize);
692 _scopes_data_offset = _metadata_offset + round_to(code_buffer->total_metadata_size(), wordSize);
693 _scopes_pcs_offset = _scopes_data_offset;
694 _dependencies_offset = _scopes_pcs_offset;
695 _handler_table_offset = _dependencies_offset;
696 _nul_chk_table_offset = _handler_table_offset;
697 _nmethod_end_offset = _nul_chk_table_offset;
698 _compile_id = compile_id;
699 _comp_level = CompLevel_none;
700 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry);
701 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry);
702 _osr_entry_point = NULL;
703 _exception_cache = NULL;
704 _pc_desc_cache.reset_to(NULL);
705 _hotness_counter = NMethodSweeper::hotness_counter_reset_val();
707 code_buffer->copy_values_to(this);
708 if (ScavengeRootsInCode) {
709 if (detect_scavenge_root_oops()) {
710 CodeCache::add_scavenge_root_nmethod(this);
711 }
712 Universe::heap()->register_nmethod(this);
713 }
714 debug_only(verify_scavenge_root_oops());
715 CodeCache::commit(this);
716 }
718 if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {
719 ttyLocker ttyl; // keep the following output all in one block
720 // This output goes directly to the tty, not the compiler log.
721 // To enable tools to match it up with the compilation activity,
722 // be sure to tag this tty output with the compile ID.
723 if (xtty != NULL) {
724 xtty->begin_head("print_native_nmethod");
725 xtty->method(_method);
726 xtty->stamp();
727 xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
728 }
729 // print the header part first
730 print();
731 // then print the requested information
732 if (PrintNativeNMethods) {
733 print_code();
734 if (oop_maps != NULL) {
735 oop_maps->print();
736 }
737 }
738 if (PrintRelocations) {
739 print_relocations();
740 }
741 if (xtty != NULL) {
742 xtty->tail("print_native_nmethod");
743 }
744 }
745 }
747 // For dtrace wrappers
748 #ifdef HAVE_DTRACE_H
749 nmethod::nmethod(
750 Method* method,
751 int nmethod_size,
752 CodeOffsets* offsets,
753 CodeBuffer* code_buffer,
754 int frame_size)
755 : CodeBlob("dtrace nmethod", code_buffer, sizeof(nmethod),
756 nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, NULL),
757 _native_receiver_sp_offset(in_ByteSize(-1)),
758 _native_basic_lock_sp_offset(in_ByteSize(-1))
759 {
760 {
761 debug_only(No_Safepoint_Verifier nsv;)
762 assert_locked_or_safepoint(CodeCache_lock);
764 init_defaults();
765 _method = method;
766 _entry_bci = InvocationEntryBci;
767 // We have no exception handler or deopt handler make the
768 // values something that will never match a pc like the nmethod vtable entry
769 _exception_offset = 0;
770 _deoptimize_offset = 0;
771 _deoptimize_mh_offset = 0;
772 _unwind_handler_offset = -1;
773 _trap_offset = offsets->value(CodeOffsets::Dtrace_trap);
774 _orig_pc_offset = 0;
775 _consts_offset = data_offset();
776 _stub_offset = data_offset();
777 _oops_offset = data_offset();
778 _metadata_offset = _oops_offset + round_to(code_buffer->total_oop_size(), oopSize);
779 _scopes_data_offset = _metadata_offset + round_to(code_buffer->total_metadata_size(), wordSize);
780 _scopes_pcs_offset = _scopes_data_offset;
781 _dependencies_offset = _scopes_pcs_offset;
782 _handler_table_offset = _dependencies_offset;
783 _nul_chk_table_offset = _handler_table_offset;
784 _nmethod_end_offset = _nul_chk_table_offset;
785 _compile_id = 0; // default
786 _comp_level = CompLevel_none;
787 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry);
788 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry);
789 _osr_entry_point = NULL;
790 _exception_cache = NULL;
791 _pc_desc_cache.reset_to(NULL);
792 _hotness_counter = NMethodSweeper::hotness_counter_reset_val();
794 code_buffer->copy_values_to(this);
795 if (ScavengeRootsInCode) {
796 if (detect_scavenge_root_oops()) {
797 CodeCache::add_scavenge_root_nmethod(this);
798 }
799 Universe::heap()->register_nmethod(this);
800 }
801 DEBUG_ONLY(verify_scavenge_root_oops();)
802 CodeCache::commit(this);
803 }
805 if (PrintNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {
806 ttyLocker ttyl; // keep the following output all in one block
807 // This output goes directly to the tty, not the compiler log.
808 // To enable tools to match it up with the compilation activity,
809 // be sure to tag this tty output with the compile ID.
810 if (xtty != NULL) {
811 xtty->begin_head("print_dtrace_nmethod");
812 xtty->method(_method);
813 xtty->stamp();
814 xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
815 }
816 // print the header part first
817 print();
818 // then print the requested information
819 if (PrintNMethods) {
820 print_code();
821 }
822 if (PrintRelocations) {
823 print_relocations();
824 }
825 if (xtty != NULL) {
826 xtty->tail("print_dtrace_nmethod");
827 }
828 }
829 }
830 #endif // def HAVE_DTRACE_H
832 void* nmethod::operator new(size_t size, int nmethod_size) throw() {
833 // Not critical, may return null if there is too little continuous memory
834 return CodeCache::allocate(nmethod_size);
835 }
837 nmethod::nmethod(
838 Method* method,
839 int nmethod_size,
840 int compile_id,
841 int entry_bci,
842 CodeOffsets* offsets,
843 int orig_pc_offset,
844 DebugInformationRecorder* debug_info,
845 Dependencies* dependencies,
846 CodeBuffer *code_buffer,
847 int frame_size,
848 OopMapSet* oop_maps,
849 ExceptionHandlerTable* handler_table,
850 ImplicitExceptionTable* nul_chk_table,
851 AbstractCompiler* compiler,
852 int comp_level
853 )
854 : CodeBlob("nmethod", code_buffer, sizeof(nmethod),
855 nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps),
856 _native_receiver_sp_offset(in_ByteSize(-1)),
857 _native_basic_lock_sp_offset(in_ByteSize(-1))
858 {
859 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
860 {
861 debug_only(No_Safepoint_Verifier nsv;)
862 assert_locked_or_safepoint(CodeCache_lock);
864 init_defaults();
865 _method = method;
866 _entry_bci = entry_bci;
867 _compile_id = compile_id;
868 _comp_level = comp_level;
869 _compiler = compiler;
870 _orig_pc_offset = orig_pc_offset;
871 _hotness_counter = NMethodSweeper::hotness_counter_reset_val();
873 // Section offsets
874 _consts_offset = content_offset() + code_buffer->total_offset_of(code_buffer->consts());
875 _stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs());
877 // Exception handler and deopt handler are in the stub section
878 assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set");
879 assert(offsets->value(CodeOffsets::Deopt ) != -1, "must be set");
880 _exception_offset = _stub_offset + offsets->value(CodeOffsets::Exceptions);
881 _deoptimize_offset = _stub_offset + offsets->value(CodeOffsets::Deopt);
882 if (offsets->value(CodeOffsets::DeoptMH) != -1) {
883 _deoptimize_mh_offset = _stub_offset + offsets->value(CodeOffsets::DeoptMH);
884 } else {
885 _deoptimize_mh_offset = -1;
886 }
887 if (offsets->value(CodeOffsets::UnwindHandler) != -1) {
888 _unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler);
889 } else {
890 _unwind_handler_offset = -1;
891 }
893 _oops_offset = data_offset();
894 _metadata_offset = _oops_offset + round_to(code_buffer->total_oop_size(), oopSize);
895 _scopes_data_offset = _metadata_offset + round_to(code_buffer->total_metadata_size(), wordSize);
897 _scopes_pcs_offset = _scopes_data_offset + round_to(debug_info->data_size (), oopSize);
898 _dependencies_offset = _scopes_pcs_offset + adjust_pcs_size(debug_info->pcs_size());
899 _handler_table_offset = _dependencies_offset + round_to(dependencies->size_in_bytes (), oopSize);
900 _nul_chk_table_offset = _handler_table_offset + round_to(handler_table->size_in_bytes(), oopSize);
901 _nmethod_end_offset = _nul_chk_table_offset + round_to(nul_chk_table->size_in_bytes(), oopSize);
903 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry);
904 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry);
905 _osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry);
906 _exception_cache = NULL;
907 _pc_desc_cache.reset_to(scopes_pcs_begin());
909 // Copy contents of ScopeDescRecorder to nmethod
910 code_buffer->copy_values_to(this);
911 debug_info->copy_to(this);
912 dependencies->copy_to(this);
913 if (ScavengeRootsInCode) {
914 if (detect_scavenge_root_oops()) {
915 CodeCache::add_scavenge_root_nmethod(this);
916 }
917 Universe::heap()->register_nmethod(this);
918 }
919 debug_only(verify_scavenge_root_oops());
921 CodeCache::commit(this);
923 // Copy contents of ExceptionHandlerTable to nmethod
924 handler_table->copy_to(this);
925 nul_chk_table->copy_to(this);
927 // we use the information of entry points to find out if a method is
928 // static or non static
929 assert(compiler->is_c2() ||
930 _method->is_static() == (entry_point() == _verified_entry_point),
931 " entry points must be same for static methods and vice versa");
932 }
934 bool printnmethods = PrintNMethods
935 || CompilerOracle::should_print(_method)
936 || CompilerOracle::has_option_string(_method, "PrintNMethods");
937 if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {
938 print_nmethod(printnmethods);
939 }
940 }
943 // Print a short set of xml attributes to identify this nmethod. The
944 // output should be embedded in some other element.
945 void nmethod::log_identity(xmlStream* log) const {
946 log->print(" compile_id='%d'", compile_id());
947 const char* nm_kind = compile_kind();
948 if (nm_kind != NULL) log->print(" compile_kind='%s'", nm_kind);
949 if (compiler() != NULL) {
950 log->print(" compiler='%s'", compiler()->name());
951 }
952 if (TieredCompilation) {
953 log->print(" level='%d'", comp_level());
954 }
955 }
958 #define LOG_OFFSET(log, name) \
959 if ((intptr_t)name##_end() - (intptr_t)name##_begin()) \
960 log->print(" " XSTR(name) "_offset='%d'" , \
961 (intptr_t)name##_begin() - (intptr_t)this)
964 void nmethod::log_new_nmethod() const {
965 if (LogCompilation && xtty != NULL) {
966 ttyLocker ttyl;
967 HandleMark hm;
968 xtty->begin_elem("nmethod");
969 log_identity(xtty);
970 xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", code_begin(), size());
971 xtty->print(" address='" INTPTR_FORMAT "'", (intptr_t) this);
973 LOG_OFFSET(xtty, relocation);
974 LOG_OFFSET(xtty, consts);
975 LOG_OFFSET(xtty, insts);
976 LOG_OFFSET(xtty, stub);
977 LOG_OFFSET(xtty, scopes_data);
978 LOG_OFFSET(xtty, scopes_pcs);
979 LOG_OFFSET(xtty, dependencies);
980 LOG_OFFSET(xtty, handler_table);
981 LOG_OFFSET(xtty, nul_chk_table);
982 LOG_OFFSET(xtty, oops);
984 xtty->method(method());
985 xtty->stamp();
986 xtty->end_elem();
987 }
988 }
990 #undef LOG_OFFSET
993 // Print out more verbose output usually for a newly created nmethod.
994 void nmethod::print_on(outputStream* st, const char* msg) const {
995 if (st != NULL) {
996 ttyLocker ttyl;
997 if (WizardMode) {
998 CompileTask::print_compilation(st, this, msg, /*short_form:*/ true);
999 st->print_cr(" (" INTPTR_FORMAT ")", this);
1000 } else {
1001 CompileTask::print_compilation(st, this, msg, /*short_form:*/ false);
1002 }
1003 }
1004 }
1007 void nmethod::print_nmethod(bool printmethod) {
1008 ttyLocker ttyl; // keep the following output all in one block
1009 if (xtty != NULL) {
1010 xtty->begin_head("print_nmethod");
1011 xtty->stamp();
1012 xtty->end_head();
1013 }
1014 // print the header part first
1015 print();
1016 // then print the requested information
1017 if (printmethod) {
1018 print_code();
1019 print_pcs();
1020 if (oop_maps()) {
1021 oop_maps()->print();
1022 }
1023 }
1024 if (PrintDebugInfo) {
1025 print_scopes();
1026 }
1027 if (PrintRelocations) {
1028 print_relocations();
1029 }
1030 if (PrintDependencies) {
1031 print_dependencies();
1032 }
1033 if (PrintExceptionHandlers) {
1034 print_handler_table();
1035 print_nul_chk_table();
1036 }
1037 if (xtty != NULL) {
1038 xtty->tail("print_nmethod");
1039 }
1040 }
1043 // Promote one word from an assembly-time handle to a live embedded oop.
1044 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {
1045 if (handle == NULL ||
1046 // As a special case, IC oops are initialized to 1 or -1.
1047 handle == (jobject) Universe::non_oop_word()) {
1048 (*dest) = (oop) handle;
1049 } else {
1050 (*dest) = JNIHandles::resolve_non_null(handle);
1051 }
1052 }
1055 // Have to have the same name because it's called by a template
1056 void nmethod::copy_values(GrowableArray<jobject>* array) {
1057 int length = array->length();
1058 assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");
1059 oop* dest = oops_begin();
1060 for (int index = 0 ; index < length; index++) {
1061 initialize_immediate_oop(&dest[index], array->at(index));
1062 }
1064 // Now we can fix up all the oops in the code. We need to do this
1065 // in the code because the assembler uses jobjects as placeholders.
1066 // The code and relocations have already been initialized by the
1067 // CodeBlob constructor, so it is valid even at this early point to
1068 // iterate over relocations and patch the code.
1069 fix_oop_relocations(NULL, NULL, /*initialize_immediates=*/ true);
1070 }
1072 void nmethod::copy_values(GrowableArray<Metadata*>* array) {
1073 int length = array->length();
1074 assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough");
1075 Metadata** dest = metadata_begin();
1076 for (int index = 0 ; index < length; index++) {
1077 dest[index] = array->at(index);
1078 }
1079 }
1081 bool nmethod::is_at_poll_return(address pc) {
1082 RelocIterator iter(this, pc, pc+1);
1083 while (iter.next()) {
1084 if (iter.type() == relocInfo::poll_return_type)
1085 return true;
1086 }
1087 return false;
1088 }
1091 bool nmethod::is_at_poll_or_poll_return(address pc) {
1092 RelocIterator iter(this, pc, pc+1);
1093 while (iter.next()) {
1094 relocInfo::relocType t = iter.type();
1095 if (t == relocInfo::poll_return_type || t == relocInfo::poll_type)
1096 return true;
1097 }
1098 return false;
1099 }
1102 void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) {
1103 // re-patch all oop-bearing instructions, just in case some oops moved
1104 RelocIterator iter(this, begin, end);
1105 while (iter.next()) {
1106 if (iter.type() == relocInfo::oop_type) {
1107 oop_Relocation* reloc = iter.oop_reloc();
1108 if (initialize_immediates && reloc->oop_is_immediate()) {
1109 oop* dest = reloc->oop_addr();
1110 initialize_immediate_oop(dest, (jobject) *dest);
1111 }
1112 // Refresh the oop-related bits of this instruction.
1113 reloc->fix_oop_relocation();
1114 } else if (iter.type() == relocInfo::metadata_type) {
1115 metadata_Relocation* reloc = iter.metadata_reloc();
1116 reloc->fix_metadata_relocation();
1117 }
1118 }
1119 }
1122 void nmethod::verify_oop_relocations() {
1123 // Ensure sure that the code matches the current oop values
1124 RelocIterator iter(this, NULL, NULL);
1125 while (iter.next()) {
1126 if (iter.type() == relocInfo::oop_type) {
1127 oop_Relocation* reloc = iter.oop_reloc();
1128 if (!reloc->oop_is_immediate()) {
1129 reloc->verify_oop_relocation();
1130 }
1131 }
1132 }
1133 }
1136 ScopeDesc* nmethod::scope_desc_at(address pc) {
1137 PcDesc* pd = pc_desc_at(pc);
1138 guarantee(pd != NULL, "scope must be present");
1139 return new ScopeDesc(this, pd->scope_decode_offset(),
1140 pd->obj_decode_offset(), pd->should_reexecute(),
1141 pd->return_oop());
1142 }
1145 void nmethod::clear_inline_caches() {
1146 assert(SafepointSynchronize::is_at_safepoint(), "cleaning of IC's only allowed at safepoint");
1147 if (is_zombie()) {
1148 return;
1149 }
1151 RelocIterator iter(this);
1152 while (iter.next()) {
1153 iter.reloc()->clear_inline_cache();
1154 }
1155 }
1158 void nmethod::cleanup_inline_caches() {
1160 assert_locked_or_safepoint(CompiledIC_lock);
1162 // If the method is not entrant or zombie then a JMP is plastered over the
1163 // first few bytes. If an oop in the old code was there, that oop
1164 // should not get GC'd. Skip the first few bytes of oops on
1165 // not-entrant methods.
1166 address low_boundary = verified_entry_point();
1167 if (!is_in_use()) {
1168 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
1169 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
1170 // This means that the low_boundary is going to be a little too high.
1171 // This shouldn't matter, since oops of non-entrant methods are never used.
1172 // In fact, why are we bothering to look at oops in a non-entrant method??
1173 }
1175 // Find all calls in an nmethod, and clear the ones that points to zombie methods
1176 ResourceMark rm;
1177 RelocIterator iter(this, low_boundary);
1178 while(iter.next()) {
1179 switch(iter.type()) {
1180 case relocInfo::virtual_call_type:
1181 case relocInfo::opt_virtual_call_type: {
1182 CompiledIC *ic = CompiledIC_at(&iter);
1183 // Ok, to lookup references to zombies here
1184 CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());
1185 if( cb != NULL && cb->is_nmethod() ) {
1186 nmethod* nm = (nmethod*)cb;
1187 // Clean inline caches pointing to both zombie and not_entrant methods
1188 if (!nm->is_in_use() || (nm->method()->code() != nm)) ic->set_to_clean();
1189 }
1190 break;
1191 }
1192 case relocInfo::static_call_type: {
1193 CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());
1194 CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());
1195 if( cb != NULL && cb->is_nmethod() ) {
1196 nmethod* nm = (nmethod*)cb;
1197 // Clean inline caches pointing to both zombie and not_entrant methods
1198 if (!nm->is_in_use() || (nm->method()->code() != nm)) csc->set_to_clean();
1199 }
1200 break;
1201 }
1202 }
1203 }
1204 }
1206 void nmethod::verify_clean_inline_caches() {
1207 assert_locked_or_safepoint(CompiledIC_lock);
1209 // If the method is not entrant or zombie then a JMP is plastered over the
1210 // first few bytes. If an oop in the old code was there, that oop
1211 // should not get GC'd. Skip the first few bytes of oops on
1212 // not-entrant methods.
1213 address low_boundary = verified_entry_point();
1214 if (!is_in_use()) {
1215 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
1216 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
1217 // This means that the low_boundary is going to be a little too high.
1218 // This shouldn't matter, since oops of non-entrant methods are never used.
1219 // In fact, why are we bothering to look at oops in a non-entrant method??
1220 }
1222 ResourceMark rm;
1223 RelocIterator iter(this, low_boundary);
1224 while(iter.next()) {
1225 switch(iter.type()) {
1226 case relocInfo::virtual_call_type:
1227 case relocInfo::opt_virtual_call_type: {
1228 CompiledIC *ic = CompiledIC_at(&iter);
1229 // Ok, to lookup references to zombies here
1230 CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());
1231 if( cb != NULL && cb->is_nmethod() ) {
1232 nmethod* nm = (nmethod*)cb;
1233 // Verify that inline caches pointing to both zombie and not_entrant methods are clean
1234 if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1235 assert(ic->is_clean(), "IC should be clean");
1236 }
1237 }
1238 break;
1239 }
1240 case relocInfo::static_call_type: {
1241 CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());
1242 CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());
1243 if( cb != NULL && cb->is_nmethod() ) {
1244 nmethod* nm = (nmethod*)cb;
1245 // Verify that inline caches pointing to both zombie and not_entrant methods are clean
1246 if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1247 assert(csc->is_clean(), "IC should be clean");
1248 }
1249 }
1250 break;
1251 }
1252 }
1253 }
1254 }
1256 int nmethod::verify_icholder_relocations() {
1257 int count = 0;
1259 RelocIterator iter(this);
1260 while(iter.next()) {
1261 if (iter.type() == relocInfo::virtual_call_type) {
1262 if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc())) {
1263 CompiledIC *ic = CompiledIC_at(&iter);
1264 if (TraceCompiledIC) {
1265 tty->print("noticed icholder " INTPTR_FORMAT " ", p2i(ic->cached_icholder()));
1266 ic->print();
1267 }
1268 assert(ic->cached_icholder() != NULL, "must be non-NULL");
1269 count++;
1270 }
1271 }
1272 }
1274 return count;
1275 }
1277 // This is a private interface with the sweeper.
1278 void nmethod::mark_as_seen_on_stack() {
1279 assert(is_alive(), "Must be an alive method");
1280 // Set the traversal mark to ensure that the sweeper does 2
1281 // cleaning passes before moving to zombie.
1282 set_stack_traversal_mark(NMethodSweeper::traversal_count());
1283 }
1285 // Tell if a non-entrant method can be converted to a zombie (i.e.,
1286 // there are no activations on the stack, not in use by the VM,
1287 // and not in use by the ServiceThread)
1288 bool nmethod::can_not_entrant_be_converted() {
1289 assert(is_not_entrant(), "must be a non-entrant method");
1291 // Since the nmethod sweeper only does partial sweep the sweeper's traversal
1292 // count can be greater than the stack traversal count before it hits the
1293 // nmethod for the second time.
1294 return stack_traversal_mark()+1 < NMethodSweeper::traversal_count() &&
1295 !is_locked_by_vm();
1296 }
1298 void nmethod::inc_decompile_count() {
1299 if (!is_compiled_by_c2()) return;
1300 // Could be gated by ProfileTraps, but do not bother...
1301 Method* m = method();
1302 if (m == NULL) return;
1303 MethodData* mdo = m->method_data();
1304 if (mdo == NULL) return;
1305 // There is a benign race here. See comments in methodData.hpp.
1306 mdo->inc_decompile_count();
1307 }
1309 void nmethod::increase_unloading_clock() {
1310 _global_unloading_clock++;
1311 if (_global_unloading_clock == 0) {
1312 // _nmethods are allocated with _unloading_clock == 0,
1313 // so 0 is never used as a clock value.
1314 _global_unloading_clock = 1;
1315 }
1316 }
1318 void nmethod::set_unloading_clock(unsigned char unloading_clock) {
1319 OrderAccess::release_store((volatile jubyte*)&_unloading_clock, unloading_clock);
1320 }
1322 unsigned char nmethod::unloading_clock() {
1323 return (unsigned char)OrderAccess::load_acquire((volatile jubyte*)&_unloading_clock);
1324 }
1326 void nmethod::make_unloaded(BoolObjectClosure* is_alive, oop cause) {
1328 post_compiled_method_unload();
1330 // Since this nmethod is being unloaded, make sure that dependencies
1331 // recorded in instanceKlasses get flushed and pass non-NULL closure to
1332 // indicate that this work is being done during a GC.
1333 assert(Universe::heap()->is_gc_active(), "should only be called during gc");
1334 assert(is_alive != NULL, "Should be non-NULL");
1335 // A non-NULL is_alive closure indicates that this is being called during GC.
1336 flush_dependencies(is_alive);
1338 // Break cycle between nmethod & method
1339 if (TraceClassUnloading && WizardMode) {
1340 tty->print_cr("[Class unloading: Making nmethod " INTPTR_FORMAT
1341 " unloadable], Method*(" INTPTR_FORMAT
1342 "), cause(" INTPTR_FORMAT ")",
1343 this, (address)_method, (address)cause);
1344 if (!Universe::heap()->is_gc_active())
1345 cause->klass()->print();
1346 }
1347 // Unlink the osr method, so we do not look this up again
1348 if (is_osr_method()) {
1349 invalidate_osr_method();
1350 }
1351 // If _method is already NULL the Method* is about to be unloaded,
1352 // so we don't have to break the cycle. Note that it is possible to
1353 // have the Method* live here, in case we unload the nmethod because
1354 // it is pointing to some oop (other than the Method*) being unloaded.
1355 if (_method != NULL) {
1356 // OSR methods point to the Method*, but the Method* does not
1357 // point back!
1358 if (_method->code() == this) {
1359 _method->clear_code(); // Break a cycle
1360 }
1361 _method = NULL; // Clear the method of this dead nmethod
1362 }
1363 // Make the class unloaded - i.e., change state and notify sweeper
1364 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1365 if (is_in_use()) {
1366 // Transitioning directly from live to unloaded -- so
1367 // we need to force a cache clean-up; remember this
1368 // for later on.
1369 CodeCache::set_needs_cache_clean(true);
1370 }
1372 // Unregister must be done before the state change
1373 Universe::heap()->unregister_nmethod(this);
1375 _state = unloaded;
1377 // Log the unloading.
1378 log_state_change();
1380 // The Method* is gone at this point
1381 assert(_method == NULL, "Tautology");
1383 set_osr_link(NULL);
1384 //set_scavenge_root_link(NULL); // done by prune_scavenge_root_nmethods
1385 NMethodSweeper::report_state_change(this);
1386 }
1388 void nmethod::invalidate_osr_method() {
1389 assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
1390 // Remove from list of active nmethods
1391 if (method() != NULL)
1392 method()->method_holder()->remove_osr_nmethod(this);
1393 // Set entry as invalid
1394 _entry_bci = InvalidOSREntryBci;
1395 }
1397 void nmethod::log_state_change() const {
1398 if (LogCompilation) {
1399 if (xtty != NULL) {
1400 ttyLocker ttyl; // keep the following output all in one block
1401 if (_state == unloaded) {
1402 xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'",
1403 os::current_thread_id());
1404 } else {
1405 xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s",
1406 os::current_thread_id(),
1407 (_state == zombie ? " zombie='1'" : ""));
1408 }
1409 log_identity(xtty);
1410 xtty->stamp();
1411 xtty->end_elem();
1412 }
1413 }
1414 if (PrintCompilation && _state != unloaded) {
1415 print_on(tty, _state == zombie ? "made zombie" : "made not entrant");
1416 }
1417 }
1419 /**
1420 * Common functionality for both make_not_entrant and make_zombie
1421 */
1422 bool nmethod::make_not_entrant_or_zombie(unsigned int state) {
1423 assert(state == zombie || state == not_entrant, "must be zombie or not_entrant");
1424 assert(!is_zombie(), "should not already be a zombie");
1426 // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below.
1427 nmethodLocker nml(this);
1428 methodHandle the_method(method());
1429 No_Safepoint_Verifier nsv;
1431 // during patching, depending on the nmethod state we must notify the GC that
1432 // code has been unloaded, unregistering it. We cannot do this right while
1433 // holding the Patching_lock because we need to use the CodeCache_lock. This
1434 // would be prone to deadlocks.
1435 // This flag is used to remember whether we need to later lock and unregister.
1436 bool nmethod_needs_unregister = false;
1438 {
1439 // invalidate osr nmethod before acquiring the patching lock since
1440 // they both acquire leaf locks and we don't want a deadlock.
1441 // This logic is equivalent to the logic below for patching the
1442 // verified entry point of regular methods.
1443 if (is_osr_method()) {
1444 // this effectively makes the osr nmethod not entrant
1445 invalidate_osr_method();
1446 }
1448 // Enter critical section. Does not block for safepoint.
1449 MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
1451 if (_state == state) {
1452 // another thread already performed this transition so nothing
1453 // to do, but return false to indicate this.
1454 return false;
1455 }
1457 // The caller can be calling the method statically or through an inline
1458 // cache call.
1459 if (!is_osr_method() && !is_not_entrant()) {
1460 NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::patch_verified_entry(entry_point(), verified_entry_point(),
1461 SharedRuntime::get_handle_wrong_method_stub());
1462 }
1464 if (is_in_use()) {
1465 // It's a true state change, so mark the method as decompiled.
1466 // Do it only for transition from alive.
1467 inc_decompile_count();
1468 }
1470 // If the state is becoming a zombie, signal to unregister the nmethod with
1471 // the heap.
1472 // This nmethod may have already been unloaded during a full GC.
1473 if ((state == zombie) && !is_unloaded()) {
1474 nmethod_needs_unregister = true;
1475 }
1477 // Must happen before state change. Otherwise we have a race condition in
1478 // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately
1479 // transition its state from 'not_entrant' to 'zombie' without having to wait
1480 // for stack scanning.
1481 if (state == not_entrant) {
1482 mark_as_seen_on_stack();
1483 OrderAccess::storestore();
1484 }
1486 // Change state
1487 _state = state;
1489 // Log the transition once
1490 log_state_change();
1492 // Remove nmethod from method.
1493 // We need to check if both the _code and _from_compiled_code_entry_point
1494 // refer to this nmethod because there is a race in setting these two fields
1495 // in Method* as seen in bugid 4947125.
1496 // If the vep() points to the zombie nmethod, the memory for the nmethod
1497 // could be flushed and the compiler and vtable stubs could still call
1498 // through it.
1499 if (method() != NULL && (method()->code() == this ||
1500 method()->from_compiled_entry() == verified_entry_point())) {
1501 HandleMark hm;
1502 method()->clear_code();
1503 }
1504 } // leave critical region under Patching_lock
1506 // When the nmethod becomes zombie it is no longer alive so the
1507 // dependencies must be flushed. nmethods in the not_entrant
1508 // state will be flushed later when the transition to zombie
1509 // happens or they get unloaded.
1510 if (state == zombie) {
1511 {
1512 // Flushing dependecies must be done before any possible
1513 // safepoint can sneak in, otherwise the oops used by the
1514 // dependency logic could have become stale.
1515 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1516 if (nmethod_needs_unregister) {
1517 Universe::heap()->unregister_nmethod(this);
1518 }
1519 flush_dependencies(NULL);
1520 }
1522 // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload
1523 // event and it hasn't already been reported for this nmethod then
1524 // report it now. The event may have been reported earilier if the GC
1525 // marked it for unloading). JvmtiDeferredEventQueue support means
1526 // we no longer go to a safepoint here.
1527 post_compiled_method_unload();
1529 #ifdef ASSERT
1530 // It's no longer safe to access the oops section since zombie
1531 // nmethods aren't scanned for GC.
1532 _oops_are_stale = true;
1533 #endif
1534 // the Method may be reclaimed by class unloading now that the
1535 // nmethod is in zombie state
1536 set_method(NULL);
1537 } else {
1538 assert(state == not_entrant, "other cases may need to be handled differently");
1539 }
1541 if (TraceCreateZombies) {
1542 tty->print_cr("nmethod <" INTPTR_FORMAT "> code made %s", this, (state == not_entrant) ? "not entrant" : "zombie");
1543 }
1545 NMethodSweeper::report_state_change(this);
1546 return true;
1547 }
1549 void nmethod::flush() {
1550 // Note that there are no valid oops in the nmethod anymore.
1551 assert(is_zombie() || (is_osr_method() && is_unloaded()), "must be a zombie method");
1552 assert(is_marked_for_reclamation() || (is_osr_method() && is_unloaded()), "must be marked for reclamation");
1554 assert (!is_locked_by_vm(), "locked methods shouldn't be flushed");
1555 assert_locked_or_safepoint(CodeCache_lock);
1557 // completely deallocate this method
1558 Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, this);
1559 if (PrintMethodFlushing) {
1560 tty->print_cr("*flushing nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT "/Free CodeCache:" SIZE_FORMAT "Kb",
1561 _compile_id, this, CodeCache::nof_blobs(), CodeCache::unallocated_capacity()/1024);
1562 }
1564 // We need to deallocate any ExceptionCache data.
1565 // Note that we do not need to grab the nmethod lock for this, it
1566 // better be thread safe if we're disposing of it!
1567 ExceptionCache* ec = exception_cache();
1568 set_exception_cache(NULL);
1569 while(ec != NULL) {
1570 ExceptionCache* next = ec->next();
1571 delete ec;
1572 ec = next;
1573 }
1575 if (on_scavenge_root_list()) {
1576 CodeCache::drop_scavenge_root_nmethod(this);
1577 }
1579 #ifdef SHARK
1580 ((SharkCompiler *) compiler())->free_compiled_method(insts_begin());
1581 #endif // SHARK
1583 ((CodeBlob*)(this))->flush();
1585 CodeCache::free(this);
1586 }
1589 //
1590 // Notify all classes this nmethod is dependent on that it is no
1591 // longer dependent. This should only be called in two situations.
1592 // First, when a nmethod transitions to a zombie all dependents need
1593 // to be clear. Since zombification happens at a safepoint there's no
1594 // synchronization issues. The second place is a little more tricky.
1595 // During phase 1 of mark sweep class unloading may happen and as a
1596 // result some nmethods may get unloaded. In this case the flushing
1597 // of dependencies must happen during phase 1 since after GC any
1598 // dependencies in the unloaded nmethod won't be updated, so
1599 // traversing the dependency information in unsafe. In that case this
1600 // function is called with a non-NULL argument and this function only
1601 // notifies instanceKlasses that are reachable
1603 void nmethod::flush_dependencies(BoolObjectClosure* is_alive) {
1604 assert_locked_or_safepoint(CodeCache_lock);
1605 assert(Universe::heap()->is_gc_active() == (is_alive != NULL),
1606 "is_alive is non-NULL if and only if we are called during GC");
1607 if (!has_flushed_dependencies()) {
1608 set_has_flushed_dependencies();
1609 for (Dependencies::DepStream deps(this); deps.next(); ) {
1610 Klass* klass = deps.context_type();
1611 if (klass == NULL) continue; // ignore things like evol_method
1613 // During GC the is_alive closure is non-NULL, and is used to
1614 // determine liveness of dependees that need to be updated.
1615 if (is_alive == NULL || klass->is_loader_alive(is_alive)) {
1616 InstanceKlass::cast(klass)->remove_dependent_nmethod(this);
1617 }
1618 }
1619 }
1620 }
1623 // If this oop is not live, the nmethod can be unloaded.
1624 bool nmethod::can_unload(BoolObjectClosure* is_alive, oop* root, bool unloading_occurred) {
1625 assert(root != NULL, "just checking");
1626 oop obj = *root;
1627 if (obj == NULL || is_alive->do_object_b(obj)) {
1628 return false;
1629 }
1631 // If ScavengeRootsInCode is true, an nmethod might be unloaded
1632 // simply because one of its constant oops has gone dead.
1633 // No actual classes need to be unloaded in order for this to occur.
1634 assert(unloading_occurred || ScavengeRootsInCode, "Inconsistency in unloading");
1635 make_unloaded(is_alive, obj);
1636 return true;
1637 }
1639 // ------------------------------------------------------------------
1640 // post_compiled_method_load_event
1641 // new method for install_code() path
1642 // Transfer information from compilation to jvmti
1643 void nmethod::post_compiled_method_load_event() {
1645 Method* moop = method();
1646 #ifndef USDT2
1647 HS_DTRACE_PROBE8(hotspot, compiled__method__load,
1648 moop->klass_name()->bytes(),
1649 moop->klass_name()->utf8_length(),
1650 moop->name()->bytes(),
1651 moop->name()->utf8_length(),
1652 moop->signature()->bytes(),
1653 moop->signature()->utf8_length(),
1654 insts_begin(), insts_size());
1655 #else /* USDT2 */
1656 HOTSPOT_COMPILED_METHOD_LOAD(
1657 (char *) moop->klass_name()->bytes(),
1658 moop->klass_name()->utf8_length(),
1659 (char *) moop->name()->bytes(),
1660 moop->name()->utf8_length(),
1661 (char *) moop->signature()->bytes(),
1662 moop->signature()->utf8_length(),
1663 insts_begin(), insts_size());
1664 #endif /* USDT2 */
1666 if (JvmtiExport::should_post_compiled_method_load() ||
1667 JvmtiExport::should_post_compiled_method_unload()) {
1668 get_and_cache_jmethod_id();
1669 }
1671 if (JvmtiExport::should_post_compiled_method_load()) {
1672 // Let the Service thread (which is a real Java thread) post the event
1673 MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
1674 JvmtiDeferredEventQueue::enqueue(
1675 JvmtiDeferredEvent::compiled_method_load_event(this));
1676 }
1677 }
1679 jmethodID nmethod::get_and_cache_jmethod_id() {
1680 if (_jmethod_id == NULL) {
1681 // Cache the jmethod_id since it can no longer be looked up once the
1682 // method itself has been marked for unloading.
1683 _jmethod_id = method()->jmethod_id();
1684 }
1685 return _jmethod_id;
1686 }
1688 void nmethod::post_compiled_method_unload() {
1689 if (unload_reported()) {
1690 // During unloading we transition to unloaded and then to zombie
1691 // and the unloading is reported during the first transition.
1692 return;
1693 }
1695 assert(_method != NULL && !is_unloaded(), "just checking");
1696 DTRACE_METHOD_UNLOAD_PROBE(method());
1698 // If a JVMTI agent has enabled the CompiledMethodUnload event then
1699 // post the event. Sometime later this nmethod will be made a zombie
1700 // by the sweeper but the Method* will not be valid at that point.
1701 // If the _jmethod_id is null then no load event was ever requested
1702 // so don't bother posting the unload. The main reason for this is
1703 // that the jmethodID is a weak reference to the Method* so if
1704 // it's being unloaded there's no way to look it up since the weak
1705 // ref will have been cleared.
1706 if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) {
1707 assert(!unload_reported(), "already unloaded");
1708 JvmtiDeferredEvent event =
1709 JvmtiDeferredEvent::compiled_method_unload_event(this,
1710 _jmethod_id, insts_begin());
1711 if (SafepointSynchronize::is_at_safepoint()) {
1712 // Don't want to take the queueing lock. Add it as pending and
1713 // it will get enqueued later.
1714 JvmtiDeferredEventQueue::add_pending_event(event);
1715 } else {
1716 MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
1717 JvmtiDeferredEventQueue::enqueue(event);
1718 }
1719 }
1721 // The JVMTI CompiledMethodUnload event can be enabled or disabled at
1722 // any time. As the nmethod is being unloaded now we mark it has
1723 // having the unload event reported - this will ensure that we don't
1724 // attempt to report the event in the unlikely scenario where the
1725 // event is enabled at the time the nmethod is made a zombie.
1726 set_unload_reported();
1727 }
1729 void static clean_ic_if_metadata_is_dead(CompiledIC *ic, BoolObjectClosure *is_alive, bool mark_on_stack) {
1730 if (ic->is_icholder_call()) {
1731 // The only exception is compiledICHolder oops which may
1732 // yet be marked below. (We check this further below).
1733 CompiledICHolder* cichk_oop = ic->cached_icholder();
1735 if (mark_on_stack) {
1736 Metadata::mark_on_stack(cichk_oop->holder_method());
1737 Metadata::mark_on_stack(cichk_oop->holder_klass());
1738 }
1740 if (cichk_oop->holder_method()->method_holder()->is_loader_alive(is_alive) &&
1741 cichk_oop->holder_klass()->is_loader_alive(is_alive)) {
1742 return;
1743 }
1744 } else {
1745 Metadata* ic_oop = ic->cached_metadata();
1746 if (ic_oop != NULL) {
1747 if (mark_on_stack) {
1748 Metadata::mark_on_stack(ic_oop);
1749 }
1751 if (ic_oop->is_klass()) {
1752 if (((Klass*)ic_oop)->is_loader_alive(is_alive)) {
1753 return;
1754 }
1755 } else if (ic_oop->is_method()) {
1756 if (((Method*)ic_oop)->method_holder()->is_loader_alive(is_alive)) {
1757 return;
1758 }
1759 } else {
1760 ShouldNotReachHere();
1761 }
1762 }
1763 }
1765 ic->set_to_clean();
1766 }
1768 // This is called at the end of the strong tracing/marking phase of a
1769 // GC to unload an nmethod if it contains otherwise unreachable
1770 // oops.
1772 void nmethod::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
1773 // Make sure the oop's ready to receive visitors
1774 assert(!is_zombie() && !is_unloaded(),
1775 "should not call follow on zombie or unloaded nmethod");
1777 // If the method is not entrant then a JMP is plastered over the
1778 // first few bytes. If an oop in the old code was there, that oop
1779 // should not get GC'd. Skip the first few bytes of oops on
1780 // not-entrant methods.
1781 address low_boundary = verified_entry_point();
1782 if (is_not_entrant()) {
1783 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
1784 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
1785 // (See comment above.)
1786 }
1788 // The RedefineClasses() API can cause the class unloading invariant
1789 // to no longer be true. See jvmtiExport.hpp for details.
1790 // Also, leave a debugging breadcrumb in local flag.
1791 bool a_class_was_redefined = JvmtiExport::has_redefined_a_class();
1792 if (a_class_was_redefined) {
1793 // This set of the unloading_occurred flag is done before the
1794 // call to post_compiled_method_unload() so that the unloading
1795 // of this nmethod is reported.
1796 unloading_occurred = true;
1797 }
1799 // Exception cache
1800 clean_exception_cache(is_alive);
1802 // If class unloading occurred we first iterate over all inline caches and
1803 // clear ICs where the cached oop is referring to an unloaded klass or method.
1804 // The remaining live cached oops will be traversed in the relocInfo::oop_type
1805 // iteration below.
1806 if (unloading_occurred) {
1807 RelocIterator iter(this, low_boundary);
1808 while(iter.next()) {
1809 if (iter.type() == relocInfo::virtual_call_type) {
1810 CompiledIC *ic = CompiledIC_at(&iter);
1811 clean_ic_if_metadata_is_dead(ic, is_alive, false);
1812 }
1813 }
1814 }
1816 // Compiled code
1817 {
1818 RelocIterator iter(this, low_boundary);
1819 while (iter.next()) {
1820 if (iter.type() == relocInfo::oop_type) {
1821 oop_Relocation* r = iter.oop_reloc();
1822 // In this loop, we must only traverse those oops directly embedded in
1823 // the code. Other oops (oop_index>0) are seen as part of scopes_oops.
1824 assert(1 == (r->oop_is_immediate()) +
1825 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1826 "oop must be found in exactly one place");
1827 if (r->oop_is_immediate() && r->oop_value() != NULL) {
1828 if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1829 return;
1830 }
1831 }
1832 }
1833 }
1834 }
1837 // Scopes
1838 for (oop* p = oops_begin(); p < oops_end(); p++) {
1839 if (*p == Universe::non_oop_word()) continue; // skip non-oops
1840 if (can_unload(is_alive, p, unloading_occurred)) {
1841 return;
1842 }
1843 }
1845 // Ensure that all metadata is still alive
1846 verify_metadata_loaders(low_boundary, is_alive);
1847 }
1849 template <class CompiledICorStaticCall>
1850 static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, BoolObjectClosure *is_alive, nmethod* from) {
1851 // Ok, to lookup references to zombies here
1852 CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
1853 if (cb != NULL && cb->is_nmethod()) {
1854 nmethod* nm = (nmethod*)cb;
1856 if (nm->unloading_clock() != nmethod::global_unloading_clock()) {
1857 // The nmethod has not been processed yet.
1858 return true;
1859 }
1861 // Clean inline caches pointing to both zombie and not_entrant methods
1862 if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1863 ic->set_to_clean();
1864 assert(ic->is_clean(), err_msg("nmethod " PTR_FORMAT "not clean %s", from, from->method()->name_and_sig_as_C_string()));
1865 }
1866 }
1868 return false;
1869 }
1871 static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, BoolObjectClosure *is_alive, nmethod* from) {
1872 return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), is_alive, from);
1873 }
1875 static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, BoolObjectClosure *is_alive, nmethod* from) {
1876 return clean_if_nmethod_is_unloaded(csc, csc->destination(), is_alive, from);
1877 }
1879 bool nmethod::unload_if_dead_at(RelocIterator* iter_at_oop, BoolObjectClosure *is_alive, bool unloading_occurred) {
1880 assert(iter_at_oop->type() == relocInfo::oop_type, "Wrong relocation type");
1882 oop_Relocation* r = iter_at_oop->oop_reloc();
1883 // Traverse those oops directly embedded in the code.
1884 // Other oops (oop_index>0) are seen as part of scopes_oops.
1885 assert(1 == (r->oop_is_immediate()) +
1886 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1887 "oop must be found in exactly one place");
1888 if (r->oop_is_immediate() && r->oop_value() != NULL) {
1889 // Unload this nmethod if the oop is dead.
1890 if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1891 return true;;
1892 }
1893 }
1895 return false;
1896 }
1898 void nmethod::mark_metadata_on_stack_at(RelocIterator* iter_at_metadata) {
1899 assert(iter_at_metadata->type() == relocInfo::metadata_type, "Wrong relocation type");
1901 metadata_Relocation* r = iter_at_metadata->metadata_reloc();
1902 // In this metadata, we must only follow those metadatas directly embedded in
1903 // the code. Other metadatas (oop_index>0) are seen as part of
1904 // the metadata section below.
1905 assert(1 == (r->metadata_is_immediate()) +
1906 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
1907 "metadata must be found in exactly one place");
1908 if (r->metadata_is_immediate() && r->metadata_value() != NULL) {
1909 Metadata* md = r->metadata_value();
1910 if (md != _method) Metadata::mark_on_stack(md);
1911 }
1912 }
1914 void nmethod::mark_metadata_on_stack_non_relocs() {
1915 // Visit the metadata section
1916 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
1917 if (*p == Universe::non_oop_word() || *p == NULL) continue; // skip non-oops
1918 Metadata* md = *p;
1919 Metadata::mark_on_stack(md);
1920 }
1922 // Visit metadata not embedded in the other places.
1923 if (_method != NULL) Metadata::mark_on_stack(_method);
1924 }
1926 bool nmethod::do_unloading_parallel(BoolObjectClosure* is_alive, bool unloading_occurred) {
1927 ResourceMark rm;
1929 // Make sure the oop's ready to receive visitors
1930 assert(!is_zombie() && !is_unloaded(),
1931 "should not call follow on zombie or unloaded nmethod");
1933 // If the method is not entrant then a JMP is plastered over the
1934 // first few bytes. If an oop in the old code was there, that oop
1935 // should not get GC'd. Skip the first few bytes of oops on
1936 // not-entrant methods.
1937 address low_boundary = verified_entry_point();
1938 if (is_not_entrant()) {
1939 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
1940 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
1941 // (See comment above.)
1942 }
1944 // The RedefineClasses() API can cause the class unloading invariant
1945 // to no longer be true. See jvmtiExport.hpp for details.
1946 // Also, leave a debugging breadcrumb in local flag.
1947 bool a_class_was_redefined = JvmtiExport::has_redefined_a_class();
1948 if (a_class_was_redefined) {
1949 // This set of the unloading_occurred flag is done before the
1950 // call to post_compiled_method_unload() so that the unloading
1951 // of this nmethod is reported.
1952 unloading_occurred = true;
1953 }
1955 // When class redefinition is used all metadata in the CodeCache has to be recorded,
1956 // so that unused "previous versions" can be purged. Since walking the CodeCache can
1957 // be expensive, the "mark on stack" is piggy-backed on this parallel unloading code.
1958 bool mark_metadata_on_stack = a_class_was_redefined;
1960 // Exception cache
1961 clean_exception_cache(is_alive);
1963 bool is_unloaded = false;
1964 bool postponed = false;
1966 RelocIterator iter(this, low_boundary);
1967 while(iter.next()) {
1969 switch (iter.type()) {
1971 case relocInfo::virtual_call_type:
1972 if (unloading_occurred) {
1973 // If class unloading occurred we first iterate over all inline caches and
1974 // clear ICs where the cached oop is referring to an unloaded klass or method.
1975 clean_ic_if_metadata_is_dead(CompiledIC_at(&iter), is_alive, mark_metadata_on_stack);
1976 }
1978 postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1979 break;
1981 case relocInfo::opt_virtual_call_type:
1982 postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1983 break;
1985 case relocInfo::static_call_type:
1986 postponed |= clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
1987 break;
1989 case relocInfo::oop_type:
1990 if (!is_unloaded) {
1991 is_unloaded = unload_if_dead_at(&iter, is_alive, unloading_occurred);
1992 }
1993 break;
1995 case relocInfo::metadata_type:
1996 if (mark_metadata_on_stack) {
1997 mark_metadata_on_stack_at(&iter);
1998 }
1999 }
2000 }
2002 if (mark_metadata_on_stack) {
2003 mark_metadata_on_stack_non_relocs();
2004 }
2006 if (is_unloaded) {
2007 return postponed;
2008 }
2010 // Scopes
2011 for (oop* p = oops_begin(); p < oops_end(); p++) {
2012 if (*p == Universe::non_oop_word()) continue; // skip non-oops
2013 if (can_unload(is_alive, p, unloading_occurred)) {
2014 is_unloaded = true;
2015 break;
2016 }
2017 }
2019 if (is_unloaded) {
2020 return postponed;
2021 }
2023 // Ensure that all metadata is still alive
2024 verify_metadata_loaders(low_boundary, is_alive);
2026 return postponed;
2027 }
2029 void nmethod::do_unloading_parallel_postponed(BoolObjectClosure* is_alive, bool unloading_occurred) {
2030 ResourceMark rm;
2032 // Make sure the oop's ready to receive visitors
2033 assert(!is_zombie(),
2034 "should not call follow on zombie nmethod");
2036 // If the method is not entrant then a JMP is plastered over the
2037 // first few bytes. If an oop in the old code was there, that oop
2038 // should not get GC'd. Skip the first few bytes of oops on
2039 // not-entrant methods.
2040 address low_boundary = verified_entry_point();
2041 if (is_not_entrant()) {
2042 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
2043 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
2044 // (See comment above.)
2045 }
2047 RelocIterator iter(this, low_boundary);
2048 while(iter.next()) {
2050 switch (iter.type()) {
2052 case relocInfo::virtual_call_type:
2053 clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
2054 break;
2056 case relocInfo::opt_virtual_call_type:
2057 clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
2058 break;
2060 case relocInfo::static_call_type:
2061 clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
2062 break;
2063 }
2064 }
2065 }
2067 #ifdef ASSERT
2069 class CheckClass : AllStatic {
2070 static BoolObjectClosure* _is_alive;
2072 // Check class_loader is alive for this bit of metadata.
2073 static void check_class(Metadata* md) {
2074 Klass* klass = NULL;
2075 if (md->is_klass()) {
2076 klass = ((Klass*)md);
2077 } else if (md->is_method()) {
2078 klass = ((Method*)md)->method_holder();
2079 } else if (md->is_methodData()) {
2080 klass = ((MethodData*)md)->method()->method_holder();
2081 } else {
2082 md->print();
2083 ShouldNotReachHere();
2084 }
2085 assert(klass->is_loader_alive(_is_alive), "must be alive");
2086 }
2087 public:
2088 static void do_check_class(BoolObjectClosure* is_alive, nmethod* nm) {
2089 assert(SafepointSynchronize::is_at_safepoint(), "this is only ok at safepoint");
2090 _is_alive = is_alive;
2091 nm->metadata_do(check_class);
2092 }
2093 };
2095 // This is called during a safepoint so can use static data
2096 BoolObjectClosure* CheckClass::_is_alive = NULL;
2097 #endif // ASSERT
2100 // Processing of oop references should have been sufficient to keep
2101 // all strong references alive. Any weak references should have been
2102 // cleared as well. Visit all the metadata and ensure that it's
2103 // really alive.
2104 void nmethod::verify_metadata_loaders(address low_boundary, BoolObjectClosure* is_alive) {
2105 #ifdef ASSERT
2106 RelocIterator iter(this, low_boundary);
2107 while (iter.next()) {
2108 // static_stub_Relocations may have dangling references to
2109 // Method*s so trim them out here. Otherwise it looks like
2110 // compiled code is maintaining a link to dead metadata.
2111 address static_call_addr = NULL;
2112 if (iter.type() == relocInfo::opt_virtual_call_type) {
2113 CompiledIC* cic = CompiledIC_at(&iter);
2114 if (!cic->is_call_to_interpreted()) {
2115 static_call_addr = iter.addr();
2116 }
2117 } else if (iter.type() == relocInfo::static_call_type) {
2118 CompiledStaticCall* csc = compiledStaticCall_at(iter.reloc());
2119 if (!csc->is_call_to_interpreted()) {
2120 static_call_addr = iter.addr();
2121 }
2122 }
2123 if (static_call_addr != NULL) {
2124 RelocIterator sciter(this, low_boundary);
2125 while (sciter.next()) {
2126 if (sciter.type() == relocInfo::static_stub_type &&
2127 sciter.static_stub_reloc()->static_call() == static_call_addr) {
2128 sciter.static_stub_reloc()->clear_inline_cache();
2129 }
2130 }
2131 }
2132 }
2133 // Check that the metadata embedded in the nmethod is alive
2134 CheckClass::do_check_class(is_alive, this);
2135 #endif
2136 }
2139 // Iterate over metadata calling this function. Used by RedefineClasses
2140 void nmethod::metadata_do(void f(Metadata*)) {
2141 address low_boundary = verified_entry_point();
2142 if (is_not_entrant()) {
2143 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
2144 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
2145 // (See comment above.)
2146 }
2147 {
2148 // Visit all immediate references that are embedded in the instruction stream.
2149 RelocIterator iter(this, low_boundary);
2150 while (iter.next()) {
2151 if (iter.type() == relocInfo::metadata_type ) {
2152 metadata_Relocation* r = iter.metadata_reloc();
2153 // In this metadata, we must only follow those metadatas directly embedded in
2154 // the code. Other metadatas (oop_index>0) are seen as part of
2155 // the metadata section below.
2156 assert(1 == (r->metadata_is_immediate()) +
2157 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
2158 "metadata must be found in exactly one place");
2159 if (r->metadata_is_immediate() && r->metadata_value() != NULL) {
2160 Metadata* md = r->metadata_value();
2161 f(md);
2162 }
2163 } else if (iter.type() == relocInfo::virtual_call_type) {
2164 // Check compiledIC holders associated with this nmethod
2165 CompiledIC *ic = CompiledIC_at(&iter);
2166 if (ic->is_icholder_call()) {
2167 CompiledICHolder* cichk = ic->cached_icholder();
2168 f(cichk->holder_method());
2169 f(cichk->holder_klass());
2170 } else {
2171 Metadata* ic_oop = ic->cached_metadata();
2172 if (ic_oop != NULL) {
2173 f(ic_oop);
2174 }
2175 }
2176 }
2177 }
2178 }
2180 // Visit the metadata section
2181 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2182 if (*p == Universe::non_oop_word() || *p == NULL) continue; // skip non-oops
2183 Metadata* md = *p;
2184 f(md);
2185 }
2187 // Visit metadata not embedded in the other places.
2188 if (_method != NULL) f(_method);
2189 }
2191 void nmethod::oops_do(OopClosure* f, bool allow_zombie) {
2192 // make sure the oops ready to receive visitors
2193 assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod");
2194 assert(!is_unloaded(), "should not call follow on unloaded nmethod");
2196 // If the method is not entrant or zombie then a JMP is plastered over the
2197 // first few bytes. If an oop in the old code was there, that oop
2198 // should not get GC'd. Skip the first few bytes of oops on
2199 // not-entrant methods.
2200 address low_boundary = verified_entry_point();
2201 if (is_not_entrant()) {
2202 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
2203 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
2204 // (See comment above.)
2205 }
2207 RelocIterator iter(this, low_boundary);
2209 while (iter.next()) {
2210 if (iter.type() == relocInfo::oop_type ) {
2211 oop_Relocation* r = iter.oop_reloc();
2212 // In this loop, we must only follow those oops directly embedded in
2213 // the code. Other oops (oop_index>0) are seen as part of scopes_oops.
2214 assert(1 == (r->oop_is_immediate()) +
2215 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2216 "oop must be found in exactly one place");
2217 if (r->oop_is_immediate() && r->oop_value() != NULL) {
2218 f->do_oop(r->oop_addr());
2219 }
2220 }
2221 }
2223 // Scopes
2224 // This includes oop constants not inlined in the code stream.
2225 for (oop* p = oops_begin(); p < oops_end(); p++) {
2226 if (*p == Universe::non_oop_word()) continue; // skip non-oops
2227 f->do_oop(p);
2228 }
2229 }
2231 #define NMETHOD_SENTINEL ((nmethod*)badAddress)
2233 nmethod* volatile nmethod::_oops_do_mark_nmethods;
2235 // An nmethod is "marked" if its _mark_link is set non-null.
2236 // Even if it is the end of the linked list, it will have a non-null link value,
2237 // as long as it is on the list.
2238 // This code must be MP safe, because it is used from parallel GC passes.
2239 bool nmethod::test_set_oops_do_mark() {
2240 assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called");
2241 nmethod* observed_mark_link = _oops_do_mark_link;
2242 if (observed_mark_link == NULL) {
2243 // Claim this nmethod for this thread to mark.
2244 observed_mark_link = (nmethod*)
2245 Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_link, NULL);
2246 if (observed_mark_link == NULL) {
2248 // Atomically append this nmethod (now claimed) to the head of the list:
2249 nmethod* observed_mark_nmethods = _oops_do_mark_nmethods;
2250 for (;;) {
2251 nmethod* required_mark_nmethods = observed_mark_nmethods;
2252 _oops_do_mark_link = required_mark_nmethods;
2253 observed_mark_nmethods = (nmethod*)
2254 Atomic::cmpxchg_ptr(this, &_oops_do_mark_nmethods, required_mark_nmethods);
2255 if (observed_mark_nmethods == required_mark_nmethods)
2256 break;
2257 }
2258 // Mark was clear when we first saw this guy.
2259 NOT_PRODUCT(if (TraceScavenge) print_on(tty, "oops_do, mark"));
2260 return false;
2261 }
2262 }
2263 // On fall through, another racing thread marked this nmethod before we did.
2264 return true;
2265 }
2267 void nmethod::oops_do_marking_prologue() {
2268 NOT_PRODUCT(if (TraceScavenge) tty->print_cr("[oops_do_marking_prologue"));
2269 assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row");
2270 // We use cmpxchg_ptr instead of regular assignment here because the user
2271 // may fork a bunch of threads, and we need them all to see the same state.
2272 void* observed = Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, NULL);
2273 guarantee(observed == NULL, "no races in this sequential code");
2274 }
2276 void nmethod::oops_do_marking_epilogue() {
2277 assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row");
2278 nmethod* cur = _oops_do_mark_nmethods;
2279 while (cur != NMETHOD_SENTINEL) {
2280 assert(cur != NULL, "not NULL-terminated");
2281 nmethod* next = cur->_oops_do_mark_link;
2282 cur->_oops_do_mark_link = NULL;
2283 cur->verify_oop_relocations();
2284 NOT_PRODUCT(if (TraceScavenge) cur->print_on(tty, "oops_do, unmark"));
2285 cur = next;
2286 }
2287 void* required = _oops_do_mark_nmethods;
2288 void* observed = Atomic::cmpxchg_ptr(NULL, &_oops_do_mark_nmethods, required);
2289 guarantee(observed == required, "no races in this sequential code");
2290 NOT_PRODUCT(if (TraceScavenge) tty->print_cr("oops_do_marking_epilogue]"));
2291 }
2293 class DetectScavengeRoot: public OopClosure {
2294 bool _detected_scavenge_root;
2295 public:
2296 DetectScavengeRoot() : _detected_scavenge_root(false)
2297 { NOT_PRODUCT(_print_nm = NULL); }
2298 bool detected_scavenge_root() { return _detected_scavenge_root; }
2299 virtual void do_oop(oop* p) {
2300 if ((*p) != NULL && (*p)->is_scavengable()) {
2301 NOT_PRODUCT(maybe_print(p));
2302 _detected_scavenge_root = true;
2303 }
2304 }
2305 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2307 #ifndef PRODUCT
2308 nmethod* _print_nm;
2309 void maybe_print(oop* p) {
2310 if (_print_nm == NULL) return;
2311 if (!_detected_scavenge_root) _print_nm->print_on(tty, "new scavenge root");
2312 tty->print_cr(""PTR_FORMAT"[offset=%d] detected scavengable oop "PTR_FORMAT" (found at "PTR_FORMAT")",
2313 _print_nm, (int)((intptr_t)p - (intptr_t)_print_nm),
2314 (void *)(*p), (intptr_t)p);
2315 (*p)->print();
2316 }
2317 #endif //PRODUCT
2318 };
2320 bool nmethod::detect_scavenge_root_oops() {
2321 DetectScavengeRoot detect_scavenge_root;
2322 NOT_PRODUCT(if (TraceScavenge) detect_scavenge_root._print_nm = this);
2323 oops_do(&detect_scavenge_root);
2324 return detect_scavenge_root.detected_scavenge_root();
2325 }
2327 // Method that knows how to preserve outgoing arguments at call. This method must be
2328 // called with a frame corresponding to a Java invoke
2329 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
2330 #ifndef SHARK
2331 if (!method()->is_native()) {
2332 SimpleScopeDesc ssd(this, fr.pc());
2333 Bytecode_invoke call(ssd.method(), ssd.bci());
2334 bool has_receiver = call.has_receiver();
2335 bool has_appendix = call.has_appendix();
2336 Symbol* signature = call.signature();
2337 fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
2338 }
2339 #endif // !SHARK
2340 }
2343 oop nmethod::embeddedOop_at(u_char* p) {
2344 RelocIterator iter(this, p, p + 1);
2345 while (iter.next())
2346 if (iter.type() == relocInfo::oop_type) {
2347 return iter.oop_reloc()->oop_value();
2348 }
2349 return NULL;
2350 }
2353 inline bool includes(void* p, void* from, void* to) {
2354 return from <= p && p < to;
2355 }
2358 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
2359 assert(count >= 2, "must be sentinel values, at least");
2361 #ifdef ASSERT
2362 // must be sorted and unique; we do a binary search in find_pc_desc()
2363 int prev_offset = pcs[0].pc_offset();
2364 assert(prev_offset == PcDesc::lower_offset_limit,
2365 "must start with a sentinel");
2366 for (int i = 1; i < count; i++) {
2367 int this_offset = pcs[i].pc_offset();
2368 assert(this_offset > prev_offset, "offsets must be sorted");
2369 prev_offset = this_offset;
2370 }
2371 assert(prev_offset == PcDesc::upper_offset_limit,
2372 "must end with a sentinel");
2373 #endif //ASSERT
2375 // Search for MethodHandle invokes and tag the nmethod.
2376 for (int i = 0; i < count; i++) {
2377 if (pcs[i].is_method_handle_invoke()) {
2378 set_has_method_handle_invokes(true);
2379 break;
2380 }
2381 }
2382 assert(has_method_handle_invokes() == (_deoptimize_mh_offset != -1), "must have deopt mh handler");
2384 int size = count * sizeof(PcDesc);
2385 assert(scopes_pcs_size() >= size, "oob");
2386 memcpy(scopes_pcs_begin(), pcs, size);
2388 // Adjust the final sentinel downward.
2389 PcDesc* last_pc = &scopes_pcs_begin()[count-1];
2390 assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
2391 last_pc->set_pc_offset(content_size() + 1);
2392 for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
2393 // Fill any rounding gaps with copies of the last record.
2394 last_pc[1] = last_pc[0];
2395 }
2396 // The following assert could fail if sizeof(PcDesc) is not
2397 // an integral multiple of oopSize (the rounding term).
2398 // If it fails, change the logic to always allocate a multiple
2399 // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
2400 assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
2401 }
2403 void nmethod::copy_scopes_data(u_char* buffer, int size) {
2404 assert(scopes_data_size() >= size, "oob");
2405 memcpy(scopes_data_begin(), buffer, size);
2406 }
2409 #ifdef ASSERT
2410 static PcDesc* linear_search(nmethod* nm, int pc_offset, bool approximate) {
2411 PcDesc* lower = nm->scopes_pcs_begin();
2412 PcDesc* upper = nm->scopes_pcs_end();
2413 lower += 1; // exclude initial sentinel
2414 PcDesc* res = NULL;
2415 for (PcDesc* p = lower; p < upper; p++) {
2416 NOT_PRODUCT(--nmethod_stats.pc_desc_tests); // don't count this call to match_desc
2417 if (match_desc(p, pc_offset, approximate)) {
2418 if (res == NULL)
2419 res = p;
2420 else
2421 res = (PcDesc*) badAddress;
2422 }
2423 }
2424 return res;
2425 }
2426 #endif
2429 // Finds a PcDesc with real-pc equal to "pc"
2430 PcDesc* nmethod::find_pc_desc_internal(address pc, bool approximate) {
2431 address base_address = code_begin();
2432 if ((pc < base_address) ||
2433 (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
2434 return NULL; // PC is wildly out of range
2435 }
2436 int pc_offset = (int) (pc - base_address);
2438 // Check the PcDesc cache if it contains the desired PcDesc
2439 // (This as an almost 100% hit rate.)
2440 PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
2441 if (res != NULL) {
2442 assert(res == linear_search(this, pc_offset, approximate), "cache ok");
2443 return res;
2444 }
2446 // Fallback algorithm: quasi-linear search for the PcDesc
2447 // Find the last pc_offset less than the given offset.
2448 // The successor must be the required match, if there is a match at all.
2449 // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
2450 PcDesc* lower = scopes_pcs_begin();
2451 PcDesc* upper = scopes_pcs_end();
2452 upper -= 1; // exclude final sentinel
2453 if (lower >= upper) return NULL; // native method; no PcDescs at all
2455 #define assert_LU_OK \
2456 /* invariant on lower..upper during the following search: */ \
2457 assert(lower->pc_offset() < pc_offset, "sanity"); \
2458 assert(upper->pc_offset() >= pc_offset, "sanity")
2459 assert_LU_OK;
2461 // Use the last successful return as a split point.
2462 PcDesc* mid = _pc_desc_cache.last_pc_desc();
2463 NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
2464 if (mid->pc_offset() < pc_offset) {
2465 lower = mid;
2466 } else {
2467 upper = mid;
2468 }
2470 // Take giant steps at first (4096, then 256, then 16, then 1)
2471 const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1);
2472 const int RADIX = (1 << LOG2_RADIX);
2473 for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
2474 while ((mid = lower + step) < upper) {
2475 assert_LU_OK;
2476 NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
2477 if (mid->pc_offset() < pc_offset) {
2478 lower = mid;
2479 } else {
2480 upper = mid;
2481 break;
2482 }
2483 }
2484 assert_LU_OK;
2485 }
2487 // Sneak up on the value with a linear search of length ~16.
2488 while (true) {
2489 assert_LU_OK;
2490 mid = lower + 1;
2491 NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
2492 if (mid->pc_offset() < pc_offset) {
2493 lower = mid;
2494 } else {
2495 upper = mid;
2496 break;
2497 }
2498 }
2499 #undef assert_LU_OK
2501 if (match_desc(upper, pc_offset, approximate)) {
2502 assert(upper == linear_search(this, pc_offset, approximate), "search ok");
2503 _pc_desc_cache.add_pc_desc(upper);
2504 return upper;
2505 } else {
2506 assert(NULL == linear_search(this, pc_offset, approximate), "search ok");
2507 return NULL;
2508 }
2509 }
2512 bool nmethod::check_all_dependencies() {
2513 bool found_check = false;
2514 // wholesale check of all dependencies
2515 for (Dependencies::DepStream deps(this); deps.next(); ) {
2516 if (deps.check_dependency() != NULL) {
2517 found_check = true;
2518 NOT_DEBUG(break);
2519 }
2520 }
2521 return found_check; // tell caller if we found anything
2522 }
2524 bool nmethod::check_dependency_on(DepChange& changes) {
2525 // What has happened:
2526 // 1) a new class dependee has been added
2527 // 2) dependee and all its super classes have been marked
2528 bool found_check = false; // set true if we are upset
2529 for (Dependencies::DepStream deps(this); deps.next(); ) {
2530 // Evaluate only relevant dependencies.
2531 if (deps.spot_check_dependency_at(changes) != NULL) {
2532 found_check = true;
2533 NOT_DEBUG(break);
2534 }
2535 }
2536 return found_check;
2537 }
2539 bool nmethod::is_evol_dependent_on(Klass* dependee) {
2540 InstanceKlass *dependee_ik = InstanceKlass::cast(dependee);
2541 Array<Method*>* dependee_methods = dependee_ik->methods();
2542 for (Dependencies::DepStream deps(this); deps.next(); ) {
2543 if (deps.type() == Dependencies::evol_method) {
2544 Method* method = deps.method_argument(0);
2545 for (int j = 0; j < dependee_methods->length(); j++) {
2546 if (dependee_methods->at(j) == method) {
2547 // RC_TRACE macro has an embedded ResourceMark
2548 RC_TRACE(0x01000000,
2549 ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on method %s.%s(%s)",
2550 _method->method_holder()->external_name(),
2551 _method->name()->as_C_string(),
2552 _method->signature()->as_C_string(), compile_id(),
2553 method->method_holder()->external_name(),
2554 method->name()->as_C_string(),
2555 method->signature()->as_C_string()));
2556 if (TraceDependencies || LogCompilation)
2557 deps.log_dependency(dependee);
2558 return true;
2559 }
2560 }
2561 }
2562 }
2563 return false;
2564 }
2566 // Called from mark_for_deoptimization, when dependee is invalidated.
2567 bool nmethod::is_dependent_on_method(Method* dependee) {
2568 for (Dependencies::DepStream deps(this); deps.next(); ) {
2569 if (deps.type() != Dependencies::evol_method)
2570 continue;
2571 Method* method = deps.method_argument(0);
2572 if (method == dependee) return true;
2573 }
2574 return false;
2575 }
2578 bool nmethod::is_patchable_at(address instr_addr) {
2579 assert(insts_contains(instr_addr), "wrong nmethod used");
2580 if (is_zombie()) {
2581 // a zombie may never be patched
2582 return false;
2583 }
2584 return true;
2585 }
2588 address nmethod::continuation_for_implicit_exception(address pc) {
2589 // Exception happened outside inline-cache check code => we are inside
2590 // an active nmethod => use cpc to determine a return address
2591 int exception_offset = pc - code_begin();
2592 int cont_offset = ImplicitExceptionTable(this).at( exception_offset );
2593 #ifdef ASSERT
2594 if (cont_offset == 0) {
2595 Thread* thread = ThreadLocalStorage::get_thread_slow();
2596 ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY
2597 HandleMark hm(thread);
2598 ResourceMark rm(thread);
2599 CodeBlob* cb = CodeCache::find_blob(pc);
2600 assert(cb != NULL && cb == this, "");
2601 tty->print_cr("implicit exception happened at " INTPTR_FORMAT, pc);
2602 print();
2603 method()->print_codes();
2604 print_code();
2605 print_pcs();
2606 }
2607 #endif
2608 if (cont_offset == 0) {
2609 // Let the normal error handling report the exception
2610 return NULL;
2611 }
2612 return code_begin() + cont_offset;
2613 }
2617 void nmethod_init() {
2618 // make sure you didn't forget to adjust the filler fields
2619 assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
2620 }
2623 //-------------------------------------------------------------------------------------------
2626 // QQQ might we make this work from a frame??
2627 nmethodLocker::nmethodLocker(address pc) {
2628 CodeBlob* cb = CodeCache::find_blob(pc);
2629 guarantee(cb != NULL && cb->is_nmethod(), "bad pc for a nmethod found");
2630 _nm = (nmethod*)cb;
2631 lock_nmethod(_nm);
2632 }
2634 // Only JvmtiDeferredEvent::compiled_method_unload_event()
2635 // should pass zombie_ok == true.
2636 void nmethodLocker::lock_nmethod(nmethod* nm, bool zombie_ok) {
2637 if (nm == NULL) return;
2638 Atomic::inc(&nm->_lock_count);
2639 guarantee(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method");
2640 }
2642 void nmethodLocker::unlock_nmethod(nmethod* nm) {
2643 if (nm == NULL) return;
2644 Atomic::dec(&nm->_lock_count);
2645 guarantee(nm->_lock_count >= 0, "unmatched nmethod lock/unlock");
2646 }
2649 // -----------------------------------------------------------------------------
2650 // nmethod::get_deopt_original_pc
2651 //
2652 // Return the original PC for the given PC if:
2653 // (a) the given PC belongs to a nmethod and
2654 // (b) it is a deopt PC
2655 address nmethod::get_deopt_original_pc(const frame* fr) {
2656 if (fr->cb() == NULL) return NULL;
2658 nmethod* nm = fr->cb()->as_nmethod_or_null();
2659 if (nm != NULL && nm->is_deopt_pc(fr->pc()))
2660 return nm->get_original_pc(fr);
2662 return NULL;
2663 }
2666 // -----------------------------------------------------------------------------
2667 // MethodHandle
2669 bool nmethod::is_method_handle_return(address return_pc) {
2670 if (!has_method_handle_invokes()) return false;
2671 PcDesc* pd = pc_desc_at(return_pc);
2672 if (pd == NULL)
2673 return false;
2674 return pd->is_method_handle_invoke();
2675 }
2678 // -----------------------------------------------------------------------------
2679 // Verification
2681 class VerifyOopsClosure: public OopClosure {
2682 nmethod* _nm;
2683 bool _ok;
2684 public:
2685 VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
2686 bool ok() { return _ok; }
2687 virtual void do_oop(oop* p) {
2688 if ((*p) == NULL || (*p)->is_oop()) return;
2689 if (_ok) {
2690 _nm->print_nmethod(true);
2691 _ok = false;
2692 }
2693 tty->print_cr("*** non-oop "PTR_FORMAT" found at "PTR_FORMAT" (offset %d)",
2694 (void *)(*p), (intptr_t)p, (int)((intptr_t)p - (intptr_t)_nm));
2695 }
2696 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2697 };
2699 void nmethod::verify() {
2701 // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant
2702 // seems odd.
2704 if( is_zombie() || is_not_entrant() )
2705 return;
2707 // Make sure all the entry points are correctly aligned for patching.
2708 NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::check_verified_entry_alignment(entry_point(), verified_entry_point());
2710 // assert(method()->is_oop(), "must be valid");
2712 ResourceMark rm;
2714 if (!CodeCache::contains(this)) {
2715 fatal(err_msg("nmethod at " INTPTR_FORMAT " not in zone", this));
2716 }
2718 if(is_native_method() )
2719 return;
2721 nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
2722 if (nm != this) {
2723 fatal(err_msg("findNMethod did not find this nmethod (" INTPTR_FORMAT ")",
2724 this));
2725 }
2727 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2728 if (! p->verify(this)) {
2729 tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", this);
2730 }
2731 }
2733 VerifyOopsClosure voc(this);
2734 oops_do(&voc);
2735 assert(voc.ok(), "embedded oops must be OK");
2736 verify_scavenge_root_oops();
2738 verify_scopes();
2739 }
2742 void nmethod::verify_interrupt_point(address call_site) {
2743 // Verify IC only when nmethod installation is finished.
2744 bool is_installed = (method()->code() == this) // nmethod is in state 'in_use' and installed
2745 || !this->is_in_use(); // nmethod is installed, but not in 'in_use' state
2746 if (is_installed) {
2747 Thread *cur = Thread::current();
2748 if (CompiledIC_lock->owner() == cur ||
2749 ((cur->is_VM_thread() || cur->is_ConcurrentGC_thread()) &&
2750 SafepointSynchronize::is_at_safepoint())) {
2751 CompiledIC_at(this, call_site);
2752 CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
2753 } else {
2754 MutexLocker ml_verify (CompiledIC_lock);
2755 CompiledIC_at(this, call_site);
2756 }
2757 }
2759 PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
2760 assert(pd != NULL, "PcDesc must exist");
2761 for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(),
2762 pd->obj_decode_offset(), pd->should_reexecute(),
2763 pd->return_oop());
2764 !sd->is_top(); sd = sd->sender()) {
2765 sd->verify();
2766 }
2767 }
2769 void nmethod::verify_scopes() {
2770 if( !method() ) return; // Runtime stubs have no scope
2771 if (method()->is_native()) return; // Ignore stub methods.
2772 // iterate through all interrupt point
2773 // and verify the debug information is valid.
2774 RelocIterator iter((nmethod*)this);
2775 while (iter.next()) {
2776 address stub = NULL;
2777 switch (iter.type()) {
2778 case relocInfo::virtual_call_type:
2779 verify_interrupt_point(iter.addr());
2780 break;
2781 case relocInfo::opt_virtual_call_type:
2782 stub = iter.opt_virtual_call_reloc()->static_stub();
2783 verify_interrupt_point(iter.addr());
2784 break;
2785 case relocInfo::static_call_type:
2786 stub = iter.static_call_reloc()->static_stub();
2787 //verify_interrupt_point(iter.addr());
2788 break;
2789 case relocInfo::runtime_call_type:
2790 address destination = iter.reloc()->value();
2791 // Right now there is no way to find out which entries support
2792 // an interrupt point. It would be nice if we had this
2793 // information in a table.
2794 break;
2795 }
2796 assert(stub == NULL || stub_contains(stub), "static call stub outside stub section");
2797 }
2798 }
2801 // -----------------------------------------------------------------------------
2802 // Non-product code
2803 #ifndef PRODUCT
2805 class DebugScavengeRoot: public OopClosure {
2806 nmethod* _nm;
2807 bool _ok;
2808 public:
2809 DebugScavengeRoot(nmethod* nm) : _nm(nm), _ok(true) { }
2810 bool ok() { return _ok; }
2811 virtual void do_oop(oop* p) {
2812 if ((*p) == NULL || !(*p)->is_scavengable()) return;
2813 if (_ok) {
2814 _nm->print_nmethod(true);
2815 _ok = false;
2816 }
2817 tty->print_cr("*** scavengable oop "PTR_FORMAT" found at "PTR_FORMAT" (offset %d)",
2818 (void *)(*p), (intptr_t)p, (int)((intptr_t)p - (intptr_t)_nm));
2819 (*p)->print();
2820 }
2821 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2822 };
2824 void nmethod::verify_scavenge_root_oops() {
2825 if (UseG1GC) {
2826 return;
2827 }
2829 if (!on_scavenge_root_list()) {
2830 // Actually look inside, to verify the claim that it's clean.
2831 DebugScavengeRoot debug_scavenge_root(this);
2832 oops_do(&debug_scavenge_root);
2833 if (!debug_scavenge_root.ok())
2834 fatal("found an unadvertised bad scavengable oop in the code cache");
2835 }
2836 assert(scavenge_root_not_marked(), "");
2837 }
2839 #endif // PRODUCT
2841 // Printing operations
2843 void nmethod::print() const {
2844 ResourceMark rm;
2845 ttyLocker ttyl; // keep the following output all in one block
2847 tty->print("Compiled method ");
2849 if (is_compiled_by_c1()) {
2850 tty->print("(c1) ");
2851 } else if (is_compiled_by_c2()) {
2852 tty->print("(c2) ");
2853 } else if (is_compiled_by_shark()) {
2854 tty->print("(shark) ");
2855 } else {
2856 tty->print("(nm) ");
2857 }
2859 print_on(tty, NULL);
2861 if (WizardMode) {
2862 tty->print("((nmethod*) "INTPTR_FORMAT ") ", this);
2863 tty->print(" for method " INTPTR_FORMAT , (address)method());
2864 tty->print(" { ");
2865 if (is_in_use()) tty->print("in_use ");
2866 if (is_not_entrant()) tty->print("not_entrant ");
2867 if (is_zombie()) tty->print("zombie ");
2868 if (is_unloaded()) tty->print("unloaded ");
2869 if (on_scavenge_root_list()) tty->print("scavenge_root ");
2870 tty->print_cr("}:");
2871 }
2872 if (size () > 0) tty->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2873 (address)this,
2874 (address)this + size(),
2875 size());
2876 if (relocation_size () > 0) tty->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2877 relocation_begin(),
2878 relocation_end(),
2879 relocation_size());
2880 if (consts_size () > 0) tty->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2881 consts_begin(),
2882 consts_end(),
2883 consts_size());
2884 if (insts_size () > 0) tty->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2885 insts_begin(),
2886 insts_end(),
2887 insts_size());
2888 if (stub_size () > 0) tty->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2889 stub_begin(),
2890 stub_end(),
2891 stub_size());
2892 if (oops_size () > 0) tty->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2893 oops_begin(),
2894 oops_end(),
2895 oops_size());
2896 if (metadata_size () > 0) tty->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2897 metadata_begin(),
2898 metadata_end(),
2899 metadata_size());
2900 if (scopes_data_size () > 0) tty->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2901 scopes_data_begin(),
2902 scopes_data_end(),
2903 scopes_data_size());
2904 if (scopes_pcs_size () > 0) tty->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2905 scopes_pcs_begin(),
2906 scopes_pcs_end(),
2907 scopes_pcs_size());
2908 if (dependencies_size () > 0) tty->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2909 dependencies_begin(),
2910 dependencies_end(),
2911 dependencies_size());
2912 if (handler_table_size() > 0) tty->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2913 handler_table_begin(),
2914 handler_table_end(),
2915 handler_table_size());
2916 if (nul_chk_table_size() > 0) tty->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2917 nul_chk_table_begin(),
2918 nul_chk_table_end(),
2919 nul_chk_table_size());
2920 }
2922 void nmethod::print_code() {
2923 HandleMark hm;
2924 ResourceMark m;
2925 Disassembler::decode(this);
2926 }
2929 #ifndef PRODUCT
2931 void nmethod::print_scopes() {
2932 // Find the first pc desc for all scopes in the code and print it.
2933 ResourceMark rm;
2934 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2935 if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
2936 continue;
2938 ScopeDesc* sd = scope_desc_at(p->real_pc(this));
2939 sd->print_on(tty, p);
2940 }
2941 }
2943 void nmethod::print_dependencies() {
2944 ResourceMark rm;
2945 ttyLocker ttyl; // keep the following output all in one block
2946 tty->print_cr("Dependencies:");
2947 for (Dependencies::DepStream deps(this); deps.next(); ) {
2948 deps.print_dependency();
2949 Klass* ctxk = deps.context_type();
2950 if (ctxk != NULL) {
2951 if (ctxk->oop_is_instance() && ((InstanceKlass*)ctxk)->is_dependent_nmethod(this)) {
2952 tty->print_cr(" [nmethod<=klass]%s", ctxk->external_name());
2953 }
2954 }
2955 deps.log_dependency(); // put it into the xml log also
2956 }
2957 }
2960 void nmethod::print_relocations() {
2961 ResourceMark m; // in case methods get printed via the debugger
2962 tty->print_cr("relocations:");
2963 RelocIterator iter(this);
2964 iter.print();
2965 if (UseRelocIndex) {
2966 jint* index_end = (jint*)relocation_end() - 1;
2967 jint index_size = *index_end;
2968 jint* index_start = (jint*)( (address)index_end - index_size );
2969 tty->print_cr(" index @" INTPTR_FORMAT ": index_size=%d", index_start, index_size);
2970 if (index_size > 0) {
2971 jint* ip;
2972 for (ip = index_start; ip+2 <= index_end; ip += 2)
2973 tty->print_cr(" (%d %d) addr=" INTPTR_FORMAT " @" INTPTR_FORMAT,
2974 ip[0],
2975 ip[1],
2976 header_end()+ip[0],
2977 relocation_begin()-1+ip[1]);
2978 for (; ip < index_end; ip++)
2979 tty->print_cr(" (%d ?)", ip[0]);
2980 tty->print_cr(" @" INTPTR_FORMAT ": index_size=%d", ip, *ip);
2981 ip++;
2982 tty->print_cr("reloc_end @" INTPTR_FORMAT ":", ip);
2983 }
2984 }
2985 }
2988 void nmethod::print_pcs() {
2989 ResourceMark m; // in case methods get printed via debugger
2990 tty->print_cr("pc-bytecode offsets:");
2991 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2992 p->print(this);
2993 }
2994 }
2996 #endif // PRODUCT
2998 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
2999 RelocIterator iter(this, begin, end);
3000 bool have_one = false;
3001 while (iter.next()) {
3002 have_one = true;
3003 switch (iter.type()) {
3004 case relocInfo::none: return "no_reloc";
3005 case relocInfo::oop_type: {
3006 stringStream st;
3007 oop_Relocation* r = iter.oop_reloc();
3008 oop obj = r->oop_value();
3009 st.print("oop(");
3010 if (obj == NULL) st.print("NULL");
3011 else obj->print_value_on(&st);
3012 st.print(")");
3013 return st.as_string();
3014 }
3015 case relocInfo::metadata_type: {
3016 stringStream st;
3017 metadata_Relocation* r = iter.metadata_reloc();
3018 Metadata* obj = r->metadata_value();
3019 st.print("metadata(");
3020 if (obj == NULL) st.print("NULL");
3021 else obj->print_value_on(&st);
3022 st.print(")");
3023 return st.as_string();
3024 }
3025 case relocInfo::virtual_call_type: return "virtual_call";
3026 case relocInfo::opt_virtual_call_type: return "optimized virtual_call";
3027 case relocInfo::static_call_type: return "static_call";
3028 case relocInfo::static_stub_type: return "static_stub";
3029 case relocInfo::runtime_call_type: return "runtime_call";
3030 case relocInfo::external_word_type: return "external_word";
3031 case relocInfo::internal_word_type: return "internal_word";
3032 case relocInfo::section_word_type: return "section_word";
3033 case relocInfo::poll_type: return "poll";
3034 case relocInfo::poll_return_type: return "poll_return";
3035 case relocInfo::type_mask: return "type_bit_mask";
3036 }
3037 }
3038 return have_one ? "other" : NULL;
3039 }
3041 // Return a the last scope in (begin..end]
3042 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
3043 PcDesc* p = pc_desc_near(begin+1);
3044 if (p != NULL && p->real_pc(this) <= end) {
3045 return new ScopeDesc(this, p->scope_decode_offset(),
3046 p->obj_decode_offset(), p->should_reexecute(),
3047 p->return_oop());
3048 }
3049 return NULL;
3050 }
3052 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const {
3053 if (block_begin == entry_point()) stream->print_cr("[Entry Point]");
3054 if (block_begin == verified_entry_point()) stream->print_cr("[Verified Entry Point]");
3055 if (block_begin == exception_begin()) stream->print_cr("[Exception Handler]");
3056 if (block_begin == stub_begin()) stream->print_cr("[Stub Code]");
3057 if (block_begin == deopt_handler_begin()) stream->print_cr("[Deopt Handler Code]");
3059 if (has_method_handle_invokes())
3060 if (block_begin == deopt_mh_handler_begin()) stream->print_cr("[Deopt MH Handler Code]");
3062 if (block_begin == consts_begin()) stream->print_cr("[Constants]");
3064 if (block_begin == entry_point()) {
3065 methodHandle m = method();
3066 if (m.not_null()) {
3067 stream->print(" # ");
3068 m->print_value_on(stream);
3069 stream->cr();
3070 }
3071 if (m.not_null() && !is_osr_method()) {
3072 ResourceMark rm;
3073 int sizeargs = m->size_of_parameters();
3074 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
3075 VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
3076 {
3077 int sig_index = 0;
3078 if (!m->is_static())
3079 sig_bt[sig_index++] = T_OBJECT; // 'this'
3080 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {
3081 BasicType t = ss.type();
3082 sig_bt[sig_index++] = t;
3083 if (type2size[t] == 2) {
3084 sig_bt[sig_index++] = T_VOID;
3085 } else {
3086 assert(type2size[t] == 1, "size is 1 or 2");
3087 }
3088 }
3089 assert(sig_index == sizeargs, "");
3090 }
3091 const char* spname = "sp"; // make arch-specific?
3092 intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false);
3093 int stack_slot_offset = this->frame_size() * wordSize;
3094 int tab1 = 14, tab2 = 24;
3095 int sig_index = 0;
3096 int arg_index = (m->is_static() ? 0 : -1);
3097 bool did_old_sp = false;
3098 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {
3099 bool at_this = (arg_index == -1);
3100 bool at_old_sp = false;
3101 BasicType t = (at_this ? T_OBJECT : ss.type());
3102 assert(t == sig_bt[sig_index], "sigs in sync");
3103 if (at_this)
3104 stream->print(" # this: ");
3105 else
3106 stream->print(" # parm%d: ", arg_index);
3107 stream->move_to(tab1);
3108 VMReg fst = regs[sig_index].first();
3109 VMReg snd = regs[sig_index].second();
3110 if (fst->is_reg()) {
3111 stream->print("%s", fst->name());
3112 if (snd->is_valid()) {
3113 stream->print(":%s", snd->name());
3114 }
3115 } else if (fst->is_stack()) {
3116 int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
3117 if (offset == stack_slot_offset) at_old_sp = true;
3118 stream->print("[%s+0x%x]", spname, offset);
3119 } else {
3120 stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
3121 }
3122 stream->print(" ");
3123 stream->move_to(tab2);
3124 stream->print("= ");
3125 if (at_this) {
3126 m->method_holder()->print_value_on(stream);
3127 } else {
3128 bool did_name = false;
3129 if (!at_this && ss.is_object()) {
3130 Symbol* name = ss.as_symbol_or_null();
3131 if (name != NULL) {
3132 name->print_value_on(stream);
3133 did_name = true;
3134 }
3135 }
3136 if (!did_name)
3137 stream->print("%s", type2name(t));
3138 }
3139 if (at_old_sp) {
3140 stream->print(" (%s of caller)", spname);
3141 did_old_sp = true;
3142 }
3143 stream->cr();
3144 sig_index += type2size[t];
3145 arg_index += 1;
3146 if (!at_this) ss.next();
3147 }
3148 if (!did_old_sp) {
3149 stream->print(" # ");
3150 stream->move_to(tab1);
3151 stream->print("[%s+0x%x]", spname, stack_slot_offset);
3152 stream->print(" (%s of caller)", spname);
3153 stream->cr();
3154 }
3155 }
3156 }
3157 }
3159 void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, u_char* end) {
3160 // First, find an oopmap in (begin, end].
3161 // We use the odd half-closed interval so that oop maps and scope descs
3162 // which are tied to the byte after a call are printed with the call itself.
3163 address base = code_begin();
3164 OopMapSet* oms = oop_maps();
3165 if (oms != NULL) {
3166 for (int i = 0, imax = oms->size(); i < imax; i++) {
3167 OopMap* om = oms->at(i);
3168 address pc = base + om->offset();
3169 if (pc > begin) {
3170 if (pc <= end) {
3171 st->move_to(column);
3172 st->print("; ");
3173 om->print_on(st);
3174 }
3175 break;
3176 }
3177 }
3178 }
3180 // Print any debug info present at this pc.
3181 ScopeDesc* sd = scope_desc_in(begin, end);
3182 if (sd != NULL) {
3183 st->move_to(column);
3184 if (sd->bci() == SynchronizationEntryBCI) {
3185 st->print(";*synchronization entry");
3186 } else {
3187 if (sd->method() == NULL) {
3188 st->print("method is NULL");
3189 } else if (sd->method()->is_native()) {
3190 st->print("method is native");
3191 } else {
3192 Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
3193 st->print(";*%s", Bytecodes::name(bc));
3194 switch (bc) {
3195 case Bytecodes::_invokevirtual:
3196 case Bytecodes::_invokespecial:
3197 case Bytecodes::_invokestatic:
3198 case Bytecodes::_invokeinterface:
3199 {
3200 Bytecode_invoke invoke(sd->method(), sd->bci());
3201 st->print(" ");
3202 if (invoke.name() != NULL)
3203 invoke.name()->print_symbol_on(st);
3204 else
3205 st->print("<UNKNOWN>");
3206 break;
3207 }
3208 case Bytecodes::_getfield:
3209 case Bytecodes::_putfield:
3210 case Bytecodes::_getstatic:
3211 case Bytecodes::_putstatic:
3212 {
3213 Bytecode_field field(sd->method(), sd->bci());
3214 st->print(" ");
3215 if (field.name() != NULL)
3216 field.name()->print_symbol_on(st);
3217 else
3218 st->print("<UNKNOWN>");
3219 }
3220 }
3221 }
3222 }
3224 // Print all scopes
3225 for (;sd != NULL; sd = sd->sender()) {
3226 st->move_to(column);
3227 st->print("; -");
3228 if (sd->method() == NULL) {
3229 st->print("method is NULL");
3230 } else {
3231 sd->method()->print_short_name(st);
3232 }
3233 int lineno = sd->method()->line_number_from_bci(sd->bci());
3234 if (lineno != -1) {
3235 st->print("@%d (line %d)", sd->bci(), lineno);
3236 } else {
3237 st->print("@%d", sd->bci());
3238 }
3239 st->cr();
3240 }
3241 }
3243 // Print relocation information
3244 const char* str = reloc_string_for(begin, end);
3245 if (str != NULL) {
3246 if (sd != NULL) st->cr();
3247 st->move_to(column);
3248 st->print("; {%s}", str);
3249 }
3250 int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin());
3251 if (cont_offset != 0) {
3252 st->move_to(column);
3253 st->print("; implicit exception: dispatches to " INTPTR_FORMAT, code_begin() + cont_offset);
3254 }
3256 }
3258 #ifndef PRODUCT
3260 void nmethod::print_value_on(outputStream* st) const {
3261 st->print("nmethod");
3262 print_on(st, NULL);
3263 }
3265 void nmethod::print_calls(outputStream* st) {
3266 RelocIterator iter(this);
3267 while (iter.next()) {
3268 switch (iter.type()) {
3269 case relocInfo::virtual_call_type:
3270 case relocInfo::opt_virtual_call_type: {
3271 VerifyMutexLocker mc(CompiledIC_lock);
3272 CompiledIC_at(&iter)->print();
3273 break;
3274 }
3275 case relocInfo::static_call_type:
3276 st->print_cr("Static call at " INTPTR_FORMAT, iter.reloc()->addr());
3277 compiledStaticCall_at(iter.reloc())->print();
3278 break;
3279 }
3280 }
3281 }
3283 void nmethod::print_handler_table() {
3284 ExceptionHandlerTable(this).print();
3285 }
3287 void nmethod::print_nul_chk_table() {
3288 ImplicitExceptionTable(this).print(code_begin());
3289 }
3291 void nmethod::print_statistics() {
3292 ttyLocker ttyl;
3293 if (xtty != NULL) xtty->head("statistics type='nmethod'");
3294 nmethod_stats.print_native_nmethod_stats();
3295 nmethod_stats.print_nmethod_stats();
3296 DebugInformationRecorder::print_statistics();
3297 nmethod_stats.print_pc_stats();
3298 Dependencies::print_statistics();
3299 if (xtty != NULL) xtty->tail("statistics");
3300 }
3302 #endif // PRODUCT