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