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