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