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