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