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