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