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