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