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