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