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()) {
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   // Remove from list of active nmethods
1391   if (method() != NULL)
1392     method()->method_holder()->remove_osr_nmethod(this);
1393 }
1394 
1395 void nmethod::log_state_change() const {
1396   if (LogCompilation) {
1397     if (xtty != NULL) {
1398       ttyLocker ttyl;  // keep the following output all in one block
1399       if (_state == unloaded) {
1400         xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'",
1401                          os::current_thread_id());
1402       } else {
1403         xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s",
1404                          os::current_thread_id(),
1405                          (_state == zombie ? " zombie='1'" : ""));
1406       }
1407       log_identity(xtty);
1408       xtty->stamp();
1409       xtty->end_elem();
1410     }
1411   }
1412   if (PrintCompilation && _state != unloaded) {
1413     print_on(tty, _state == zombie ? "made zombie" : "made not entrant");
1414   }
1415 }
1416 
1417 /**
1418  * Common functionality for both make_not_entrant and make_zombie
1419  */
1420 bool nmethod::make_not_entrant_or_zombie(unsigned int state) {
1421   assert(state == zombie || state == not_entrant, "must be zombie or not_entrant");
1422   assert(!is_zombie(), "should not already be a zombie");
1423 
1424   // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below.
1425   nmethodLocker nml(this);
1426   methodHandle the_method(method());
1427   NoSafepointVerifier nsv;
1428 
1429   // during patching, depending on the nmethod state we must notify the GC that
1430   // code has been unloaded, unregistering it. We cannot do this right while
1431   // holding the Patching_lock because we need to use the CodeCache_lock. This
1432   // would be prone to deadlocks.
1433   // This flag is used to remember whether we need to later lock and unregister.
1434   bool nmethod_needs_unregister = false;
1435 
1436   {
1437     // invalidate osr nmethod before acquiring the patching lock since
1438     // they both acquire leaf locks and we don't want a deadlock.
1439     // This logic is equivalent to the logic below for patching the
1440     // verified entry point of regular methods.
1441     if (is_osr_method()) {
1442       // this effectively makes the osr nmethod not entrant
1443       invalidate_osr_method();
1444     }
1445 
1446     // Enter critical section.  Does not block for safepoint.
1447     MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
1448 
1449     if (_state == state) {
1450       // another thread already performed this transition so nothing
1451       // to do, but return false to indicate this.
1452       return false;
1453     }
1454 
1455     // The caller can be calling the method statically or through an inline
1456     // cache call.
1457     if (!is_osr_method() && !is_not_entrant()) {
1458       NativeJump::patch_verified_entry(entry_point(), verified_entry_point(),
1459                   SharedRuntime::get_handle_wrong_method_stub());
1460     }
1461 
1462     if (is_in_use() && update_recompile_counts()) {
1463       // It's a true state change, so mark the method as decompiled.
1464       // Do it only for transition from alive.
1465       inc_decompile_count();
1466     }
1467 
1468     // If the state is becoming a zombie, signal to unregister the nmethod with
1469     // the heap.
1470     // This nmethod may have already been unloaded during a full GC.
1471     if ((state == zombie) && !is_unloaded()) {
1472       nmethod_needs_unregister = true;
1473     }
1474 
1475     // Must happen before state change. Otherwise we have a race condition in
1476     // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately
1477     // transition its state from 'not_entrant' to 'zombie' without having to wait
1478     // for stack scanning.
1479     if (state == not_entrant) {
1480       mark_as_seen_on_stack();
1481       OrderAccess::storestore();
1482     }
1483 
1484     // Change state
1485     _state = state;
1486 
1487     // Log the transition once
1488     log_state_change();
1489 
1490     // Invalidate while holding the patching lock
1491     JVMCI_ONLY(maybe_invalidate_installed_code());
1492 
1493     // Remove nmethod from method.
1494     // We need to check if both the _code and _from_compiled_code_entry_point
1495     // refer to this nmethod because there is a race in setting these two fields
1496     // in Method* as seen in bugid 4947125.
1497     // If the vep() points to the zombie nmethod, the memory for the nmethod
1498     // could be flushed and the compiler and vtable stubs could still call
1499     // through it.
1500     if (method() != NULL && (method()->code() == this ||
1501                              method()->from_compiled_entry() == verified_entry_point())) {
1502       HandleMark hm;
1503       method()->clear_code();
1504     }
1505   } // leave critical region under Patching_lock
1506 
1507   // When the nmethod becomes zombie it is no longer alive so the
1508   // dependencies must be flushed.  nmethods in the not_entrant
1509   // state will be flushed later when the transition to zombie
1510   // happens or they get unloaded.
1511   if (state == zombie) {
1512     {
1513       // Flushing dependecies must be done before any possible
1514       // safepoint can sneak in, otherwise the oops used by the
1515       // dependency logic could have become stale.
1516       MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1517       if (nmethod_needs_unregister) {
1518         Universe::heap()->unregister_nmethod(this);
1519 #ifdef JVMCI
1520         _jvmci_installed_code = NULL;
1521         _speculation_log = NULL;
1522 #endif
1523       }
1524       flush_dependencies(NULL);
1525     }
1526 
1527     // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload
1528     // event and it hasn't already been reported for this nmethod then
1529     // report it now. The event may have been reported earilier if the GC
1530     // marked it for unloading). JvmtiDeferredEventQueue support means
1531     // we no longer go to a safepoint here.
1532     post_compiled_method_unload();
1533 
1534 #ifdef ASSERT
1535     // It's no longer safe to access the oops section since zombie
1536     // nmethods aren't scanned for GC.
1537     _oops_are_stale = true;
1538 #endif
1539      // the Method may be reclaimed by class unloading now that the
1540      // nmethod is in zombie state
1541     set_method(NULL);
1542   } else {
1543     assert(state == not_entrant, "other cases may need to be handled differently");
1544   }
1545 
1546   if (TraceCreateZombies) {
1547     ResourceMark m;
1548     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");
1549   }
1550 
1551   NMethodSweeper::report_state_change(this);
1552   return true;
1553 }
1554 
1555 void nmethod::flush() {
1556   // Note that there are no valid oops in the nmethod anymore.
1557   assert(is_zombie() || (is_osr_method() && is_unloaded()), "must be a zombie method");
1558   assert(is_marked_for_reclamation() || (is_osr_method() && is_unloaded()), "must be marked for reclamation");
1559 
1560   assert (!is_locked_by_vm(), "locked methods shouldn't be flushed");
1561   assert_locked_or_safepoint(CodeCache_lock);
1562 
1563   // completely deallocate this method
1564   Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, p2i(this));
1565   if (PrintMethodFlushing) {
1566     tty->print_cr("*flushing nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT
1567                   "/Free CodeCache:" SIZE_FORMAT "Kb",
1568                   _compile_id, p2i(this), CodeCache::blob_count(),
1569                   CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024);
1570   }
1571 
1572   // We need to deallocate any ExceptionCache data.
1573   // Note that we do not need to grab the nmethod lock for this, it
1574   // better be thread safe if we're disposing of it!
1575   ExceptionCache* ec = exception_cache();
1576   set_exception_cache(NULL);
1577   while(ec != NULL) {
1578     ExceptionCache* next = ec->next();
1579     delete ec;
1580     ec = next;
1581   }
1582 
1583   if (on_scavenge_root_list()) {
1584     CodeCache::drop_scavenge_root_nmethod(this);
1585   }
1586 
1587 #ifdef SHARK
1588   ((SharkCompiler *) compiler())->free_compiled_method(insts_begin());
1589 #endif // SHARK
1590 
1591   ((CodeBlob*)(this))->flush();
1592 
1593   CodeCache::free(this);
1594 }
1595 
1596 //
1597 // Notify all classes this nmethod is dependent on that it is no
1598 // longer dependent. This should only be called in two situations.
1599 // First, when a nmethod transitions to a zombie all dependents need
1600 // to be clear.  Since zombification happens at a safepoint there's no
1601 // synchronization issues.  The second place is a little more tricky.
1602 // During phase 1 of mark sweep class unloading may happen and as a
1603 // result some nmethods may get unloaded.  In this case the flushing
1604 // of dependencies must happen during phase 1 since after GC any
1605 // dependencies in the unloaded nmethod won't be updated, so
1606 // traversing the dependency information in unsafe.  In that case this
1607 // function is called with a non-NULL argument and this function only
1608 // notifies instanceKlasses that are reachable
1609 
1610 void nmethod::flush_dependencies(BoolObjectClosure* is_alive) {
1611   assert_locked_or_safepoint(CodeCache_lock);
1612   assert(Universe::heap()->is_gc_active() == (is_alive != NULL),
1613   "is_alive is non-NULL if and only if we are called during GC");
1614   if (!has_flushed_dependencies()) {
1615     set_has_flushed_dependencies();
1616     for (Dependencies::DepStream deps(this); deps.next(); ) {
1617       if (deps.type() == Dependencies::call_site_target_value) {
1618         // CallSite dependencies are managed on per-CallSite instance basis.
1619         oop call_site = deps.argument_oop(0);
1620         MethodHandles::remove_dependent_nmethod(call_site, this);
1621       } else {
1622         Klass* klass = deps.context_type();
1623         if (klass == NULL) {
1624           continue;  // ignore things like evol_method
1625         }
1626         // During GC the is_alive closure is non-NULL, and is used to
1627         // determine liveness of dependees that need to be updated.
1628         if (is_alive == NULL || klass->is_loader_alive(is_alive)) {
1629           // The GC defers deletion of this entry, since there might be multiple threads
1630           // iterating over the _dependencies graph. Other call paths are single-threaded
1631           // and may delete it immediately.
1632           bool delete_immediately = is_alive == NULL;
1633           InstanceKlass::cast(klass)->remove_dependent_nmethod(this, delete_immediately);
1634         }
1635       }
1636     }
1637   }
1638 }
1639 
1640 
1641 // If this oop is not live, the nmethod can be unloaded.
1642 bool nmethod::can_unload(BoolObjectClosure* is_alive, oop* root, bool unloading_occurred) {
1643   assert(root != NULL, "just checking");
1644   oop obj = *root;
1645   if (obj == NULL || is_alive->do_object_b(obj)) {
1646       return false;
1647   }
1648 
1649   // If ScavengeRootsInCode is true, an nmethod might be unloaded
1650   // simply because one of its constant oops has gone dead.
1651   // No actual classes need to be unloaded in order for this to occur.
1652   assert(unloading_occurred || ScavengeRootsInCode, "Inconsistency in unloading");
1653   make_unloaded(is_alive, obj);
1654   return true;
1655 }
1656 
1657 // ------------------------------------------------------------------
1658 // post_compiled_method_load_event
1659 // new method for install_code() path
1660 // Transfer information from compilation to jvmti
1661 void nmethod::post_compiled_method_load_event() {
1662 
1663   Method* moop = method();
1664   HOTSPOT_COMPILED_METHOD_LOAD(
1665       (char *) moop->klass_name()->bytes(),
1666       moop->klass_name()->utf8_length(),
1667       (char *) moop->name()->bytes(),
1668       moop->name()->utf8_length(),
1669       (char *) moop->signature()->bytes(),
1670       moop->signature()->utf8_length(),
1671       insts_begin(), insts_size());
1672 
1673   if (JvmtiExport::should_post_compiled_method_load() ||
1674       JvmtiExport::should_post_compiled_method_unload()) {
1675     get_and_cache_jmethod_id();
1676   }
1677 
1678   if (JvmtiExport::should_post_compiled_method_load()) {
1679     // Let the Service thread (which is a real Java thread) post the event
1680     MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
1681     JvmtiDeferredEventQueue::enqueue(
1682       JvmtiDeferredEvent::compiled_method_load_event(this));
1683   }
1684 }
1685 
1686 jmethodID nmethod::get_and_cache_jmethod_id() {
1687   if (_jmethod_id == NULL) {
1688     // Cache the jmethod_id since it can no longer be looked up once the
1689     // method itself has been marked for unloading.
1690     _jmethod_id = method()->jmethod_id();
1691   }
1692   return _jmethod_id;
1693 }
1694 
1695 void nmethod::post_compiled_method_unload() {
1696   if (unload_reported()) {
1697     // During unloading we transition to unloaded and then to zombie
1698     // and the unloading is reported during the first transition.
1699     return;
1700   }
1701 
1702   assert(_method != NULL && !is_unloaded(), "just checking");
1703   DTRACE_METHOD_UNLOAD_PROBE(method());
1704 
1705   // If a JVMTI agent has enabled the CompiledMethodUnload event then
1706   // post the event. Sometime later this nmethod will be made a zombie
1707   // by the sweeper but the Method* will not be valid at that point.
1708   // If the _jmethod_id is null then no load event was ever requested
1709   // so don't bother posting the unload.  The main reason for this is
1710   // that the jmethodID is a weak reference to the Method* so if
1711   // it's being unloaded there's no way to look it up since the weak
1712   // ref will have been cleared.
1713   if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) {
1714     assert(!unload_reported(), "already unloaded");
1715     JvmtiDeferredEvent event =
1716       JvmtiDeferredEvent::compiled_method_unload_event(this,
1717           _jmethod_id, insts_begin());
1718     if (SafepointSynchronize::is_at_safepoint()) {
1719       // Don't want to take the queueing lock. Add it as pending and
1720       // it will get enqueued later.
1721       JvmtiDeferredEventQueue::add_pending_event(event);
1722     } else {
1723       MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
1724       JvmtiDeferredEventQueue::enqueue(event);
1725     }
1726   }
1727 
1728   // The JVMTI CompiledMethodUnload event can be enabled or disabled at
1729   // any time. As the nmethod is being unloaded now we mark it has
1730   // having the unload event reported - this will ensure that we don't
1731   // attempt to report the event in the unlikely scenario where the
1732   // event is enabled at the time the nmethod is made a zombie.
1733   set_unload_reported();
1734 }
1735 
1736 void static clean_ic_if_metadata_is_dead(CompiledIC *ic, BoolObjectClosure *is_alive) {
1737   if (ic->is_icholder_call()) {
1738     // The only exception is compiledICHolder oops which may
1739     // yet be marked below. (We check this further below).
1740     CompiledICHolder* cichk_oop = ic->cached_icholder();
1741 
1742     if (cichk_oop->holder_method()->method_holder()->is_loader_alive(is_alive) &&
1743         cichk_oop->holder_klass()->is_loader_alive(is_alive)) {
1744       return;
1745     }
1746   } else {
1747     Metadata* ic_oop = ic->cached_metadata();
1748     if (ic_oop != NULL) {
1749       if (ic_oop->is_klass()) {
1750         if (((Klass*)ic_oop)->is_loader_alive(is_alive)) {
1751           return;
1752         }
1753       } else if (ic_oop->is_method()) {
1754         if (((Method*)ic_oop)->method_holder()->is_loader_alive(is_alive)) {
1755           return;
1756         }
1757       } else {
1758         ShouldNotReachHere();
1759       }
1760     }
1761   }
1762 
1763   ic->set_to_clean();
1764 }
1765 
1766 // This is called at the end of the strong tracing/marking phase of a
1767 // GC to unload an nmethod if it contains otherwise unreachable
1768 // oops.
1769 
1770 void nmethod::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
1771   // Make sure the oop's ready to receive visitors
1772   assert(!is_zombie() && !is_unloaded(),
1773          "should not call follow on zombie or unloaded nmethod");
1774 
1775   // If the method is not entrant then a JMP is plastered over the
1776   // first few bytes.  If an oop in the old code was there, that oop
1777   // should not get GC'd.  Skip the first few bytes of oops on
1778   // not-entrant methods.
1779   address low_boundary = verified_entry_point();
1780   if (is_not_entrant()) {
1781     low_boundary += NativeJump::instruction_size;
1782     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1783     // (See comment above.)
1784   }
1785 
1786   // The RedefineClasses() API can cause the class unloading invariant
1787   // to no longer be true. See jvmtiExport.hpp for details.
1788   // Also, leave a debugging breadcrumb in local flag.
1789   if (JvmtiExport::has_redefined_a_class()) {
1790     // This set of the unloading_occurred flag is done before the
1791     // call to post_compiled_method_unload() so that the unloading
1792     // of this nmethod is reported.
1793     unloading_occurred = true;
1794   }
1795 
1796   // Exception cache
1797   clean_exception_cache(is_alive);
1798 
1799   // If class unloading occurred we first iterate over all inline caches and
1800   // clear ICs where the cached oop is referring to an unloaded klass or method.
1801   // The remaining live cached oops will be traversed in the relocInfo::oop_type
1802   // iteration below.
1803   if (unloading_occurred) {
1804     RelocIterator iter(this, low_boundary);
1805     while(iter.next()) {
1806       if (iter.type() == relocInfo::virtual_call_type) {
1807         CompiledIC *ic = CompiledIC_at(&iter);
1808         clean_ic_if_metadata_is_dead(ic, is_alive);
1809       }
1810     }
1811   }
1812 
1813   // Compiled code
1814   {
1815   RelocIterator iter(this, low_boundary);
1816   while (iter.next()) {
1817     if (iter.type() == relocInfo::oop_type) {
1818       oop_Relocation* r = iter.oop_reloc();
1819       // In this loop, we must only traverse those oops directly embedded in
1820       // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
1821       assert(1 == (r->oop_is_immediate()) +
1822                   (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1823              "oop must be found in exactly one place");
1824       if (r->oop_is_immediate() && r->oop_value() != NULL) {
1825         if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1826           return;
1827         }
1828       }
1829     }
1830   }
1831   }
1832 
1833 
1834   // Scopes
1835   for (oop* p = oops_begin(); p < oops_end(); p++) {
1836     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
1837     if (can_unload(is_alive, p, unloading_occurred)) {
1838       return;
1839     }
1840   }
1841 
1842 #if INCLUDE_JVMCI
1843   // Follow JVMCI method
1844   BarrierSet* bs = Universe::heap()->barrier_set();
1845   if (_jvmci_installed_code != NULL) {
1846     if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) {
1847       if (!is_alive->do_object_b(_jvmci_installed_code)) {
1848         clear_jvmci_installed_code();
1849       }
1850     } else {
1851       if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) {
1852         return;
1853       }
1854     }
1855   }
1856 
1857   if (_speculation_log != NULL) {
1858     if (!is_alive->do_object_b(_speculation_log)) {
1859       bs->write_ref_nmethod_pre(&_speculation_log, this);
1860       _speculation_log = NULL;
1861       bs->write_ref_nmethod_post(&_speculation_log, this);
1862     }
1863   }
1864 #endif
1865 
1866 
1867   // Ensure that all metadata is still alive
1868   verify_metadata_loaders(low_boundary, is_alive);
1869 }
1870 
1871 template <class CompiledICorStaticCall>
1872 static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, BoolObjectClosure *is_alive, nmethod* from) {
1873   // Ok, to lookup references to zombies here
1874   CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
1875   if (cb != NULL && cb->is_nmethod()) {
1876     nmethod* nm = (nmethod*)cb;
1877 
1878     if (nm->unloading_clock() != nmethod::global_unloading_clock()) {
1879       // The nmethod has not been processed yet.
1880       return true;
1881     }
1882 
1883     // Clean inline caches pointing to both zombie and not_entrant methods
1884     if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1885       ic->set_to_clean();
1886       assert(ic->is_clean(), "nmethod " PTR_FORMAT "not clean %s", p2i(from), from->method()->name_and_sig_as_C_string());
1887     }
1888   }
1889 
1890   return false;
1891 }
1892 
1893 static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, BoolObjectClosure *is_alive, nmethod* from) {
1894   return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), is_alive, from);
1895 }
1896 
1897 static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, BoolObjectClosure *is_alive, nmethod* from) {
1898   return clean_if_nmethod_is_unloaded(csc, csc->destination(), is_alive, from);
1899 }
1900 
1901 bool nmethod::unload_if_dead_at(RelocIterator* iter_at_oop, BoolObjectClosure *is_alive, bool unloading_occurred) {
1902   assert(iter_at_oop->type() == relocInfo::oop_type, "Wrong relocation type");
1903 
1904   oop_Relocation* r = iter_at_oop->oop_reloc();
1905   // Traverse those oops directly embedded in the code.
1906   // Other oops (oop_index>0) are seen as part of scopes_oops.
1907   assert(1 == (r->oop_is_immediate()) +
1908          (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1909          "oop must be found in exactly one place");
1910   if (r->oop_is_immediate() && r->oop_value() != NULL) {
1911     // Unload this nmethod if the oop is dead.
1912     if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1913       return true;;
1914     }
1915   }
1916 
1917   return false;
1918 }
1919 
1920 
1921 bool nmethod::do_unloading_parallel(BoolObjectClosure* is_alive, bool unloading_occurred) {
1922   ResourceMark rm;
1923 
1924   // Make sure the oop's ready to receive visitors
1925   assert(!is_zombie() && !is_unloaded(),
1926          "should not call follow on zombie or unloaded nmethod");
1927 
1928   // If the method is not entrant then a JMP is plastered over the
1929   // first few bytes.  If an oop in the old code was there, that oop
1930   // should not get GC'd.  Skip the first few bytes of oops on
1931   // not-entrant methods.
1932   address low_boundary = verified_entry_point();
1933   if (is_not_entrant()) {
1934     low_boundary += NativeJump::instruction_size;
1935     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1936     // (See comment above.)
1937   }
1938 
1939   // The RedefineClasses() API can cause the class unloading invariant
1940   // to no longer be true. See jvmtiExport.hpp for details.
1941   // Also, leave a debugging breadcrumb in local flag.
1942   if (JvmtiExport::has_redefined_a_class()) {
1943     // This set of the unloading_occurred flag is done before the
1944     // call to post_compiled_method_unload() so that the unloading
1945     // of this nmethod is reported.
1946     unloading_occurred = true;
1947   }
1948 
1949   // Exception cache
1950   clean_exception_cache(is_alive);
1951 
1952   bool is_unloaded = false;
1953   bool postponed = false;
1954 
1955   RelocIterator iter(this, low_boundary);
1956   while(iter.next()) {
1957 
1958     switch (iter.type()) {
1959 
1960     case relocInfo::virtual_call_type:
1961       if (unloading_occurred) {
1962         // If class unloading occurred we first iterate over all inline caches and
1963         // clear ICs where the cached oop is referring to an unloaded klass or method.
1964         clean_ic_if_metadata_is_dead(CompiledIC_at(&iter), is_alive);
1965       }
1966 
1967       postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1968       break;
1969 
1970     case relocInfo::opt_virtual_call_type:
1971       postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1972       break;
1973 
1974     case relocInfo::static_call_type:
1975       postponed |= clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
1976       break;
1977 
1978     case relocInfo::oop_type:
1979       if (!is_unloaded) {
1980         is_unloaded = unload_if_dead_at(&iter, is_alive, unloading_occurred);
1981       }
1982       break;
1983 
1984     case relocInfo::metadata_type:
1985       break; // nothing to do.
1986     }
1987   }
1988 
1989   if (is_unloaded) {
1990     return postponed;
1991   }
1992 
1993   // Scopes
1994   for (oop* p = oops_begin(); p < oops_end(); p++) {
1995     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
1996     if (can_unload(is_alive, p, unloading_occurred)) {
1997       is_unloaded = true;
1998       break;
1999     }
2000   }
2001 
2002   if (is_unloaded) {
2003     return postponed;
2004   }
2005 
2006 #if INCLUDE_JVMCI
2007   // Follow JVMCI method
2008   BarrierSet* bs = Universe::heap()->barrier_set();
2009   if (_jvmci_installed_code != NULL) {
2010     if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) {
2011       if (!is_alive->do_object_b(_jvmci_installed_code)) {
2012         clear_jvmci_installed_code();
2013       }
2014     } else {
2015       if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) {
2016         is_unloaded = true;
2017       }
2018     }
2019   }
2020 
2021   if (_speculation_log != NULL) {
2022     if (!is_alive->do_object_b(_speculation_log)) {
2023       bs->write_ref_nmethod_pre(&_speculation_log, this);
2024       _speculation_log = NULL;
2025       bs->write_ref_nmethod_post(&_speculation_log, this);
2026     }
2027   }
2028 #endif
2029 
2030   // Ensure that all metadata is still alive
2031   verify_metadata_loaders(low_boundary, is_alive);
2032 
2033   return postponed;
2034 }
2035 
2036 void nmethod::do_unloading_parallel_postponed(BoolObjectClosure* is_alive, bool unloading_occurred) {
2037   ResourceMark rm;
2038 
2039   // Make sure the oop's ready to receive visitors
2040   assert(!is_zombie(),
2041          "should not call follow on zombie nmethod");
2042 
2043   // If the method is not entrant then a JMP is plastered over the
2044   // first few bytes.  If an oop in the old code was there, that oop
2045   // should not get GC'd.  Skip the first few bytes of oops on
2046   // not-entrant methods.
2047   address low_boundary = verified_entry_point();
2048   if (is_not_entrant()) {
2049     low_boundary += NativeJump::instruction_size;
2050     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
2051     // (See comment above.)
2052   }
2053 
2054   RelocIterator iter(this, low_boundary);
2055   while(iter.next()) {
2056 
2057     switch (iter.type()) {
2058 
2059     case relocInfo::virtual_call_type:
2060       clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
2061       break;
2062 
2063     case relocInfo::opt_virtual_call_type:
2064       clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
2065       break;
2066 
2067     case relocInfo::static_call_type:
2068       clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
2069       break;
2070     }
2071   }
2072 }
2073 
2074 #ifdef ASSERT
2075 
2076 class CheckClass : AllStatic {
2077   static BoolObjectClosure* _is_alive;
2078 
2079   // Check class_loader is alive for this bit of metadata.
2080   static void check_class(Metadata* md) {
2081     Klass* klass = NULL;
2082     if (md->is_klass()) {
2083       klass = ((Klass*)md);
2084     } else if (md->is_method()) {
2085       klass = ((Method*)md)->method_holder();
2086     } else if (md->is_methodData()) {
2087       klass = ((MethodData*)md)->method()->method_holder();
2088     } else {
2089       md->print();
2090       ShouldNotReachHere();
2091     }
2092     assert(klass->is_loader_alive(_is_alive), "must be alive");
2093   }
2094  public:
2095   static void do_check_class(BoolObjectClosure* is_alive, nmethod* nm) {
2096     assert(SafepointSynchronize::is_at_safepoint(), "this is only ok at safepoint");
2097     _is_alive = is_alive;
2098     nm->metadata_do(check_class);
2099   }
2100 };
2101 
2102 // This is called during a safepoint so can use static data
2103 BoolObjectClosure* CheckClass::_is_alive = NULL;
2104 #endif // ASSERT
2105 
2106 
2107 // Processing of oop references should have been sufficient to keep
2108 // all strong references alive.  Any weak references should have been
2109 // cleared as well.  Visit all the metadata and ensure that it's
2110 // really alive.
2111 void nmethod::verify_metadata_loaders(address low_boundary, BoolObjectClosure* is_alive) {
2112 #ifdef ASSERT
2113     RelocIterator iter(this, low_boundary);
2114     while (iter.next()) {
2115     // static_stub_Relocations may have dangling references to
2116     // Method*s so trim them out here.  Otherwise it looks like
2117     // compiled code is maintaining a link to dead metadata.
2118     address static_call_addr = NULL;
2119     if (iter.type() == relocInfo::opt_virtual_call_type) {
2120       CompiledIC* cic = CompiledIC_at(&iter);
2121       if (!cic->is_call_to_interpreted()) {
2122         static_call_addr = iter.addr();
2123       }
2124     } else if (iter.type() == relocInfo::static_call_type) {
2125       CompiledStaticCall* csc = compiledStaticCall_at(iter.reloc());
2126       if (!csc->is_call_to_interpreted()) {
2127         static_call_addr = iter.addr();
2128       }
2129     }
2130     if (static_call_addr != NULL) {
2131       RelocIterator sciter(this, low_boundary);
2132       while (sciter.next()) {
2133         if (sciter.type() == relocInfo::static_stub_type &&
2134             sciter.static_stub_reloc()->static_call() == static_call_addr) {
2135           sciter.static_stub_reloc()->clear_inline_cache();
2136         }
2137       }
2138     }
2139   }
2140   // Check that the metadata embedded in the nmethod is alive
2141   CheckClass::do_check_class(is_alive, this);
2142 #endif
2143 }
2144 
2145 
2146 // Iterate over metadata calling this function.   Used by RedefineClasses
2147 void nmethod::metadata_do(void f(Metadata*)) {
2148   address low_boundary = verified_entry_point();
2149   if (is_not_entrant()) {
2150     low_boundary += NativeJump::instruction_size;
2151     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
2152     // (See comment above.)
2153   }
2154   {
2155     // Visit all immediate references that are embedded in the instruction stream.
2156     RelocIterator iter(this, low_boundary);
2157     while (iter.next()) {
2158       if (iter.type() == relocInfo::metadata_type ) {
2159         metadata_Relocation* r = iter.metadata_reloc();
2160         // In this metadata, we must only follow those metadatas directly embedded in
2161         // the code.  Other metadatas (oop_index>0) are seen as part of
2162         // the metadata section below.
2163         assert(1 == (r->metadata_is_immediate()) +
2164                (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
2165                "metadata must be found in exactly one place");
2166         if (r->metadata_is_immediate() && r->metadata_value() != NULL) {
2167           Metadata* md = r->metadata_value();
2168           if (md != _method) f(md);
2169         }
2170       } else if (iter.type() == relocInfo::virtual_call_type) {
2171         // Check compiledIC holders associated with this nmethod
2172         CompiledIC *ic = CompiledIC_at(&iter);
2173         if (ic->is_icholder_call()) {
2174           CompiledICHolder* cichk = ic->cached_icholder();
2175           f(cichk->holder_method());
2176           f(cichk->holder_klass());
2177         } else {
2178           Metadata* ic_oop = ic->cached_metadata();
2179           if (ic_oop != NULL) {
2180             f(ic_oop);
2181           }
2182         }
2183       }
2184     }
2185   }
2186 
2187   // Visit the metadata section
2188   for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2189     if (*p == Universe::non_oop_word() || *p == NULL)  continue;  // skip non-oops
2190     Metadata* md = *p;
2191     f(md);
2192   }
2193 
2194   // Visit metadata not embedded in the other places.
2195   if (_method != NULL) f(_method);
2196 }
2197 
2198 void nmethod::oops_do(OopClosure* f, bool allow_zombie) {
2199   // make sure the oops ready to receive visitors
2200   assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod");
2201   assert(!is_unloaded(), "should not call follow on unloaded nmethod");
2202 
2203   // If the method is not entrant or zombie then a JMP is plastered over the
2204   // first few bytes.  If an oop in the old code was there, that oop
2205   // should not get GC'd.  Skip the first few bytes of oops on
2206   // not-entrant methods.
2207   address low_boundary = verified_entry_point();
2208   if (is_not_entrant()) {
2209     low_boundary += NativeJump::instruction_size;
2210     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
2211     // (See comment above.)
2212   }
2213 
2214 #if INCLUDE_JVMCI
2215   if (_jvmci_installed_code != NULL) {
2216     f->do_oop((oop*) &_jvmci_installed_code);
2217   }
2218   if (_speculation_log != NULL) {
2219     f->do_oop((oop*) &_speculation_log);
2220   }
2221 #endif
2222 
2223   RelocIterator iter(this, low_boundary);
2224 
2225   while (iter.next()) {
2226     if (iter.type() == relocInfo::oop_type ) {
2227       oop_Relocation* r = iter.oop_reloc();
2228       // In this loop, we must only follow those oops directly embedded in
2229       // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
2230       assert(1 == (r->oop_is_immediate()) +
2231                    (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2232              "oop must be found in exactly one place");
2233       if (r->oop_is_immediate() && r->oop_value() != NULL) {
2234         f->do_oop(r->oop_addr());
2235       }
2236     }
2237   }
2238 
2239   // Scopes
2240   // This includes oop constants not inlined in the code stream.
2241   for (oop* p = oops_begin(); p < oops_end(); p++) {
2242     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
2243     f->do_oop(p);
2244   }
2245 }
2246 
2247 #define NMETHOD_SENTINEL ((nmethod*)badAddress)
2248 
2249 nmethod* volatile nmethod::_oops_do_mark_nmethods;
2250 
2251 // An nmethod is "marked" if its _mark_link is set non-null.
2252 // Even if it is the end of the linked list, it will have a non-null link value,
2253 // as long as it is on the list.
2254 // This code must be MP safe, because it is used from parallel GC passes.
2255 bool nmethod::test_set_oops_do_mark() {
2256   assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called");
2257   nmethod* observed_mark_link = _oops_do_mark_link;
2258   if (observed_mark_link == NULL) {
2259     // Claim this nmethod for this thread to mark.
2260     observed_mark_link = (nmethod*)
2261       Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_link, NULL);
2262     if (observed_mark_link == NULL) {
2263 
2264       // Atomically append this nmethod (now claimed) to the head of the list:
2265       nmethod* observed_mark_nmethods = _oops_do_mark_nmethods;
2266       for (;;) {
2267         nmethod* required_mark_nmethods = observed_mark_nmethods;
2268         _oops_do_mark_link = required_mark_nmethods;
2269         observed_mark_nmethods = (nmethod*)
2270           Atomic::cmpxchg_ptr(this, &_oops_do_mark_nmethods, required_mark_nmethods);
2271         if (observed_mark_nmethods == required_mark_nmethods)
2272           break;
2273       }
2274       // Mark was clear when we first saw this guy.
2275       if (TraceScavenge) { print_on(tty, "oops_do, mark"); }
2276       return false;
2277     }
2278   }
2279   // On fall through, another racing thread marked this nmethod before we did.
2280   return true;
2281 }
2282 
2283 void nmethod::oops_do_marking_prologue() {
2284   if (TraceScavenge) { tty->print_cr("[oops_do_marking_prologue"); }
2285   assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row");
2286   // We use cmpxchg_ptr instead of regular assignment here because the user
2287   // may fork a bunch of threads, and we need them all to see the same state.
2288   void* observed = Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, NULL);
2289   guarantee(observed == NULL, "no races in this sequential code");
2290 }
2291 
2292 void nmethod::oops_do_marking_epilogue() {
2293   assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row");
2294   nmethod* cur = _oops_do_mark_nmethods;
2295   while (cur != NMETHOD_SENTINEL) {
2296     assert(cur != NULL, "not NULL-terminated");
2297     nmethod* next = cur->_oops_do_mark_link;
2298     cur->_oops_do_mark_link = NULL;
2299     DEBUG_ONLY(cur->verify_oop_relocations());
2300     NOT_PRODUCT(if (TraceScavenge)  cur->print_on(tty, "oops_do, unmark"));
2301     cur = next;
2302   }
2303   void* required = _oops_do_mark_nmethods;
2304   void* observed = Atomic::cmpxchg_ptr(NULL, &_oops_do_mark_nmethods, required);
2305   guarantee(observed == required, "no races in this sequential code");
2306   if (TraceScavenge) { tty->print_cr("oops_do_marking_epilogue]"); }
2307 }
2308 
2309 class DetectScavengeRoot: public OopClosure {
2310   bool     _detected_scavenge_root;
2311 public:
2312   DetectScavengeRoot() : _detected_scavenge_root(false)
2313   { NOT_PRODUCT(_print_nm = NULL); }
2314   bool detected_scavenge_root() { return _detected_scavenge_root; }
2315   virtual void do_oop(oop* p) {
2316     if ((*p) != NULL && (*p)->is_scavengable()) {
2317       NOT_PRODUCT(maybe_print(p));
2318       _detected_scavenge_root = true;
2319     }
2320   }
2321   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2322 
2323 #ifndef PRODUCT
2324   nmethod* _print_nm;
2325   void maybe_print(oop* p) {
2326     if (_print_nm == NULL)  return;
2327     if (!_detected_scavenge_root)  _print_nm->print_on(tty, "new scavenge root");
2328     tty->print_cr("" PTR_FORMAT "[offset=%d] detected scavengable oop " PTR_FORMAT " (found at " PTR_FORMAT ")",
2329                   p2i(_print_nm), (int)((intptr_t)p - (intptr_t)_print_nm),
2330                   p2i(*p), p2i(p));
2331     (*p)->print();
2332   }
2333 #endif //PRODUCT
2334 };
2335 
2336 bool nmethod::detect_scavenge_root_oops() {
2337   DetectScavengeRoot detect_scavenge_root;
2338   NOT_PRODUCT(if (TraceScavenge)  detect_scavenge_root._print_nm = this);
2339   oops_do(&detect_scavenge_root);
2340   return detect_scavenge_root.detected_scavenge_root();
2341 }
2342 
2343 // Method that knows how to preserve outgoing arguments at call. This method must be
2344 // called with a frame corresponding to a Java invoke
2345 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
2346 #ifndef SHARK
2347   if (method() != NULL && !method()->is_native()) {
2348     address pc = fr.pc();
2349     SimpleScopeDesc ssd(this, pc);
2350     Bytecode_invoke call(ssd.method(), ssd.bci());
2351     bool has_receiver = call.has_receiver();
2352     bool has_appendix = call.has_appendix();
2353     Symbol* signature = call.signature();
2354 
2355     // The method attached by JIT-compilers should be used, if present.
2356     // Bytecode can be inaccurate in such case.
2357     Method* callee = attached_method_before_pc(pc);
2358     if (callee != NULL) {
2359       has_receiver = !(callee->access_flags().is_static());
2360       has_appendix = false;
2361       signature = callee->signature();
2362     }
2363 
2364     // If value types are passed as fields, use the extended signature
2365     // which contains the types of all (oop) fields of the value type.
2366     if (ValueTypePassFieldsAsArgs) {
2367       // Check if callee signature contains a value type argument
2368       // TODO if invokedirect is going to be removed we need another way to figure out that the receiver is a value type
2369       bool has_value_argument = call.is_invokedirect();
2370       const int len = signature->utf8_length();
2371       for (int i = 0; i < len && !has_value_argument; ++i) {
2372         if (signature->byte_at(i) == 'Q') {
2373           has_value_argument = true;
2374         }
2375       }
2376       if (has_value_argument) {
2377         // Get the extended signature from the callee's adapter
2378         // TODO what about methods that do not have an adapter (for example, abstract methods)?
2379         Thread* THREAD = Thread::current();
2380         methodHandle dest_method = call.static_target(THREAD);
2381         assert(!HAS_PENDING_EXCEPTION, "should not have pending exception");
2382         callee = dest_method();
2383         assert(callee != NULL, "failed to resolve callee");
2384         signature = callee->adapter()->get_sig_extended();
2385         assert(signature != NULL, "signature is null");
2386         has_receiver = false; // The signature contains the receiver type
2387       }
2388     }
2389 
2390     fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
2391   }
2392 #endif // !SHARK
2393 }
2394 
2395 inline bool includes(void* p, void* from, void* to) {
2396   return from <= p && p < to;
2397 }
2398 
2399 
2400 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
2401   assert(count >= 2, "must be sentinel values, at least");
2402 
2403 #ifdef ASSERT
2404   // must be sorted and unique; we do a binary search in find_pc_desc()
2405   int prev_offset = pcs[0].pc_offset();
2406   assert(prev_offset == PcDesc::lower_offset_limit,
2407          "must start with a sentinel");
2408   for (int i = 1; i < count; i++) {
2409     int this_offset = pcs[i].pc_offset();
2410     assert(this_offset > prev_offset, "offsets must be sorted");
2411     prev_offset = this_offset;
2412   }
2413   assert(prev_offset == PcDesc::upper_offset_limit,
2414          "must end with a sentinel");
2415 #endif //ASSERT
2416 
2417   // Search for MethodHandle invokes and tag the nmethod.
2418   for (int i = 0; i < count; i++) {
2419     if (pcs[i].is_method_handle_invoke()) {
2420       set_has_method_handle_invokes(true);
2421       break;
2422     }
2423   }
2424   assert(has_method_handle_invokes() == (_deoptimize_mh_offset != -1), "must have deopt mh handler");
2425 
2426   int size = count * sizeof(PcDesc);
2427   assert(scopes_pcs_size() >= size, "oob");
2428   memcpy(scopes_pcs_begin(), pcs, size);
2429 
2430   // Adjust the final sentinel downward.
2431   PcDesc* last_pc = &scopes_pcs_begin()[count-1];
2432   assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
2433   last_pc->set_pc_offset(content_size() + 1);
2434   for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
2435     // Fill any rounding gaps with copies of the last record.
2436     last_pc[1] = last_pc[0];
2437   }
2438   // The following assert could fail if sizeof(PcDesc) is not
2439   // an integral multiple of oopSize (the rounding term).
2440   // If it fails, change the logic to always allocate a multiple
2441   // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
2442   assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
2443 }
2444 
2445 void nmethod::copy_scopes_data(u_char* buffer, int size) {
2446   assert(scopes_data_size() >= size, "oob");
2447   memcpy(scopes_data_begin(), buffer, size);
2448 }
2449 
2450 // When using JVMCI the address might be off by the size of a call instruction.
2451 bool nmethod::is_deopt_entry(address pc) {
2452   return pc == deopt_handler_begin()
2453 #if INCLUDE_JVMCI
2454     || pc == (deopt_handler_begin() + NativeCall::instruction_size)
2455 #endif
2456     ;
2457 }
2458 
2459 #ifdef ASSERT
2460 static PcDesc* linear_search(nmethod* nm, int pc_offset, bool approximate) {
2461   PcDesc* lower = nm->scopes_pcs_begin();
2462   PcDesc* upper = nm->scopes_pcs_end();
2463   lower += 1; // exclude initial sentinel
2464   PcDesc* res = NULL;
2465   for (PcDesc* p = lower; p < upper; p++) {
2466     NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests);  // don't count this call to match_desc
2467     if (match_desc(p, pc_offset, approximate)) {
2468       if (res == NULL)
2469         res = p;
2470       else
2471         res = (PcDesc*) badAddress;
2472     }
2473   }
2474   return res;
2475 }
2476 #endif
2477 
2478 
2479 // Finds a PcDesc with real-pc equal to "pc"
2480 PcDesc* nmethod::find_pc_desc_internal(address pc, bool approximate) {
2481   address base_address = code_begin();
2482   if ((pc < base_address) ||
2483       (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
2484     return NULL;  // PC is wildly out of range
2485   }
2486   int pc_offset = (int) (pc - base_address);
2487 
2488   // Check the PcDesc cache if it contains the desired PcDesc
2489   // (This as an almost 100% hit rate.)
2490   PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
2491   if (res != NULL) {
2492     assert(res == linear_search(this, pc_offset, approximate), "cache ok");
2493     return res;
2494   }
2495 
2496   // Fallback algorithm: quasi-linear search for the PcDesc
2497   // Find the last pc_offset less than the given offset.
2498   // The successor must be the required match, if there is a match at all.
2499   // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
2500   PcDesc* lower = scopes_pcs_begin();
2501   PcDesc* upper = scopes_pcs_end();
2502   upper -= 1; // exclude final sentinel
2503   if (lower >= upper)  return NULL;  // native method; no PcDescs at all
2504 
2505 #define assert_LU_OK \
2506   /* invariant on lower..upper during the following search: */ \
2507   assert(lower->pc_offset() <  pc_offset, "sanity"); \
2508   assert(upper->pc_offset() >= pc_offset, "sanity")
2509   assert_LU_OK;
2510 
2511   // Use the last successful return as a split point.
2512   PcDesc* mid = _pc_desc_cache.last_pc_desc();
2513   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2514   if (mid->pc_offset() < pc_offset) {
2515     lower = mid;
2516   } else {
2517     upper = mid;
2518   }
2519 
2520   // Take giant steps at first (4096, then 256, then 16, then 1)
2521   const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1);
2522   const int RADIX = (1 << LOG2_RADIX);
2523   for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
2524     while ((mid = lower + step) < upper) {
2525       assert_LU_OK;
2526       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2527       if (mid->pc_offset() < pc_offset) {
2528         lower = mid;
2529       } else {
2530         upper = mid;
2531         break;
2532       }
2533     }
2534     assert_LU_OK;
2535   }
2536 
2537   // Sneak up on the value with a linear search of length ~16.
2538   while (true) {
2539     assert_LU_OK;
2540     mid = lower + 1;
2541     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2542     if (mid->pc_offset() < pc_offset) {
2543       lower = mid;
2544     } else {
2545       upper = mid;
2546       break;
2547     }
2548   }
2549 #undef assert_LU_OK
2550 
2551   if (match_desc(upper, pc_offset, approximate)) {
2552     assert(upper == linear_search(this, pc_offset, approximate), "search ok");
2553     _pc_desc_cache.add_pc_desc(upper);
2554     return upper;
2555   } else {
2556     assert(NULL == linear_search(this, pc_offset, approximate), "search ok");
2557     return NULL;
2558   }
2559 }
2560 
2561 
2562 void nmethod::check_all_dependencies(DepChange& changes) {
2563   // Checked dependencies are allocated into this ResourceMark
2564   ResourceMark rm;
2565 
2566   // Turn off dependency tracing while actually testing dependencies.
2567   NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) );
2568 
2569   typedef ResourceHashtable<DependencySignature, int, &DependencySignature::hash,
2570                             &DependencySignature::equals, 11027> DepTable;
2571 
2572   DepTable* table = new DepTable();
2573 
2574   // Iterate over live nmethods and check dependencies of all nmethods that are not
2575   // marked for deoptimization. A particular dependency is only checked once.
2576   NMethodIterator iter;
2577   while(iter.next()) {
2578     nmethod* nm = iter.method();
2579     // Only notify for live nmethods
2580     if (nm->is_alive() && !nm->is_marked_for_deoptimization()) {
2581       for (Dependencies::DepStream deps(nm); deps.next(); ) {
2582         // Construct abstraction of a dependency.
2583         DependencySignature* current_sig = new DependencySignature(deps);
2584 
2585         // Determine if dependency is already checked. table->put(...) returns
2586         // 'true' if the dependency is added (i.e., was not in the hashtable).
2587         if (table->put(*current_sig, 1)) {
2588           if (deps.check_dependency() != NULL) {
2589             // Dependency checking failed. Print out information about the failed
2590             // dependency and finally fail with an assert. We can fail here, since
2591             // dependency checking is never done in a product build.
2592             tty->print_cr("Failed dependency:");
2593             changes.print();
2594             nm->print();
2595             nm->print_dependencies();
2596             assert(false, "Should have been marked for deoptimization");
2597           }
2598         }
2599       }
2600     }
2601   }
2602 }
2603 
2604 bool nmethod::check_dependency_on(DepChange& changes) {
2605   // What has happened:
2606   // 1) a new class dependee has been added
2607   // 2) dependee and all its super classes have been marked
2608   bool found_check = false;  // set true if we are upset
2609   for (Dependencies::DepStream deps(this); deps.next(); ) {
2610     // Evaluate only relevant dependencies.
2611     if (deps.spot_check_dependency_at(changes) != NULL) {
2612       found_check = true;
2613       NOT_DEBUG(break);
2614     }
2615   }
2616   return found_check;
2617 }
2618 
2619 bool nmethod::is_evol_dependent_on(Klass* dependee) {
2620   InstanceKlass *dependee_ik = InstanceKlass::cast(dependee);
2621   Array<Method*>* dependee_methods = dependee_ik->methods();
2622   for (Dependencies::DepStream deps(this); deps.next(); ) {
2623     if (deps.type() == Dependencies::evol_method) {
2624       Method* method = deps.method_argument(0);
2625       for (int j = 0; j < dependee_methods->length(); j++) {
2626         if (dependee_methods->at(j) == method) {
2627           // RC_TRACE macro has an embedded ResourceMark
2628           RC_TRACE(0x01000000,
2629             ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on method %s.%s(%s)",
2630             _method->method_holder()->external_name(),
2631             _method->name()->as_C_string(),
2632             _method->signature()->as_C_string(), compile_id(),
2633             method->method_holder()->external_name(),
2634             method->name()->as_C_string(),
2635             method->signature()->as_C_string()));
2636           if (TraceDependencies || LogCompilation)
2637             deps.log_dependency(dependee);
2638           return true;
2639         }
2640       }
2641     }
2642   }
2643   return false;
2644 }
2645 
2646 // Called from mark_for_deoptimization, when dependee is invalidated.
2647 bool nmethod::is_dependent_on_method(Method* dependee) {
2648   for (Dependencies::DepStream deps(this); deps.next(); ) {
2649     if (deps.type() != Dependencies::evol_method)
2650       continue;
2651     Method* method = deps.method_argument(0);
2652     if (method == dependee) return true;
2653   }
2654   return false;
2655 }
2656 
2657 
2658 bool nmethod::is_patchable_at(address instr_addr) {
2659   assert(insts_contains(instr_addr), "wrong nmethod used");
2660   if (is_zombie()) {
2661     // a zombie may never be patched
2662     return false;
2663   }
2664   return true;
2665 }
2666 
2667 
2668 address nmethod::continuation_for_implicit_exception(address pc) {
2669   // Exception happened outside inline-cache check code => we are inside
2670   // an active nmethod => use cpc to determine a return address
2671   int exception_offset = pc - code_begin();
2672   int cont_offset = ImplicitExceptionTable(this).at( exception_offset );
2673 #ifdef ASSERT
2674   if (cont_offset == 0) {
2675     Thread* thread = Thread::current();
2676     ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY
2677     HandleMark hm(thread);
2678     ResourceMark rm(thread);
2679     CodeBlob* cb = CodeCache::find_blob(pc);
2680     assert(cb != NULL && cb == this, "");
2681     ttyLocker ttyl;
2682     tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc));
2683     print();
2684     method()->print_codes();
2685     print_code();
2686     print_pcs();
2687   }
2688 #endif
2689   if (cont_offset == 0) {
2690     // Let the normal error handling report the exception
2691     return NULL;
2692   }
2693   return code_begin() + cont_offset;
2694 }
2695 
2696 
2697 
2698 void nmethod_init() {
2699   // make sure you didn't forget to adjust the filler fields
2700   assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
2701 }
2702 
2703 
2704 //-------------------------------------------------------------------------------------------
2705 
2706 
2707 // QQQ might we make this work from a frame??
2708 nmethodLocker::nmethodLocker(address pc) {
2709   CodeBlob* cb = CodeCache::find_blob(pc);
2710   guarantee(cb != NULL && cb->is_nmethod(), "bad pc for a nmethod found");
2711   _nm = (nmethod*)cb;
2712   lock_nmethod(_nm);
2713 }
2714 
2715 // Only JvmtiDeferredEvent::compiled_method_unload_event()
2716 // should pass zombie_ok == true.
2717 void nmethodLocker::lock_nmethod(nmethod* nm, bool zombie_ok) {
2718   if (nm == NULL)  return;
2719   Atomic::inc(&nm->_lock_count);
2720   assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method");
2721 }
2722 
2723 void nmethodLocker::unlock_nmethod(nmethod* nm) {
2724   if (nm == NULL)  return;
2725   Atomic::dec(&nm->_lock_count);
2726   assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock");
2727 }
2728 
2729 // -----------------------------------------------------------------------------
2730 // nmethod::get_deopt_original_pc
2731 //
2732 // Return the original PC for the given PC if:
2733 // (a) the given PC belongs to a nmethod and
2734 // (b) it is a deopt PC
2735 address nmethod::get_deopt_original_pc(const frame* fr) {
2736   if (fr->cb() == NULL)  return NULL;
2737 
2738   nmethod* nm = fr->cb()->as_nmethod_or_null();
2739   if (nm != NULL && nm->is_deopt_pc(fr->pc()))
2740     return nm->get_original_pc(fr);
2741 
2742   return NULL;
2743 }
2744 
2745 
2746 // -----------------------------------------------------------------------------
2747 // MethodHandle
2748 
2749 bool nmethod::is_method_handle_return(address return_pc) {
2750   if (!has_method_handle_invokes())  return false;
2751   PcDesc* pd = pc_desc_at(return_pc);
2752   if (pd == NULL)
2753     return false;
2754   return pd->is_method_handle_invoke();
2755 }
2756 
2757 
2758 // -----------------------------------------------------------------------------
2759 // Verification
2760 
2761 class VerifyOopsClosure: public OopClosure {
2762   nmethod* _nm;
2763   bool     _ok;
2764 public:
2765   VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
2766   bool ok() { return _ok; }
2767   virtual void do_oop(oop* p) {
2768     if ((*p) == NULL || (*p)->is_oop())  return;
2769     if (_ok) {
2770       _nm->print_nmethod(true);
2771       _ok = false;
2772     }
2773     tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
2774                   p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));
2775   }
2776   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2777 };
2778 
2779 void nmethod::verify() {
2780 
2781   // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant
2782   // seems odd.
2783 
2784   if (is_zombie() || is_not_entrant() || is_unloaded())
2785     return;
2786 
2787   // Make sure all the entry points are correctly aligned for patching.
2788   NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point());
2789 
2790   // assert(method()->is_oop(), "must be valid");
2791 
2792   ResourceMark rm;
2793 
2794   if (!CodeCache::contains(this)) {
2795     fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this));
2796   }
2797 
2798   if(is_native_method() )
2799     return;
2800 
2801   nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
2802   if (nm != this) {
2803     fatal("findNMethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this));
2804   }
2805 
2806   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2807     if (! p->verify(this)) {
2808       tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this));
2809     }
2810   }
2811 
2812   VerifyOopsClosure voc(this);
2813   oops_do(&voc);
2814   assert(voc.ok(), "embedded oops must be OK");
2815   verify_scavenge_root_oops();
2816 
2817   verify_scopes();
2818 }
2819 
2820 
2821 void nmethod::verify_interrupt_point(address call_site) {
2822   // Verify IC only when nmethod installation is finished.
2823   bool is_installed = (method()->code() == this) // nmethod is in state 'in_use' and installed
2824                       || !this->is_in_use();     // nmethod is installed, but not in 'in_use' state
2825   if (is_installed) {
2826     Thread *cur = Thread::current();
2827     if (CompiledIC_lock->owner() == cur ||
2828         ((cur->is_VM_thread() || cur->is_ConcurrentGC_thread()) &&
2829          SafepointSynchronize::is_at_safepoint())) {
2830       CompiledIC_at(this, call_site);
2831       CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
2832     } else {
2833       MutexLocker ml_verify (CompiledIC_lock);
2834       CompiledIC_at(this, call_site);
2835     }
2836   }
2837 
2838   PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
2839   assert(pd != NULL, "PcDesc must exist");
2840   for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(),
2841                                      pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),
2842                                      pd->return_oop());
2843        !sd->is_top(); sd = sd->sender()) {
2844     sd->verify();
2845   }
2846 }
2847 
2848 void nmethod::verify_scopes() {
2849   if( !method() ) return;       // Runtime stubs have no scope
2850   if (method()->is_native()) return; // Ignore stub methods.
2851   // iterate through all interrupt point
2852   // and verify the debug information is valid.
2853   RelocIterator iter((nmethod*)this);
2854   while (iter.next()) {
2855     address stub = NULL;
2856     switch (iter.type()) {
2857       case relocInfo::virtual_call_type:
2858         verify_interrupt_point(iter.addr());
2859         break;
2860       case relocInfo::opt_virtual_call_type:
2861         stub = iter.opt_virtual_call_reloc()->static_stub();
2862         verify_interrupt_point(iter.addr());
2863         break;
2864       case relocInfo::static_call_type:
2865         stub = iter.static_call_reloc()->static_stub();
2866         //verify_interrupt_point(iter.addr());
2867         break;
2868       case relocInfo::runtime_call_type:
2869         address destination = iter.reloc()->value();
2870         // Right now there is no way to find out which entries support
2871         // an interrupt point.  It would be nice if we had this
2872         // information in a table.
2873         break;
2874     }
2875     assert(stub == NULL || stub_contains(stub), "static call stub outside stub section");
2876   }
2877 }
2878 
2879 
2880 // -----------------------------------------------------------------------------
2881 // Non-product code
2882 #ifndef PRODUCT
2883 
2884 class DebugScavengeRoot: public OopClosure {
2885   nmethod* _nm;
2886   bool     _ok;
2887 public:
2888   DebugScavengeRoot(nmethod* nm) : _nm(nm), _ok(true) { }
2889   bool ok() { return _ok; }
2890   virtual void do_oop(oop* p) {
2891     if ((*p) == NULL || !(*p)->is_scavengable())  return;
2892     if (_ok) {
2893       _nm->print_nmethod(true);
2894       _ok = false;
2895     }
2896     tty->print_cr("*** scavengable oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
2897                   p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));
2898     (*p)->print();
2899   }
2900   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2901 };
2902 
2903 void nmethod::verify_scavenge_root_oops() {
2904   if (UseG1GC) {
2905     return;
2906   }
2907 
2908   if (!on_scavenge_root_list()) {
2909     // Actually look inside, to verify the claim that it's clean.
2910     DebugScavengeRoot debug_scavenge_root(this);
2911     oops_do(&debug_scavenge_root);
2912     if (!debug_scavenge_root.ok())
2913       fatal("found an unadvertised bad scavengable oop in the code cache");
2914   }
2915   assert(scavenge_root_not_marked(), "");
2916 }
2917 
2918 #endif // PRODUCT
2919 
2920 // Printing operations
2921 
2922 void nmethod::print() const {
2923   ResourceMark rm;
2924   ttyLocker ttyl;   // keep the following output all in one block
2925 
2926   tty->print("Compiled method ");
2927 
2928   if (is_compiled_by_c1()) {
2929     tty->print("(c1) ");
2930   } else if (is_compiled_by_c2()) {
2931     tty->print("(c2) ");
2932   } else if (is_compiled_by_shark()) {
2933     tty->print("(shark) ");
2934   } else if (is_compiled_by_jvmci()) {
2935     tty->print("(JVMCI) ");
2936   } else {
2937     tty->print("(nm) ");
2938   }
2939 
2940   print_on(tty, NULL);
2941 
2942   if (WizardMode) {
2943     tty->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this));
2944     tty->print(" for method " INTPTR_FORMAT , p2i(method()));
2945     tty->print(" { ");
2946     if (is_in_use())      tty->print("in_use ");
2947     if (is_not_entrant()) tty->print("not_entrant ");
2948     if (is_zombie())      tty->print("zombie ");
2949     if (is_unloaded())    tty->print("unloaded ");
2950     if (on_scavenge_root_list())  tty->print("scavenge_root ");
2951     tty->print_cr("}:");
2952   }
2953   if (size              () > 0) tty->print_cr(" total in heap  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2954                                               p2i(this),
2955                                               p2i(this) + size(),
2956                                               size());
2957   if (relocation_size   () > 0) tty->print_cr(" relocation     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2958                                               p2i(relocation_begin()),
2959                                               p2i(relocation_end()),
2960                                               relocation_size());
2961   if (consts_size       () > 0) tty->print_cr(" constants      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2962                                               p2i(consts_begin()),
2963                                               p2i(consts_end()),
2964                                               consts_size());
2965   if (insts_size        () > 0) tty->print_cr(" main code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2966                                               p2i(insts_begin()),
2967                                               p2i(insts_end()),
2968                                               insts_size());
2969   if (stub_size         () > 0) tty->print_cr(" stub code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2970                                               p2i(stub_begin()),
2971                                               p2i(stub_end()),
2972                                               stub_size());
2973   if (oops_size         () > 0) tty->print_cr(" oops           [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2974                                               p2i(oops_begin()),
2975                                               p2i(oops_end()),
2976                                               oops_size());
2977   if (metadata_size      () > 0) tty->print_cr(" metadata       [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2978                                               p2i(metadata_begin()),
2979                                               p2i(metadata_end()),
2980                                               metadata_size());
2981   if (scopes_data_size  () > 0) tty->print_cr(" scopes data    [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2982                                               p2i(scopes_data_begin()),
2983                                               p2i(scopes_data_end()),
2984                                               scopes_data_size());
2985   if (scopes_pcs_size   () > 0) tty->print_cr(" scopes pcs     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2986                                               p2i(scopes_pcs_begin()),
2987                                               p2i(scopes_pcs_end()),
2988                                               scopes_pcs_size());
2989   if (dependencies_size () > 0) tty->print_cr(" dependencies   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2990                                               p2i(dependencies_begin()),
2991                                               p2i(dependencies_end()),
2992                                               dependencies_size());
2993   if (handler_table_size() > 0) tty->print_cr(" handler table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2994                                               p2i(handler_table_begin()),
2995                                               p2i(handler_table_end()),
2996                                               handler_table_size());
2997   if (nul_chk_table_size() > 0) tty->print_cr(" nul chk table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2998                                               p2i(nul_chk_table_begin()),
2999                                               p2i(nul_chk_table_end()),
3000                                               nul_chk_table_size());
3001 }
3002 
3003 #ifndef PRODUCT
3004 
3005 void nmethod::print_scopes() {
3006   // Find the first pc desc for all scopes in the code and print it.
3007   ResourceMark rm;
3008   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3009     if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
3010       continue;
3011 
3012     ScopeDesc* sd = scope_desc_at(p->real_pc(this));
3013     while (sd != NULL) {
3014       sd->print_on(tty, p);
3015       sd = sd->sender();
3016     }
3017   }
3018 }
3019 
3020 void nmethod::print_dependencies() {
3021   ResourceMark rm;
3022   ttyLocker ttyl;   // keep the following output all in one block
3023   tty->print_cr("Dependencies:");
3024   for (Dependencies::DepStream deps(this); deps.next(); ) {
3025     deps.print_dependency();
3026     Klass* ctxk = deps.context_type();
3027     if (ctxk != NULL) {
3028       if (ctxk->is_instance_klass() && InstanceKlass::cast(ctxk)->is_dependent_nmethod(this)) {
3029         tty->print_cr("   [nmethod<=klass]%s", ctxk->external_name());
3030       }
3031     }
3032     deps.log_dependency();  // put it into the xml log also
3033   }
3034 }
3035 
3036 
3037 void nmethod::print_relocations() {
3038   ResourceMark m;       // in case methods get printed via the debugger
3039   tty->print_cr("relocations:");
3040   RelocIterator iter(this);
3041   iter.print();
3042   if (UseRelocIndex) {
3043     jint* index_end   = (jint*)relocation_end() - 1;
3044     jint  index_size  = *index_end;
3045     jint* index_start = (jint*)( (address)index_end - index_size );
3046     tty->print_cr("    index @" INTPTR_FORMAT ": index_size=%d", p2i(index_start), index_size);
3047     if (index_size > 0) {
3048       jint* ip;
3049       for (ip = index_start; ip+2 <= index_end; ip += 2)
3050         tty->print_cr("  (%d %d) addr=" INTPTR_FORMAT " @" INTPTR_FORMAT,
3051                       ip[0],
3052                       ip[1],
3053                       p2i(header_end()+ip[0]),
3054                       p2i(relocation_begin()-1+ip[1]));
3055       for (; ip < index_end; ip++)
3056         tty->print_cr("  (%d ?)", ip[0]);
3057       tty->print_cr("          @" INTPTR_FORMAT ": index_size=%d", p2i(ip), *ip);
3058       ip++;
3059       tty->print_cr("reloc_end @" INTPTR_FORMAT ":", p2i(ip));
3060     }
3061   }
3062 }
3063 
3064 
3065 void nmethod::print_pcs() {
3066   ResourceMark m;       // in case methods get printed via debugger
3067   tty->print_cr("pc-bytecode offsets:");
3068   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3069     p->print(this);
3070   }
3071 }
3072 
3073 void nmethod::print_recorded_oops() {
3074   tty->print_cr("Recorded oops:");
3075   for (int i = 0; i < oops_count(); i++) {
3076     oop o = oop_at(i);
3077     tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(o));
3078     if (o == (oop)Universe::non_oop_word()) {
3079       tty->print("non-oop word");
3080     } else {
3081       o->print_value();
3082     }
3083     tty->cr();
3084   }
3085 }
3086 
3087 void nmethod::print_recorded_metadata() {
3088   tty->print_cr("Recorded metadata:");
3089   for (int i = 0; i < metadata_count(); i++) {
3090     Metadata* m = metadata_at(i);
3091     tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(m));
3092     if (m == (Metadata*)Universe::non_oop_word()) {
3093       tty->print("non-metadata word");
3094     } else {
3095       m->print_value_on_maybe_null(tty);
3096     }
3097     tty->cr();
3098   }
3099 }
3100 
3101 #endif // PRODUCT
3102 
3103 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
3104   RelocIterator iter(this, begin, end);
3105   bool have_one = false;
3106   while (iter.next()) {
3107     have_one = true;
3108     switch (iter.type()) {
3109         case relocInfo::none:                  return "no_reloc";
3110         case relocInfo::oop_type: {
3111           stringStream st;
3112           oop_Relocation* r = iter.oop_reloc();
3113           oop obj = r->oop_value();
3114           st.print("oop(");
3115           if (obj == NULL) st.print("NULL");
3116           else obj->print_value_on(&st);
3117           st.print(")");
3118           return st.as_string();
3119         }
3120         case relocInfo::metadata_type: {
3121           stringStream st;
3122           metadata_Relocation* r = iter.metadata_reloc();
3123           Metadata* obj = r->metadata_value();
3124           st.print("metadata(");
3125           if (obj == NULL) st.print("NULL");
3126           else obj->print_value_on(&st);
3127           st.print(")");
3128           return st.as_string();
3129         }
3130         case relocInfo::runtime_call_type: {
3131           stringStream st;
3132           st.print("runtime_call");
3133           runtime_call_Relocation* r = iter.runtime_call_reloc();
3134           address dest = r->destination();
3135           CodeBlob* cb = CodeCache::find_blob(dest);
3136           if (cb != NULL) {
3137             st.print(" %s", cb->name());
3138           } else {
3139             ResourceMark rm;
3140             const int buflen = 1024;
3141             char* buf = NEW_RESOURCE_ARRAY(char, buflen);
3142             int offset;
3143             if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {
3144               st.print(" %s", buf);
3145               if (offset != 0) {
3146                 st.print("+%d", offset);
3147               }
3148             }
3149           }
3150           return st.as_string();
3151         }
3152         case relocInfo::virtual_call_type: {
3153           stringStream st;
3154           st.print_raw("virtual_call");
3155           virtual_call_Relocation* r = iter.virtual_call_reloc();
3156           Method* m = r->method_value();
3157           if (m != NULL) {
3158             assert(m->is_method(), "");
3159             m->print_short_name(&st);
3160           }
3161           return st.as_string();
3162         }
3163         case relocInfo::opt_virtual_call_type: {
3164           stringStream st;
3165           st.print_raw("optimized virtual_call");
3166           opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc();
3167           Method* m = r->method_value();
3168           if (m != NULL) {
3169             assert(m->is_method(), "");
3170             m->print_short_name(&st);
3171           }
3172           return st.as_string();
3173         }
3174         case relocInfo::static_call_type: {
3175           stringStream st;
3176           st.print_raw("static_call");
3177           static_call_Relocation* r = iter.static_call_reloc();
3178           Method* m = r->method_value();
3179           if (m != NULL) {
3180             assert(m->is_method(), "");
3181             m->print_short_name(&st);
3182           }
3183           return st.as_string();
3184         }
3185         case relocInfo::static_stub_type:      return "static_stub";
3186         case relocInfo::external_word_type:    return "external_word";
3187         case relocInfo::internal_word_type:    return "internal_word";
3188         case relocInfo::section_word_type:     return "section_word";
3189         case relocInfo::poll_type:             return "poll";
3190         case relocInfo::poll_return_type:      return "poll_return";
3191         case relocInfo::type_mask:             return "type_bit_mask";
3192     }
3193   }
3194   return have_one ? "other" : NULL;
3195 }
3196 
3197 // Return a the last scope in (begin..end]
3198 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
3199   PcDesc* p = pc_desc_near(begin+1);
3200   if (p != NULL && p->real_pc(this) <= end) {
3201     return new ScopeDesc(this, p->scope_decode_offset(),
3202                          p->obj_decode_offset(), p->should_reexecute(), p->rethrow_exception(),
3203                          p->return_oop());
3204   }
3205   return NULL;
3206 }
3207 
3208 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const {
3209   if (block_begin == entry_point())             stream->print_cr("[Entry Point]");
3210   if (block_begin == verified_entry_point())    stream->print_cr("[Verified Entry Point]");
3211   if (JVMCI_ONLY(_exception_offset >= 0 &&) block_begin == exception_begin())         stream->print_cr("[Exception Handler]");
3212   if (block_begin == stub_begin())              stream->print_cr("[Stub Code]");
3213   if (JVMCI_ONLY(_deoptimize_offset >= 0 &&) block_begin == deopt_handler_begin())     stream->print_cr("[Deopt Handler Code]");
3214 
3215   if (has_method_handle_invokes())
3216     if (block_begin == deopt_mh_handler_begin())  stream->print_cr("[Deopt MH Handler Code]");
3217 
3218   if (block_begin == consts_begin())            stream->print_cr("[Constants]");
3219 
3220   if (block_begin == entry_point()) {
3221     methodHandle m = method();
3222     if (m.not_null()) {
3223       stream->print("  # ");
3224       m->print_value_on(stream);
3225       stream->cr();
3226     }
3227     if (m.not_null() && !is_osr_method()) {
3228       ResourceMark rm;
3229       int sizeargs = m->size_of_parameters();
3230       BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
3231       VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
3232       {
3233         int sig_index = 0;
3234         if (!m->is_static())
3235           sig_bt[sig_index++] = T_OBJECT; // 'this'
3236         for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {
3237           BasicType t = ss.type();
3238           sig_bt[sig_index++] = t;
3239           if (type2size[t] == 2) {
3240             sig_bt[sig_index++] = T_VOID;
3241           } else {
3242             assert(type2size[t] == 1, "size is 1 or 2");
3243           }
3244         }
3245         assert(sig_index == sizeargs, "");
3246       }
3247       const char* spname = "sp"; // make arch-specific?
3248       intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false);
3249       int stack_slot_offset = this->frame_size() * wordSize;
3250       int tab1 = 14, tab2 = 24;
3251       int sig_index = 0;
3252       int arg_index = (m->is_static() ? 0 : -1);
3253       bool did_old_sp = false;
3254       for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {
3255         bool at_this = (arg_index == -1);
3256         bool at_old_sp = false;
3257         BasicType t = (at_this ? T_OBJECT : ss.type());
3258         assert(t == sig_bt[sig_index], "sigs in sync");
3259         if (at_this)
3260           stream->print("  # this: ");
3261         else
3262           stream->print("  # parm%d: ", arg_index);
3263         stream->move_to(tab1);
3264         VMReg fst = regs[sig_index].first();
3265         VMReg snd = regs[sig_index].second();
3266         if (fst->is_reg()) {
3267           stream->print("%s", fst->name());
3268           if (snd->is_valid())  {
3269             stream->print(":%s", snd->name());
3270           }
3271         } else if (fst->is_stack()) {
3272           int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
3273           if (offset == stack_slot_offset)  at_old_sp = true;
3274           stream->print("[%s+0x%x]", spname, offset);
3275         } else {
3276           stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
3277         }
3278         stream->print(" ");
3279         stream->move_to(tab2);
3280         stream->print("= ");
3281         if (at_this) {
3282           m->method_holder()->print_value_on(stream);
3283         } else {
3284           bool did_name = false;
3285           if (!at_this && ss.is_object()) {
3286             Symbol* name = ss.as_symbol_or_null();
3287             if (name != NULL) {
3288               name->print_value_on(stream);
3289               did_name = true;
3290             }
3291           }
3292           if (!did_name)
3293             stream->print("%s", type2name(t));
3294         }
3295         if (at_old_sp) {
3296           stream->print("  (%s of caller)", spname);
3297           did_old_sp = true;
3298         }
3299         stream->cr();
3300         sig_index += type2size[t];
3301         arg_index += 1;
3302         if (!at_this)  ss.next();
3303       }
3304       if (!did_old_sp) {
3305         stream->print("  # ");
3306         stream->move_to(tab1);
3307         stream->print("[%s+0x%x]", spname, stack_slot_offset);
3308         stream->print("  (%s of caller)", spname);
3309         stream->cr();
3310       }
3311     }
3312   }
3313 }
3314 
3315 void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, u_char* end) {
3316   // First, find an oopmap in (begin, end].
3317   // We use the odd half-closed interval so that oop maps and scope descs
3318   // which are tied to the byte after a call are printed with the call itself.
3319   address base = code_begin();
3320   ImmutableOopMapSet* oms = oop_maps();
3321   if (oms != NULL) {
3322     for (int i = 0, imax = oms->count(); i < imax; i++) {
3323       const ImmutableOopMapPair* pair = oms->pair_at(i);
3324       const ImmutableOopMap* om = pair->get_from(oms);
3325       address pc = base + pair->pc_offset();
3326       if (pc > begin) {
3327         if (pc <= end) {
3328           st->move_to(column);
3329           st->print("; ");
3330           om->print_on(st);
3331         }
3332         break;
3333       }
3334     }
3335   }
3336 
3337   // Print any debug info present at this pc.
3338   ScopeDesc* sd  = scope_desc_in(begin, end);
3339   if (sd != NULL) {
3340     st->move_to(column);
3341     if (sd->bci() == SynchronizationEntryBCI) {
3342       st->print(";*synchronization entry");
3343     } else {
3344       if (sd->method() == NULL) {
3345         st->print("method is NULL");
3346       } else if (sd->method()->is_native()) {
3347         st->print("method is native");
3348       } else {
3349         Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
3350         st->print(";*%s", Bytecodes::name(bc));
3351         switch (bc) {
3352         case Bytecodes::_invokevirtual:
3353         case Bytecodes::_invokespecial:
3354         case Bytecodes::_invokestatic:
3355         case Bytecodes::_invokeinterface:
3356           {
3357             Bytecode_invoke invoke(sd->method(), sd->bci());
3358             st->print(" ");
3359             if (invoke.name() != NULL)
3360               invoke.name()->print_symbol_on(st);
3361             else
3362               st->print("<UNKNOWN>");
3363             break;
3364           }
3365         case Bytecodes::_getfield:
3366         case Bytecodes::_putfield:
3367         case Bytecodes::_getstatic:
3368         case Bytecodes::_putstatic:
3369           {
3370             Bytecode_field field(sd->method(), sd->bci());
3371             st->print(" ");
3372             if (field.name() != NULL)
3373               field.name()->print_symbol_on(st);
3374             else
3375               st->print("<UNKNOWN>");
3376           }
3377         }
3378       }
3379       st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop());
3380     }
3381 
3382     // Print all scopes
3383     for (;sd != NULL; sd = sd->sender()) {
3384       st->move_to(column);
3385       st->print("; -");
3386       if (sd->method() == NULL) {
3387         st->print("method is NULL");
3388       } else {
3389         sd->method()->print_short_name(st);
3390       }
3391       int lineno = sd->method()->line_number_from_bci(sd->bci());
3392       if (lineno != -1) {
3393         st->print("@%d (line %d)", sd->bci(), lineno);
3394       } else {
3395         st->print("@%d", sd->bci());
3396       }
3397       st->cr();
3398     }
3399   }
3400 
3401   // Print relocation information
3402   const char* str = reloc_string_for(begin, end);
3403   if (str != NULL) {
3404     if (sd != NULL) st->cr();
3405     st->move_to(column);
3406     st->print(";   {%s}", str);
3407   }
3408   int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin());
3409   if (cont_offset != 0) {
3410     st->move_to(column);
3411     st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));
3412   }
3413 
3414 }
3415 
3416 #ifndef PRODUCT
3417 
3418 void nmethod::print_value_on(outputStream* st) const {
3419   st->print("nmethod");
3420   print_on(st, NULL);
3421 }
3422 
3423 void nmethod::print_calls(outputStream* st) {
3424   RelocIterator iter(this);
3425   while (iter.next()) {
3426     switch (iter.type()) {
3427     case relocInfo::virtual_call_type:
3428     case relocInfo::opt_virtual_call_type: {
3429       VerifyMutexLocker mc(CompiledIC_lock);
3430       CompiledIC_at(&iter)->print();
3431       break;
3432     }
3433     case relocInfo::static_call_type:
3434       st->print_cr("Static call at " INTPTR_FORMAT, p2i(iter.reloc()->addr()));
3435       compiledStaticCall_at(iter.reloc())->print();
3436       break;
3437     }
3438   }
3439 }
3440 
3441 void nmethod::print_handler_table() {
3442   ExceptionHandlerTable(this).print();
3443 }
3444 
3445 void nmethod::print_nul_chk_table() {
3446   ImplicitExceptionTable(this).print(code_begin());
3447 }
3448 
3449 void nmethod::print_statistics() {
3450   ttyLocker ttyl;
3451   if (xtty != NULL)  xtty->head("statistics type='nmethod'");
3452   native_nmethod_stats.print_native_nmethod_stats();
3453 #ifdef COMPILER1
3454   c1_java_nmethod_stats.print_nmethod_stats("C1");
3455 #endif
3456 #ifdef COMPILER2
3457   c2_java_nmethod_stats.print_nmethod_stats("C2");
3458 #endif
3459 #if INCLUDE_JVMCI
3460   jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");
3461 #endif
3462 #ifdef SHARK
3463   shark_java_nmethod_stats.print_nmethod_stats("Shark");
3464 #endif
3465   unknown_java_nmethod_stats.print_nmethod_stats("Unknown");
3466   DebugInformationRecorder::print_statistics();
3467 #ifndef PRODUCT
3468   pc_nmethod_stats.print_pc_stats();
3469 #endif
3470   Dependencies::print_statistics();
3471   if (xtty != NULL)  xtty->tail("statistics");
3472 }
3473 
3474 #endif // !PRODUCT
3475 
3476 #if INCLUDE_JVMCI
3477 void nmethod::clear_jvmci_installed_code() {
3478   // write_ref_method_pre/post can only be safely called at a
3479   // safepoint or while holding the CodeCache_lock
3480   assert(CodeCache_lock->is_locked() ||
3481          SafepointSynchronize::is_at_safepoint(), "should be performed under a lock for consistency");
3482   if (_jvmci_installed_code != NULL) {
3483     // This must be done carefully to maintain nmethod remembered sets properly
3484     BarrierSet* bs = Universe::heap()->barrier_set();
3485     bs->write_ref_nmethod_pre(&_jvmci_installed_code, this);
3486     _jvmci_installed_code = NULL;
3487     bs->write_ref_nmethod_post(&_jvmci_installed_code, this);
3488   }
3489 }
3490 
3491 void nmethod::maybe_invalidate_installed_code() {
3492   assert(Patching_lock->is_locked() ||
3493          SafepointSynchronize::is_at_safepoint(), "should be performed under a lock for consistency");
3494   oop installed_code = jvmci_installed_code();
3495   if (installed_code != NULL) {
3496     nmethod* nm = (nmethod*)InstalledCode::address(installed_code);
3497     if (nm == NULL || nm != this) {
3498       // The link has been broken or the InstalledCode instance is
3499       // associated with another nmethod so do nothing.
3500       return;
3501     }
3502     if (!is_alive()) {
3503       // Break the link between nmethod and InstalledCode such that the nmethod
3504       // can subsequently be flushed safely.  The link must be maintained while
3505       // the method could have live activations since invalidateInstalledCode
3506       // might want to invalidate all existing activations.
3507       InstalledCode::set_address(installed_code, 0);
3508       InstalledCode::set_entryPoint(installed_code, 0);
3509     } else if (is_not_entrant()) {
3510       // Remove the entry point so any invocation will fail but keep
3511       // the address link around that so that existing activations can
3512       // be invalidated.
3513       InstalledCode::set_entryPoint(installed_code, 0);
3514     }
3515   }
3516 }
3517 
3518 void nmethod::invalidate_installed_code(Handle installedCode, TRAPS) {
3519   if (installedCode() == NULL) {
3520     THROW(vmSymbols::java_lang_NullPointerException());
3521   }
3522   jlong nativeMethod = InstalledCode::address(installedCode);
3523   nmethod* nm = (nmethod*)nativeMethod;
3524   if (nm == NULL) {
3525     // Nothing to do
3526     return;
3527   }
3528 
3529   nmethodLocker nml(nm);
3530 #ifdef ASSERT
3531   {
3532     MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
3533     // This relationship can only be checked safely under a lock
3534     assert(nm == NULL || !nm->is_alive() || nm->jvmci_installed_code() == installedCode(), "sanity check");
3535   }
3536 #endif
3537 
3538   if (nm->is_alive()) {
3539     // The nmethod state machinery maintains the link between the
3540     // HotSpotInstalledCode and nmethod* so as long as the nmethod appears to be
3541     // alive assume there is work to do and deoptimize the nmethod.
3542     nm->mark_for_deoptimization();
3543     VM_Deoptimize op;
3544     VMThread::execute(&op);
3545   }
3546 
3547   MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
3548   // Check that it's still associated with the same nmethod and break
3549   // the link if it is.
3550   if (InstalledCode::address(installedCode) == nativeMethod) {
3551     InstalledCode::set_address(installedCode, 0);
3552   }
3553 }
3554 
3555 char* nmethod::jvmci_installed_code_name(char* buf, size_t buflen) {
3556   if (!this->is_compiled_by_jvmci()) {
3557     return NULL;
3558   }
3559   oop installedCode = this->jvmci_installed_code();
3560   if (installedCode != NULL) {
3561     oop installedCodeName = NULL;
3562     if (installedCode->is_a(InstalledCode::klass())) {
3563       installedCodeName = InstalledCode::name(installedCode);
3564     }
3565     if (installedCodeName != NULL) {
3566       return java_lang_String::as_utf8_string(installedCodeName, buf, (int)buflen);
3567     } else {
3568       jio_snprintf(buf, buflen, "null");
3569       return buf;
3570     }
3571   }
3572   jio_snprintf(buf, buflen, "noInstalledCode");
3573   return buf;
3574 }
3575 #endif
3576 
3577 Method* nmethod::attached_method(address call_instr) {
3578   assert(code_contains(call_instr), "not part of the nmethod");
3579   RelocIterator iter(this, call_instr, call_instr + 1);
3580   while (iter.next()) {
3581     if (iter.addr() == call_instr) {
3582       switch(iter.type()) {
3583         case relocInfo::static_call_type:      return iter.static_call_reloc()->method_value();
3584         case relocInfo::opt_virtual_call_type: return iter.opt_virtual_call_reloc()->method_value();
3585         case relocInfo::virtual_call_type:     return iter.virtual_call_reloc()->method_value();
3586       }
3587     }
3588   }
3589   return NULL; // not found
3590 }
3591 
3592 Method* nmethod::attached_method_before_pc(address pc) {
3593   if (NativeCall::is_call_before(pc)) {
3594     NativeCall* ncall = nativeCall_before(pc);
3595     return attached_method(ncall->instruction_address());
3596   }
3597   return NULL; // not a call
3598 }
3599