nmethod.cpp 115.6 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27
#include "precompiled.hpp"
#include "code/codeCache.hpp"
#include "code/compiledIC.hpp"
28
#include "code/dependencies.hpp"
29 30 31
#include "code/nmethod.hpp"
#include "code/scopeDesc.hpp"
#include "compiler/abstractCompiler.hpp"
32
#include "compiler/compileBroker.hpp"
33 34 35 36
#include "compiler/compileLog.hpp"
#include "compiler/compilerOracle.hpp"
#include "compiler/disassembler.hpp"
#include "interpreter/bytecode.hpp"
K
Kuai Wei 已提交
37
#include "jwarmup/jitWarmUp.hpp"
38
#include "oops/methodData.hpp"
39
#include "prims/jvmtiRedefineClassesTrace.hpp"
40
#include "prims/jvmtiImpl.hpp"
41
#include "runtime/orderAccess.inline.hpp"
42 43 44 45 46 47 48 49
#include "runtime/sharedRuntime.hpp"
#include "runtime/sweeper.hpp"
#include "utilities/dtrace.hpp"
#include "utilities/events.hpp"
#include "utilities/xmlstream.hpp"
#ifdef SHARK
#include "shark/sharkCompiler.hpp"
#endif
D
duke 已提交
50

51 52
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC

53 54
unsigned char nmethod::_global_unloading_clock = 0;

D
duke 已提交
55 56 57 58
#ifdef DTRACE_ENABLED

// Only bother with this argument setup if dtrace is available

D
dcubed 已提交
59
#ifndef USDT2
D
duke 已提交
60 61 62 63 64 65 66 67
HS_DTRACE_PROBE_DECL8(hotspot, compiled__method__load,
  const char*, int, const char*, int, const char*, int, void*, size_t);

HS_DTRACE_PROBE_DECL6(hotspot, compiled__method__unload,
  char*, int, char*, int, char*, int);

#define DTRACE_METHOD_UNLOAD_PROBE(method)                                \
  {                                                                       \
68
    Method* m = (method);                                                 \
D
duke 已提交
69
    if (m != NULL) {                                                      \
70 71 72
      Symbol* klass_name = m->klass_name();                               \
      Symbol* name = m->name();                                           \
      Symbol* signature = m->signature();                                 \
D
duke 已提交
73 74 75 76 77 78
      HS_DTRACE_PROBE6(hotspot, compiled__method__unload,                 \
        klass_name->bytes(), klass_name->utf8_length(),                   \
        name->bytes(), name->utf8_length(),                               \
        signature->bytes(), signature->utf8_length());                    \
    }                                                                     \
  }
D
dcubed 已提交
79 80 81
#else /* USDT2 */
#define DTRACE_METHOD_UNLOAD_PROBE(method)                                \
  {                                                                       \
82
    Method* m = (method);                                                 \
D
dcubed 已提交
83 84 85 86 87 88 89 90 91 92 93
    if (m != NULL) {                                                      \
      Symbol* klass_name = m->klass_name();                               \
      Symbol* name = m->name();                                           \
      Symbol* signature = m->signature();                                 \
      HOTSPOT_COMPILED_METHOD_UNLOAD(                                     \
        (char *) klass_name->bytes(), klass_name->utf8_length(),                   \
        (char *) name->bytes(), name->utf8_length(),                               \
        (char *) signature->bytes(), signature->utf8_length());                    \
    }                                                                     \
  }
#endif /* USDT2 */
D
duke 已提交
94 95 96 97 98 99 100 101

#else //  ndef DTRACE_ENABLED

#define DTRACE_METHOD_UNLOAD_PROBE(method)

#endif

bool nmethod::is_compiled_by_c1() const {
102 103 104
  if (compiler() == NULL) {
    return false;
  }
D
duke 已提交
105 106 107
  return compiler()->is_c1();
}
bool nmethod::is_compiled_by_c2() const {
108 109 110
  if (compiler() == NULL) {
    return false;
  }
D
duke 已提交
111 112
  return compiler()->is_c2();
}
113
bool nmethod::is_compiled_by_shark() const {
114 115 116
  if (compiler() == NULL) {
    return false;
  }
117 118
  return compiler()->is_shark();
}
D
duke 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135



//---------------------------------------------------------------------------------
// NMethod statistics
// They are printed under various flags, including:
//   PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.
// (In the latter two cases, they like other stats are printed to the log only.)

#ifndef PRODUCT
// These variables are put into one block to reduce relocations
// and make it simpler to print from the debugger.
static
struct nmethod_stats_struct {
  int nmethod_count;
  int total_size;
  int relocation_size;
136
  int consts_size;
T
twisti 已提交
137
  int insts_size;
D
duke 已提交
138 139 140 141 142 143 144 145 146 147 148 149
  int stub_size;
  int scopes_data_size;
  int scopes_pcs_size;
  int dependencies_size;
  int handler_table_size;
  int nul_chk_table_size;
  int oops_size;

  void note_nmethod(nmethod* nm) {
    nmethod_count += 1;
    total_size          += nm->size();
    relocation_size     += nm->relocation_size();
150
    consts_size         += nm->consts_size();
T
twisti 已提交
151
    insts_size          += nm->insts_size();
D
duke 已提交
152
    stub_size           += nm->stub_size();
153
    oops_size           += nm->oops_size();
D
duke 已提交
154 155 156 157 158 159 160 161 162 163 164
    scopes_data_size    += nm->scopes_data_size();
    scopes_pcs_size     += nm->scopes_pcs_size();
    dependencies_size   += nm->dependencies_size();
    handler_table_size  += nm->handler_table_size();
    nul_chk_table_size  += nm->nul_chk_table_size();
  }
  void print_nmethod_stats() {
    if (nmethod_count == 0)  return;
    tty->print_cr("Statistics for %d bytecoded nmethods:", nmethod_count);
    if (total_size != 0)          tty->print_cr(" total in heap  = %d", total_size);
    if (relocation_size != 0)     tty->print_cr(" relocation     = %d", relocation_size);
165
    if (consts_size != 0)         tty->print_cr(" constants      = %d", consts_size);
T
twisti 已提交
166
    if (insts_size != 0)          tty->print_cr(" main code      = %d", insts_size);
D
duke 已提交
167
    if (stub_size != 0)           tty->print_cr(" stub code      = %d", stub_size);
168
    if (oops_size != 0)           tty->print_cr(" oops           = %d", oops_size);
D
duke 已提交
169 170 171 172 173 174 175 176 177 178
    if (scopes_data_size != 0)    tty->print_cr(" scopes data    = %d", scopes_data_size);
    if (scopes_pcs_size != 0)     tty->print_cr(" scopes pcs     = %d", scopes_pcs_size);
    if (dependencies_size != 0)   tty->print_cr(" dependencies   = %d", dependencies_size);
    if (handler_table_size != 0)  tty->print_cr(" handler table  = %d", handler_table_size);
    if (nul_chk_table_size != 0)  tty->print_cr(" nul chk table  = %d", nul_chk_table_size);
  }

  int native_nmethod_count;
  int native_total_size;
  int native_relocation_size;
T
twisti 已提交
179
  int native_insts_size;
D
duke 已提交
180 181 182 183 184
  int native_oops_size;
  void note_native_nmethod(nmethod* nm) {
    native_nmethod_count += 1;
    native_total_size       += nm->size();
    native_relocation_size  += nm->relocation_size();
T
twisti 已提交
185
    native_insts_size       += nm->insts_size();
D
duke 已提交
186 187 188 189 190 191 192
    native_oops_size        += nm->oops_size();
  }
  void print_native_nmethod_stats() {
    if (native_nmethod_count == 0)  return;
    tty->print_cr("Statistics for %d native nmethods:", native_nmethod_count);
    if (native_total_size != 0)       tty->print_cr(" N. total size  = %d", native_total_size);
    if (native_relocation_size != 0)  tty->print_cr(" N. relocation  = %d", native_relocation_size);
T
twisti 已提交
193
    if (native_insts_size != 0)       tty->print_cr(" N. main code   = %d", native_insts_size);
D
duke 已提交
194 195 196 197 198 199
    if (native_oops_size != 0)        tty->print_cr(" N. oops        = %d", native_oops_size);
  }

  int pc_desc_resets;   // number of resets (= number of caches)
  int pc_desc_queries;  // queries to nmethod::find_pc_desc
  int pc_desc_approx;   // number of those which have approximate true
200
  int pc_desc_repeats;  // number of _pc_descs[0] hits
D
duke 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
  int pc_desc_hits;     // number of LRU cache hits
  int pc_desc_tests;    // total number of PcDesc examinations
  int pc_desc_searches; // total number of quasi-binary search steps
  int pc_desc_adds;     // number of LUR cache insertions

  void print_pc_stats() {
    tty->print_cr("PcDesc Statistics:  %d queries, %.2f comparisons per query",
                  pc_desc_queries,
                  (double)(pc_desc_tests + pc_desc_searches)
                  / pc_desc_queries);
    tty->print_cr("  caches=%d queries=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d",
                  pc_desc_resets,
                  pc_desc_queries, pc_desc_approx,
                  pc_desc_repeats, pc_desc_hits,
                  pc_desc_tests, pc_desc_searches, pc_desc_adds);
  }
} nmethod_stats;
#endif //PRODUCT


221
//---------------------------------------------------------------------------------
D
duke 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257


ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {
  assert(pc != NULL, "Must be non null");
  assert(exception.not_null(), "Must be non null");
  assert(handler != NULL, "Must be non null");

  _count = 0;
  _exception_type = exception->klass();
  _next = NULL;

  add_address_and_handler(pc,handler);
}


address ExceptionCache::match(Handle exception, address pc) {
  assert(pc != NULL,"Must be non null");
  assert(exception.not_null(),"Must be non null");
  if (exception->klass() == exception_type()) {
    return (test_address(pc));
  }

  return NULL;
}


bool ExceptionCache::match_exception_with_space(Handle exception) {
  assert(exception.not_null(),"Must be non null");
  if (exception->klass() == exception_type() && count() < cache_size) {
    return true;
  }
  return false;
}


address ExceptionCache::test_address(address addr) {
258 259
  int limit = count();
  for (int i = 0; i < limit; i++) {
D
duke 已提交
260 261 262 263 264 265 266 267 268 269
    if (pc_at(i) == addr) {
      return handler_at(i);
    }
  }
  return NULL;
}


bool ExceptionCache::add_address_and_handler(address addr, address handler) {
  if (test_address(addr) == handler) return true;
270 271 272 273 274

  int index = count();
  if (index < cache_size) {
    set_pc_at(index, addr);
    set_handler_at(index, handler);
D
duke 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    increment_count();
    return true;
  }
  return false;
}


// private method for handling exception cache
// These methods are private, and used to manipulate the exception cache
// directly.
ExceptionCache* nmethod::exception_cache_entry_for_exception(Handle exception) {
  ExceptionCache* ec = exception_cache();
  while (ec != NULL) {
    if (ec->match_exception_with_space(exception)) {
      return ec;
    }
    ec = ec->next();
  }
  return NULL;
}


//-----------------------------------------------------------------------------


// Helper used by both find_pc_desc methods.
static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {
  NOT_PRODUCT(++nmethod_stats.pc_desc_tests);
  if (!approximate)
    return pc->pc_offset() == pc_offset;
  else
    return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset();
}

void PcDescCache::reset_to(PcDesc* initial_pc_desc) {
  if (initial_pc_desc == NULL) {
311
    _pc_descs[0] = NULL; // native method; no PcDescs at all
D
duke 已提交
312 313 314 315 316 317 318 319 320 321 322
    return;
  }
  NOT_PRODUCT(++nmethod_stats.pc_desc_resets);
  // reset the cache by filling it with benign (non-null) values
  assert(initial_pc_desc->pc_offset() < 0, "must be sentinel");
  for (int i = 0; i < cache_size; i++)
    _pc_descs[i] = initial_pc_desc;
}

PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {
  NOT_PRODUCT(++nmethod_stats.pc_desc_queries);
323 324 325 326 327 328 329
  NOT_PRODUCT(if (approximate) ++nmethod_stats.pc_desc_approx);

  // Note: one might think that caching the most recently
  // read value separately would be a win, but one would be
  // wrong.  When many threads are updating it, the cache
  // line it's in would bounce between caches, negating
  // any benefit.
D
duke 已提交
330 331 332 333 334

  // In order to prevent race conditions do not load cache elements
  // repeatedly, but use a local copy:
  PcDesc* res;

335 336 337
  // Step one:  Check the most recently added value.
  res = _pc_descs[0];
  if (res == NULL) return NULL;  // native method; no PcDescs at all
D
duke 已提交
338 339 340 341 342
  if (match_desc(res, pc_offset, approximate)) {
    NOT_PRODUCT(++nmethod_stats.pc_desc_repeats);
    return res;
  }

343 344
  // Step two:  Check the rest of the LRU cache.
  for (int i = 1; i < cache_size; ++i) {
D
duke 已提交
345
    res = _pc_descs[i];
346
    if (res->pc_offset() < 0) break;  // optimization: skip empty cache
D
duke 已提交
347 348 349 350 351 352 353 354 355 356 357 358
    if (match_desc(res, pc_offset, approximate)) {
      NOT_PRODUCT(++nmethod_stats.pc_desc_hits);
      return res;
    }
  }

  // Report failure.
  return NULL;
}

void PcDescCache::add_pc_desc(PcDesc* pc_desc) {
  NOT_PRODUCT(++nmethod_stats.pc_desc_adds);
359
  // Update the LRU cache by shifting pc_desc forward.
D
duke 已提交
360 361 362 363 364 365 366 367 368 369
  for (int i = 0; i < cache_size; i++)  {
    PcDesc* next = _pc_descs[i];
    _pc_descs[i] = pc_desc;
    pc_desc = next;
  }
}

// adjust pcs_size so that it is a multiple of both oopSize and
// sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple
// of oopSize, then 2*sizeof(PcDesc) is)
370
static int adjust_pcs_size(int pcs_size) {
D
duke 已提交
371 372 373 374
  int nsize = round_to(pcs_size,   oopSize);
  if ((nsize % sizeof(PcDesc)) != 0) {
    nsize = pcs_size + sizeof(PcDesc);
  }
375
  assert((nsize % oopSize) == 0, "correct alignment");
D
duke 已提交
376 377 378 379 380 381 382 383 384 385 386
  return nsize;
}

//-----------------------------------------------------------------------------


void nmethod::add_exception_cache_entry(ExceptionCache* new_entry) {
  assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock");
  assert(new_entry != NULL,"Must be non null");
  assert(new_entry->next() == NULL, "Must be null");

387 388 389
  ExceptionCache *ec = exception_cache();
  if (ec != NULL) {
    new_entry->set_next(ec);
D
duke 已提交
390
  }
391
  release_set_exception_cache(new_entry);
D
duke 已提交
392 393
}

394
void nmethod::clean_exception_cache(BoolObjectClosure* is_alive) {
D
duke 已提交
395 396
  ExceptionCache* prev = NULL;
  ExceptionCache* curr = exception_cache();
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414

  while (curr != NULL) {
    ExceptionCache* next = curr->next();

    Klass* ex_klass = curr->exception_type();
    if (ex_klass != NULL && !ex_klass->is_loader_alive(is_alive)) {
      if (prev == NULL) {
        set_exception_cache(next);
      } else {
        prev->set_next(next);
      }
      delete curr;
      // prev stays the same.
    } else {
      prev = curr;
    }

    curr = next;
D
duke 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
  }
}

// public method for accessing the exception cache
// These are the public access methods.
address nmethod::handler_for_exception_and_pc(Handle exception, address pc) {
  // We never grab a lock to read the exception cache, so we may
  // have false negatives. This is okay, as it can only happen during
  // the first few exception lookups for a given nmethod.
  ExceptionCache* ec = exception_cache();
  while (ec != NULL) {
    address ret_val;
    if ((ret_val = ec->match(exception,pc)) != NULL) {
      return ret_val;
    }
    ec = ec->next();
  }
  return NULL;
}


void nmethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
  // There are potential race conditions during exception cache updates, so we
  // must own the ExceptionCache_lock before doing ANY modifications. Because
T
twisti 已提交
439
  // we don't lock during reads, it is possible to have several threads attempt
D
duke 已提交
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
  // to update the cache with the same data. We need to check for already inserted
  // copies of the current data before adding it.

  MutexLocker ml(ExceptionCache_lock);
  ExceptionCache* target_entry = exception_cache_entry_for_exception(exception);

  if (target_entry == NULL || !target_entry->add_address_and_handler(pc,handler)) {
    target_entry = new ExceptionCache(exception,pc,handler);
    add_exception_cache_entry(target_entry);
  }
}


//-------------end of code for ExceptionCache--------------


int nmethod::total_size() const {
  return
458
    consts_size()        +
T
twisti 已提交
459
    insts_size()         +
D
duke 已提交
460 461 462 463 464 465 466 467 468
    stub_size()          +
    scopes_data_size()   +
    scopes_pcs_size()    +
    handler_table_size() +
    nul_chk_table_size();
}

const char* nmethod::compile_kind() const {
  if (is_osr_method())     return "osr";
469
  if (method() != NULL && is_native_method())  return "c2n";
D
duke 已提交
470 471 472
  return NULL;
}

473 474
// Fill in default values for various flag fields
void nmethod::init_defaults() {
K
kvn 已提交
475
  _state                      = in_use;
476
  _unloading_clock            = 0;
477 478 479 480
  _marked_for_reclamation     = 0;
  _has_flushed_dependencies   = 0;
  _has_unsafe_access          = 0;
  _has_method_handle_invokes  = 0;
481
  _lazy_critical_native       = 0;
482
  _has_wide_vectors           = 0;
483 484 485 486 487
  _marked_for_deoptimization  = 0;
  _lock_count                 = 0;
  _stack_traversal_mark       = 0;
  _unload_reported            = false;           // jvmti state

488 489 490 491
#ifdef ASSERT
  _oops_are_stale             = false;
#endif

492 493 494
  _oops_do_mark_link       = NULL;
  _jmethod_id              = NULL;
  _osr_link                = NULL;
495 496 497 498 499
  if (UseG1GC) {
    _unloading_next        = NULL;
  } else {
    _scavenge_root_link    = NULL;
  }
500 501
  _scavenge_root_state     = 0;
  _compiler                = NULL;
502 503 504
#if INCLUDE_RTM_OPT
  _rtm_state               = NoRTM;
#endif
505 506 507 508
#ifdef HAVE_DTRACE_H
  _trap_offset             = 0;
#endif // def HAVE_DTRACE_H
}
D
duke 已提交
509 510

nmethod* nmethod::new_native_nmethod(methodHandle method,
511
  int compile_id,
D
duke 已提交
512 513 514 515 516 517 518
  CodeBuffer *code_buffer,
  int vep_offset,
  int frame_complete,
  int frame_size,
  ByteSize basic_lock_owner_sp_offset,
  ByteSize basic_lock_sp_offset,
  OopMapSet* oop_maps) {
519
  code_buffer->finalize_oop_references(method);
D
duke 已提交
520 521 522 523 524
  // create nmethod
  nmethod* nm = NULL;
  {
    MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
    int native_nmethod_size = allocation_size(code_buffer, sizeof(nmethod));
525 526 527 528 529 530 531 532 533 534 535
    CodeOffsets offsets;
    offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
    offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
    nm = new (native_nmethod_size) nmethod(method(), native_nmethod_size,
                                            compile_id, &offsets,
                                            code_buffer, frame_size,
                                            basic_lock_owner_sp_offset,
                                            basic_lock_sp_offset, oop_maps);
    NOT_PRODUCT(if (nm != NULL)  nmethod_stats.note_native_nmethod(nm));
    if (PrintAssembly && nm != NULL) {
      Disassembler::decode(nm);
536
    }
D
duke 已提交
537 538 539 540 541 542 543 544 545 546 547
  }
  // verify nmethod
  debug_only(if (nm) nm->verify();) // might block

  if (nm != NULL) {
    nm->log_new_nmethod();
  }

  return nm;
}

548 549 550 551 552 553 554
#ifdef HAVE_DTRACE_H
nmethod* nmethod::new_dtrace_nmethod(methodHandle method,
                                     CodeBuffer *code_buffer,
                                     int vep_offset,
                                     int trap_offset,
                                     int frame_complete,
                                     int frame_size) {
555
  code_buffer->finalize_oop_references(method);
556 557 558 559 560
  // create nmethod
  nmethod* nm = NULL;
  {
    MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
    int nmethod_size = allocation_size(code_buffer, sizeof(nmethod));
561 562 563 564 565 566 567 568 569 570 571
    CodeOffsets offsets;
    offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
    offsets.set_value(CodeOffsets::Dtrace_trap, trap_offset);
    offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);

    nm = new (nmethod_size) nmethod(method(), nmethod_size,
                                    &offsets, code_buffer, frame_size);

    NOT_PRODUCT(if (nm != NULL)  nmethod_stats.note_nmethod(nm));
    if (PrintAssembly && nm != NULL) {
      Disassembler::decode(nm);
572
    }
573 574 575 576 577 578 579 580 581 582 583 584 585
  }
  // verify nmethod
  debug_only(if (nm) nm->verify();) // might block

  if (nm != NULL) {
    nm->log_new_nmethod();
  }

  return nm;
}

#endif // def HAVE_DTRACE_H

D
duke 已提交
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
nmethod* nmethod::new_nmethod(methodHandle method,
  int compile_id,
  int entry_bci,
  CodeOffsets* offsets,
  int orig_pc_offset,
  DebugInformationRecorder* debug_info,
  Dependencies* dependencies,
  CodeBuffer* code_buffer, int frame_size,
  OopMapSet* oop_maps,
  ExceptionHandlerTable* handler_table,
  ImplicitExceptionTable* nul_chk_table,
  AbstractCompiler* compiler,
  int comp_level
)
{
  assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
602
  code_buffer->finalize_oop_references(method);
D
duke 已提交
603 604 605 606 607 608 609 610 611 612
  // create nmethod
  nmethod* nm = NULL;
  { MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
    int nmethod_size =
      allocation_size(code_buffer, sizeof(nmethod))
      + adjust_pcs_size(debug_info->pcs_size())
      + round_to(dependencies->size_in_bytes() , oopSize)
      + round_to(handler_table->size_in_bytes(), oopSize)
      + round_to(nul_chk_table->size_in_bytes(), oopSize)
      + round_to(debug_info->data_size()       , oopSize);
613 614 615 616 617 618 619 620 621 622

    nm = new (nmethod_size)
    nmethod(method(), nmethod_size, compile_id, entry_bci, offsets,
            orig_pc_offset, debug_info, dependencies, code_buffer, frame_size,
            oop_maps,
            handler_table,
            nul_chk_table,
            compiler,
            comp_level);

D
duke 已提交
623 624 625 626 627 628 629 630 631 632
    if (nm != NULL) {
      // To make dependency checking during class loading fast, record
      // the nmethod dependencies in the classes it is dependent on.
      // This allows the dependency checking code to simply walk the
      // class hierarchy above the loaded class, checking only nmethods
      // which are dependent on those classes.  The slow way is to
      // check every nmethod for dependencies which makes it linear in
      // the number of methods compiled.  For applications with a lot
      // classes the slow way is too slow.
      for (Dependencies::DepStream deps(nm); deps.next(); ) {
633
        Klass* klass = deps.context_type();
634 635 636
        if (klass == NULL) {
          continue;  // ignore things like evol_method
        }
D
duke 已提交
637 638

        // record this nmethod as dependent on this klass
639
        InstanceKlass::cast(klass)->add_dependent_nmethod(nm);
D
duke 已提交
640
      }
641
      NOT_PRODUCT(nmethod_stats.note_nmethod(nm));
642
      if (PrintAssembly || CompilerOracle::has_option_string(method, "PrintAssembly")) {
643 644
        Disassembler::decode(nm);
      }
645
    }
D
duke 已提交
646
  }
647
  // Do verification and logging outside CodeCache_lock.
D
duke 已提交
648
  if (nm != NULL) {
649 650
    // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
    DEBUG_ONLY(nm->verify();)
D
duke 已提交
651 652
    nm->log_new_nmethod();
  }
K
Kuai Wei 已提交
653 654 655 656
  if (CompilationWarmUpRecording && nm != NULL && comp_level >= CompilationWarmUpRecordMinLevel) {
    int bci = nm->is_osr_method() ? nm->osr_entry_bci() : InvocationEntryBci;
    JitWarmUp::instance()->recorder()->add_method(nm->method(), bci);
  }
D
duke 已提交
657 658 659 660 661 662
  return nm;
}


// For native wrappers
nmethod::nmethod(
663
  Method* method,
D
duke 已提交
664
  int nmethod_size,
665
  int compile_id,
D
duke 已提交
666 667 668 669 670 671 672 673
  CodeOffsets* offsets,
  CodeBuffer* code_buffer,
  int frame_size,
  ByteSize basic_lock_owner_sp_offset,
  ByteSize basic_lock_sp_offset,
  OopMapSet* oop_maps )
  : CodeBlob("native nmethod", code_buffer, sizeof(nmethod),
             nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps),
674 675
  _native_receiver_sp_offset(basic_lock_owner_sp_offset),
  _native_basic_lock_sp_offset(basic_lock_sp_offset)
D
duke 已提交
676 677 678 679 680
{
  {
    debug_only(No_Safepoint_Verifier nsv;)
    assert_locked_or_safepoint(CodeCache_lock);

681
    init_defaults();
D
duke 已提交
682 683 684 685 686 687
    _method                  = method;
    _entry_bci               = InvocationEntryBci;
    // We have no exception handler or deopt handler make the
    // values something that will never match a pc like the nmethod vtable entry
    _exception_offset        = 0;
    _deoptimize_offset       = 0;
688
    _deoptimize_mh_offset    = 0;
D
duke 已提交
689
    _orig_pc_offset          = 0;
690

D
duke 已提交
691
    _consts_offset           = data_offset();
T
twisti 已提交
692
    _stub_offset             = data_offset();
693
    _oops_offset             = data_offset();
694 695
    _metadata_offset         = _oops_offset         + round_to(code_buffer->total_oop_size(), oopSize);
    _scopes_data_offset      = _metadata_offset     + round_to(code_buffer->total_metadata_size(), wordSize);
D
duke 已提交
696 697 698 699 700
    _scopes_pcs_offset       = _scopes_data_offset;
    _dependencies_offset     = _scopes_pcs_offset;
    _handler_table_offset    = _dependencies_offset;
    _nul_chk_table_offset    = _handler_table_offset;
    _nmethod_end_offset      = _nul_chk_table_offset;
701
    _compile_id              = compile_id;
D
duke 已提交
702
    _comp_level              = CompLevel_none;
T
twisti 已提交
703 704
    _entry_point             = code_begin()          + offsets->value(CodeOffsets::Entry);
    _verified_entry_point    = code_begin()          + offsets->value(CodeOffsets::Verified_Entry);
D
duke 已提交
705 706 707
    _osr_entry_point         = NULL;
    _exception_cache         = NULL;
    _pc_desc_cache.reset_to(NULL);
708
    _hotness_counter         = NMethodSweeper::hotness_counter_reset_val();
D
duke 已提交
709

710
    code_buffer->copy_values_to(this);
711 712 713 714
    if (ScavengeRootsInCode) {
      if (detect_scavenge_root_oops()) {
        CodeCache::add_scavenge_root_nmethod(this);
      }
J
johnc 已提交
715
      Universe::heap()->register_nmethod(this);
716
    }
717
    debug_only(verify_scavenge_root_oops());
D
duke 已提交
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
    CodeCache::commit(this);
  }

  if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {
    ttyLocker ttyl;  // keep the following output all in one block
    // This output goes directly to the tty, not the compiler log.
    // To enable tools to match it up with the compilation activity,
    // be sure to tag this tty output with the compile ID.
    if (xtty != NULL) {
      xtty->begin_head("print_native_nmethod");
      xtty->method(_method);
      xtty->stamp();
      xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
    }
    // print the header part first
    print();
    // then print the requested information
    if (PrintNativeNMethods) {
      print_code();
737 738 739
      if (oop_maps != NULL) {
        oop_maps->print();
      }
D
duke 已提交
740 741 742 743 744 745 746 747 748 749
    }
    if (PrintRelocations) {
      print_relocations();
    }
    if (xtty != NULL) {
      xtty->tail("print_native_nmethod");
    }
  }
}

750 751 752
// For dtrace wrappers
#ifdef HAVE_DTRACE_H
nmethod::nmethod(
753
  Method* method,
754 755 756 757 758 759
  int nmethod_size,
  CodeOffsets* offsets,
  CodeBuffer* code_buffer,
  int frame_size)
  : CodeBlob("dtrace nmethod", code_buffer, sizeof(nmethod),
             nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, NULL),
760 761
  _native_receiver_sp_offset(in_ByteSize(-1)),
  _native_basic_lock_sp_offset(in_ByteSize(-1))
762 763 764 765 766
{
  {
    debug_only(No_Safepoint_Verifier nsv;)
    assert_locked_or_safepoint(CodeCache_lock);

767
    init_defaults();
768 769 770 771 772 773
    _method                  = method;
    _entry_bci               = InvocationEntryBci;
    // We have no exception handler or deopt handler make the
    // values something that will never match a pc like the nmethod vtable entry
    _exception_offset        = 0;
    _deoptimize_offset       = 0;
774
    _deoptimize_mh_offset    = 0;
775
    _unwind_handler_offset   = -1;
776 777 778
    _trap_offset             = offsets->value(CodeOffsets::Dtrace_trap);
    _orig_pc_offset          = 0;
    _consts_offset           = data_offset();
T
twisti 已提交
779
    _stub_offset             = data_offset();
780
    _oops_offset             = data_offset();
781 782
    _metadata_offset         = _oops_offset         + round_to(code_buffer->total_oop_size(), oopSize);
    _scopes_data_offset      = _metadata_offset     + round_to(code_buffer->total_metadata_size(), wordSize);
783 784 785 786 787 788 789
    _scopes_pcs_offset       = _scopes_data_offset;
    _dependencies_offset     = _scopes_pcs_offset;
    _handler_table_offset    = _dependencies_offset;
    _nul_chk_table_offset    = _handler_table_offset;
    _nmethod_end_offset      = _nul_chk_table_offset;
    _compile_id              = 0;  // default
    _comp_level              = CompLevel_none;
T
twisti 已提交
790 791
    _entry_point             = code_begin()          + offsets->value(CodeOffsets::Entry);
    _verified_entry_point    = code_begin()          + offsets->value(CodeOffsets::Verified_Entry);
792 793 794
    _osr_entry_point         = NULL;
    _exception_cache         = NULL;
    _pc_desc_cache.reset_to(NULL);
795
    _hotness_counter         = NMethodSweeper::hotness_counter_reset_val();
796

797
    code_buffer->copy_values_to(this);
798 799 800 801
    if (ScavengeRootsInCode) {
      if (detect_scavenge_root_oops()) {
        CodeCache::add_scavenge_root_nmethod(this);
      }
802 803 804
      Universe::heap()->register_nmethod(this);
    }
    DEBUG_ONLY(verify_scavenge_root_oops();)
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
    CodeCache::commit(this);
  }

  if (PrintNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {
    ttyLocker ttyl;  // keep the following output all in one block
    // This output goes directly to the tty, not the compiler log.
    // To enable tools to match it up with the compilation activity,
    // be sure to tag this tty output with the compile ID.
    if (xtty != NULL) {
      xtty->begin_head("print_dtrace_nmethod");
      xtty->method(_method);
      xtty->stamp();
      xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
    }
    // print the header part first
    print();
    // then print the requested information
    if (PrintNMethods) {
      print_code();
    }
    if (PrintRelocations) {
      print_relocations();
    }
    if (xtty != NULL) {
      xtty->tail("print_dtrace_nmethod");
    }
  }
}
#endif // def HAVE_DTRACE_H
D
duke 已提交
834

835
void* nmethod::operator new(size_t size, int nmethod_size) throw() {
836 837
  // Not critical, may return null if there is too little continuous memory
  return CodeCache::allocate(nmethod_size);
D
duke 已提交
838 839 840
}

nmethod::nmethod(
841
  Method* method,
D
duke 已提交
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
  int nmethod_size,
  int compile_id,
  int entry_bci,
  CodeOffsets* offsets,
  int orig_pc_offset,
  DebugInformationRecorder* debug_info,
  Dependencies* dependencies,
  CodeBuffer *code_buffer,
  int frame_size,
  OopMapSet* oop_maps,
  ExceptionHandlerTable* handler_table,
  ImplicitExceptionTable* nul_chk_table,
  AbstractCompiler* compiler,
  int comp_level
  )
  : CodeBlob("nmethod", code_buffer, sizeof(nmethod),
             nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps),
859 860
  _native_receiver_sp_offset(in_ByteSize(-1)),
  _native_basic_lock_sp_offset(in_ByteSize(-1))
D
duke 已提交
861 862 863 864 865 866
{
  assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
  {
    debug_only(No_Safepoint_Verifier nsv;)
    assert_locked_or_safepoint(CodeCache_lock);

867
    init_defaults();
D
duke 已提交
868
    _method                  = method;
869
    _entry_bci               = entry_bci;
D
duke 已提交
870 871 872 873
    _compile_id              = compile_id;
    _comp_level              = comp_level;
    _compiler                = compiler;
    _orig_pc_offset          = orig_pc_offset;
874
    _hotness_counter         = NMethodSweeper::hotness_counter_reset_val();
T
twisti 已提交
875 876

    // Section offsets
877 878
    _consts_offset           = content_offset()      + code_buffer->total_offset_of(code_buffer->consts());
    _stub_offset             = content_offset()      + code_buffer->total_offset_of(code_buffer->stubs());
D
duke 已提交
879 880

    // Exception handler and deopt handler are in the stub section
881 882
    assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set");
    assert(offsets->value(CodeOffsets::Deopt     ) != -1, "must be set");
T
twisti 已提交
883 884
    _exception_offset        = _stub_offset          + offsets->value(CodeOffsets::Exceptions);
    _deoptimize_offset       = _stub_offset          + offsets->value(CodeOffsets::Deopt);
885
    if (offsets->value(CodeOffsets::DeoptMH) != -1) {
886 887 888 889
      _deoptimize_mh_offset  = _stub_offset          + offsets->value(CodeOffsets::DeoptMH);
    } else {
      _deoptimize_mh_offset  = -1;
    }
890
    if (offsets->value(CodeOffsets::UnwindHandler) != -1) {
T
twisti 已提交
891
      _unwind_handler_offset = code_offset()         + offsets->value(CodeOffsets::UnwindHandler);
892
    } else {
T
twisti 已提交
893
      _unwind_handler_offset = -1;
894
    }
T
twisti 已提交
895

896
    _oops_offset             = data_offset();
897 898 899
    _metadata_offset         = _oops_offset          + round_to(code_buffer->total_oop_size(), oopSize);
    _scopes_data_offset      = _metadata_offset      + round_to(code_buffer->total_metadata_size(), wordSize);

900
    _scopes_pcs_offset       = _scopes_data_offset   + round_to(debug_info->data_size       (), oopSize);
D
duke 已提交
901 902 903 904 905
    _dependencies_offset     = _scopes_pcs_offset    + adjust_pcs_size(debug_info->pcs_size());
    _handler_table_offset    = _dependencies_offset  + round_to(dependencies->size_in_bytes (), oopSize);
    _nul_chk_table_offset    = _handler_table_offset + round_to(handler_table->size_in_bytes(), oopSize);
    _nmethod_end_offset      = _nul_chk_table_offset + round_to(nul_chk_table->size_in_bytes(), oopSize);

T
twisti 已提交
906 907 908
    _entry_point             = code_begin()          + offsets->value(CodeOffsets::Entry);
    _verified_entry_point    = code_begin()          + offsets->value(CodeOffsets::Verified_Entry);
    _osr_entry_point         = code_begin()          + offsets->value(CodeOffsets::OSR_Entry);
D
duke 已提交
909 910 911 912
    _exception_cache         = NULL;
    _pc_desc_cache.reset_to(scopes_pcs_begin());

    // Copy contents of ScopeDescRecorder to nmethod
913
    code_buffer->copy_values_to(this);
D
duke 已提交
914 915
    debug_info->copy_to(this);
    dependencies->copy_to(this);
916 917 918 919
    if (ScavengeRootsInCode) {
      if (detect_scavenge_root_oops()) {
        CodeCache::add_scavenge_root_nmethod(this);
      }
J
johnc 已提交
920
      Universe::heap()->register_nmethod(this);
921 922
    }
    debug_only(verify_scavenge_root_oops());
D
duke 已提交
923 924 925 926 927 928 929 930 931 932 933 934 935 936

    CodeCache::commit(this);

    // Copy contents of ExceptionHandlerTable to nmethod
    handler_table->copy_to(this);
    nul_chk_table->copy_to(this);

    // we use the information of entry points to find out if a method is
    // static or non static
    assert(compiler->is_c2() ||
           _method->is_static() == (entry_point() == _verified_entry_point),
           " entry points must be same for static methods and vice versa");
  }

937 938 939
  bool printnmethods = PrintNMethods
    || CompilerOracle::should_print(_method)
    || CompilerOracle::has_option_string(_method, "PrintNMethods");
D
duke 已提交
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
  if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {
    print_nmethod(printnmethods);
  }
}


// Print a short set of xml attributes to identify this nmethod.  The
// output should be embedded in some other element.
void nmethod::log_identity(xmlStream* log) const {
  log->print(" compile_id='%d'", compile_id());
  const char* nm_kind = compile_kind();
  if (nm_kind != NULL)  log->print(" compile_kind='%s'", nm_kind);
  if (compiler() != NULL) {
    log->print(" compiler='%s'", compiler()->name());
  }
I
iveresov 已提交
955 956 957
  if (TieredCompilation) {
    log->print(" level='%d'", comp_level());
  }
D
duke 已提交
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
}


#define LOG_OFFSET(log, name)                    \
  if ((intptr_t)name##_end() - (intptr_t)name##_begin()) \
    log->print(" " XSTR(name) "_offset='%d'"    , \
               (intptr_t)name##_begin() - (intptr_t)this)


void nmethod::log_new_nmethod() const {
  if (LogCompilation && xtty != NULL) {
    ttyLocker ttyl;
    HandleMark hm;
    xtty->begin_elem("nmethod");
    log_identity(xtty);
T
twisti 已提交
973
    xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", code_begin(), size());
D
duke 已提交
974 975 976
    xtty->print(" address='" INTPTR_FORMAT "'", (intptr_t) this);

    LOG_OFFSET(xtty, relocation);
977
    LOG_OFFSET(xtty, consts);
T
twisti 已提交
978
    LOG_OFFSET(xtty, insts);
D
duke 已提交
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
    LOG_OFFSET(xtty, stub);
    LOG_OFFSET(xtty, scopes_data);
    LOG_OFFSET(xtty, scopes_pcs);
    LOG_OFFSET(xtty, dependencies);
    LOG_OFFSET(xtty, handler_table);
    LOG_OFFSET(xtty, nul_chk_table);
    LOG_OFFSET(xtty, oops);

    xtty->method(method());
    xtty->stamp();
    xtty->end_elem();
  }
}

#undef LOG_OFFSET


I
iveresov 已提交
996
// Print out more verbose output usually for a newly created nmethod.
997
void nmethod::print_on(outputStream* st, const char* msg) const {
I
iveresov 已提交
998 999
  if (st != NULL) {
    ttyLocker ttyl;
1000 1001 1002 1003 1004 1005
    if (WizardMode) {
      CompileTask::print_compilation(st, this, msg, /*short_form:*/ true);
      st->print_cr(" (" INTPTR_FORMAT ")", this);
    } else {
      CompileTask::print_compilation(st, this, msg, /*short_form:*/ false);
    }
D
duke 已提交
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
  }
}


void nmethod::print_nmethod(bool printmethod) {
  ttyLocker ttyl;  // keep the following output all in one block
  if (xtty != NULL) {
    xtty->begin_head("print_nmethod");
    xtty->stamp();
    xtty->end_head();
  }
  // print the header part first
  print();
  // then print the requested information
  if (printmethod) {
    print_code();
    print_pcs();
1023 1024 1025
    if (oop_maps()) {
      oop_maps()->print();
    }
D
duke 已提交
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
  }
  if (PrintDebugInfo) {
    print_scopes();
  }
  if (PrintRelocations) {
    print_relocations();
  }
  if (PrintDependencies) {
    print_dependencies();
  }
  if (PrintExceptionHandlers) {
    print_handler_table();
    print_nul_chk_table();
  }
  if (xtty != NULL) {
    xtty->tail("print_nmethod");
  }
}


1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
// Promote one word from an assembly-time handle to a live embedded oop.
inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {
  if (handle == NULL ||
      // As a special case, IC oops are initialized to 1 or -1.
      handle == (jobject) Universe::non_oop_word()) {
    (*dest) = (oop) handle;
  } else {
    (*dest) = JNIHandles::resolve_non_null(handle);
  }
}


1058 1059
// Have to have the same name because it's called by a template
void nmethod::copy_values(GrowableArray<jobject>* array) {
1060
  int length = array->length();
1061
  assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
  oop* dest = oops_begin();
  for (int index = 0 ; index < length; index++) {
    initialize_immediate_oop(&dest[index], array->at(index));
  }

  // Now we can fix up all the oops in the code.  We need to do this
  // in the code because the assembler uses jobjects as placeholders.
  // The code and relocations have already been initialized by the
  // CodeBlob constructor, so it is valid even at this early point to
  // iterate over relocations and patch the code.
  fix_oop_relocations(NULL, NULL, /*initialize_immediates=*/ true);
}

1075 1076 1077 1078 1079 1080 1081 1082
void nmethod::copy_values(GrowableArray<Metadata*>* array) {
  int length = array->length();
  assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough");
  Metadata** dest = metadata_begin();
  for (int index = 0 ; index < length; index++) {
    dest[index] = array->at(index);
  }
}
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116

bool nmethod::is_at_poll_return(address pc) {
  RelocIterator iter(this, pc, pc+1);
  while (iter.next()) {
    if (iter.type() == relocInfo::poll_return_type)
      return true;
  }
  return false;
}


bool nmethod::is_at_poll_or_poll_return(address pc) {
  RelocIterator iter(this, pc, pc+1);
  while (iter.next()) {
    relocInfo::relocType t = iter.type();
    if (t == relocInfo::poll_return_type || t == relocInfo::poll_type)
      return true;
  }
  return false;
}


void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) {
  // re-patch all oop-bearing instructions, just in case some oops moved
  RelocIterator iter(this, begin, end);
  while (iter.next()) {
    if (iter.type() == relocInfo::oop_type) {
      oop_Relocation* reloc = iter.oop_reloc();
      if (initialize_immediates && reloc->oop_is_immediate()) {
        oop* dest = reloc->oop_addr();
        initialize_immediate_oop(dest, (jobject) *dest);
      }
      // Refresh the oop-related bits of this instruction.
      reloc->fix_oop_relocation();
1117 1118 1119
    } else if (iter.type() == relocInfo::metadata_type) {
      metadata_Relocation* reloc = iter.metadata_reloc();
      reloc->fix_metadata_relocation();
1120 1121 1122 1123 1124
    }
  }
}


1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
void nmethod::verify_oop_relocations() {
  // Ensure sure that the code matches the current oop values
  RelocIterator iter(this, NULL, NULL);
  while (iter.next()) {
    if (iter.type() == relocInfo::oop_type) {
      oop_Relocation* reloc = iter.oop_reloc();
      if (!reloc->oop_is_immediate()) {
        reloc->verify_oop_relocation();
      }
    }
  }
}


D
duke 已提交
1139 1140 1141 1142
ScopeDesc* nmethod::scope_desc_at(address pc) {
  PcDesc* pd = pc_desc_at(pc);
  guarantee(pd != NULL, "scope must be present");
  return new ScopeDesc(this, pd->scope_decode_offset(),
1143 1144
                       pd->obj_decode_offset(), pd->should_reexecute(),
                       pd->return_oop());
D
duke 已提交
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
}


void nmethod::clear_inline_caches() {
  assert(SafepointSynchronize::is_at_safepoint(), "cleaning of IC's only allowed at safepoint");
  if (is_zombie()) {
    return;
  }

  RelocIterator iter(this);
  while (iter.next()) {
    iter.reloc()->clear_inline_cache();
  }
}

1160 1161 1162
// Clear ICStubs of all compiled ICs
void nmethod::clear_ic_stubs() {
  assert_locked_or_safepoint(CompiledIC_lock);
1163
  ResourceMark rm;
1164 1165 1166 1167 1168 1169 1170 1171 1172
  RelocIterator iter(this);
  while(iter.next()) {
    if (iter.type() == relocInfo::virtual_call_type) {
      CompiledIC* ic = CompiledIC_at(&iter);
      ic->clear_ic_stub();
    }
  }
}

D
duke 已提交
1173 1174

void nmethod::cleanup_inline_caches() {
1175
  assert_locked_or_safepoint(CompiledIC_lock);
D
duke 已提交
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189

  // If the method is not entrant or zombie then a JMP is plastered over the
  // first few bytes.  If an oop in the old code was there, that oop
  // should not get GC'd.  Skip the first few bytes of oops on
  // not-entrant methods.
  address low_boundary = verified_entry_point();
  if (!is_in_use()) {
    low_boundary += NativeJump::instruction_size;
    // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
    // This means that the low_boundary is going to be a little too high.
    // This shouldn't matter, since oops of non-entrant methods are never used.
    // In fact, why are we bothering to look at oops in a non-entrant method??
  }

1190 1191
  // Find all calls in an nmethod and clear the ones that point to non-entrant,
  // zombie and unloaded nmethods.
D
duke 已提交
1192 1193 1194 1195 1196 1197
  ResourceMark rm;
  RelocIterator iter(this, low_boundary);
  while(iter.next()) {
    switch(iter.type()) {
      case relocInfo::virtual_call_type:
      case relocInfo::opt_virtual_call_type: {
1198
        CompiledIC *ic = CompiledIC_at(&iter);
D
duke 已提交
1199 1200 1201 1202
        // Ok, to lookup references to zombies here
        CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());
        if( cb != NULL && cb->is_nmethod() ) {
          nmethod* nm = (nmethod*)cb;
1203
          // Clean inline caches pointing to zombie, non-entrant and unloaded methods
1204
          if (!nm->is_in_use() || (nm->method()->code() != nm)) ic->set_to_clean(is_alive());
D
duke 已提交
1205 1206 1207 1208 1209 1210 1211 1212
        }
        break;
      }
      case relocInfo::static_call_type: {
        CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());
        CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());
        if( cb != NULL && cb->is_nmethod() ) {
          nmethod* nm = (nmethod*)cb;
1213
          // Clean inline caches pointing to zombie, non-entrant and unloaded methods
1214
          if (!nm->is_in_use() || (nm->method()->code() != nm)) csc->set_to_clean();
D
duke 已提交
1215 1216 1217 1218 1219 1220 1221
        }
        break;
      }
    }
  }
}

1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
void nmethod::verify_clean_inline_caches() {
  assert_locked_or_safepoint(CompiledIC_lock);

  // If the method is not entrant or zombie then a JMP is plastered over the
  // first few bytes.  If an oop in the old code was there, that oop
  // should not get GC'd.  Skip the first few bytes of oops on
  // not-entrant methods.
  address low_boundary = verified_entry_point();
  if (!is_in_use()) {
    low_boundary += NativeJump::instruction_size;
    // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
    // This means that the low_boundary is going to be a little too high.
    // This shouldn't matter, since oops of non-entrant methods are never used.
    // In fact, why are we bothering to look at oops in a non-entrant method??
  }

  ResourceMark rm;
  RelocIterator iter(this, low_boundary);
  while(iter.next()) {
    switch(iter.type()) {
      case relocInfo::virtual_call_type:
      case relocInfo::opt_virtual_call_type: {
        CompiledIC *ic = CompiledIC_at(&iter);
        // Ok, to lookup references to zombies here
        CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());
        if( cb != NULL && cb->is_nmethod() ) {
          nmethod* nm = (nmethod*)cb;
          // Verify that inline caches pointing to both zombie and not_entrant methods are clean
          if (!nm->is_in_use() || (nm->method()->code() != nm)) {
            assert(ic->is_clean(), "IC should be clean");
          }
        }
        break;
      }
      case relocInfo::static_call_type: {
        CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());
        CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());
        if( cb != NULL && cb->is_nmethod() ) {
          nmethod* nm = (nmethod*)cb;
          // Verify that inline caches pointing to both zombie and not_entrant methods are clean
          if (!nm->is_in_use() || (nm->method()->code() != nm)) {
            assert(csc->is_clean(), "IC should be clean");
          }
        }
        break;
      }
    }
  }
}

int nmethod::verify_icholder_relocations() {
  int count = 0;

  RelocIterator iter(this);
  while(iter.next()) {
    if (iter.type() == relocInfo::virtual_call_type) {
      if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc())) {
        CompiledIC *ic = CompiledIC_at(&iter);
        if (TraceCompiledIC) {
          tty->print("noticed icholder " INTPTR_FORMAT " ", p2i(ic->cached_icholder()));
          ic->print();
        }
        assert(ic->cached_icholder() != NULL, "must be non-NULL");
        count++;
      }
    }
  }

  return count;
}

1293
// This is a private interface with the sweeper.
D
duke 已提交
1294
void nmethod::mark_as_seen_on_stack() {
1295
  assert(is_alive(), "Must be an alive method");
1296 1297
  // Set the traversal mark to ensure that the sweeper does 2
  // cleaning passes before moving to zombie.
D
duke 已提交
1298 1299 1300
  set_stack_traversal_mark(NMethodSweeper::traversal_count());
}

1301 1302 1303
// Tell if a non-entrant method can be converted to a zombie (i.e.,
// there are no activations on the stack, not in use by the VM,
// and not in use by the ServiceThread)
1304
bool nmethod::can_convert_to_zombie() {
D
duke 已提交
1305 1306 1307 1308 1309
  assert(is_not_entrant(), "must be a non-entrant method");

  // Since the nmethod sweeper only does partial sweep the sweeper's traversal
  // count can be greater than the stack traversal count before it hits the
  // nmethod for the second time.
1310 1311
  return stack_traversal_mark()+1 < NMethodSweeper::traversal_count() &&
         !is_locked_by_vm();
D
duke 已提交
1312 1313 1314
}

void nmethod::inc_decompile_count() {
I
iveresov 已提交
1315
  if (!is_compiled_by_c2()) return;
D
duke 已提交
1316
  // Could be gated by ProfileTraps, but do not bother...
1317
  Method* m = method();
D
duke 已提交
1318
  if (m == NULL)  return;
1319
  MethodData* mdo = m->method_data();
D
duke 已提交
1320
  if (mdo == NULL)  return;
1321
  // There is a benign race here.  See comments in methodData.hpp.
D
duke 已提交
1322 1323 1324
  mdo->inc_decompile_count();
}

1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
void nmethod::increase_unloading_clock() {
  _global_unloading_clock++;
  if (_global_unloading_clock == 0) {
    // _nmethods are allocated with _unloading_clock == 0,
    // so 0 is never used as a clock value.
    _global_unloading_clock = 1;
  }
}

void nmethod::set_unloading_clock(unsigned char unloading_clock) {
  OrderAccess::release_store((volatile jubyte*)&_unloading_clock, unloading_clock);
}

unsigned char nmethod::unloading_clock() {
  return (unsigned char)OrderAccess::load_acquire((volatile jubyte*)&_unloading_clock);
}

D
duke 已提交
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
void nmethod::make_unloaded(BoolObjectClosure* is_alive, oop cause) {

  post_compiled_method_unload();

  // Since this nmethod is being unloaded, make sure that dependencies
  // recorded in instanceKlasses get flushed and pass non-NULL closure to
  // indicate that this work is being done during a GC.
  assert(Universe::heap()->is_gc_active(), "should only be called during gc");
  assert(is_alive != NULL, "Should be non-NULL");
  // A non-NULL is_alive closure indicates that this is being called during GC.
  flush_dependencies(is_alive);

  // Break cycle between nmethod & method
  if (TraceClassUnloading && WizardMode) {
    tty->print_cr("[Class unloading: Making nmethod " INTPTR_FORMAT
1357
                  " unloadable], Method*(" INTPTR_FORMAT
D
duke 已提交
1358 1359
                  "), cause(" INTPTR_FORMAT ")",
                  this, (address)_method, (address)cause);
1360 1361
    if (!Universe::heap()->is_gc_active())
      cause->klass()->print();
D
duke 已提交
1362
  }
Y
ysr 已提交
1363 1364 1365 1366
  // Unlink the osr method, so we do not look this up again
  if (is_osr_method()) {
    invalidate_osr_method();
  }
1367
  // If _method is already NULL the Method* is about to be unloaded,
D
duke 已提交
1368
  // so we don't have to break the cycle. Note that it is possible to
1369 1370
  // have the Method* live here, in case we unload the nmethod because
  // it is pointing to some oop (other than the Method*) being unloaded.
D
duke 已提交
1371
  if (_method != NULL) {
1372
    // OSR methods point to the Method*, but the Method* does not
D
duke 已提交
1373 1374 1375 1376 1377 1378 1379
    // point back!
    if (_method->code() == this) {
      _method->clear_code(); // Break a cycle
    }
    _method = NULL;            // Clear the method of this dead nmethod
  }
  // Make the class unloaded - i.e., change state and notify sweeper
1380
  assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
D
duke 已提交
1381 1382 1383 1384 1385 1386
  if (is_in_use()) {
    // Transitioning directly from live to unloaded -- so
    // we need to force a cache clean-up; remember this
    // for later on.
    CodeCache::set_needs_cache_clean(true);
  }
1387 1388 1389 1390

  // Unregister must be done before the state change
  Universe::heap()->unregister_nmethod(this);

1391
  _state = unloaded;
D
duke 已提交
1392

1393 1394 1395
  // Log the unloading.
  log_state_change();

1396
  // The Method* is gone at this point
D
duke 已提交
1397 1398
  assert(_method == NULL, "Tautology");

1399
  set_osr_link(NULL);
1400
  NMethodSweeper::report_state_change(this);
D
duke 已提交
1401 1402 1403 1404 1405 1406
}

void nmethod::invalidate_osr_method() {
  assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
  // Remove from list of active nmethods
  if (method() != NULL)
1407
    method()->method_holder()->remove_osr_nmethod(this);
D
duke 已提交
1408 1409 1410 1411
  // Set entry as invalid
  _entry_bci = InvalidOSREntryBci;
}

1412
void nmethod::log_state_change() const {
D
duke 已提交
1413 1414 1415
  if (LogCompilation) {
    if (xtty != NULL) {
      ttyLocker ttyl;  // keep the following output all in one block
1416
      if (_state == unloaded) {
1417 1418 1419 1420 1421
        xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'",
                         os::current_thread_id());
      } else {
        xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s",
                         os::current_thread_id(),
1422
                         (_state == zombie ? " zombie='1'" : ""));
1423
      }
D
duke 已提交
1424 1425 1426 1427 1428
      log_identity(xtty);
      xtty->stamp();
      xtty->end_elem();
    }
  }
1429
  if (PrintCompilation && _state != unloaded) {
1430
    print_on(tty, _state == zombie ? "made zombie" : "made not entrant");
D
duke 已提交
1431 1432 1433
  }
}

1434 1435 1436
/**
 * Common functionality for both make_not_entrant and make_zombie
 */
1437
bool nmethod::make_not_entrant_or_zombie(unsigned int state) {
D
duke 已提交
1438
  assert(state == zombie || state == not_entrant, "must be zombie or not_entrant");
1439
  assert(!is_zombie(), "should not already be a zombie");
D
duke 已提交
1440

1441
  // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below.
D
duke 已提交
1442
  nmethodLocker nml(this);
1443
  methodHandle the_method(method());
1444
  No_Safepoint_Verifier nsv;
D
duke 已提交
1445

J
johnc 已提交
1446 1447 1448 1449 1450 1451 1452
  // during patching, depending on the nmethod state we must notify the GC that
  // code has been unloaded, unregistering it. We cannot do this right while
  // holding the Patching_lock because we need to use the CodeCache_lock. This
  // would be prone to deadlocks.
  // This flag is used to remember whether we need to later lock and unregister.
  bool nmethod_needs_unregister = false;

D
duke 已提交
1453
  {
1454 1455 1456 1457 1458 1459 1460 1461 1462
    // invalidate osr nmethod before acquiring the patching lock since
    // they both acquire leaf locks and we don't want a deadlock.
    // This logic is equivalent to the logic below for patching the
    // verified entry point of regular methods.
    if (is_osr_method()) {
      // this effectively makes the osr nmethod not entrant
      invalidate_osr_method();
    }

D
duke 已提交
1463 1464
    // Enter critical section.  Does not block for safepoint.
    MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
1465

1466
    if (_state == state) {
1467 1468 1469 1470 1471
      // another thread already performed this transition so nothing
      // to do, but return false to indicate this.
      return false;
    }

D
duke 已提交
1472 1473
    // The caller can be calling the method statically or through an inline
    // cache call.
1474
    if (!is_osr_method() && !is_not_entrant()) {
D
duke 已提交
1475 1476 1477 1478
      NativeJump::patch_verified_entry(entry_point(), verified_entry_point(),
                  SharedRuntime::get_handle_wrong_method_stub());
    }

1479 1480 1481 1482 1483
    if (is_in_use()) {
      // It's a true state change, so mark the method as decompiled.
      // Do it only for transition from alive.
      inc_decompile_count();
    }
1484

J
johnc 已提交
1485 1486 1487 1488 1489 1490 1491
    // If the state is becoming a zombie, signal to unregister the nmethod with
    // the heap.
    // This nmethod may have already been unloaded during a full GC.
    if ((state == zombie) && !is_unloaded()) {
      nmethod_needs_unregister = true;
    }

1492 1493 1494 1495 1496 1497 1498 1499 1500
    // Must happen before state change. Otherwise we have a race condition in
    // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately
    // transition its state from 'not_entrant' to 'zombie' without having to wait
    // for stack scanning.
    if (state == not_entrant) {
      mark_as_seen_on_stack();
      OrderAccess::storestore();
    }

D
duke 已提交
1501
    // Change state
1502
    _state = state;
1503 1504 1505 1506

    // Log the transition once
    log_state_change();

1507 1508 1509
    // Remove nmethod from method.
    // We need to check if both the _code and _from_compiled_code_entry_point
    // refer to this nmethod because there is a race in setting these two fields
1510
    // in Method* as seen in bugid 4947125.
1511 1512 1513 1514 1515 1516
    // If the vep() points to the zombie nmethod, the memory for the nmethod
    // could be flushed and the compiler and vtable stubs could still call
    // through it.
    if (method() != NULL && (method()->code() == this ||
                             method()->from_compiled_entry() == verified_entry_point())) {
      HandleMark hm;
1517
      method()->clear_code(false /* already owns Patching_lock */);
1518
    }
D
duke 已提交
1519 1520
  } // leave critical region under Patching_lock

1521 1522 1523 1524 1525
  // When the nmethod becomes zombie it is no longer alive so the
  // dependencies must be flushed.  nmethods in the not_entrant
  // state will be flushed later when the transition to zombie
  // happens or they get unloaded.
  if (state == zombie) {
1526 1527 1528 1529 1530
    {
      // Flushing dependecies must be done before any possible
      // safepoint can sneak in, otherwise the oops used by the
      // dependency logic could have become stale.
      MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
J
johnc 已提交
1531 1532 1533
      if (nmethod_needs_unregister) {
        Universe::heap()->unregister_nmethod(this);
      }
1534 1535
      flush_dependencies(NULL);
    }
1536

1537 1538 1539 1540 1541 1542
    // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload
    // event and it hasn't already been reported for this nmethod then
    // report it now. The event may have been reported earilier if the GC
    // marked it for unloading). JvmtiDeferredEventQueue support means
    // we no longer go to a safepoint here.
    post_compiled_method_unload();
1543 1544 1545 1546 1547 1548

#ifdef ASSERT
    // It's no longer safe to access the oops section since zombie
    // nmethods aren't scanned for GC.
    _oops_are_stale = true;
#endif
1549 1550 1551
     // the Method may be reclaimed by class unloading now that the
     // nmethod is in zombie state
    set_method(NULL);
1552 1553 1554 1555
  } else {
    assert(state == not_entrant, "other cases may need to be handled differently");
  }

D
duke 已提交
1556 1557 1558 1559
  if (TraceCreateZombies) {
    tty->print_cr("nmethod <" INTPTR_FORMAT "> code made %s", this, (state == not_entrant) ? "not entrant" : "zombie");
  }

1560
  NMethodSweeper::report_state_change(this);
1561
  return true;
D
duke 已提交
1562 1563 1564 1565 1566 1567 1568 1569
}

void nmethod::flush() {
  // Note that there are no valid oops in the nmethod anymore.
  assert(is_zombie() || (is_osr_method() && is_unloaded()), "must be a zombie method");
  assert(is_marked_for_reclamation() || (is_osr_method() && is_unloaded()), "must be marked for reclamation");

  assert (!is_locked_by_vm(), "locked methods shouldn't be flushed");
1570
  assert_locked_or_safepoint(CodeCache_lock);
D
duke 已提交
1571 1572

  // completely deallocate this method
1573
  Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, this);
D
duke 已提交
1574
  if (PrintMethodFlushing) {
1575 1576
    tty->print_cr("*flushing nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT "/Free CodeCache:" SIZE_FORMAT "Kb",
        _compile_id, this, CodeCache::nof_blobs(), CodeCache::unallocated_capacity()/1024);
D
duke 已提交
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
  }

  // We need to deallocate any ExceptionCache data.
  // Note that we do not need to grab the nmethod lock for this, it
  // better be thread safe if we're disposing of it!
  ExceptionCache* ec = exception_cache();
  set_exception_cache(NULL);
  while(ec != NULL) {
    ExceptionCache* next = ec->next();
    delete ec;
    ec = next;
  }

1590 1591 1592 1593
  if (on_scavenge_root_list()) {
    CodeCache::drop_scavenge_root_nmethod(this);
  }

1594
#ifdef SHARK
1595
  ((SharkCompiler *) compiler())->free_compiled_method(insts_begin());
1596 1597
#endif // SHARK

D
duke 已提交
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
  ((CodeBlob*)(this))->flush();

  CodeCache::free(this);
}


//
// Notify all classes this nmethod is dependent on that it is no
// longer dependent. This should only be called in two situations.
// First, when a nmethod transitions to a zombie all dependents need
// to be clear.  Since zombification happens at a safepoint there's no
// synchronization issues.  The second place is a little more tricky.
// During phase 1 of mark sweep class unloading may happen and as a
// result some nmethods may get unloaded.  In this case the flushing
// of dependencies must happen during phase 1 since after GC any
// dependencies in the unloaded nmethod won't be updated, so
// traversing the dependency information in unsafe.  In that case this
// function is called with a non-NULL argument and this function only
// notifies instanceKlasses that are reachable

void nmethod::flush_dependencies(BoolObjectClosure* is_alive) {
1619
  assert_locked_or_safepoint(CodeCache_lock);
D
duke 已提交
1620 1621 1622 1623 1624
  assert(Universe::heap()->is_gc_active() == (is_alive != NULL),
  "is_alive is non-NULL if and only if we are called during GC");
  if (!has_flushed_dependencies()) {
    set_has_flushed_dependencies();
    for (Dependencies::DepStream deps(this); deps.next(); ) {
1625
      Klass* klass = deps.context_type();
D
duke 已提交
1626 1627 1628 1629
      if (klass == NULL)  continue;  // ignore things like evol_method

      // During GC the is_alive closure is non-NULL, and is used to
      // determine liveness of dependees that need to be updated.
1630
      if (is_alive == NULL || klass->is_loader_alive(is_alive)) {
1631 1632 1633 1634 1635
        // The GC defers deletion of this entry, since there might be multiple threads
        // iterating over the _dependencies graph. Other call paths are single-threaded
        // and may delete it immediately.
        bool delete_immediately = is_alive == NULL;
        InstanceKlass::cast(klass)->remove_dependent_nmethod(this, delete_immediately);
D
duke 已提交
1636 1637 1638 1639 1640 1641 1642
      }
    }
  }
}


// If this oop is not live, the nmethod can be unloaded.
1643
bool nmethod::can_unload(BoolObjectClosure* is_alive, oop* root, bool unloading_occurred) {
D
duke 已提交
1644 1645 1646 1647 1648
  assert(root != NULL, "just checking");
  oop obj = *root;
  if (obj == NULL || is_alive->do_object_b(obj)) {
      return false;
  }
1649

1650 1651 1652 1653
  // If ScavengeRootsInCode is true, an nmethod might be unloaded
  // simply because one of its constant oops has gone dead.
  // No actual classes need to be unloaded in order for this to occur.
  assert(unloading_occurred || ScavengeRootsInCode, "Inconsistency in unloading");
D
duke 已提交
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
  make_unloaded(is_alive, obj);
  return true;
}

// ------------------------------------------------------------------
// post_compiled_method_load_event
// new method for install_code() path
// Transfer information from compilation to jvmti
void nmethod::post_compiled_method_load_event() {

1664
  Method* moop = method();
D
dcubed 已提交
1665
#ifndef USDT2
D
duke 已提交
1666 1667 1668 1669 1670 1671 1672
  HS_DTRACE_PROBE8(hotspot, compiled__method__load,
      moop->klass_name()->bytes(),
      moop->klass_name()->utf8_length(),
      moop->name()->bytes(),
      moop->name()->utf8_length(),
      moop->signature()->bytes(),
      moop->signature()->utf8_length(),
T
twisti 已提交
1673
      insts_begin(), insts_size());
D
dcubed 已提交
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
#else /* USDT2 */
  HOTSPOT_COMPILED_METHOD_LOAD(
      (char *) moop->klass_name()->bytes(),
      moop->klass_name()->utf8_length(),
      (char *) moop->name()->bytes(),
      moop->name()->utf8_length(),
      (char *) moop->signature()->bytes(),
      moop->signature()->utf8_length(),
      insts_begin(), insts_size());
#endif /* USDT2 */
D
duke 已提交
1684

1685 1686 1687 1688 1689
  if (JvmtiExport::should_post_compiled_method_load() ||
      JvmtiExport::should_post_compiled_method_unload()) {
    get_and_cache_jmethod_id();
  }

D
duke 已提交
1690
  if (JvmtiExport::should_post_compiled_method_load()) {
1691 1692 1693 1694
    // Let the Service thread (which is a real Java thread) post the event
    MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
    JvmtiDeferredEventQueue::enqueue(
      JvmtiDeferredEvent::compiled_method_load_event(this));
D
duke 已提交
1695 1696 1697
  }
}

1698 1699 1700 1701 1702 1703 1704 1705 1706
jmethodID nmethod::get_and_cache_jmethod_id() {
  if (_jmethod_id == NULL) {
    // Cache the jmethod_id since it can no longer be looked up once the
    // method itself has been marked for unloading.
    _jmethod_id = method()->jmethod_id();
  }
  return _jmethod_id;
}

D
duke 已提交
1707
void nmethod::post_compiled_method_unload() {
1708 1709 1710 1711 1712 1713
  if (unload_reported()) {
    // During unloading we transition to unloaded and then to zombie
    // and the unloading is reported during the first transition.
    return;
  }

D
duke 已提交
1714 1715 1716 1717
  assert(_method != NULL && !is_unloaded(), "just checking");
  DTRACE_METHOD_UNLOAD_PROBE(method());

  // If a JVMTI agent has enabled the CompiledMethodUnload event then
1718
  // post the event. Sometime later this nmethod will be made a zombie
1719
  // by the sweeper but the Method* will not be valid at that point.
1720 1721
  // If the _jmethod_id is null then no load event was ever requested
  // so don't bother posting the unload.  The main reason for this is
1722
  // that the jmethodID is a weak reference to the Method* so if
1723 1724 1725
  // it's being unloaded there's no way to look it up since the weak
  // ref will have been cleared.
  if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) {
D
duke 已提交
1726
    assert(!unload_reported(), "already unloaded");
1727
    JvmtiDeferredEvent event =
1728
      JvmtiDeferredEvent::compiled_method_unload_event(this,
1729 1730 1731 1732 1733 1734 1735 1736 1737
          _jmethod_id, insts_begin());
    if (SafepointSynchronize::is_at_safepoint()) {
      // Don't want to take the queueing lock. Add it as pending and
      // it will get enqueued later.
      JvmtiDeferredEventQueue::add_pending_event(event);
    } else {
      MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
      JvmtiDeferredEventQueue::enqueue(event);
    }
D
duke 已提交
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
  }

  // The JVMTI CompiledMethodUnload event can be enabled or disabled at
  // any time. As the nmethod is being unloaded now we mark it has
  // having the unload event reported - this will ensure that we don't
  // attempt to report the event in the unlikely scenario where the
  // event is enabled at the time the nmethod is made a zombie.
  set_unload_reported();
}

1748
void static clean_ic_if_metadata_is_dead(CompiledIC *ic, BoolObjectClosure *is_alive, bool mark_on_stack) {
1749 1750 1751 1752
  if (ic->is_icholder_call()) {
    // The only exception is compiledICHolder oops which may
    // yet be marked below. (We check this further below).
    CompiledICHolder* cichk_oop = ic->cached_icholder();
1753 1754

    if (mark_on_stack) {
D
dbuck 已提交
1755
      Metadata::mark_on_stack(cichk_oop->holder_metadata());
1756 1757 1758
      Metadata::mark_on_stack(cichk_oop->holder_klass());
    }

D
dbuck 已提交
1759
    if (cichk_oop->is_loader_alive(is_alive)) {
1760 1761 1762 1763 1764
      return;
    }
  } else {
    Metadata* ic_oop = ic->cached_metadata();
    if (ic_oop != NULL) {
1765 1766 1767 1768
      if (mark_on_stack) {
        Metadata::mark_on_stack(ic_oop);
      }

1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
      if (ic_oop->is_klass()) {
        if (((Klass*)ic_oop)->is_loader_alive(is_alive)) {
          return;
        }
      } else if (ic_oop->is_method()) {
        if (((Method*)ic_oop)->method_holder()->is_loader_alive(is_alive)) {
          return;
        }
      } else {
        ShouldNotReachHere();
      }
    }
  }

  ic->set_to_clean();
}

D
duke 已提交
1786 1787 1788 1789
// This is called at the end of the strong tracing/marking phase of a
// GC to unload an nmethod if it contains otherwise unreachable
// oops.

1790
void nmethod::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
D
duke 已提交
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
  // Make sure the oop's ready to receive visitors
  assert(!is_zombie() && !is_unloaded(),
         "should not call follow on zombie or unloaded nmethod");

  // If the method is not entrant then a JMP is plastered over the
  // first few bytes.  If an oop in the old code was there, that oop
  // should not get GC'd.  Skip the first few bytes of oops on
  // not-entrant methods.
  address low_boundary = verified_entry_point();
  if (is_not_entrant()) {
    low_boundary += NativeJump::instruction_size;
    // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
    // (See comment above.)
  }

  // The RedefineClasses() API can cause the class unloading invariant
  // to no longer be true. See jvmtiExport.hpp for details.
  // Also, leave a debugging breadcrumb in local flag.
  bool a_class_was_redefined = JvmtiExport::has_redefined_a_class();
  if (a_class_was_redefined) {
    // This set of the unloading_occurred flag is done before the
    // call to post_compiled_method_unload() so that the unloading
    // of this nmethod is reported.
    unloading_occurred = true;
  }

  // Exception cache
1818
  clean_exception_cache(is_alive);
D
duke 已提交
1819 1820 1821 1822 1823 1824 1825 1826 1827

  // If class unloading occurred we first iterate over all inline caches and
  // clear ICs where the cached oop is referring to an unloaded klass or method.
  // The remaining live cached oops will be traversed in the relocInfo::oop_type
  // iteration below.
  if (unloading_occurred) {
    RelocIterator iter(this, low_boundary);
    while(iter.next()) {
      if (iter.type() == relocInfo::virtual_call_type) {
1828
        CompiledIC *ic = CompiledIC_at(&iter);
1829
        clean_ic_if_metadata_is_dead(ic, is_alive, false);
D
duke 已提交
1830 1831 1832 1833 1834
      }
    }
  }

  // Compiled code
1835
  {
D
duke 已提交
1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
  RelocIterator iter(this, low_boundary);
  while (iter.next()) {
    if (iter.type() == relocInfo::oop_type) {
      oop_Relocation* r = iter.oop_reloc();
      // In this loop, we must only traverse those oops directly embedded in
      // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
      assert(1 == (r->oop_is_immediate()) +
                  (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
             "oop must be found in exactly one place");
      if (r->oop_is_immediate() && r->oop_value() != NULL) {
1846
        if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
D
duke 已提交
1847 1848 1849 1850 1851
          return;
        }
      }
    }
  }
1852
  }
D
duke 已提交
1853 1854 1855 1856 1857


  // Scopes
  for (oop* p = oops_begin(); p < oops_end(); p++) {
    if (*p == Universe::non_oop_word())  continue;  // skip non-oops
1858
    if (can_unload(is_alive, p, unloading_occurred)) {
D
duke 已提交
1859 1860 1861 1862
      return;
    }
  }

1863 1864 1865 1866
  // Ensure that all metadata is still alive
  verify_metadata_loaders(low_boundary, is_alive);
}

1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
template <class CompiledICorStaticCall>
static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, BoolObjectClosure *is_alive, nmethod* from) {
  // Ok, to lookup references to zombies here
  CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
  if (cb != NULL && cb->is_nmethod()) {
    nmethod* nm = (nmethod*)cb;

    if (nm->unloading_clock() != nmethod::global_unloading_clock()) {
      // The nmethod has not been processed yet.
      return true;
    }

    // Clean inline caches pointing to both zombie and not_entrant methods
    if (!nm->is_in_use() || (nm->method()->code() != nm)) {
      ic->set_to_clean();
      assert(ic->is_clean(), err_msg("nmethod " PTR_FORMAT "not clean %s", from, from->method()->name_and_sig_as_C_string()));
    }
  }

  return false;
}

static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, BoolObjectClosure *is_alive, nmethod* from) {
  return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), is_alive, from);
}

static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, BoolObjectClosure *is_alive, nmethod* from) {
  return clean_if_nmethod_is_unloaded(csc, csc->destination(), is_alive, from);
}

1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
bool nmethod::unload_if_dead_at(RelocIterator* iter_at_oop, BoolObjectClosure *is_alive, bool unloading_occurred) {
  assert(iter_at_oop->type() == relocInfo::oop_type, "Wrong relocation type");

  oop_Relocation* r = iter_at_oop->oop_reloc();
  // Traverse those oops directly embedded in the code.
  // Other oops (oop_index>0) are seen as part of scopes_oops.
  assert(1 == (r->oop_is_immediate()) +
         (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
         "oop must be found in exactly one place");
  if (r->oop_is_immediate() && r->oop_value() != NULL) {
    // Unload this nmethod if the oop is dead.
    if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
      return true;;
    }
  }

  return false;
}

void nmethod::mark_metadata_on_stack_at(RelocIterator* iter_at_metadata) {
  assert(iter_at_metadata->type() == relocInfo::metadata_type, "Wrong relocation type");

  metadata_Relocation* r = iter_at_metadata->metadata_reloc();
  // In this metadata, we must only follow those metadatas directly embedded in
  // the code.  Other metadatas (oop_index>0) are seen as part of
  // the metadata section below.
  assert(1 == (r->metadata_is_immediate()) +
         (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
         "metadata must be found in exactly one place");
  if (r->metadata_is_immediate() && r->metadata_value() != NULL) {
    Metadata* md = r->metadata_value();
    if (md != _method) Metadata::mark_on_stack(md);
  }
}

void nmethod::mark_metadata_on_stack_non_relocs() {
    // Visit the metadata section
    for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
      if (*p == Universe::non_oop_word() || *p == NULL)  continue;  // skip non-oops
      Metadata* md = *p;
      Metadata::mark_on_stack(md);
    }

    // Visit metadata not embedded in the other places.
    if (_method != NULL) Metadata::mark_on_stack(_method);
}

1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
bool nmethod::do_unloading_parallel(BoolObjectClosure* is_alive, bool unloading_occurred) {
  ResourceMark rm;

  // Make sure the oop's ready to receive visitors
  assert(!is_zombie() && !is_unloaded(),
         "should not call follow on zombie or unloaded nmethod");

  // If the method is not entrant then a JMP is plastered over the
  // first few bytes.  If an oop in the old code was there, that oop
  // should not get GC'd.  Skip the first few bytes of oops on
  // not-entrant methods.
  address low_boundary = verified_entry_point();
  if (is_not_entrant()) {
    low_boundary += NativeJump::instruction_size;
    // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
    // (See comment above.)
  }

  // The RedefineClasses() API can cause the class unloading invariant
  // to no longer be true. See jvmtiExport.hpp for details.
  // Also, leave a debugging breadcrumb in local flag.
  bool a_class_was_redefined = JvmtiExport::has_redefined_a_class();
  if (a_class_was_redefined) {
    // This set of the unloading_occurred flag is done before the
    // call to post_compiled_method_unload() so that the unloading
    // of this nmethod is reported.
    unloading_occurred = true;
  }

1973 1974 1975 1976 1977
  // When class redefinition is used all metadata in the CodeCache has to be recorded,
  // so that unused "previous versions" can be purged. Since walking the CodeCache can
  // be expensive, the "mark on stack" is piggy-backed on this parallel unloading code.
  bool mark_metadata_on_stack = a_class_was_redefined;

1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
  // Exception cache
  clean_exception_cache(is_alive);

  bool is_unloaded = false;
  bool postponed = false;

  RelocIterator iter(this, low_boundary);
  while(iter.next()) {

    switch (iter.type()) {

    case relocInfo::virtual_call_type:
      if (unloading_occurred) {
        // If class unloading occurred we first iterate over all inline caches and
        // clear ICs where the cached oop is referring to an unloaded klass or method.
1993
        clean_ic_if_metadata_is_dead(CompiledIC_at(&iter), is_alive, mark_metadata_on_stack);
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
      }

      postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
      break;

    case relocInfo::opt_virtual_call_type:
      postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
      break;

    case relocInfo::static_call_type:
      postponed |= clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
      break;

    case relocInfo::oop_type:
      if (!is_unloaded) {
2009
        is_unloaded = unload_if_dead_at(&iter, is_alive, unloading_occurred);
2010 2011 2012
      }
      break;

2013 2014 2015 2016
    case relocInfo::metadata_type:
      if (mark_metadata_on_stack) {
        mark_metadata_on_stack_at(&iter);
      }
2017 2018 2019
    }
  }

2020 2021 2022 2023
  if (mark_metadata_on_stack) {
    mark_metadata_on_stack_non_relocs();
  }

2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
  if (is_unloaded) {
    return postponed;
  }

  // Scopes
  for (oop* p = oops_begin(); p < oops_end(); p++) {
    if (*p == Universe::non_oop_word())  continue;  // skip non-oops
    if (can_unload(is_alive, p, unloading_occurred)) {
      is_unloaded = true;
      break;
    }
  }

  if (is_unloaded) {
    return postponed;
  }

  // Ensure that all metadata is still alive
  verify_metadata_loaders(low_boundary, is_alive);

  return postponed;
}

void nmethod::do_unloading_parallel_postponed(BoolObjectClosure* is_alive, bool unloading_occurred) {
  ResourceMark rm;

  // Make sure the oop's ready to receive visitors
  assert(!is_zombie(),
         "should not call follow on zombie nmethod");

  // If the method is not entrant then a JMP is plastered over the
  // first few bytes.  If an oop in the old code was there, that oop
  // should not get GC'd.  Skip the first few bytes of oops on
  // not-entrant methods.
  address low_boundary = verified_entry_point();
  if (is_not_entrant()) {
    low_boundary += NativeJump::instruction_size;
    // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
    // (See comment above.)
  }

  RelocIterator iter(this, low_boundary);
  while(iter.next()) {

    switch (iter.type()) {

    case relocInfo::virtual_call_type:
      clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
      break;

    case relocInfo::opt_virtual_call_type:
      clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
      break;

    case relocInfo::static_call_type:
      clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
      break;
    }
  }
}

2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
#ifdef ASSERT

class CheckClass : AllStatic {
  static BoolObjectClosure* _is_alive;

  // Check class_loader is alive for this bit of metadata.
  static void check_class(Metadata* md) {
    Klass* klass = NULL;
    if (md->is_klass()) {
      klass = ((Klass*)md);
    } else if (md->is_method()) {
      klass = ((Method*)md)->method_holder();
    } else if (md->is_methodData()) {
      klass = ((MethodData*)md)->method()->method_holder();
    } else {
      md->print();
      ShouldNotReachHere();
    }
    assert(klass->is_loader_alive(_is_alive), "must be alive");
  }
 public:
  static void do_check_class(BoolObjectClosure* is_alive, nmethod* nm) {
    assert(SafepointSynchronize::is_at_safepoint(), "this is only ok at safepoint");
    _is_alive = is_alive;
    nm->metadata_do(check_class);
  }
};

// This is called during a safepoint so can use static data
BoolObjectClosure* CheckClass::_is_alive = NULL;
#endif // ASSERT


// Processing of oop references should have been sufficient to keep
// all strong references alive.  Any weak references should have been
// cleared as well.  Visit all the metadata and ensure that it's
// really alive.
void nmethod::verify_metadata_loaders(address low_boundary, BoolObjectClosure* is_alive) {
#ifdef ASSERT
    RelocIterator iter(this, low_boundary);
    while (iter.next()) {
    // static_stub_Relocations may have dangling references to
    // Method*s so trim them out here.  Otherwise it looks like
    // compiled code is maintaining a link to dead metadata.
    address static_call_addr = NULL;
    if (iter.type() == relocInfo::opt_virtual_call_type) {
2131
      CompiledIC* cic = CompiledIC_at(&iter);
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
      if (!cic->is_call_to_interpreted()) {
        static_call_addr = iter.addr();
      }
    } else if (iter.type() == relocInfo::static_call_type) {
      CompiledStaticCall* csc = compiledStaticCall_at(iter.reloc());
      if (!csc->is_call_to_interpreted()) {
        static_call_addr = iter.addr();
      }
    }
    if (static_call_addr != NULL) {
      RelocIterator sciter(this, low_boundary);
      while (sciter.next()) {
        if (sciter.type() == relocInfo::static_stub_type &&
            sciter.static_stub_reloc()->static_call() == static_call_addr) {
          sciter.static_stub_reloc()->clear_inline_cache();
        }
      }
    }
  }
  // Check that the metadata embedded in the nmethod is alive
  CheckClass::do_check_class(is_alive, this);
#endif
}


// Iterate over metadata calling this function.   Used by RedefineClasses
void nmethod::metadata_do(void f(Metadata*)) {
  address low_boundary = verified_entry_point();
  if (is_not_entrant()) {
    low_boundary += NativeJump::instruction_size;
    // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
    // (See comment above.)
  }
D
duke 已提交
2165
  {
2166
    // Visit all immediate references that are embedded in the instruction stream.
D
duke 已提交
2167 2168
    RelocIterator iter(this, low_boundary);
    while (iter.next()) {
2169 2170
      if (iter.type() == relocInfo::metadata_type ) {
        metadata_Relocation* r = iter.metadata_reloc();
2171
        // In this metadata, we must only follow those metadatas directly embedded in
2172 2173 2174 2175 2176 2177 2178
        // the code.  Other metadatas (oop_index>0) are seen as part of
        // the metadata section below.
        assert(1 == (r->metadata_is_immediate()) +
               (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
               "metadata must be found in exactly one place");
        if (r->metadata_is_immediate() && r->metadata_value() != NULL) {
          Metadata* md = r->metadata_value();
2179
          if (md != _method) f(md);
2180
        }
2181 2182
      } else if (iter.type() == relocInfo::virtual_call_type) {
        // Check compiledIC holders associated with this nmethod
2183
        ResourceMark rm;
2184
        CompiledIC *ic = CompiledIC_at(&iter);
2185 2186
        if (ic->is_icholder_call()) {
          CompiledICHolder* cichk = ic->cached_icholder();
D
dbuck 已提交
2187
          f(cichk->holder_metadata());
2188 2189 2190 2191 2192 2193 2194
          f(cichk->holder_klass());
        } else {
          Metadata* ic_oop = ic->cached_metadata();
          if (ic_oop != NULL) {
            f(ic_oop);
          }
        }
2195
      }
D
duke 已提交
2196 2197
    }
  }
2198 2199 2200 2201 2202 2203 2204

  // Visit the metadata section
  for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
    if (*p == Universe::non_oop_word() || *p == NULL)  continue;  // skip non-oops
    Metadata* md = *p;
    f(md);
  }
2205

2206
  // Call function Method*, not embedded in these other places.
2207
  if (_method != NULL) f(_method);
D
duke 已提交
2208 2209
}

J
johnc 已提交
2210
void nmethod::oops_do(OopClosure* f, bool allow_zombie) {
D
duke 已提交
2211
  // make sure the oops ready to receive visitors
J
johnc 已提交
2212 2213
  assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod");
  assert(!is_unloaded(), "should not call follow on unloaded nmethod");
D
duke 已提交
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226

  // If the method is not entrant or zombie then a JMP is plastered over the
  // first few bytes.  If an oop in the old code was there, that oop
  // should not get GC'd.  Skip the first few bytes of oops on
  // not-entrant methods.
  address low_boundary = verified_entry_point();
  if (is_not_entrant()) {
    low_boundary += NativeJump::instruction_size;
    // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
    // (See comment above.)
  }

  RelocIterator iter(this, low_boundary);
Y
ysr 已提交
2227

D
duke 已提交
2228 2229 2230 2231 2232
  while (iter.next()) {
    if (iter.type() == relocInfo::oop_type ) {
      oop_Relocation* r = iter.oop_reloc();
      // In this loop, we must only follow those oops directly embedded in
      // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
Y
ysr 已提交
2233 2234 2235
      assert(1 == (r->oop_is_immediate()) +
                   (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
             "oop must be found in exactly one place");
D
duke 已提交
2236 2237 2238 2239 2240 2241 2242
      if (r->oop_is_immediate() && r->oop_value() != NULL) {
        f->do_oop(r->oop_addr());
      }
    }
  }

  // Scopes
2243
  // This includes oop constants not inlined in the code stream.
D
duke 已提交
2244 2245 2246 2247 2248 2249
  for (oop* p = oops_begin(); p < oops_end(); p++) {
    if (*p == Universe::non_oop_word())  continue;  // skip non-oops
    f->do_oop(p);
  }
}

2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
#define NMETHOD_SENTINEL ((nmethod*)badAddress)

nmethod* volatile nmethod::_oops_do_mark_nmethods;

// An nmethod is "marked" if its _mark_link is set non-null.
// Even if it is the end of the linked list, it will have a non-null link value,
// as long as it is on the list.
// This code must be MP safe, because it is used from parallel GC passes.
bool nmethod::test_set_oops_do_mark() {
  assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called");
  nmethod* observed_mark_link = _oops_do_mark_link;
  if (observed_mark_link == NULL) {
    // Claim this nmethod for this thread to mark.
    observed_mark_link = (nmethod*)
      Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_link, NULL);
    if (observed_mark_link == NULL) {

      // Atomically append this nmethod (now claimed) to the head of the list:
      nmethod* observed_mark_nmethods = _oops_do_mark_nmethods;
      for (;;) {
        nmethod* required_mark_nmethods = observed_mark_nmethods;
        _oops_do_mark_link = required_mark_nmethods;
        observed_mark_nmethods = (nmethod*)
          Atomic::cmpxchg_ptr(this, &_oops_do_mark_nmethods, required_mark_nmethods);
        if (observed_mark_nmethods == required_mark_nmethods)
          break;
      }
      // Mark was clear when we first saw this guy.
2278
      NOT_PRODUCT(if (TraceScavenge)  print_on(tty, "oops_do, mark"));
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
      return false;
    }
  }
  // On fall through, another racing thread marked this nmethod before we did.
  return true;
}

void nmethod::oops_do_marking_prologue() {
  NOT_PRODUCT(if (TraceScavenge)  tty->print_cr("[oops_do_marking_prologue"));
  assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row");
  // We use cmpxchg_ptr instead of regular assignment here because the user
  // may fork a bunch of threads, and we need them all to see the same state.
  void* observed = Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, NULL);
  guarantee(observed == NULL, "no races in this sequential code");
}

void nmethod::oops_do_marking_epilogue() {
  assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row");
  nmethod* cur = _oops_do_mark_nmethods;
  while (cur != NMETHOD_SENTINEL) {
    assert(cur != NULL, "not NULL-terminated");
    nmethod* next = cur->_oops_do_mark_link;
    cur->_oops_do_mark_link = NULL;
2302
    DEBUG_ONLY(cur->verify_oop_relocations());
2303
    NOT_PRODUCT(if (TraceScavenge)  cur->print_on(tty, "oops_do, unmark"));
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
    cur = next;
  }
  void* required = _oops_do_mark_nmethods;
  void* observed = Atomic::cmpxchg_ptr(NULL, &_oops_do_mark_nmethods, required);
  guarantee(observed == required, "no races in this sequential code");
  NOT_PRODUCT(if (TraceScavenge)  tty->print_cr("oops_do_marking_epilogue]"));
}

class DetectScavengeRoot: public OopClosure {
  bool     _detected_scavenge_root;
public:
  DetectScavengeRoot() : _detected_scavenge_root(false)
  { NOT_PRODUCT(_print_nm = NULL); }
  bool detected_scavenge_root() { return _detected_scavenge_root; }
  virtual void do_oop(oop* p) {
    if ((*p) != NULL && (*p)->is_scavengable()) {
      NOT_PRODUCT(maybe_print(p));
      _detected_scavenge_root = true;
    }
  }
  virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }

#ifndef PRODUCT
  nmethod* _print_nm;
  void maybe_print(oop* p) {
    if (_print_nm == NULL)  return;
    if (!_detected_scavenge_root)  _print_nm->print_on(tty, "new scavenge root");
2331
    tty->print_cr("" PTR_FORMAT "[offset=%d] detected scavengable oop " PTR_FORMAT " (found at " PTR_FORMAT ")",
2332
                  _print_nm, (int)((intptr_t)p - (intptr_t)_print_nm),
2333
                  (void *)(*p), (intptr_t)p);
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
    (*p)->print();
  }
#endif //PRODUCT
};

bool nmethod::detect_scavenge_root_oops() {
  DetectScavengeRoot detect_scavenge_root;
  NOT_PRODUCT(if (TraceScavenge)  detect_scavenge_root._print_nm = this);
  oops_do(&detect_scavenge_root);
  return detect_scavenge_root.detected_scavenge_root();
}

D
duke 已提交
2346 2347 2348
// Method that knows how to preserve outgoing arguments at call. This method must be
// called with a frame corresponding to a Java invoke
void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
2349
#ifndef SHARK
D
duke 已提交
2350 2351
  if (!method()->is_native()) {
    SimpleScopeDesc ssd(this, fr.pc());
2352
    Bytecode_invoke call(ssd.method(), ssd.bci());
2353 2354
    bool has_receiver = call.has_receiver();
    bool has_appendix = call.has_appendix();
2355
    Symbol* signature = call.signature();
2356
    fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
D
duke 已提交
2357
  }
2358
#endif // !SHARK
D
duke 已提交
2359 2360 2361 2362
}


oop nmethod::embeddedOop_at(u_char* p) {
2363
  RelocIterator iter(this, p, p + 1);
D
duke 已提交
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
  while (iter.next())
    if (iter.type() == relocInfo::oop_type) {
      return iter.oop_reloc()->oop_value();
    }
  return NULL;
}


inline bool includes(void* p, void* from, void* to) {
  return from <= p && p < to;
}


void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
  assert(count >= 2, "must be sentinel values, at least");

#ifdef ASSERT
  // must be sorted and unique; we do a binary search in find_pc_desc()
  int prev_offset = pcs[0].pc_offset();
  assert(prev_offset == PcDesc::lower_offset_limit,
         "must start with a sentinel");
  for (int i = 1; i < count; i++) {
    int this_offset = pcs[i].pc_offset();
    assert(this_offset > prev_offset, "offsets must be sorted");
    prev_offset = this_offset;
  }
  assert(prev_offset == PcDesc::upper_offset_limit,
         "must end with a sentinel");
#endif //ASSERT

2394 2395 2396 2397 2398 2399 2400
  // Search for MethodHandle invokes and tag the nmethod.
  for (int i = 0; i < count; i++) {
    if (pcs[i].is_method_handle_invoke()) {
      set_has_method_handle_invokes(true);
      break;
    }
  }
2401
  assert(has_method_handle_invokes() == (_deoptimize_mh_offset != -1), "must have deopt mh handler");
2402

D
duke 已提交
2403 2404 2405 2406 2407 2408 2409
  int size = count * sizeof(PcDesc);
  assert(scopes_pcs_size() >= size, "oob");
  memcpy(scopes_pcs_begin(), pcs, size);

  // Adjust the final sentinel downward.
  PcDesc* last_pc = &scopes_pcs_begin()[count-1];
  assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
T
twisti 已提交
2410
  last_pc->set_pc_offset(content_size() + 1);
D
duke 已提交
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
  for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
    // Fill any rounding gaps with copies of the last record.
    last_pc[1] = last_pc[0];
  }
  // The following assert could fail if sizeof(PcDesc) is not
  // an integral multiple of oopSize (the rounding term).
  // If it fails, change the logic to always allocate a multiple
  // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
  assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
}

void nmethod::copy_scopes_data(u_char* buffer, int size) {
  assert(scopes_data_size() >= size, "oob");
  memcpy(scopes_data_begin(), buffer, size);
}


#ifdef ASSERT
static PcDesc* linear_search(nmethod* nm, int pc_offset, bool approximate) {
  PcDesc* lower = nm->scopes_pcs_begin();
  PcDesc* upper = nm->scopes_pcs_end();
  lower += 1; // exclude initial sentinel
  PcDesc* res = NULL;
  for (PcDesc* p = lower; p < upper; p++) {
    NOT_PRODUCT(--nmethod_stats.pc_desc_tests);  // don't count this call to match_desc
    if (match_desc(p, pc_offset, approximate)) {
      if (res == NULL)
        res = p;
      else
        res = (PcDesc*) badAddress;
    }
  }
  return res;
}
#endif


// Finds a PcDesc with real-pc equal to "pc"
PcDesc* nmethod::find_pc_desc_internal(address pc, bool approximate) {
T
twisti 已提交
2450
  address base_address = code_begin();
D
duke 已提交
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
  if ((pc < base_address) ||
      (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
    return NULL;  // PC is wildly out of range
  }
  int pc_offset = (int) (pc - base_address);

  // Check the PcDesc cache if it contains the desired PcDesc
  // (This as an almost 100% hit rate.)
  PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
  if (res != NULL) {
    assert(res == linear_search(this, pc_offset, approximate), "cache ok");
    return res;
  }

  // Fallback algorithm: quasi-linear search for the PcDesc
  // Find the last pc_offset less than the given offset.
  // The successor must be the required match, if there is a match at all.
  // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
  PcDesc* lower = scopes_pcs_begin();
  PcDesc* upper = scopes_pcs_end();
  upper -= 1; // exclude final sentinel
  if (lower >= upper)  return NULL;  // native method; no PcDescs at all

#define assert_LU_OK \
  /* invariant on lower..upper during the following search: */ \
  assert(lower->pc_offset() <  pc_offset, "sanity"); \
  assert(upper->pc_offset() >= pc_offset, "sanity")
  assert_LU_OK;

  // Use the last successful return as a split point.
  PcDesc* mid = _pc_desc_cache.last_pc_desc();
  NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
  if (mid->pc_offset() < pc_offset) {
    lower = mid;
  } else {
    upper = mid;
  }

  // Take giant steps at first (4096, then 256, then 16, then 1)
  const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1);
  const int RADIX = (1 << LOG2_RADIX);
  for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
    while ((mid = lower + step) < upper) {
      assert_LU_OK;
      NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
      if (mid->pc_offset() < pc_offset) {
        lower = mid;
      } else {
        upper = mid;
        break;
      }
    }
    assert_LU_OK;
  }

  // Sneak up on the value with a linear search of length ~16.
  while (true) {
    assert_LU_OK;
    mid = lower + 1;
    NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
    if (mid->pc_offset() < pc_offset) {
      lower = mid;
    } else {
      upper = mid;
      break;
    }
  }
#undef assert_LU_OK

  if (match_desc(upper, pc_offset, approximate)) {
    assert(upper == linear_search(this, pc_offset, approximate), "search ok");
    _pc_desc_cache.add_pc_desc(upper);
    return upper;
  } else {
    assert(NULL == linear_search(this, pc_offset, approximate), "search ok");
    return NULL;
  }
}


bool nmethod::check_all_dependencies() {
  bool found_check = false;
  // wholesale check of all dependencies
  for (Dependencies::DepStream deps(this); deps.next(); ) {
    if (deps.check_dependency() != NULL) {
      found_check = true;
      NOT_DEBUG(break);
    }
  }
  return found_check;  // tell caller if we found anything
}

bool nmethod::check_dependency_on(DepChange& changes) {
  // What has happened:
  // 1) a new class dependee has been added
  // 2) dependee and all its super classes have been marked
  bool found_check = false;  // set true if we are upset
  for (Dependencies::DepStream deps(this); deps.next(); ) {
    // Evaluate only relevant dependencies.
    if (deps.spot_check_dependency_at(changes) != NULL) {
      found_check = true;
      NOT_DEBUG(break);
    }
  }
  return found_check;
}

2558 2559 2560
bool nmethod::is_evol_dependent_on(Klass* dependee) {
  InstanceKlass *dependee_ik = InstanceKlass::cast(dependee);
  Array<Method*>* dependee_methods = dependee_ik->methods();
D
duke 已提交
2561 2562
  for (Dependencies::DepStream deps(this); deps.next(); ) {
    if (deps.type() == Dependencies::evol_method) {
2563
      Method* method = deps.method_argument(0);
D
duke 已提交
2564
      for (int j = 0; j < dependee_methods->length(); j++) {
2565
        if (dependee_methods->at(j) == method) {
D
duke 已提交
2566 2567 2568
          // RC_TRACE macro has an embedded ResourceMark
          RC_TRACE(0x01000000,
            ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on method %s.%s(%s)",
2569
            _method->method_holder()->external_name(),
D
duke 已提交
2570 2571
            _method->name()->as_C_string(),
            _method->signature()->as_C_string(), compile_id(),
2572
            method->method_holder()->external_name(),
D
duke 已提交
2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585
            method->name()->as_C_string(),
            method->signature()->as_C_string()));
          if (TraceDependencies || LogCompilation)
            deps.log_dependency(dependee);
          return true;
        }
      }
    }
  }
  return false;
}

// Called from mark_for_deoptimization, when dependee is invalidated.
2586
bool nmethod::is_dependent_on_method(Method* dependee) {
D
duke 已提交
2587 2588 2589
  for (Dependencies::DepStream deps(this); deps.next(); ) {
    if (deps.type() != Dependencies::evol_method)
      continue;
2590
    Method* method = deps.method_argument(0);
D
duke 已提交
2591 2592 2593 2594 2595 2596 2597
    if (method == dependee) return true;
  }
  return false;
}


bool nmethod::is_patchable_at(address instr_addr) {
T
twisti 已提交
2598
  assert(insts_contains(instr_addr), "wrong nmethod used");
D
duke 已提交
2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
  if (is_zombie()) {
    // a zombie may never be patched
    return false;
  }
  return true;
}


address nmethod::continuation_for_implicit_exception(address pc) {
  // Exception happened outside inline-cache check code => we are inside
  // an active nmethod => use cpc to determine a return address
T
twisti 已提交
2610
  int exception_offset = pc - code_begin();
D
duke 已提交
2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
  int cont_offset = ImplicitExceptionTable(this).at( exception_offset );
#ifdef ASSERT
  if (cont_offset == 0) {
    Thread* thread = ThreadLocalStorage::get_thread_slow();
    ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY
    HandleMark hm(thread);
    ResourceMark rm(thread);
    CodeBlob* cb = CodeCache::find_blob(pc);
    assert(cb != NULL && cb == this, "");
    tty->print_cr("implicit exception happened at " INTPTR_FORMAT, pc);
    print();
    method()->print_codes();
    print_code();
    print_pcs();
  }
#endif
2627 2628 2629 2630
  if (cont_offset == 0) {
    // Let the normal error handling report the exception
    return NULL;
  }
T
twisti 已提交
2631
  return code_begin() + cont_offset;
D
duke 已提交
2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
}



void nmethod_init() {
  // make sure you didn't forget to adjust the filler fields
  assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
}


//-------------------------------------------------------------------------------------------


// QQQ might we make this work from a frame??
nmethodLocker::nmethodLocker(address pc) {
  CodeBlob* cb = CodeCache::find_blob(pc);
  guarantee(cb != NULL && cb->is_nmethod(), "bad pc for a nmethod found");
  _nm = (nmethod*)cb;
  lock_nmethod(_nm);
}

2653 2654 2655
// Only JvmtiDeferredEvent::compiled_method_unload_event()
// should pass zombie_ok == true.
void nmethodLocker::lock_nmethod(nmethod* nm, bool zombie_ok) {
D
duke 已提交
2656 2657
  if (nm == NULL)  return;
  Atomic::inc(&nm->_lock_count);
2658
  guarantee(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method");
D
duke 已提交
2659 2660 2661 2662 2663 2664 2665 2666
}

void nmethodLocker::unlock_nmethod(nmethod* nm) {
  if (nm == NULL)  return;
  Atomic::dec(&nm->_lock_count);
  guarantee(nm->_lock_count >= 0, "unmatched nmethod lock/unlock");
}

2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681

// -----------------------------------------------------------------------------
// nmethod::get_deopt_original_pc
//
// Return the original PC for the given PC if:
// (a) the given PC belongs to a nmethod and
// (b) it is a deopt PC
address nmethod::get_deopt_original_pc(const frame* fr) {
  if (fr->cb() == NULL)  return NULL;

  nmethod* nm = fr->cb()->as_nmethod_or_null();
  if (nm != NULL && nm->is_deopt_pc(fr->pc()))
    return nm->get_original_pc(fr);

  return NULL;
D
duke 已提交
2682 2683 2684
}


2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
// -----------------------------------------------------------------------------
// MethodHandle

bool nmethod::is_method_handle_return(address return_pc) {
  if (!has_method_handle_invokes())  return false;
  PcDesc* pd = pc_desc_at(return_pc);
  if (pd == NULL)
    return false;
  return pd->is_method_handle_invoke();
}


D
duke 已提交
2697 2698 2699
// -----------------------------------------------------------------------------
// Verification

2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
class VerifyOopsClosure: public OopClosure {
  nmethod* _nm;
  bool     _ok;
public:
  VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
  bool ok() { return _ok; }
  virtual void do_oop(oop* p) {
    if ((*p) == NULL || (*p)->is_oop())  return;
    if (_ok) {
      _nm->print_nmethod(true);
      _ok = false;
    }
2712
    tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
2713
                  (void *)(*p), (intptr_t)p, (int)((intptr_t)p - (intptr_t)_nm));
2714 2715 2716 2717
  }
  virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
};

D
duke 已提交
2718 2719 2720 2721 2722
void nmethod::verify() {

  // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant
  // seems odd.

2723
  if (is_zombie() || is_not_entrant() || is_unloaded())
D
duke 已提交
2724 2725 2726 2727 2728
    return;

  // Make sure all the entry points are correctly aligned for patching.
  NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point());

2729
  // assert(method()->is_oop(), "must be valid");
D
duke 已提交
2730 2731 2732 2733

  ResourceMark rm;

  if (!CodeCache::contains(this)) {
2734
    fatal(err_msg("nmethod at " INTPTR_FORMAT " not in zone", this));
D
duke 已提交
2735 2736 2737 2738 2739 2740 2741
  }

  if(is_native_method() )
    return;

  nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
  if (nm != this) {
2742 2743
    fatal(err_msg("findNMethod did not find this nmethod (" INTPTR_FORMAT ")",
                  this));
D
duke 已提交
2744 2745 2746 2747 2748 2749 2750 2751
  }

  for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
    if (! p->verify(this)) {
      tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", this);
    }
  }

2752 2753 2754 2755 2756
  VerifyOopsClosure voc(this);
  oops_do(&voc);
  assert(voc.ok(), "embedded oops must be OK");
  verify_scavenge_root_oops();

D
duke 已提交
2757 2758 2759 2760 2761
  verify_scopes();
}


void nmethod::verify_interrupt_point(address call_site) {
2762
  // Verify IC only when nmethod installation is finished.
K
kvn 已提交
2763 2764
  bool is_installed = (method()->code() == this) // nmethod is in state 'in_use' and installed
                      || !this->is_in_use();     // nmethod is installed, but not in 'in_use' state
2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775
  if (is_installed) {
    Thread *cur = Thread::current();
    if (CompiledIC_lock->owner() == cur ||
        ((cur->is_VM_thread() || cur->is_ConcurrentGC_thread()) &&
         SafepointSynchronize::is_at_safepoint())) {
      CompiledIC_at(this, call_site);
      CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
    } else {
      MutexLocker ml_verify (CompiledIC_lock);
      CompiledIC_at(this, call_site);
    }
D
duke 已提交
2776
  }
2777 2778

  PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
D
duke 已提交
2779 2780
  assert(pd != NULL, "PcDesc must exist");
  for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(),
2781 2782
                                     pd->obj_decode_offset(), pd->should_reexecute(),
                                     pd->return_oop());
D
duke 已提交
2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
       !sd->is_top(); sd = sd->sender()) {
    sd->verify();
  }
}

void nmethod::verify_scopes() {
  if( !method() ) return;       // Runtime stubs have no scope
  if (method()->is_native()) return; // Ignore stub methods.
  // iterate through all interrupt point
  // and verify the debug information is valid.
  RelocIterator iter((nmethod*)this);
  while (iter.next()) {
    address stub = NULL;
    switch (iter.type()) {
      case relocInfo::virtual_call_type:
        verify_interrupt_point(iter.addr());
        break;
      case relocInfo::opt_virtual_call_type:
        stub = iter.opt_virtual_call_reloc()->static_stub();
        verify_interrupt_point(iter.addr());
        break;
      case relocInfo::static_call_type:
        stub = iter.static_call_reloc()->static_stub();
        //verify_interrupt_point(iter.addr());
        break;
      case relocInfo::runtime_call_type:
        address destination = iter.reloc()->value();
        // Right now there is no way to find out which entries support
        // an interrupt point.  It would be nice if we had this
        // information in a table.
        break;
    }
    assert(stub == NULL || stub_contains(stub), "static call stub outside stub section");
  }
}


// -----------------------------------------------------------------------------
// Non-product code
#ifndef PRODUCT

2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834
class DebugScavengeRoot: public OopClosure {
  nmethod* _nm;
  bool     _ok;
public:
  DebugScavengeRoot(nmethod* nm) : _nm(nm), _ok(true) { }
  bool ok() { return _ok; }
  virtual void do_oop(oop* p) {
    if ((*p) == NULL || !(*p)->is_scavengable())  return;
    if (_ok) {
      _nm->print_nmethod(true);
      _ok = false;
D
duke 已提交
2835
    }
2836
    tty->print_cr("*** scavengable oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
2837
                  (void *)(*p), (intptr_t)p, (int)((intptr_t)p - (intptr_t)_nm));
2838 2839 2840 2841 2842 2843
    (*p)->print();
  }
  virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
};

void nmethod::verify_scavenge_root_oops() {
2844 2845 2846 2847
  if (UseG1GC) {
    return;
  }

2848 2849 2850 2851 2852
  if (!on_scavenge_root_list()) {
    // Actually look inside, to verify the claim that it's clean.
    DebugScavengeRoot debug_scavenge_root(this);
    oops_do(&debug_scavenge_root);
    if (!debug_scavenge_root.ok())
2853
      fatal("found an unadvertised bad scavengable oop in the code cache");
D
duke 已提交
2854
  }
2855
  assert(scavenge_root_not_marked(), "");
D
duke 已提交
2856 2857
}

2858
#endif // PRODUCT
D
duke 已提交
2859 2860 2861 2862 2863 2864 2865

// Printing operations

void nmethod::print() const {
  ResourceMark rm;
  ttyLocker ttyl;   // keep the following output all in one block

2866
  tty->print("Compiled method ");
D
duke 已提交
2867 2868 2869 2870 2871

  if (is_compiled_by_c1()) {
    tty->print("(c1) ");
  } else if (is_compiled_by_c2()) {
    tty->print("(c2) ");
2872 2873
  } else if (is_compiled_by_shark()) {
    tty->print("(shark) ");
D
duke 已提交
2874 2875 2876 2877
  } else {
    tty->print("(nm) ");
  }

2878 2879
  print_on(tty, NULL);

D
duke 已提交
2880
  if (WizardMode) {
2881
    tty->print("((nmethod*) " INTPTR_FORMAT ") ", this);
D
duke 已提交
2882 2883 2884 2885 2886 2887
    tty->print(" for method " INTPTR_FORMAT , (address)method());
    tty->print(" { ");
    if (is_in_use())      tty->print("in_use ");
    if (is_not_entrant()) tty->print("not_entrant ");
    if (is_zombie())      tty->print("zombie ");
    if (is_unloaded())    tty->print("unloaded ");
2888
    if (on_scavenge_root_list())  tty->print("scavenge_root ");
D
duke 已提交
2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
    tty->print_cr("}:");
  }
  if (size              () > 0) tty->print_cr(" total in heap  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
                                              (address)this,
                                              (address)this + size(),
                                              size());
  if (relocation_size   () > 0) tty->print_cr(" relocation     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
                                              relocation_begin(),
                                              relocation_end(),
                                              relocation_size());
2899 2900 2901 2902
  if (consts_size       () > 0) tty->print_cr(" constants      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
                                              consts_begin(),
                                              consts_end(),
                                              consts_size());
T
twisti 已提交
2903 2904 2905 2906
  if (insts_size        () > 0) tty->print_cr(" main code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
                                              insts_begin(),
                                              insts_end(),
                                              insts_size());
D
duke 已提交
2907 2908 2909 2910
  if (stub_size         () > 0) tty->print_cr(" stub code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
                                              stub_begin(),
                                              stub_end(),
                                              stub_size());
2911 2912 2913 2914
  if (oops_size         () > 0) tty->print_cr(" oops           [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
                                              oops_begin(),
                                              oops_end(),
                                              oops_size());
2915 2916 2917 2918
  if (metadata_size      () > 0) tty->print_cr(" metadata       [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
                                              metadata_begin(),
                                              metadata_end(),
                                              metadata_size());
D
duke 已提交
2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
  if (scopes_data_size  () > 0) tty->print_cr(" scopes data    [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
                                              scopes_data_begin(),
                                              scopes_data_end(),
                                              scopes_data_size());
  if (scopes_pcs_size   () > 0) tty->print_cr(" scopes pcs     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
                                              scopes_pcs_begin(),
                                              scopes_pcs_end(),
                                              scopes_pcs_size());
  if (dependencies_size () > 0) tty->print_cr(" dependencies   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
                                              dependencies_begin(),
                                              dependencies_end(),
                                              dependencies_size());
  if (handler_table_size() > 0) tty->print_cr(" handler table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
                                              handler_table_begin(),
                                              handler_table_end(),
                                              handler_table_size());
  if (nul_chk_table_size() > 0) tty->print_cr(" nul chk table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
                                              nul_chk_table_begin(),
                                              nul_chk_table_end(),
                                              nul_chk_table_size());
}

2941 2942 2943 2944 2945 2946 2947 2948
void nmethod::print_code() {
  HandleMark hm;
  ResourceMark m;
  Disassembler::decode(this);
}


#ifndef PRODUCT
D
duke 已提交
2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967

void nmethod::print_scopes() {
  // Find the first pc desc for all scopes in the code and print it.
  ResourceMark rm;
  for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
    if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
      continue;

    ScopeDesc* sd = scope_desc_at(p->real_pc(this));
    sd->print_on(tty, p);
  }
}

void nmethod::print_dependencies() {
  ResourceMark rm;
  ttyLocker ttyl;   // keep the following output all in one block
  tty->print_cr("Dependencies:");
  for (Dependencies::DepStream deps(this); deps.next(); ) {
    deps.print_dependency();
2968
    Klass* ctxk = deps.context_type();
D
duke 已提交
2969
    if (ctxk != NULL) {
H
hseigel 已提交
2970 2971
      if (ctxk->oop_is_instance() && ((InstanceKlass*)ctxk)->is_dependent_nmethod(this)) {
        tty->print_cr("   [nmethod<=klass]%s", ctxk->external_name());
D
duke 已提交
2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998
      }
    }
    deps.log_dependency();  // put it into the xml log also
  }
}


void nmethod::print_relocations() {
  ResourceMark m;       // in case methods get printed via the debugger
  tty->print_cr("relocations:");
  RelocIterator iter(this);
  iter.print();
  if (UseRelocIndex) {
    jint* index_end   = (jint*)relocation_end() - 1;
    jint  index_size  = *index_end;
    jint* index_start = (jint*)( (address)index_end - index_size );
    tty->print_cr("    index @" INTPTR_FORMAT ": index_size=%d", index_start, index_size);
    if (index_size > 0) {
      jint* ip;
      for (ip = index_start; ip+2 <= index_end; ip += 2)
        tty->print_cr("  (%d %d) addr=" INTPTR_FORMAT " @" INTPTR_FORMAT,
                      ip[0],
                      ip[1],
                      header_end()+ip[0],
                      relocation_begin()-1+ip[1]);
      for (; ip < index_end; ip++)
        tty->print_cr("  (%d ?)", ip[0]);
2999 3000
      tty->print_cr("          @" INTPTR_FORMAT ": index_size=%d", ip, *ip);
      ip++;
D
duke 已提交
3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014
      tty->print_cr("reloc_end @" INTPTR_FORMAT ":", ip);
    }
  }
}


void nmethod::print_pcs() {
  ResourceMark m;       // in case methods get printed via debugger
  tty->print_cr("pc-bytecode offsets:");
  for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
    p->print(this);
  }
}

3015
#endif // PRODUCT
D
duke 已提交
3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033

const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
  RelocIterator iter(this, begin, end);
  bool have_one = false;
  while (iter.next()) {
    have_one = true;
    switch (iter.type()) {
        case relocInfo::none:                  return "no_reloc";
        case relocInfo::oop_type: {
          stringStream st;
          oop_Relocation* r = iter.oop_reloc();
          oop obj = r->oop_value();
          st.print("oop(");
          if (obj == NULL) st.print("NULL");
          else obj->print_value_on(&st);
          st.print(")");
          return st.as_string();
        }
3034 3035 3036 3037 3038 3039 3040 3041 3042 3043
        case relocInfo::metadata_type: {
          stringStream st;
          metadata_Relocation* r = iter.metadata_reloc();
          Metadata* obj = r->metadata_value();
          st.print("metadata(");
          if (obj == NULL) st.print("NULL");
          else obj->print_value_on(&st);
          st.print(")");
          return st.as_string();
        }
D
duke 已提交
3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064
        case relocInfo::virtual_call_type:     return "virtual_call";
        case relocInfo::opt_virtual_call_type: return "optimized virtual_call";
        case relocInfo::static_call_type:      return "static_call";
        case relocInfo::static_stub_type:      return "static_stub";
        case relocInfo::runtime_call_type:     return "runtime_call";
        case relocInfo::external_word_type:    return "external_word";
        case relocInfo::internal_word_type:    return "internal_word";
        case relocInfo::section_word_type:     return "section_word";
        case relocInfo::poll_type:             return "poll";
        case relocInfo::poll_return_type:      return "poll_return";
        case relocInfo::type_mask:             return "type_bit_mask";
    }
  }
  return have_one ? "other" : NULL;
}

// Return a the last scope in (begin..end]
ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
  PcDesc* p = pc_desc_near(begin+1);
  if (p != NULL && p->real_pc(this) <= end) {
    return new ScopeDesc(this, p->scope_decode_offset(),
3065 3066
                         p->obj_decode_offset(), p->should_reexecute(),
                         p->return_oop());
D
duke 已提交
3067 3068 3069 3070
  }
  return NULL;
}

3071
void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const {
3072 3073 3074 3075
  if (block_begin == entry_point())             stream->print_cr("[Entry Point]");
  if (block_begin == verified_entry_point())    stream->print_cr("[Verified Entry Point]");
  if (block_begin == exception_begin())         stream->print_cr("[Exception Handler]");
  if (block_begin == stub_begin())              stream->print_cr("[Stub Code]");
3076
  if (block_begin == deopt_handler_begin())     stream->print_cr("[Deopt Handler Code]");
3077 3078 3079 3080

  if (has_method_handle_invokes())
    if (block_begin == deopt_mh_handler_begin())  stream->print_cr("[Deopt MH Handler Code]");

3081
  if (block_begin == consts_begin())            stream->print_cr("[Constants]");
3082

3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148
  if (block_begin == entry_point()) {
    methodHandle m = method();
    if (m.not_null()) {
      stream->print("  # ");
      m->print_value_on(stream);
      stream->cr();
    }
    if (m.not_null() && !is_osr_method()) {
      ResourceMark rm;
      int sizeargs = m->size_of_parameters();
      BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
      VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
      {
        int sig_index = 0;
        if (!m->is_static())
          sig_bt[sig_index++] = T_OBJECT; // 'this'
        for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {
          BasicType t = ss.type();
          sig_bt[sig_index++] = t;
          if (type2size[t] == 2) {
            sig_bt[sig_index++] = T_VOID;
          } else {
            assert(type2size[t] == 1, "size is 1 or 2");
          }
        }
        assert(sig_index == sizeargs, "");
      }
      const char* spname = "sp"; // make arch-specific?
      intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false);
      int stack_slot_offset = this->frame_size() * wordSize;
      int tab1 = 14, tab2 = 24;
      int sig_index = 0;
      int arg_index = (m->is_static() ? 0 : -1);
      bool did_old_sp = false;
      for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {
        bool at_this = (arg_index == -1);
        bool at_old_sp = false;
        BasicType t = (at_this ? T_OBJECT : ss.type());
        assert(t == sig_bt[sig_index], "sigs in sync");
        if (at_this)
          stream->print("  # this: ");
        else
          stream->print("  # parm%d: ", arg_index);
        stream->move_to(tab1);
        VMReg fst = regs[sig_index].first();
        VMReg snd = regs[sig_index].second();
        if (fst->is_reg()) {
          stream->print("%s", fst->name());
          if (snd->is_valid())  {
            stream->print(":%s", snd->name());
          }
        } else if (fst->is_stack()) {
          int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
          if (offset == stack_slot_offset)  at_old_sp = true;
          stream->print("[%s+0x%x]", spname, offset);
        } else {
          stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
        }
        stream->print(" ");
        stream->move_to(tab2);
        stream->print("= ");
        if (at_this) {
          m->method_holder()->print_value_on(stream);
        } else {
          bool did_name = false;
          if (!at_this && ss.is_object()) {
3149
            Symbol* name = ss.as_symbol_or_null();
3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177
            if (name != NULL) {
              name->print_value_on(stream);
              did_name = true;
            }
          }
          if (!did_name)
            stream->print("%s", type2name(t));
        }
        if (at_old_sp) {
          stream->print("  (%s of caller)", spname);
          did_old_sp = true;
        }
        stream->cr();
        sig_index += type2size[t];
        arg_index += 1;
        if (!at_this)  ss.next();
      }
      if (!did_old_sp) {
        stream->print("  # ");
        stream->move_to(tab1);
        stream->print("[%s+0x%x]", spname, stack_slot_offset);
        stream->print("  (%s of caller)", spname);
        stream->cr();
      }
    }
  }
}

D
duke 已提交
3178 3179 3180 3181
void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, u_char* end) {
  // First, find an oopmap in (begin, end].
  // We use the odd half-closed interval so that oop maps and scope descs
  // which are tied to the byte after a call are printed with the call itself.
T
twisti 已提交
3182
  address base = code_begin();
D
duke 已提交
3183 3184 3185 3186 3187 3188 3189
  OopMapSet* oms = oop_maps();
  if (oms != NULL) {
    for (int i = 0, imax = oms->size(); i < imax; i++) {
      OopMap* om = oms->at(i);
      address pc = base + om->offset();
      if (pc > begin) {
        if (pc <= end) {
3190 3191 3192
          st->move_to(column);
          st->print("; ");
          om->print_on(st);
D
duke 已提交
3193 3194 3195 3196 3197
        }
        break;
      }
    }
  }
3198 3199

  // Print any debug info present at this pc.
D
duke 已提交
3200 3201
  ScopeDesc* sd  = scope_desc_in(begin, end);
  if (sd != NULL) {
3202
    st->move_to(column);
D
duke 已提交
3203 3204 3205
    if (sd->bci() == SynchronizationEntryBCI) {
      st->print(";*synchronization entry");
    } else {
3206
      if (sd->method() == NULL) {
3207
        st->print("method is NULL");
D
duke 已提交
3208
      } else if (sd->method()->is_native()) {
3209
        st->print("method is native");
D
duke 已提交
3210
      } else {
3211
        Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
D
duke 已提交
3212 3213 3214 3215 3216 3217 3218
        st->print(";*%s", Bytecodes::name(bc));
        switch (bc) {
        case Bytecodes::_invokevirtual:
        case Bytecodes::_invokespecial:
        case Bytecodes::_invokestatic:
        case Bytecodes::_invokeinterface:
          {
3219
            Bytecode_invoke invoke(sd->method(), sd->bci());
D
duke 已提交
3220
            st->print(" ");
3221 3222
            if (invoke.name() != NULL)
              invoke.name()->print_symbol_on(st);
D
duke 已提交
3223 3224 3225 3226 3227 3228 3229 3230 3231
            else
              st->print("<UNKNOWN>");
            break;
          }
        case Bytecodes::_getfield:
        case Bytecodes::_putfield:
        case Bytecodes::_getstatic:
        case Bytecodes::_putstatic:
          {
3232
            Bytecode_field field(sd->method(), sd->bci());
D
duke 已提交
3233
            st->print(" ");
3234 3235
            if (field.name() != NULL)
              field.name()->print_symbol_on(st);
D
duke 已提交
3236 3237 3238 3239 3240 3241
            else
              st->print("<UNKNOWN>");
          }
        }
      }
    }
3242

D
duke 已提交
3243 3244
    // Print all scopes
    for (;sd != NULL; sd = sd->sender()) {
3245
      st->move_to(column);
D
duke 已提交
3246
      st->print("; -");
3247
      if (sd->method() == NULL) {
3248
        st->print("method is NULL");
D
duke 已提交
3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265
      } else {
        sd->method()->print_short_name(st);
      }
      int lineno = sd->method()->line_number_from_bci(sd->bci());
      if (lineno != -1) {
        st->print("@%d (line %d)", sd->bci(), lineno);
      } else {
        st->print("@%d", sd->bci());
      }
      st->cr();
    }
  }

  // Print relocation information
  const char* str = reloc_string_for(begin, end);
  if (str != NULL) {
    if (sd != NULL) st->cr();
3266
    st->move_to(column);
D
duke 已提交
3267 3268
    st->print(";   {%s}", str);
  }
T
twisti 已提交
3269
  int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin());
D
duke 已提交
3270
  if (cont_offset != 0) {
3271
    st->move_to(column);
T
twisti 已提交
3272
    st->print("; implicit exception: dispatches to " INTPTR_FORMAT, code_begin() + cont_offset);
D
duke 已提交
3273 3274 3275 3276
  }

}

3277 3278
#ifndef PRODUCT

D
duke 已提交
3279
void nmethod::print_value_on(outputStream* st) const {
3280 3281
  st->print("nmethod");
  print_on(st, NULL);
D
duke 已提交
3282 3283 3284 3285 3286 3287 3288 3289 3290
}

void nmethod::print_calls(outputStream* st) {
  RelocIterator iter(this);
  while (iter.next()) {
    switch (iter.type()) {
    case relocInfo::virtual_call_type:
    case relocInfo::opt_virtual_call_type: {
      VerifyMutexLocker mc(CompiledIC_lock);
3291
      CompiledIC_at(&iter)->print();
D
duke 已提交
3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306
      break;
    }
    case relocInfo::static_call_type:
      st->print_cr("Static call at " INTPTR_FORMAT, iter.reloc()->addr());
      compiledStaticCall_at(iter.reloc())->print();
      break;
    }
  }
}

void nmethod::print_handler_table() {
  ExceptionHandlerTable(this).print();
}

void nmethod::print_nul_chk_table() {
T
twisti 已提交
3307
  ImplicitExceptionTable(this).print(code_begin());
D
duke 已提交
3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321
}

void nmethod::print_statistics() {
  ttyLocker ttyl;
  if (xtty != NULL)  xtty->head("statistics type='nmethod'");
  nmethod_stats.print_native_nmethod_stats();
  nmethod_stats.print_nmethod_stats();
  DebugInformationRecorder::print_statistics();
  nmethod_stats.print_pc_stats();
  Dependencies::print_statistics();
  if (xtty != NULL)  xtty->tail("statistics");
}

#endif // PRODUCT