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