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