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/atomic.inline.hpp"
  41 #include "runtime/orderAccess.inline.hpp"
  42 #include "runtime/sharedRuntime.hpp"
  43 #include "runtime/sweeper.hpp"
  44 #include "utilities/dtrace.hpp"
  45 #include "utilities/events.hpp"
  46 #include "utilities/xmlstream.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 
1153 void nmethod::cleanup_inline_caches() {
1154 
1155   assert_locked_or_safepoint(CompiledIC_lock);
1156 
1157   // If the method is not entrant or zombie then a JMP is plastered over the
1158   // first few bytes.  If an oop in the old code was there, that oop
1159   // should not get GC'd.  Skip the first few bytes of oops on
1160   // not-entrant methods.
1161   address low_boundary = verified_entry_point();
1162   if (!is_in_use()) {
1163     low_boundary += NativeJump::instruction_size;
1164     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1165     // This means that the low_boundary is going to be a little too high.
1166     // This shouldn't matter, since oops of non-entrant methods are never used.
1167     // In fact, why are we bothering to look at oops in a non-entrant method??
1168   }
1169 
1170   // Find all calls in an nmethod, and clear the ones that points to zombie methods
1171   ResourceMark rm;
1172   RelocIterator iter(this, low_boundary);
1173   while(iter.next()) {
1174     switch(iter.type()) {
1175       case relocInfo::virtual_call_type:
1176       case relocInfo::opt_virtual_call_type: {
1177         CompiledIC *ic = CompiledIC_at(&iter);
1178         // Ok, to lookup references to zombies here
1179         CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());
1180         if( cb != NULL && cb->is_nmethod() ) {
1181           nmethod* nm = (nmethod*)cb;
1182           // Clean inline caches pointing to both zombie and not_entrant methods
1183           if (!nm->is_in_use() || (nm->method()->code() != nm)) ic->set_to_clean();
1184         }
1185         break;
1186       }
1187       case relocInfo::static_call_type: {
1188         CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());
1189         CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());
1190         if( cb != NULL && cb->is_nmethod() ) {
1191           nmethod* nm = (nmethod*)cb;
1192           // Clean inline caches pointing to both zombie and not_entrant methods
1193           if (!nm->is_in_use() || (nm->method()->code() != nm)) csc->set_to_clean();
1194         }
1195         break;
1196       }
1197     }
1198   }
1199 }
1200 
1201 void nmethod::verify_clean_inline_caches() {
1202   assert_locked_or_safepoint(CompiledIC_lock);
1203 
1204   // If the method is not entrant or zombie then a JMP is plastered over the
1205   // first few bytes.  If an oop in the old code was there, that oop
1206   // should not get GC'd.  Skip the first few bytes of oops on
1207   // not-entrant methods.
1208   address low_boundary = verified_entry_point();
1209   if (!is_in_use()) {
1210     low_boundary += NativeJump::instruction_size;
1211     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1212     // This means that the low_boundary is going to be a little too high.
1213     // This shouldn't matter, since oops of non-entrant methods are never used.
1214     // In fact, why are we bothering to look at oops in a non-entrant method??
1215   }
1216 
1217   ResourceMark rm;
1218   RelocIterator iter(this, low_boundary);
1219   while(iter.next()) {
1220     switch(iter.type()) {
1221       case relocInfo::virtual_call_type:
1222       case relocInfo::opt_virtual_call_type: {
1223         CompiledIC *ic = CompiledIC_at(&iter);
1224         // Ok, to lookup references to zombies here
1225         CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());
1226         if( cb != NULL && cb->is_nmethod() ) {
1227           nmethod* nm = (nmethod*)cb;
1228           // Verify that inline caches pointing to both zombie and not_entrant methods are clean
1229           if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1230             assert(ic->is_clean(), "IC should be clean");
1231           }
1232         }
1233         break;
1234       }
1235       case relocInfo::static_call_type: {
1236         CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());
1237         CodeBlob *cb = CodeCache::find_blob_unsafe(csc->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(csc->is_clean(), "IC should be clean");
1243           }
1244         }
1245         break;
1246       }
1247     }
1248   }
1249 }
1250 
1251 int nmethod::verify_icholder_relocations() {
1252   int count = 0;
1253 
1254   RelocIterator iter(this);
1255   while(iter.next()) {
1256     if (iter.type() == relocInfo::virtual_call_type) {
1257       if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc())) {
1258         CompiledIC *ic = CompiledIC_at(&iter);
1259         if (TraceCompiledIC) {
1260           tty->print("noticed icholder " INTPTR_FORMAT " ", p2i(ic->cached_icholder()));
1261           ic->print();
1262         }
1263         assert(ic->cached_icholder() != NULL, "must be non-NULL");
1264         count++;
1265       }
1266     }
1267   }
1268 
1269   return count;
1270 }
1271 
1272 // This is a private interface with the sweeper.
1273 void nmethod::mark_as_seen_on_stack() {
1274   assert(is_alive(), "Must be an alive method");
1275   // Set the traversal mark to ensure that the sweeper does 2
1276   // cleaning passes before moving to zombie.
1277   set_stack_traversal_mark(NMethodSweeper::traversal_count());
1278 }
1279 
1280 // Tell if a non-entrant method can be converted to a zombie (i.e.,
1281 // there are no activations on the stack, not in use by the VM,
1282 // and not in use by the ServiceThread)
1283 bool nmethod::can_not_entrant_be_converted() {
1284   assert(is_not_entrant(), "must be a non-entrant method");
1285 
1286   // Since the nmethod sweeper only does partial sweep the sweeper's traversal
1287   // count can be greater than the stack traversal count before it hits the
1288   // nmethod for the second time.
1289   return stack_traversal_mark()+1 < NMethodSweeper::traversal_count() &&
1290          !is_locked_by_vm();
1291 }
1292 
1293 void nmethod::inc_decompile_count() {
1294   if (!is_compiled_by_c2()) return;
1295   // Could be gated by ProfileTraps, but do not bother...
1296   Method* m = method();
1297   if (m == NULL)  return;
1298   MethodData* mdo = m->method_data();
1299   if (mdo == NULL)  return;
1300   // There is a benign race here.  See comments in methodData.hpp.
1301   mdo->inc_decompile_count();
1302 }
1303 
1304 void nmethod::increase_unloading_clock() {
1305   _global_unloading_clock++;
1306   if (_global_unloading_clock == 0) {
1307     // _nmethods are allocated with _unloading_clock == 0,
1308     // so 0 is never used as a clock value.
1309     _global_unloading_clock = 1;
1310   }
1311 }
1312 
1313 void nmethod::set_unloading_clock(unsigned char unloading_clock) {
1314   OrderAccess::release_store((volatile jubyte*)&_unloading_clock, unloading_clock);
1315 }
1316 
1317 unsigned char nmethod::unloading_clock() {
1318   return (unsigned char)OrderAccess::load_acquire((volatile jubyte*)&_unloading_clock);
1319 }
1320 
1321 void nmethod::make_unloaded(BoolObjectClosure* is_alive, oop cause) {
1322 
1323   post_compiled_method_unload();
1324 
1325   // Since this nmethod is being unloaded, make sure that dependencies
1326   // recorded in instanceKlasses get flushed and pass non-NULL closure to
1327   // indicate that this work is being done during a GC.
1328   assert(Universe::heap()->is_gc_active(), "should only be called during gc");
1329   assert(is_alive != NULL, "Should be non-NULL");
1330   // A non-NULL is_alive closure indicates that this is being called during GC.
1331   flush_dependencies(is_alive);
1332 
1333   // Break cycle between nmethod & method
1334   if (TraceClassUnloading && WizardMode) {
1335     tty->print_cr("[Class unloading: Making nmethod " INTPTR_FORMAT
1336                   " unloadable], Method*(" INTPTR_FORMAT
1337                   "), cause(" INTPTR_FORMAT ")",
1338                   this, (address)_method, (address)cause);
1339     if (!Universe::heap()->is_gc_active())
1340       cause->klass()->print();
1341   }
1342   // Unlink the osr method, so we do not look this up again
1343   if (is_osr_method()) {
1344     invalidate_osr_method();
1345   }
1346   // If _method is already NULL the Method* is about to be unloaded,
1347   // so we don't have to break the cycle. Note that it is possible to
1348   // have the Method* live here, in case we unload the nmethod because
1349   // it is pointing to some oop (other than the Method*) being unloaded.
1350   if (_method != NULL) {
1351     // OSR methods point to the Method*, but the Method* does not
1352     // point back!
1353     if (_method->code() == this) {
1354       _method->clear_code(); // Break a cycle
1355     }
1356     _method = NULL;            // Clear the method of this dead nmethod
1357   }
1358   // Make the class unloaded - i.e., change state and notify sweeper
1359   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1360   if (is_in_use()) {
1361     // Transitioning directly from live to unloaded -- so
1362     // we need to force a cache clean-up; remember this
1363     // for later on.
1364     CodeCache::set_needs_cache_clean(true);
1365   }
1366 
1367   // Unregister must be done before the state change
1368   Universe::heap()->unregister_nmethod(this);
1369 
1370   _state = unloaded;
1371 
1372   // Log the unloading.
1373   log_state_change();
1374 
1375   // The Method* is gone at this point
1376   assert(_method == NULL, "Tautology");
1377 
1378   set_osr_link(NULL);
1379   //set_scavenge_root_link(NULL); // done by prune_scavenge_root_nmethods
1380   NMethodSweeper::report_state_change(this);
1381 }
1382 
1383 void nmethod::invalidate_osr_method() {
1384   assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
1385   // Remove from list of active nmethods
1386   if (method() != NULL)
1387     method()->method_holder()->remove_osr_nmethod(this);
1388   // Set entry as invalid
1389   _entry_bci = InvalidOSREntryBci;
1390 }
1391 
1392 void nmethod::log_state_change() const {
1393   if (LogCompilation) {
1394     if (xtty != NULL) {
1395       ttyLocker ttyl;  // keep the following output all in one block
1396       if (_state == unloaded) {
1397         xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'",
1398                          os::current_thread_id());
1399       } else {
1400         xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s",
1401                          os::current_thread_id(),
1402                          (_state == zombie ? " zombie='1'" : ""));
1403       }
1404       log_identity(xtty);
1405       xtty->stamp();
1406       xtty->end_elem();
1407     }
1408   }
1409   if (PrintCompilation && _state != unloaded) {
1410     print_on(tty, _state == zombie ? "made zombie" : "made not entrant");
1411   }
1412 }
1413 
1414 /**
1415  * Common functionality for both make_not_entrant and make_zombie
1416  */
1417 bool nmethod::make_not_entrant_or_zombie(unsigned int state) {
1418   assert(state == zombie || state == not_entrant, "must be zombie or not_entrant");
1419   assert(!is_zombie(), "should not already be a zombie");
1420 
1421   // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below.
1422   nmethodLocker nml(this);
1423   methodHandle the_method(method());
1424   No_Safepoint_Verifier nsv;
1425 
1426   // during patching, depending on the nmethod state we must notify the GC that
1427   // code has been unloaded, unregistering it. We cannot do this right while
1428   // holding the Patching_lock because we need to use the CodeCache_lock. This
1429   // would be prone to deadlocks.
1430   // This flag is used to remember whether we need to later lock and unregister.
1431   bool nmethod_needs_unregister = false;
1432 
1433   {
1434     // invalidate osr nmethod before acquiring the patching lock since
1435     // they both acquire leaf locks and we don't want a deadlock.
1436     // This logic is equivalent to the logic below for patching the
1437     // verified entry point of regular methods.
1438     if (is_osr_method()) {
1439       // this effectively makes the osr nmethod not entrant
1440       invalidate_osr_method();
1441     }
1442 
1443     // Enter critical section.  Does not block for safepoint.
1444     MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
1445 
1446     if (_state == state) {
1447       // another thread already performed this transition so nothing
1448       // to do, but return false to indicate this.
1449       return false;
1450     }
1451 
1452     // The caller can be calling the method statically or through an inline
1453     // cache call.
1454     if (!is_osr_method() && !is_not_entrant()) {
1455       NativeJump::patch_verified_entry(entry_point(), verified_entry_point(),
1456                   SharedRuntime::get_handle_wrong_method_stub());
1457     }
1458 
1459     if (is_in_use()) {
1460       // It's a true state change, so mark the method as decompiled.
1461       // Do it only for transition from alive.
1462       inc_decompile_count();
1463     }
1464 
1465     // If the state is becoming a zombie, signal to unregister the nmethod with
1466     // the heap.
1467     // This nmethod may have already been unloaded during a full GC.
1468     if ((state == zombie) && !is_unloaded()) {
1469       nmethod_needs_unregister = true;
1470     }
1471 
1472     // Must happen before state change. Otherwise we have a race condition in
1473     // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately
1474     // transition its state from 'not_entrant' to 'zombie' without having to wait
1475     // for stack scanning.
1476     if (state == not_entrant) {
1477       mark_as_seen_on_stack();
1478       OrderAccess::storestore();
1479     }
1480 
1481     // Change state
1482     _state = state;
1483 
1484     // Log the transition once
1485     log_state_change();
1486 
1487     // Remove nmethod from method.
1488     // We need to check if both the _code and _from_compiled_code_entry_point
1489     // refer to this nmethod because there is a race in setting these two fields
1490     // in Method* as seen in bugid 4947125.
1491     // If the vep() points to the zombie nmethod, the memory for the nmethod
1492     // could be flushed and the compiler and vtable stubs could still call
1493     // through it.
1494     if (method() != NULL && (method()->code() == this ||
1495                              method()->from_compiled_entry() == verified_entry_point())) {
1496       HandleMark hm;
1497       method()->clear_code();
1498     }
1499   } // leave critical region under Patching_lock
1500 
1501   // When the nmethod becomes zombie it is no longer alive so the
1502   // dependencies must be flushed.  nmethods in the not_entrant
1503   // state will be flushed later when the transition to zombie
1504   // happens or they get unloaded.
1505   if (state == zombie) {
1506     {
1507       // Flushing dependecies must be done before any possible
1508       // safepoint can sneak in, otherwise the oops used by the
1509       // dependency logic could have become stale.
1510       MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1511       if (nmethod_needs_unregister) {
1512         Universe::heap()->unregister_nmethod(this);
1513       }
1514       flush_dependencies(NULL);
1515     }
1516 
1517     // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload
1518     // event and it hasn't already been reported for this nmethod then
1519     // report it now. The event may have been reported earilier if the GC
1520     // marked it for unloading). JvmtiDeferredEventQueue support means
1521     // we no longer go to a safepoint here.
1522     post_compiled_method_unload();
1523 
1524 #ifdef ASSERT
1525     // It's no longer safe to access the oops section since zombie
1526     // nmethods aren't scanned for GC.
1527     _oops_are_stale = true;
1528 #endif
1529      // the Method may be reclaimed by class unloading now that the
1530      // nmethod is in zombie state
1531     set_method(NULL);
1532   } else {
1533     assert(state == not_entrant, "other cases may need to be handled differently");
1534   }
1535 
1536   if (TraceCreateZombies) {
1537     tty->print_cr("nmethod <" INTPTR_FORMAT "> code made %s", this, (state == not_entrant) ? "not entrant" : "zombie");
1538   }
1539 
1540   NMethodSweeper::report_state_change(this);
1541   return true;
1542 }
1543 
1544 void nmethod::flush() {
1545   // Note that there are no valid oops in the nmethod anymore.
1546   assert(is_zombie() || (is_osr_method() && is_unloaded()), "must be a zombie method");
1547   assert(is_marked_for_reclamation() || (is_osr_method() && is_unloaded()), "must be marked for reclamation");
1548 
1549   assert (!is_locked_by_vm(), "locked methods shouldn't be flushed");
1550   assert_locked_or_safepoint(CodeCache_lock);
1551 
1552   // completely deallocate this method
1553   Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, this);
1554   if (PrintMethodFlushing) {
1555     tty->print_cr("*flushing nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT "/Free CodeCache:" SIZE_FORMAT "Kb",
1556         _compile_id, this, CodeCache::nof_blobs(), CodeCache::unallocated_capacity()/1024);
1557   }
1558 
1559   // We need to deallocate any ExceptionCache data.
1560   // Note that we do not need to grab the nmethod lock for this, it
1561   // better be thread safe if we're disposing of it!
1562   ExceptionCache* ec = exception_cache();
1563   set_exception_cache(NULL);
1564   while(ec != NULL) {
1565     ExceptionCache* next = ec->next();
1566     delete ec;
1567     ec = next;
1568   }
1569 
1570   if (on_scavenge_root_list()) {
1571     CodeCache::drop_scavenge_root_nmethod(this);
1572   }
1573 
1574 #ifdef SHARK
1575   ((SharkCompiler *) compiler())->free_compiled_method(insts_begin());
1576 #endif // SHARK
1577 
1578   ((CodeBlob*)(this))->flush();
1579 
1580   CodeCache::free(this);
1581 }
1582 
1583 
1584 //
1585 // Notify all classes this nmethod is dependent on that it is no
1586 // longer dependent. This should only be called in two situations.
1587 // First, when a nmethod transitions to a zombie all dependents need
1588 // to be clear.  Since zombification happens at a safepoint there's no
1589 // synchronization issues.  The second place is a little more tricky.
1590 // During phase 1 of mark sweep class unloading may happen and as a
1591 // result some nmethods may get unloaded.  In this case the flushing
1592 // of dependencies must happen during phase 1 since after GC any
1593 // dependencies in the unloaded nmethod won't be updated, so
1594 // traversing the dependency information in unsafe.  In that case this
1595 // function is called with a non-NULL argument and this function only
1596 // notifies instanceKlasses that are reachable
1597 
1598 void nmethod::flush_dependencies(BoolObjectClosure* is_alive) {
1599   assert_locked_or_safepoint(CodeCache_lock);
1600   assert(Universe::heap()->is_gc_active() == (is_alive != NULL),
1601   "is_alive is non-NULL if and only if we are called during GC");
1602   if (!has_flushed_dependencies()) {
1603     set_has_flushed_dependencies();
1604     for (Dependencies::DepStream deps(this); deps.next(); ) {
1605       Klass* klass = deps.context_type();
1606       if (klass == NULL)  continue;  // ignore things like evol_method
1607 
1608       // During GC the is_alive closure is non-NULL, and is used to
1609       // determine liveness of dependees that need to be updated.
1610       if (is_alive == NULL || klass->is_loader_alive(is_alive)) {
1611         InstanceKlass::cast(klass)->remove_dependent_nmethod(this);
1612       }
1613     }
1614   }
1615 }
1616 
1617 
1618 // If this oop is not live, the nmethod can be unloaded.
1619 bool nmethod::can_unload(BoolObjectClosure* is_alive, oop* root, bool unloading_occurred) {
1620   assert(root != NULL, "just checking");
1621   oop obj = *root;
1622   if (obj == NULL || is_alive->do_object_b(obj)) {
1623       return false;
1624   }
1625 
1626   // If ScavengeRootsInCode is true, an nmethod might be unloaded
1627   // simply because one of its constant oops has gone dead.
1628   // No actual classes need to be unloaded in order for this to occur.
1629   assert(unloading_occurred || ScavengeRootsInCode, "Inconsistency in unloading");
1630   make_unloaded(is_alive, obj);
1631   return true;
1632 }
1633 
1634 // ------------------------------------------------------------------
1635 // post_compiled_method_load_event
1636 // new method for install_code() path
1637 // Transfer information from compilation to jvmti
1638 void nmethod::post_compiled_method_load_event() {
1639 
1640   Method* moop = method();
1641 #ifndef USDT2
1642   HS_DTRACE_PROBE8(hotspot, compiled__method__load,
1643       moop->klass_name()->bytes(),
1644       moop->klass_name()->utf8_length(),
1645       moop->name()->bytes(),
1646       moop->name()->utf8_length(),
1647       moop->signature()->bytes(),
1648       moop->signature()->utf8_length(),
1649       insts_begin(), insts_size());
1650 #else /* USDT2 */
1651   HOTSPOT_COMPILED_METHOD_LOAD(
1652       (char *) moop->klass_name()->bytes(),
1653       moop->klass_name()->utf8_length(),
1654       (char *) moop->name()->bytes(),
1655       moop->name()->utf8_length(),
1656       (char *) moop->signature()->bytes(),
1657       moop->signature()->utf8_length(),
1658       insts_begin(), insts_size());
1659 #endif /* USDT2 */
1660 
1661   if (JvmtiExport::should_post_compiled_method_load() ||
1662       JvmtiExport::should_post_compiled_method_unload()) {
1663     get_and_cache_jmethod_id();
1664   }
1665 
1666   if (JvmtiExport::should_post_compiled_method_load()) {
1667     // Let the Service thread (which is a real Java thread) post the event
1668     MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
1669     JvmtiDeferredEventQueue::enqueue(
1670       JvmtiDeferredEvent::compiled_method_load_event(this));
1671   }
1672 }
1673 
1674 jmethodID nmethod::get_and_cache_jmethod_id() {
1675   if (_jmethod_id == NULL) {
1676     // Cache the jmethod_id since it can no longer be looked up once the
1677     // method itself has been marked for unloading.
1678     _jmethod_id = method()->jmethod_id();
1679   }
1680   return _jmethod_id;
1681 }
1682 
1683 void nmethod::post_compiled_method_unload() {
1684   if (unload_reported()) {
1685     // During unloading we transition to unloaded and then to zombie
1686     // and the unloading is reported during the first transition.
1687     return;
1688   }
1689 
1690   assert(_method != NULL && !is_unloaded(), "just checking");
1691   DTRACE_METHOD_UNLOAD_PROBE(method());
1692 
1693   // If a JVMTI agent has enabled the CompiledMethodUnload event then
1694   // post the event. Sometime later this nmethod will be made a zombie
1695   // by the sweeper but the Method* will not be valid at that point.
1696   // If the _jmethod_id is null then no load event was ever requested
1697   // so don't bother posting the unload.  The main reason for this is
1698   // that the jmethodID is a weak reference to the Method* so if
1699   // it's being unloaded there's no way to look it up since the weak
1700   // ref will have been cleared.
1701   if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) {
1702     assert(!unload_reported(), "already unloaded");
1703     JvmtiDeferredEvent event =
1704       JvmtiDeferredEvent::compiled_method_unload_event(this,
1705           _jmethod_id, insts_begin());
1706     if (SafepointSynchronize::is_at_safepoint()) {
1707       // Don't want to take the queueing lock. Add it as pending and
1708       // it will get enqueued later.
1709       JvmtiDeferredEventQueue::add_pending_event(event);
1710     } else {
1711       MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
1712       JvmtiDeferredEventQueue::enqueue(event);
1713     }
1714   }
1715 
1716   // The JVMTI CompiledMethodUnload event can be enabled or disabled at
1717   // any time. As the nmethod is being unloaded now we mark it has
1718   // having the unload event reported - this will ensure that we don't
1719   // attempt to report the event in the unlikely scenario where the
1720   // event is enabled at the time the nmethod is made a zombie.
1721   set_unload_reported();
1722 }
1723 
1724 void static clean_ic_if_metadata_is_dead(CompiledIC *ic, BoolObjectClosure *is_alive) {
1725   if (ic->is_icholder_call()) {
1726     // The only exception is compiledICHolder oops which may
1727     // yet be marked below. (We check this further below).
1728     CompiledICHolder* cichk_oop = ic->cached_icholder();
1729     if (cichk_oop->holder_method()->method_holder()->is_loader_alive(is_alive) &&
1730         cichk_oop->holder_klass()->is_loader_alive(is_alive)) {
1731       return;
1732     }
1733   } else {
1734     Metadata* ic_oop = ic->cached_metadata();
1735     if (ic_oop != NULL) {
1736       if (ic_oop->is_klass()) {
1737         if (((Klass*)ic_oop)->is_loader_alive(is_alive)) {
1738           return;
1739         }
1740       } else if (ic_oop->is_method()) {
1741         if (((Method*)ic_oop)->method_holder()->is_loader_alive(is_alive)) {
1742           return;
1743         }
1744       } else {
1745         ShouldNotReachHere();
1746       }
1747     }
1748   }
1749 
1750   ic->set_to_clean();
1751 }
1752 
1753 // This is called at the end of the strong tracing/marking phase of a
1754 // GC to unload an nmethod if it contains otherwise unreachable
1755 // oops.
1756 
1757 void nmethod::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
1758   // Make sure the oop's ready to receive visitors
1759   assert(!is_zombie() && !is_unloaded(),
1760          "should not call follow on zombie or unloaded nmethod");
1761 
1762   // If the method is not entrant then a JMP is plastered over the
1763   // first few bytes.  If an oop in the old code was there, that oop
1764   // should not get GC'd.  Skip the first few bytes of oops on
1765   // not-entrant methods.
1766   address low_boundary = verified_entry_point();
1767   if (is_not_entrant()) {
1768     low_boundary += NativeJump::instruction_size;
1769     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1770     // (See comment above.)
1771   }
1772 
1773   // The RedefineClasses() API can cause the class unloading invariant
1774   // to no longer be true. See jvmtiExport.hpp for details.
1775   // Also, leave a debugging breadcrumb in local flag.
1776   bool a_class_was_redefined = JvmtiExport::has_redefined_a_class();
1777   if (a_class_was_redefined) {
1778     // This set of the unloading_occurred flag is done before the
1779     // call to post_compiled_method_unload() so that the unloading
1780     // of this nmethod is reported.
1781     unloading_occurred = true;
1782   }
1783 
1784   // Exception cache
1785   clean_exception_cache(is_alive);
1786 
1787   // If class unloading occurred we first iterate over all inline caches and
1788   // clear ICs where the cached oop is referring to an unloaded klass or method.
1789   // The remaining live cached oops will be traversed in the relocInfo::oop_type
1790   // iteration below.
1791   if (unloading_occurred) {
1792     RelocIterator iter(this, low_boundary);
1793     while(iter.next()) {
1794       if (iter.type() == relocInfo::virtual_call_type) {
1795         CompiledIC *ic = CompiledIC_at(&iter);
1796         clean_ic_if_metadata_is_dead(ic, is_alive);
1797       }
1798     }
1799   }
1800 
1801   // Compiled code
1802   {
1803   RelocIterator iter(this, low_boundary);
1804   while (iter.next()) {
1805     if (iter.type() == relocInfo::oop_type) {
1806       oop_Relocation* r = iter.oop_reloc();
1807       // In this loop, we must only traverse those oops directly embedded in
1808       // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
1809       assert(1 == (r->oop_is_immediate()) +
1810                   (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1811              "oop must be found in exactly one place");
1812       if (r->oop_is_immediate() && r->oop_value() != NULL) {
1813         if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1814           return;
1815         }
1816       }
1817     }
1818   }
1819   }
1820 
1821 
1822   // Scopes
1823   for (oop* p = oops_begin(); p < oops_end(); p++) {
1824     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
1825     if (can_unload(is_alive, p, unloading_occurred)) {
1826       return;
1827     }
1828   }
1829 
1830   // Ensure that all metadata is still alive
1831   verify_metadata_loaders(low_boundary, is_alive);
1832 }
1833 
1834 template <class CompiledICorStaticCall>
1835 static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, BoolObjectClosure *is_alive, nmethod* from) {
1836   // Ok, to lookup references to zombies here
1837   CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
1838   if (cb != NULL && cb->is_nmethod()) {
1839     nmethod* nm = (nmethod*)cb;
1840 
1841     if (nm->unloading_clock() != nmethod::global_unloading_clock()) {
1842       // The nmethod has not been processed yet.
1843       return true;
1844     }
1845 
1846     // Clean inline caches pointing to both zombie and not_entrant methods
1847     if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1848       ic->set_to_clean();
1849       assert(ic->is_clean(), err_msg("nmethod " PTR_FORMAT "not clean %s", from, from->method()->name_and_sig_as_C_string()));
1850     }
1851   }
1852 
1853   return false;
1854 }
1855 
1856 static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, BoolObjectClosure *is_alive, nmethod* from) {
1857   return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), is_alive, from);
1858 }
1859 
1860 static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, BoolObjectClosure *is_alive, nmethod* from) {
1861   return clean_if_nmethod_is_unloaded(csc, csc->destination(), is_alive, from);
1862 }
1863 
1864 bool nmethod::do_unloading_parallel(BoolObjectClosure* is_alive, bool unloading_occurred) {
1865   ResourceMark rm;
1866 
1867   // Make sure the oop's ready to receive visitors
1868   assert(!is_zombie() && !is_unloaded(),
1869          "should not call follow on zombie or unloaded nmethod");
1870 
1871   // If the method is not entrant then a JMP is plastered over the
1872   // first few bytes.  If an oop in the old code was there, that oop
1873   // should not get GC'd.  Skip the first few bytes of oops on
1874   // not-entrant methods.
1875   address low_boundary = verified_entry_point();
1876   if (is_not_entrant()) {
1877     low_boundary += NativeJump::instruction_size;
1878     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1879     // (See comment above.)
1880   }
1881 
1882   // The RedefineClasses() API can cause the class unloading invariant
1883   // to no longer be true. See jvmtiExport.hpp for details.
1884   // Also, leave a debugging breadcrumb in local flag.
1885   bool a_class_was_redefined = JvmtiExport::has_redefined_a_class();
1886   if (a_class_was_redefined) {
1887     // This set of the unloading_occurred flag is done before the
1888     // call to post_compiled_method_unload() so that the unloading
1889     // of this nmethod is reported.
1890     unloading_occurred = true;
1891   }
1892 
1893   // Exception cache
1894   clean_exception_cache(is_alive);
1895 
1896   bool is_unloaded = false;
1897   bool postponed = false;
1898 
1899   RelocIterator iter(this, low_boundary);
1900   while(iter.next()) {
1901 
1902     switch (iter.type()) {
1903 
1904     case relocInfo::virtual_call_type:
1905       if (unloading_occurred) {
1906         // If class unloading occurred we first iterate over all inline caches and
1907         // clear ICs where the cached oop is referring to an unloaded klass or method.
1908         clean_ic_if_metadata_is_dead(CompiledIC_at(&iter), is_alive);
1909       }
1910 
1911       postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1912       break;
1913 
1914     case relocInfo::opt_virtual_call_type:
1915       postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1916       break;
1917 
1918     case relocInfo::static_call_type:
1919       postponed |= clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
1920       break;
1921 
1922     case relocInfo::oop_type:
1923       if (!is_unloaded) {
1924         // Unload check
1925         oop_Relocation* r = iter.oop_reloc();
1926         // Traverse those oops directly embedded in the code.
1927         // Other oops (oop_index>0) are seen as part of scopes_oops.
1928         assert(1 == (r->oop_is_immediate()) +
1929                   (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1930               "oop must be found in exactly one place");
1931         if (r->oop_is_immediate() && r->oop_value() != NULL) {
1932           if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1933             is_unloaded = true;
1934           }
1935         }
1936       }
1937       break;
1938 
1939     }
1940   }
1941 
1942   if (is_unloaded) {
1943     return postponed;
1944   }
1945 
1946   // Scopes
1947   for (oop* p = oops_begin(); p < oops_end(); p++) {
1948     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
1949     if (can_unload(is_alive, p, unloading_occurred)) {
1950       is_unloaded = true;
1951       break;
1952     }
1953   }
1954 
1955   if (is_unloaded) {
1956     return postponed;
1957   }
1958 
1959   // Ensure that all metadata is still alive
1960   verify_metadata_loaders(low_boundary, is_alive);
1961 
1962   return postponed;
1963 }
1964 
1965 void nmethod::do_unloading_parallel_postponed(BoolObjectClosure* is_alive, bool unloading_occurred) {
1966   ResourceMark rm;
1967 
1968   // Make sure the oop's ready to receive visitors
1969   assert(!is_zombie(),
1970          "should not call follow on zombie nmethod");
1971 
1972   // If the method is not entrant then a JMP is plastered over the
1973   // first few bytes.  If an oop in the old code was there, that oop
1974   // should not get GC'd.  Skip the first few bytes of oops on
1975   // not-entrant methods.
1976   address low_boundary = verified_entry_point();
1977   if (is_not_entrant()) {
1978     low_boundary += NativeJump::instruction_size;
1979     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1980     // (See comment above.)
1981   }
1982 
1983   RelocIterator iter(this, low_boundary);
1984   while(iter.next()) {
1985 
1986     switch (iter.type()) {
1987 
1988     case relocInfo::virtual_call_type:
1989       clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1990       break;
1991 
1992     case relocInfo::opt_virtual_call_type:
1993       clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1994       break;
1995 
1996     case relocInfo::static_call_type:
1997       clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
1998       break;
1999     }
2000   }
2001 }
2002 
2003 #ifdef ASSERT
2004 
2005 class CheckClass : AllStatic {
2006   static BoolObjectClosure* _is_alive;
2007 
2008   // Check class_loader is alive for this bit of metadata.
2009   static void check_class(Metadata* md) {
2010     Klass* klass = NULL;
2011     if (md->is_klass()) {
2012       klass = ((Klass*)md);
2013     } else if (md->is_method()) {
2014       klass = ((Method*)md)->method_holder();
2015     } else if (md->is_methodData()) {
2016       klass = ((MethodData*)md)->method()->method_holder();
2017     } else {
2018       md->print();
2019       ShouldNotReachHere();
2020     }
2021     assert(klass->is_loader_alive(_is_alive), "must be alive");
2022   }
2023  public:
2024   static void do_check_class(BoolObjectClosure* is_alive, nmethod* nm) {
2025     assert(SafepointSynchronize::is_at_safepoint(), "this is only ok at safepoint");
2026     _is_alive = is_alive;
2027     nm->metadata_do(check_class);
2028   }
2029 };
2030 
2031 // This is called during a safepoint so can use static data
2032 BoolObjectClosure* CheckClass::_is_alive = NULL;
2033 #endif // ASSERT
2034 
2035 
2036 // Processing of oop references should have been sufficient to keep
2037 // all strong references alive.  Any weak references should have been
2038 // cleared as well.  Visit all the metadata and ensure that it's
2039 // really alive.
2040 void nmethod::verify_metadata_loaders(address low_boundary, BoolObjectClosure* is_alive) {
2041 #ifdef ASSERT
2042     RelocIterator iter(this, low_boundary);
2043     while (iter.next()) {
2044     // static_stub_Relocations may have dangling references to
2045     // Method*s so trim them out here.  Otherwise it looks like
2046     // compiled code is maintaining a link to dead metadata.
2047     address static_call_addr = NULL;
2048     if (iter.type() == relocInfo::opt_virtual_call_type) {
2049       CompiledIC* cic = CompiledIC_at(&iter);
2050       if (!cic->is_call_to_interpreted()) {
2051         static_call_addr = iter.addr();
2052       }
2053     } else if (iter.type() == relocInfo::static_call_type) {
2054       CompiledStaticCall* csc = compiledStaticCall_at(iter.reloc());
2055       if (!csc->is_call_to_interpreted()) {
2056         static_call_addr = iter.addr();
2057       }
2058     }
2059     if (static_call_addr != NULL) {
2060       RelocIterator sciter(this, low_boundary);
2061       while (sciter.next()) {
2062         if (sciter.type() == relocInfo::static_stub_type &&
2063             sciter.static_stub_reloc()->static_call() == static_call_addr) {
2064           sciter.static_stub_reloc()->clear_inline_cache();
2065         }
2066       }
2067     }
2068   }
2069   // Check that the metadata embedded in the nmethod is alive
2070   CheckClass::do_check_class(is_alive, this);
2071 #endif
2072 }
2073 
2074 
2075 // Iterate over metadata calling this function.   Used by RedefineClasses
2076 void nmethod::metadata_do(void f(Metadata*)) {
2077   address low_boundary = verified_entry_point();
2078   if (is_not_entrant()) {
2079     low_boundary += NativeJump::instruction_size;
2080     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
2081     // (See comment above.)
2082   }
2083   {
2084     // Visit all immediate references that are embedded in the instruction stream.
2085     RelocIterator iter(this, low_boundary);
2086     while (iter.next()) {
2087       if (iter.type() == relocInfo::metadata_type ) {
2088         metadata_Relocation* r = iter.metadata_reloc();
2089         // In this lmetadata, we must only follow those metadatas directly embedded in
2090         // the code.  Other metadatas (oop_index>0) are seen as part of
2091         // the metadata section below.
2092         assert(1 == (r->metadata_is_immediate()) +
2093                (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
2094                "metadata must be found in exactly one place");
2095         if (r->metadata_is_immediate() && r->metadata_value() != NULL) {
2096           Metadata* md = r->metadata_value();
2097           f(md);
2098         }
2099       } else if (iter.type() == relocInfo::virtual_call_type) {
2100         // Check compiledIC holders associated with this nmethod
2101         CompiledIC *ic = CompiledIC_at(&iter);
2102         if (ic->is_icholder_call()) {
2103           CompiledICHolder* cichk = ic->cached_icholder();
2104           f(cichk->holder_method());
2105           f(cichk->holder_klass());
2106         } else {
2107           Metadata* ic_oop = ic->cached_metadata();
2108           if (ic_oop != NULL) {
2109             f(ic_oop);
2110           }
2111         }
2112       }
2113     }
2114   }
2115 
2116   // Visit the metadata section
2117   for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2118     if (*p == Universe::non_oop_word() || *p == NULL)  continue;  // skip non-oops
2119     Metadata* md = *p;
2120     f(md);
2121   }
2122 
2123   // Call function Method*, not embedded in these other places.
2124   if (_method != NULL) f(_method);
2125 }
2126 
2127 void nmethod::oops_do(OopClosure* f, bool allow_zombie) {
2128   // make sure the oops ready to receive visitors
2129   assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod");
2130   assert(!is_unloaded(), "should not call follow on unloaded nmethod");
2131 
2132   // If the method is not entrant or zombie then a JMP is plastered over the
2133   // first few bytes.  If an oop in the old code was there, that oop
2134   // should not get GC'd.  Skip the first few bytes of oops on
2135   // not-entrant methods.
2136   address low_boundary = verified_entry_point();
2137   if (is_not_entrant()) {
2138     low_boundary += NativeJump::instruction_size;
2139     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
2140     // (See comment above.)
2141   }
2142 
2143   RelocIterator iter(this, low_boundary);
2144 
2145   while (iter.next()) {
2146     if (iter.type() == relocInfo::oop_type ) {
2147       oop_Relocation* r = iter.oop_reloc();
2148       // In this loop, we must only follow those oops directly embedded in
2149       // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
2150       assert(1 == (r->oop_is_immediate()) +
2151                    (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2152              "oop must be found in exactly one place");
2153       if (r->oop_is_immediate() && r->oop_value() != NULL) {
2154         f->do_oop(r->oop_addr());
2155       }
2156     }
2157   }
2158 
2159   // Scopes
2160   // This includes oop constants not inlined in the code stream.
2161   for (oop* p = oops_begin(); p < oops_end(); p++) {
2162     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
2163     f->do_oop(p);
2164   }
2165 }
2166 
2167 #define NMETHOD_SENTINEL ((nmethod*)badAddress)
2168 
2169 nmethod* volatile nmethod::_oops_do_mark_nmethods;
2170 
2171 // An nmethod is "marked" if its _mark_link is set non-null.
2172 // Even if it is the end of the linked list, it will have a non-null link value,
2173 // as long as it is on the list.
2174 // This code must be MP safe, because it is used from parallel GC passes.
2175 bool nmethod::test_set_oops_do_mark() {
2176   assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called");
2177   nmethod* observed_mark_link = _oops_do_mark_link;
2178   if (observed_mark_link == NULL) {
2179     // Claim this nmethod for this thread to mark.
2180     observed_mark_link = (nmethod*)
2181       Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_link, NULL);
2182     if (observed_mark_link == NULL) {
2183 
2184       // Atomically append this nmethod (now claimed) to the head of the list:
2185       nmethod* observed_mark_nmethods = _oops_do_mark_nmethods;
2186       for (;;) {
2187         nmethod* required_mark_nmethods = observed_mark_nmethods;
2188         _oops_do_mark_link = required_mark_nmethods;
2189         observed_mark_nmethods = (nmethod*)
2190           Atomic::cmpxchg_ptr(this, &_oops_do_mark_nmethods, required_mark_nmethods);
2191         if (observed_mark_nmethods == required_mark_nmethods)
2192           break;
2193       }
2194       // Mark was clear when we first saw this guy.
2195       NOT_PRODUCT(if (TraceScavenge)  print_on(tty, "oops_do, mark"));
2196       return false;
2197     }
2198   }
2199   // On fall through, another racing thread marked this nmethod before we did.
2200   return true;
2201 }
2202 
2203 void nmethod::oops_do_marking_prologue() {
2204   NOT_PRODUCT(if (TraceScavenge)  tty->print_cr("[oops_do_marking_prologue"));
2205   assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row");
2206   // We use cmpxchg_ptr instead of regular assignment here because the user
2207   // may fork a bunch of threads, and we need them all to see the same state.
2208   void* observed = Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, NULL);
2209   guarantee(observed == NULL, "no races in this sequential code");
2210 }
2211 
2212 void nmethod::oops_do_marking_epilogue() {
2213   assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row");
2214   nmethod* cur = _oops_do_mark_nmethods;
2215   while (cur != NMETHOD_SENTINEL) {
2216     assert(cur != NULL, "not NULL-terminated");
2217     nmethod* next = cur->_oops_do_mark_link;
2218     cur->_oops_do_mark_link = NULL;
2219     cur->verify_oop_relocations();
2220     NOT_PRODUCT(if (TraceScavenge)  cur->print_on(tty, "oops_do, unmark"));
2221     cur = next;
2222   }
2223   void* required = _oops_do_mark_nmethods;
2224   void* observed = Atomic::cmpxchg_ptr(NULL, &_oops_do_mark_nmethods, required);
2225   guarantee(observed == required, "no races in this sequential code");
2226   NOT_PRODUCT(if (TraceScavenge)  tty->print_cr("oops_do_marking_epilogue]"));
2227 }
2228 
2229 class DetectScavengeRoot: public OopClosure {
2230   bool     _detected_scavenge_root;
2231 public:
2232   DetectScavengeRoot() : _detected_scavenge_root(false)
2233   { NOT_PRODUCT(_print_nm = NULL); }
2234   bool detected_scavenge_root() { return _detected_scavenge_root; }
2235   virtual void do_oop(oop* p) {
2236     if ((*p) != NULL && (*p)->is_scavengable()) {
2237       NOT_PRODUCT(maybe_print(p));
2238       _detected_scavenge_root = true;
2239     }
2240   }
2241   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2242 
2243 #ifndef PRODUCT
2244   nmethod* _print_nm;
2245   void maybe_print(oop* p) {
2246     if (_print_nm == NULL)  return;
2247     if (!_detected_scavenge_root)  _print_nm->print_on(tty, "new scavenge root");
2248     tty->print_cr(""PTR_FORMAT"[offset=%d] detected scavengable oop "PTR_FORMAT" (found at "PTR_FORMAT")",
2249                   _print_nm, (int)((intptr_t)p - (intptr_t)_print_nm),
2250                   (void *)(*p), (intptr_t)p);
2251     (*p)->print();
2252   }
2253 #endif //PRODUCT
2254 };
2255 
2256 bool nmethod::detect_scavenge_root_oops() {
2257   DetectScavengeRoot detect_scavenge_root;
2258   NOT_PRODUCT(if (TraceScavenge)  detect_scavenge_root._print_nm = this);
2259   oops_do(&detect_scavenge_root);
2260   return detect_scavenge_root.detected_scavenge_root();
2261 }
2262 
2263 // Method that knows how to preserve outgoing arguments at call. This method must be
2264 // called with a frame corresponding to a Java invoke
2265 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
2266 #ifndef SHARK
2267   if (!method()->is_native()) {
2268     SimpleScopeDesc ssd(this, fr.pc());
2269     Bytecode_invoke call(ssd.method(), ssd.bci());
2270     bool has_receiver = call.has_receiver();
2271     bool has_appendix = call.has_appendix();
2272     Symbol* signature = call.signature();
2273     fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
2274   }
2275 #endif // !SHARK
2276 }
2277 
2278 
2279 oop nmethod::embeddedOop_at(u_char* p) {
2280   RelocIterator iter(this, p, p + 1);
2281   while (iter.next())
2282     if (iter.type() == relocInfo::oop_type) {
2283       return iter.oop_reloc()->oop_value();
2284     }
2285   return NULL;
2286 }
2287 
2288 
2289 inline bool includes(void* p, void* from, void* to) {
2290   return from <= p && p < to;
2291 }
2292 
2293 
2294 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
2295   assert(count >= 2, "must be sentinel values, at least");
2296 
2297 #ifdef ASSERT
2298   // must be sorted and unique; we do a binary search in find_pc_desc()
2299   int prev_offset = pcs[0].pc_offset();
2300   assert(prev_offset == PcDesc::lower_offset_limit,
2301          "must start with a sentinel");
2302   for (int i = 1; i < count; i++) {
2303     int this_offset = pcs[i].pc_offset();
2304     assert(this_offset > prev_offset, "offsets must be sorted");
2305     prev_offset = this_offset;
2306   }
2307   assert(prev_offset == PcDesc::upper_offset_limit,
2308          "must end with a sentinel");
2309 #endif //ASSERT
2310 
2311   // Search for MethodHandle invokes and tag the nmethod.
2312   for (int i = 0; i < count; i++) {
2313     if (pcs[i].is_method_handle_invoke()) {
2314       set_has_method_handle_invokes(true);
2315       break;
2316     }
2317   }
2318   assert(has_method_handle_invokes() == (_deoptimize_mh_offset != -1), "must have deopt mh handler");
2319 
2320   int size = count * sizeof(PcDesc);
2321   assert(scopes_pcs_size() >= size, "oob");
2322   memcpy(scopes_pcs_begin(), pcs, size);
2323 
2324   // Adjust the final sentinel downward.
2325   PcDesc* last_pc = &scopes_pcs_begin()[count-1];
2326   assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
2327   last_pc->set_pc_offset(content_size() + 1);
2328   for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
2329     // Fill any rounding gaps with copies of the last record.
2330     last_pc[1] = last_pc[0];
2331   }
2332   // The following assert could fail if sizeof(PcDesc) is not
2333   // an integral multiple of oopSize (the rounding term).
2334   // If it fails, change the logic to always allocate a multiple
2335   // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
2336   assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
2337 }
2338 
2339 void nmethod::copy_scopes_data(u_char* buffer, int size) {
2340   assert(scopes_data_size() >= size, "oob");
2341   memcpy(scopes_data_begin(), buffer, size);
2342 }
2343 
2344 
2345 #ifdef ASSERT
2346 static PcDesc* linear_search(nmethod* nm, int pc_offset, bool approximate) {
2347   PcDesc* lower = nm->scopes_pcs_begin();
2348   PcDesc* upper = nm->scopes_pcs_end();
2349   lower += 1; // exclude initial sentinel
2350   PcDesc* res = NULL;
2351   for (PcDesc* p = lower; p < upper; p++) {
2352     NOT_PRODUCT(--nmethod_stats.pc_desc_tests);  // don't count this call to match_desc
2353     if (match_desc(p, pc_offset, approximate)) {
2354       if (res == NULL)
2355         res = p;
2356       else
2357         res = (PcDesc*) badAddress;
2358     }
2359   }
2360   return res;
2361 }
2362 #endif
2363 
2364 
2365 // Finds a PcDesc with real-pc equal to "pc"
2366 PcDesc* nmethod::find_pc_desc_internal(address pc, bool approximate) {
2367   address base_address = code_begin();
2368   if ((pc < base_address) ||
2369       (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
2370     return NULL;  // PC is wildly out of range
2371   }
2372   int pc_offset = (int) (pc - base_address);
2373 
2374   // Check the PcDesc cache if it contains the desired PcDesc
2375   // (This as an almost 100% hit rate.)
2376   PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
2377   if (res != NULL) {
2378     assert(res == linear_search(this, pc_offset, approximate), "cache ok");
2379     return res;
2380   }
2381 
2382   // Fallback algorithm: quasi-linear search for the PcDesc
2383   // Find the last pc_offset less than the given offset.
2384   // The successor must be the required match, if there is a match at all.
2385   // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
2386   PcDesc* lower = scopes_pcs_begin();
2387   PcDesc* upper = scopes_pcs_end();
2388   upper -= 1; // exclude final sentinel
2389   if (lower >= upper)  return NULL;  // native method; no PcDescs at all
2390 
2391 #define assert_LU_OK \
2392   /* invariant on lower..upper during the following search: */ \
2393   assert(lower->pc_offset() <  pc_offset, "sanity"); \
2394   assert(upper->pc_offset() >= pc_offset, "sanity")
2395   assert_LU_OK;
2396 
2397   // Use the last successful return as a split point.
2398   PcDesc* mid = _pc_desc_cache.last_pc_desc();
2399   NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
2400   if (mid->pc_offset() < pc_offset) {
2401     lower = mid;
2402   } else {
2403     upper = mid;
2404   }
2405 
2406   // Take giant steps at first (4096, then 256, then 16, then 1)
2407   const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1);
2408   const int RADIX = (1 << LOG2_RADIX);
2409   for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
2410     while ((mid = lower + step) < upper) {
2411       assert_LU_OK;
2412       NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
2413       if (mid->pc_offset() < pc_offset) {
2414         lower = mid;
2415       } else {
2416         upper = mid;
2417         break;
2418       }
2419     }
2420     assert_LU_OK;
2421   }
2422 
2423   // Sneak up on the value with a linear search of length ~16.
2424   while (true) {
2425     assert_LU_OK;
2426     mid = lower + 1;
2427     NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
2428     if (mid->pc_offset() < pc_offset) {
2429       lower = mid;
2430     } else {
2431       upper = mid;
2432       break;
2433     }
2434   }
2435 #undef assert_LU_OK
2436 
2437   if (match_desc(upper, pc_offset, approximate)) {
2438     assert(upper == linear_search(this, pc_offset, approximate), "search ok");
2439     _pc_desc_cache.add_pc_desc(upper);
2440     return upper;
2441   } else {
2442     assert(NULL == linear_search(this, pc_offset, approximate), "search ok");
2443     return NULL;
2444   }
2445 }
2446 
2447 
2448 bool nmethod::check_all_dependencies() {
2449   bool found_check = false;
2450   // wholesale check of all dependencies
2451   for (Dependencies::DepStream deps(this); deps.next(); ) {
2452     if (deps.check_dependency() != NULL) {
2453       found_check = true;
2454       NOT_DEBUG(break);
2455     }
2456   }
2457   return found_check;  // tell caller if we found anything
2458 }
2459 
2460 bool nmethod::check_dependency_on(DepChange& changes) {
2461   // What has happened:
2462   // 1) a new class dependee has been added
2463   // 2) dependee and all its super classes have been marked
2464   bool found_check = false;  // set true if we are upset
2465   for (Dependencies::DepStream deps(this); deps.next(); ) {
2466     // Evaluate only relevant dependencies.
2467     if (deps.spot_check_dependency_at(changes) != NULL) {
2468       found_check = true;
2469       NOT_DEBUG(break);
2470     }
2471   }
2472   return found_check;
2473 }
2474 
2475 bool nmethod::is_evol_dependent_on(Klass* dependee) {
2476   InstanceKlass *dependee_ik = InstanceKlass::cast(dependee);
2477   Array<Method*>* dependee_methods = dependee_ik->methods();
2478   for (Dependencies::DepStream deps(this); deps.next(); ) {
2479     if (deps.type() == Dependencies::evol_method) {
2480       Method* method = deps.method_argument(0);
2481       for (int j = 0; j < dependee_methods->length(); j++) {
2482         if (dependee_methods->at(j) == method) {
2483           // RC_TRACE macro has an embedded ResourceMark
2484           RC_TRACE(0x01000000,
2485             ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on method %s.%s(%s)",
2486             _method->method_holder()->external_name(),
2487             _method->name()->as_C_string(),
2488             _method->signature()->as_C_string(), compile_id(),
2489             method->method_holder()->external_name(),
2490             method->name()->as_C_string(),
2491             method->signature()->as_C_string()));
2492           if (TraceDependencies || LogCompilation)
2493             deps.log_dependency(dependee);
2494           return true;
2495         }
2496       }
2497     }
2498   }
2499   return false;
2500 }
2501 
2502 // Called from mark_for_deoptimization, when dependee is invalidated.
2503 bool nmethod::is_dependent_on_method(Method* dependee) {
2504   for (Dependencies::DepStream deps(this); deps.next(); ) {
2505     if (deps.type() != Dependencies::evol_method)
2506       continue;
2507     Method* method = deps.method_argument(0);
2508     if (method == dependee) return true;
2509   }
2510   return false;
2511 }
2512 
2513 
2514 bool nmethod::is_patchable_at(address instr_addr) {
2515   assert(insts_contains(instr_addr), "wrong nmethod used");
2516   if (is_zombie()) {
2517     // a zombie may never be patched
2518     return false;
2519   }
2520   return true;
2521 }
2522 
2523 
2524 address nmethod::continuation_for_implicit_exception(address pc) {
2525   // Exception happened outside inline-cache check code => we are inside
2526   // an active nmethod => use cpc to determine a return address
2527   int exception_offset = pc - code_begin();
2528   int cont_offset = ImplicitExceptionTable(this).at( exception_offset );
2529 #ifdef ASSERT
2530   if (cont_offset == 0) {
2531     Thread* thread = ThreadLocalStorage::get_thread_slow();
2532     ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY
2533     HandleMark hm(thread);
2534     ResourceMark rm(thread);
2535     CodeBlob* cb = CodeCache::find_blob(pc);
2536     assert(cb != NULL && cb == this, "");
2537     tty->print_cr("implicit exception happened at " INTPTR_FORMAT, pc);
2538     print();
2539     method()->print_codes();
2540     print_code();
2541     print_pcs();
2542   }
2543 #endif
2544   if (cont_offset == 0) {
2545     // Let the normal error handling report the exception
2546     return NULL;
2547   }
2548   return code_begin() + cont_offset;
2549 }
2550 
2551 
2552 
2553 void nmethod_init() {
2554   // make sure you didn't forget to adjust the filler fields
2555   assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
2556 }
2557 
2558 
2559 //-------------------------------------------------------------------------------------------
2560 
2561 
2562 // QQQ might we make this work from a frame??
2563 nmethodLocker::nmethodLocker(address pc) {
2564   CodeBlob* cb = CodeCache::find_blob(pc);
2565   guarantee(cb != NULL && cb->is_nmethod(), "bad pc for a nmethod found");
2566   _nm = (nmethod*)cb;
2567   lock_nmethod(_nm);
2568 }
2569 
2570 // Only JvmtiDeferredEvent::compiled_method_unload_event()
2571 // should pass zombie_ok == true.
2572 void nmethodLocker::lock_nmethod(nmethod* nm, bool zombie_ok) {
2573   if (nm == NULL)  return;
2574   Atomic::inc(&nm->_lock_count);
2575   guarantee(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method");
2576 }
2577 
2578 void nmethodLocker::unlock_nmethod(nmethod* nm) {
2579   if (nm == NULL)  return;
2580   Atomic::dec(&nm->_lock_count);
2581   guarantee(nm->_lock_count >= 0, "unmatched nmethod lock/unlock");
2582 }
2583 
2584 
2585 // -----------------------------------------------------------------------------
2586 // nmethod::get_deopt_original_pc
2587 //
2588 // Return the original PC for the given PC if:
2589 // (a) the given PC belongs to a nmethod and
2590 // (b) it is a deopt PC
2591 address nmethod::get_deopt_original_pc(const frame* fr) {
2592   if (fr->cb() == NULL)  return NULL;
2593 
2594   nmethod* nm = fr->cb()->as_nmethod_or_null();
2595   if (nm != NULL && nm->is_deopt_pc(fr->pc()))
2596     return nm->get_original_pc(fr);
2597 
2598   return NULL;
2599 }
2600 
2601 
2602 // -----------------------------------------------------------------------------
2603 // MethodHandle
2604 
2605 bool nmethod::is_method_handle_return(address return_pc) {
2606   if (!has_method_handle_invokes())  return false;
2607   PcDesc* pd = pc_desc_at(return_pc);
2608   if (pd == NULL)
2609     return false;
2610   return pd->is_method_handle_invoke();
2611 }
2612 
2613 
2614 // -----------------------------------------------------------------------------
2615 // Verification
2616 
2617 class VerifyOopsClosure: public OopClosure {
2618   nmethod* _nm;
2619   bool     _ok;
2620 public:
2621   VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
2622   bool ok() { return _ok; }
2623   virtual void do_oop(oop* p) {
2624     if ((*p) == NULL || (*p)->is_oop())  return;
2625     if (_ok) {
2626       _nm->print_nmethod(true);
2627       _ok = false;
2628     }
2629     tty->print_cr("*** non-oop "PTR_FORMAT" found at "PTR_FORMAT" (offset %d)",
2630                   (void *)(*p), (intptr_t)p, (int)((intptr_t)p - (intptr_t)_nm));
2631   }
2632   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2633 };
2634 
2635 void nmethod::verify() {
2636 
2637   // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant
2638   // seems odd.
2639 
2640   if( is_zombie() || is_not_entrant() )
2641     return;
2642 
2643   // Make sure all the entry points are correctly aligned for patching.
2644   NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point());
2645 
2646   // assert(method()->is_oop(), "must be valid");
2647 
2648   ResourceMark rm;
2649 
2650   if (!CodeCache::contains(this)) {
2651     fatal(err_msg("nmethod at " INTPTR_FORMAT " not in zone", this));
2652   }
2653 
2654   if(is_native_method() )
2655     return;
2656 
2657   nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
2658   if (nm != this) {
2659     fatal(err_msg("findNMethod did not find this nmethod (" INTPTR_FORMAT ")",
2660                   this));
2661   }
2662 
2663   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2664     if (! p->verify(this)) {
2665       tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", this);
2666     }
2667   }
2668 
2669   VerifyOopsClosure voc(this);
2670   oops_do(&voc);
2671   assert(voc.ok(), "embedded oops must be OK");
2672   verify_scavenge_root_oops();
2673 
2674   verify_scopes();
2675 }
2676 
2677 
2678 void nmethod::verify_interrupt_point(address call_site) {
2679   // Verify IC only when nmethod installation is finished.
2680   bool is_installed = (method()->code() == this) // nmethod is in state 'in_use' and installed
2681                       || !this->is_in_use();     // nmethod is installed, but not in 'in_use' state
2682   if (is_installed) {
2683     Thread *cur = Thread::current();
2684     if (CompiledIC_lock->owner() == cur ||
2685         ((cur->is_VM_thread() || cur->is_ConcurrentGC_thread()) &&
2686          SafepointSynchronize::is_at_safepoint())) {
2687       CompiledIC_at(this, call_site);
2688       CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
2689     } else {
2690       MutexLocker ml_verify (CompiledIC_lock);
2691       CompiledIC_at(this, call_site);
2692     }
2693   }
2694 
2695   PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
2696   assert(pd != NULL, "PcDesc must exist");
2697   for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(),
2698                                      pd->obj_decode_offset(), pd->should_reexecute(),
2699                                      pd->return_oop());
2700        !sd->is_top(); sd = sd->sender()) {
2701     sd->verify();
2702   }
2703 }
2704 
2705 void nmethod::verify_scopes() {
2706   if( !method() ) return;       // Runtime stubs have no scope
2707   if (method()->is_native()) return; // Ignore stub methods.
2708   // iterate through all interrupt point
2709   // and verify the debug information is valid.
2710   RelocIterator iter((nmethod*)this);
2711   while (iter.next()) {
2712     address stub = NULL;
2713     switch (iter.type()) {
2714       case relocInfo::virtual_call_type:
2715         verify_interrupt_point(iter.addr());
2716         break;
2717       case relocInfo::opt_virtual_call_type:
2718         stub = iter.opt_virtual_call_reloc()->static_stub();
2719         verify_interrupt_point(iter.addr());
2720         break;
2721       case relocInfo::static_call_type:
2722         stub = iter.static_call_reloc()->static_stub();
2723         //verify_interrupt_point(iter.addr());
2724         break;
2725       case relocInfo::runtime_call_type:
2726         address destination = iter.reloc()->value();
2727         // Right now there is no way to find out which entries support
2728         // an interrupt point.  It would be nice if we had this
2729         // information in a table.
2730         break;
2731     }
2732     assert(stub == NULL || stub_contains(stub), "static call stub outside stub section");
2733   }
2734 }
2735 
2736 
2737 // -----------------------------------------------------------------------------
2738 // Non-product code
2739 #ifndef PRODUCT
2740 
2741 class DebugScavengeRoot: public OopClosure {
2742   nmethod* _nm;
2743   bool     _ok;
2744 public:
2745   DebugScavengeRoot(nmethod* nm) : _nm(nm), _ok(true) { }
2746   bool ok() { return _ok; }
2747   virtual void do_oop(oop* p) {
2748     if ((*p) == NULL || !(*p)->is_scavengable())  return;
2749     if (_ok) {
2750       _nm->print_nmethod(true);
2751       _ok = false;
2752     }
2753     tty->print_cr("*** scavengable oop "PTR_FORMAT" found at "PTR_FORMAT" (offset %d)",
2754                   (void *)(*p), (intptr_t)p, (int)((intptr_t)p - (intptr_t)_nm));
2755     (*p)->print();
2756   }
2757   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2758 };
2759 
2760 void nmethod::verify_scavenge_root_oops() {
2761   if (UseG1GC) {
2762     return;
2763   }
2764 
2765   if (!on_scavenge_root_list()) {
2766     // Actually look inside, to verify the claim that it's clean.
2767     DebugScavengeRoot debug_scavenge_root(this);
2768     oops_do(&debug_scavenge_root);
2769     if (!debug_scavenge_root.ok())
2770       fatal("found an unadvertised bad scavengable oop in the code cache");
2771   }
2772   assert(scavenge_root_not_marked(), "");
2773 }
2774 
2775 #endif // PRODUCT
2776 
2777 // Printing operations
2778 
2779 void nmethod::print() const {
2780   ResourceMark rm;
2781   ttyLocker ttyl;   // keep the following output all in one block
2782 
2783   tty->print("Compiled method ");
2784 
2785   if (is_compiled_by_c1()) {
2786     tty->print("(c1) ");
2787   } else if (is_compiled_by_c2()) {
2788     tty->print("(c2) ");
2789   } else if (is_compiled_by_shark()) {
2790     tty->print("(shark) ");
2791   } else {
2792     tty->print("(nm) ");
2793   }
2794 
2795   print_on(tty, NULL);
2796 
2797   if (WizardMode) {
2798     tty->print("((nmethod*) "INTPTR_FORMAT ") ", this);
2799     tty->print(" for method " INTPTR_FORMAT , (address)method());
2800     tty->print(" { ");
2801     if (is_in_use())      tty->print("in_use ");
2802     if (is_not_entrant()) tty->print("not_entrant ");
2803     if (is_zombie())      tty->print("zombie ");
2804     if (is_unloaded())    tty->print("unloaded ");
2805     if (on_scavenge_root_list())  tty->print("scavenge_root ");
2806     tty->print_cr("}:");
2807   }
2808   if (size              () > 0) tty->print_cr(" total in heap  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2809                                               (address)this,
2810                                               (address)this + size(),
2811                                               size());
2812   if (relocation_size   () > 0) tty->print_cr(" relocation     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2813                                               relocation_begin(),
2814                                               relocation_end(),
2815                                               relocation_size());
2816   if (consts_size       () > 0) tty->print_cr(" constants      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2817                                               consts_begin(),
2818                                               consts_end(),
2819                                               consts_size());
2820   if (insts_size        () > 0) tty->print_cr(" main code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2821                                               insts_begin(),
2822                                               insts_end(),
2823                                               insts_size());
2824   if (stub_size         () > 0) tty->print_cr(" stub code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2825                                               stub_begin(),
2826                                               stub_end(),
2827                                               stub_size());
2828   if (oops_size         () > 0) tty->print_cr(" oops           [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2829                                               oops_begin(),
2830                                               oops_end(),
2831                                               oops_size());
2832   if (metadata_size      () > 0) tty->print_cr(" metadata       [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2833                                               metadata_begin(),
2834                                               metadata_end(),
2835                                               metadata_size());
2836   if (scopes_data_size  () > 0) tty->print_cr(" scopes data    [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2837                                               scopes_data_begin(),
2838                                               scopes_data_end(),
2839                                               scopes_data_size());
2840   if (scopes_pcs_size   () > 0) tty->print_cr(" scopes pcs     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2841                                               scopes_pcs_begin(),
2842                                               scopes_pcs_end(),
2843                                               scopes_pcs_size());
2844   if (dependencies_size () > 0) tty->print_cr(" dependencies   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2845                                               dependencies_begin(),
2846                                               dependencies_end(),
2847                                               dependencies_size());
2848   if (handler_table_size() > 0) tty->print_cr(" handler table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2849                                               handler_table_begin(),
2850                                               handler_table_end(),
2851                                               handler_table_size());
2852   if (nul_chk_table_size() > 0) tty->print_cr(" nul chk table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2853                                               nul_chk_table_begin(),
2854                                               nul_chk_table_end(),
2855                                               nul_chk_table_size());
2856 }
2857 
2858 void nmethod::print_code() {
2859   HandleMark hm;
2860   ResourceMark m;
2861   Disassembler::decode(this);
2862 }
2863 
2864 
2865 #ifndef PRODUCT
2866 
2867 void nmethod::print_scopes() {
2868   // Find the first pc desc for all scopes in the code and print it.
2869   ResourceMark rm;
2870   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2871     if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
2872       continue;
2873 
2874     ScopeDesc* sd = scope_desc_at(p->real_pc(this));
2875     sd->print_on(tty, p);
2876   }
2877 }
2878 
2879 void nmethod::print_dependencies() {
2880   ResourceMark rm;
2881   ttyLocker ttyl;   // keep the following output all in one block
2882   tty->print_cr("Dependencies:");
2883   for (Dependencies::DepStream deps(this); deps.next(); ) {
2884     deps.print_dependency();
2885     Klass* ctxk = deps.context_type();
2886     if (ctxk != NULL) {
2887       if (ctxk->oop_is_instance() && ((InstanceKlass*)ctxk)->is_dependent_nmethod(this)) {
2888         tty->print_cr("   [nmethod<=klass]%s", ctxk->external_name());
2889       }
2890     }
2891     deps.log_dependency();  // put it into the xml log also
2892   }
2893 }
2894 
2895 
2896 void nmethod::print_relocations() {
2897   ResourceMark m;       // in case methods get printed via the debugger
2898   tty->print_cr("relocations:");
2899   RelocIterator iter(this);
2900   iter.print();
2901   if (UseRelocIndex) {
2902     jint* index_end   = (jint*)relocation_end() - 1;
2903     jint  index_size  = *index_end;
2904     jint* index_start = (jint*)( (address)index_end - index_size );
2905     tty->print_cr("    index @" INTPTR_FORMAT ": index_size=%d", index_start, index_size);
2906     if (index_size > 0) {
2907       jint* ip;
2908       for (ip = index_start; ip+2 <= index_end; ip += 2)
2909         tty->print_cr("  (%d %d) addr=" INTPTR_FORMAT " @" INTPTR_FORMAT,
2910                       ip[0],
2911                       ip[1],
2912                       header_end()+ip[0],
2913                       relocation_begin()-1+ip[1]);
2914       for (; ip < index_end; ip++)
2915         tty->print_cr("  (%d ?)", ip[0]);
2916       tty->print_cr("          @" INTPTR_FORMAT ": index_size=%d", ip, *ip);
2917       ip++;
2918       tty->print_cr("reloc_end @" INTPTR_FORMAT ":", ip);
2919     }
2920   }
2921 }
2922 
2923 
2924 void nmethod::print_pcs() {
2925   ResourceMark m;       // in case methods get printed via debugger
2926   tty->print_cr("pc-bytecode offsets:");
2927   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2928     p->print(this);
2929   }
2930 }
2931 
2932 #endif // PRODUCT
2933 
2934 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
2935   RelocIterator iter(this, begin, end);
2936   bool have_one = false;
2937   while (iter.next()) {
2938     have_one = true;
2939     switch (iter.type()) {
2940         case relocInfo::none:                  return "no_reloc";
2941         case relocInfo::oop_type: {
2942           stringStream st;
2943           oop_Relocation* r = iter.oop_reloc();
2944           oop obj = r->oop_value();
2945           st.print("oop(");
2946           if (obj == NULL) st.print("NULL");
2947           else obj->print_value_on(&st);
2948           st.print(")");
2949           return st.as_string();
2950         }
2951         case relocInfo::metadata_type: {
2952           stringStream st;
2953           metadata_Relocation* r = iter.metadata_reloc();
2954           Metadata* obj = r->metadata_value();
2955           st.print("metadata(");
2956           if (obj == NULL) st.print("NULL");
2957           else obj->print_value_on(&st);
2958           st.print(")");
2959           return st.as_string();
2960         }
2961         case relocInfo::virtual_call_type:     return "virtual_call";
2962         case relocInfo::opt_virtual_call_type: return "optimized virtual_call";
2963         case relocInfo::static_call_type:      return "static_call";
2964         case relocInfo::static_stub_type:      return "static_stub";
2965         case relocInfo::runtime_call_type:     return "runtime_call";
2966         case relocInfo::external_word_type:    return "external_word";
2967         case relocInfo::internal_word_type:    return "internal_word";
2968         case relocInfo::section_word_type:     return "section_word";
2969         case relocInfo::poll_type:             return "poll";
2970         case relocInfo::poll_return_type:      return "poll_return";
2971         case relocInfo::type_mask:             return "type_bit_mask";
2972     }
2973   }
2974   return have_one ? "other" : NULL;
2975 }
2976 
2977 // Return a the last scope in (begin..end]
2978 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
2979   PcDesc* p = pc_desc_near(begin+1);
2980   if (p != NULL && p->real_pc(this) <= end) {
2981     return new ScopeDesc(this, p->scope_decode_offset(),
2982                          p->obj_decode_offset(), p->should_reexecute(),
2983                          p->return_oop());
2984   }
2985   return NULL;
2986 }
2987 
2988 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const {
2989   if (block_begin == entry_point())             stream->print_cr("[Entry Point]");
2990   if (block_begin == verified_entry_point())    stream->print_cr("[Verified Entry Point]");
2991   if (block_begin == exception_begin())         stream->print_cr("[Exception Handler]");
2992   if (block_begin == stub_begin())              stream->print_cr("[Stub Code]");
2993   if (block_begin == deopt_handler_begin())     stream->print_cr("[Deopt Handler Code]");
2994 
2995   if (has_method_handle_invokes())
2996     if (block_begin == deopt_mh_handler_begin())  stream->print_cr("[Deopt MH Handler Code]");
2997 
2998   if (block_begin == consts_begin())            stream->print_cr("[Constants]");
2999 
3000   if (block_begin == entry_point()) {
3001     methodHandle m = method();
3002     if (m.not_null()) {
3003       stream->print("  # ");
3004       m->print_value_on(stream);
3005       stream->cr();
3006     }
3007     if (m.not_null() && !is_osr_method()) {
3008       ResourceMark rm;
3009       int sizeargs = m->size_of_parameters();
3010       BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
3011       VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
3012       {
3013         int sig_index = 0;
3014         if (!m->is_static())
3015           sig_bt[sig_index++] = T_OBJECT; // 'this'
3016         for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {
3017           BasicType t = ss.type();
3018           sig_bt[sig_index++] = t;
3019           if (type2size[t] == 2) {
3020             sig_bt[sig_index++] = T_VOID;
3021           } else {
3022             assert(type2size[t] == 1, "size is 1 or 2");
3023           }
3024         }
3025         assert(sig_index == sizeargs, "");
3026       }
3027       const char* spname = "sp"; // make arch-specific?
3028       intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false);
3029       int stack_slot_offset = this->frame_size() * wordSize;
3030       int tab1 = 14, tab2 = 24;
3031       int sig_index = 0;
3032       int arg_index = (m->is_static() ? 0 : -1);
3033       bool did_old_sp = false;
3034       for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {
3035         bool at_this = (arg_index == -1);
3036         bool at_old_sp = false;
3037         BasicType t = (at_this ? T_OBJECT : ss.type());
3038         assert(t == sig_bt[sig_index], "sigs in sync");
3039         if (at_this)
3040           stream->print("  # this: ");
3041         else
3042           stream->print("  # parm%d: ", arg_index);
3043         stream->move_to(tab1);
3044         VMReg fst = regs[sig_index].first();
3045         VMReg snd = regs[sig_index].second();
3046         if (fst->is_reg()) {
3047           stream->print("%s", fst->name());
3048           if (snd->is_valid())  {
3049             stream->print(":%s", snd->name());
3050           }
3051         } else if (fst->is_stack()) {
3052           int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
3053           if (offset == stack_slot_offset)  at_old_sp = true;
3054           stream->print("[%s+0x%x]", spname, offset);
3055         } else {
3056           stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
3057         }
3058         stream->print(" ");
3059         stream->move_to(tab2);
3060         stream->print("= ");
3061         if (at_this) {
3062           m->method_holder()->print_value_on(stream);
3063         } else {
3064           bool did_name = false;
3065           if (!at_this && ss.is_object()) {
3066             Symbol* name = ss.as_symbol_or_null();
3067             if (name != NULL) {
3068               name->print_value_on(stream);
3069               did_name = true;
3070             }
3071           }
3072           if (!did_name)
3073             stream->print("%s", type2name(t));
3074         }
3075         if (at_old_sp) {
3076           stream->print("  (%s of caller)", spname);
3077           did_old_sp = true;
3078         }
3079         stream->cr();
3080         sig_index += type2size[t];
3081         arg_index += 1;
3082         if (!at_this)  ss.next();
3083       }
3084       if (!did_old_sp) {
3085         stream->print("  # ");
3086         stream->move_to(tab1);
3087         stream->print("[%s+0x%x]", spname, stack_slot_offset);
3088         stream->print("  (%s of caller)", spname);
3089         stream->cr();
3090       }
3091     }
3092   }
3093 }
3094 
3095 void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, u_char* end) {
3096   // First, find an oopmap in (begin, end].
3097   // We use the odd half-closed interval so that oop maps and scope descs
3098   // which are tied to the byte after a call are printed with the call itself.
3099   address base = code_begin();
3100   OopMapSet* oms = oop_maps();
3101   if (oms != NULL) {
3102     for (int i = 0, imax = oms->size(); i < imax; i++) {
3103       OopMap* om = oms->at(i);
3104       address pc = base + om->offset();
3105       if (pc > begin) {
3106         if (pc <= end) {
3107           st->move_to(column);
3108           st->print("; ");
3109           om->print_on(st);
3110         }
3111         break;
3112       }
3113     }
3114   }
3115 
3116   // Print any debug info present at this pc.
3117   ScopeDesc* sd  = scope_desc_in(begin, end);
3118   if (sd != NULL) {
3119     st->move_to(column);
3120     if (sd->bci() == SynchronizationEntryBCI) {
3121       st->print(";*synchronization entry");
3122     } else {
3123       if (sd->method() == NULL) {
3124         st->print("method is NULL");
3125       } else if (sd->method()->is_native()) {
3126         st->print("method is native");
3127       } else {
3128         Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
3129         st->print(";*%s", Bytecodes::name(bc));
3130         switch (bc) {
3131         case Bytecodes::_invokevirtual:
3132         case Bytecodes::_invokespecial:
3133         case Bytecodes::_invokestatic:
3134         case Bytecodes::_invokeinterface:
3135           {
3136             Bytecode_invoke invoke(sd->method(), sd->bci());
3137             st->print(" ");
3138             if (invoke.name() != NULL)
3139               invoke.name()->print_symbol_on(st);
3140             else
3141               st->print("<UNKNOWN>");
3142             break;
3143           }
3144         case Bytecodes::_getfield:
3145         case Bytecodes::_putfield:
3146         case Bytecodes::_getstatic:
3147         case Bytecodes::_putstatic:
3148           {
3149             Bytecode_field field(sd->method(), sd->bci());
3150             st->print(" ");
3151             if (field.name() != NULL)
3152               field.name()->print_symbol_on(st);
3153             else
3154               st->print("<UNKNOWN>");
3155           }
3156         }
3157       }
3158     }
3159 
3160     // Print all scopes
3161     for (;sd != NULL; sd = sd->sender()) {
3162       st->move_to(column);
3163       st->print("; -");
3164       if (sd->method() == NULL) {
3165         st->print("method is NULL");
3166       } else {
3167         sd->method()->print_short_name(st);
3168       }
3169       int lineno = sd->method()->line_number_from_bci(sd->bci());
3170       if (lineno != -1) {
3171         st->print("@%d (line %d)", sd->bci(), lineno);
3172       } else {
3173         st->print("@%d", sd->bci());
3174       }
3175       st->cr();
3176     }
3177   }
3178 
3179   // Print relocation information
3180   const char* str = reloc_string_for(begin, end);
3181   if (str != NULL) {
3182     if (sd != NULL) st->cr();
3183     st->move_to(column);
3184     st->print(";   {%s}", str);
3185   }
3186   int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin());
3187   if (cont_offset != 0) {
3188     st->move_to(column);
3189     st->print("; implicit exception: dispatches to " INTPTR_FORMAT, code_begin() + cont_offset);
3190   }
3191 
3192 }
3193 
3194 #ifndef PRODUCT
3195 
3196 void nmethod::print_value_on(outputStream* st) const {
3197   st->print("nmethod");
3198   print_on(st, NULL);
3199 }
3200 
3201 void nmethod::print_calls(outputStream* st) {
3202   RelocIterator iter(this);
3203   while (iter.next()) {
3204     switch (iter.type()) {
3205     case relocInfo::virtual_call_type:
3206     case relocInfo::opt_virtual_call_type: {
3207       VerifyMutexLocker mc(CompiledIC_lock);
3208       CompiledIC_at(&iter)->print();
3209       break;
3210     }
3211     case relocInfo::static_call_type:
3212       st->print_cr("Static call at " INTPTR_FORMAT, iter.reloc()->addr());
3213       compiledStaticCall_at(iter.reloc())->print();
3214       break;
3215     }
3216   }
3217 }
3218 
3219 void nmethod::print_handler_table() {
3220   ExceptionHandlerTable(this).print();
3221 }
3222 
3223 void nmethod::print_nul_chk_table() {
3224   ImplicitExceptionTable(this).print(code_begin());
3225 }
3226 
3227 void nmethod::print_statistics() {
3228   ttyLocker ttyl;
3229   if (xtty != NULL)  xtty->head("statistics type='nmethod'");
3230   nmethod_stats.print_native_nmethod_stats();
3231   nmethod_stats.print_nmethod_stats();
3232   DebugInformationRecorder::print_statistics();
3233   nmethod_stats.print_pc_stats();
3234   Dependencies::print_statistics();
3235   if (xtty != NULL)  xtty->tail("statistics");
3236 }
3237 
3238 #endif // PRODUCT