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