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