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