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