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