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