1 /*
   2  * Copyright (c) 1999, 2011, 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 "classfile/systemDictionary.hpp"
  27 #include "classfile/vmSymbols.hpp"
  28 #include "code/codeCache.hpp"
  29 #include "compiler/compileBroker.hpp"
  30 #include "compiler/compileLog.hpp"
  31 #include "compiler/compilerOracle.hpp"
  32 #include "interpreter/linkResolver.hpp"
  33 #include "memory/allocation.inline.hpp"
  34 #include "oops/methodDataOop.hpp"
  35 #include "oops/methodOop.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "prims/nativeLookup.hpp"
  38 #include "runtime/arguments.hpp"
  39 #include "runtime/compilationPolicy.hpp"
  40 #include "runtime/init.hpp"
  41 #include "runtime/interfaceSupport.hpp"
  42 #include "runtime/javaCalls.hpp"
  43 #include "runtime/os.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "runtime/sweeper.hpp"
  46 #include "utilities/dtrace.hpp"
  47 #ifdef COMPILER1
  48 #include "c1/c1_Compiler.hpp"
  49 #endif
  50 #ifdef COMPILER2
  51 #include "opto/c2compiler.hpp"
  52 #endif
  53 #ifdef SHARK
  54 #include "shark/sharkCompiler.hpp"
  55 #endif
  56 
  57 #ifdef DTRACE_ENABLED
  58 
  59 // Only bother with this argument setup if dtrace is available
  60 
  61 HS_DTRACE_PROBE_DECL8(hotspot, method__compile__begin,
  62   char*, intptr_t, char*, intptr_t, char*, intptr_t, char*, intptr_t);
  63 HS_DTRACE_PROBE_DECL9(hotspot, method__compile__end,
  64   char*, intptr_t, char*, intptr_t, char*, intptr_t, char*, intptr_t, bool);
  65 
  66 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method)              \
  67   {                                                                      \
  68     char* comp_name = (char*)(compiler)->name();                         \
  69     Symbol* klass_name = (method)->klass_name();                         \
  70     Symbol* name = (method)->name();                                     \
  71     Symbol* signature = (method)->signature();                           \
  72     HS_DTRACE_PROBE8(hotspot, method__compile__begin,                    \
  73       comp_name, strlen(comp_name),                                      \
  74       klass_name->bytes(), klass_name->utf8_length(),                    \
  75       name->bytes(), name->utf8_length(),                                \
  76       signature->bytes(), signature->utf8_length());                     \
  77   }
  78 
  79 #define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method, success)       \
  80   {                                                                      \
  81     char* comp_name = (char*)(compiler)->name();                         \
  82     Symbol* klass_name = (method)->klass_name();                         \
  83     Symbol* name = (method)->name();                                     \
  84     Symbol* signature = (method)->signature();                           \
  85     HS_DTRACE_PROBE9(hotspot, method__compile__end,                      \
  86       comp_name, strlen(comp_name),                                      \
  87       klass_name->bytes(), klass_name->utf8_length(),                    \
  88       name->bytes(), name->utf8_length(),                                \
  89       signature->bytes(), signature->utf8_length(), (success));          \
  90   }
  91 
  92 #else //  ndef DTRACE_ENABLED
  93 
  94 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method)
  95 #define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method, success)
  96 
  97 #endif // ndef DTRACE_ENABLED
  98 
  99 bool CompileBroker::_initialized = false;
 100 volatile bool CompileBroker::_should_block = false;
 101 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
 102 
 103 // The installed compiler(s)
 104 AbstractCompiler* CompileBroker::_compilers[2];
 105 
 106 // These counters are used for assigning id's to each compilation
 107 uint CompileBroker::_compilation_id        = 0;
 108 uint CompileBroker::_osr_compilation_id    = 0;
 109 
 110 // Debugging information
 111 int  CompileBroker::_last_compile_type     = no_compile;
 112 int  CompileBroker::_last_compile_level    = CompLevel_none;
 113 char CompileBroker::_last_method_compiled[CompileBroker::name_buffer_length];
 114 
 115 // Performance counters
 116 PerfCounter* CompileBroker::_perf_total_compilation = NULL;
 117 PerfCounter* CompileBroker::_perf_osr_compilation = NULL;
 118 PerfCounter* CompileBroker::_perf_standard_compilation = NULL;
 119 
 120 PerfCounter* CompileBroker::_perf_total_bailout_count = NULL;
 121 PerfCounter* CompileBroker::_perf_total_invalidated_count = NULL;
 122 PerfCounter* CompileBroker::_perf_total_compile_count = NULL;
 123 PerfCounter* CompileBroker::_perf_total_osr_compile_count = NULL;
 124 PerfCounter* CompileBroker::_perf_total_standard_compile_count = NULL;
 125 
 126 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = NULL;
 127 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = NULL;
 128 PerfCounter* CompileBroker::_perf_sum_nmethod_size = NULL;
 129 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = NULL;
 130 
 131 PerfStringVariable* CompileBroker::_perf_last_method = NULL;
 132 PerfStringVariable* CompileBroker::_perf_last_failed_method = NULL;
 133 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = NULL;
 134 PerfVariable*       CompileBroker::_perf_last_compile_type = NULL;
 135 PerfVariable*       CompileBroker::_perf_last_compile_size = NULL;
 136 PerfVariable*       CompileBroker::_perf_last_failed_type = NULL;
 137 PerfVariable*       CompileBroker::_perf_last_invalidated_type = NULL;
 138 
 139 // Timers and counters for generating statistics
 140 elapsedTimer CompileBroker::_t_total_compilation;
 141 elapsedTimer CompileBroker::_t_osr_compilation;
 142 elapsedTimer CompileBroker::_t_standard_compilation;
 143 
 144 int CompileBroker::_total_bailout_count          = 0;
 145 int CompileBroker::_total_invalidated_count      = 0;
 146 int CompileBroker::_total_compile_count          = 0;
 147 int CompileBroker::_total_osr_compile_count      = 0;
 148 int CompileBroker::_total_standard_compile_count = 0;
 149 
 150 int CompileBroker::_sum_osr_bytes_compiled       = 0;
 151 int CompileBroker::_sum_standard_bytes_compiled  = 0;
 152 int CompileBroker::_sum_nmethod_size             = 0;
 153 int CompileBroker::_sum_nmethod_code_size        = 0;
 154 
 155 CompileQueue* CompileBroker::_c2_method_queue   = NULL;
 156 CompileQueue* CompileBroker::_c1_method_queue   = NULL;
 157 CompileTask*  CompileBroker::_task_free_list = NULL;
 158 
 159 GrowableArray<CompilerThread*>* CompileBroker::_method_threads = NULL;
 160 
 161 
 162 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
 163   CompilerThread* thread = CompilerThread::current();
 164   thread->set_task(task);
 165   CompileLog*     log  = thread->log();
 166   if (log != NULL)  task->log_task_start(log);
 167 }
 168 
 169 CompileTaskWrapper::~CompileTaskWrapper() {
 170   CompilerThread* thread = CompilerThread::current();
 171   CompileTask* task = thread->task();
 172   CompileLog*  log  = thread->log();
 173   if (log != NULL)  task->log_task_done(log);
 174   thread->set_task(NULL);
 175   task->set_code_handle(NULL);
 176   DEBUG_ONLY(thread->set_env((ciEnv*)badAddress));
 177   if (task->is_blocking()) {
 178     MutexLocker notifier(task->lock(), thread);
 179     task->mark_complete();
 180     // Notify the waiting thread that the compilation has completed.
 181     task->lock()->notify_all();
 182   } else {
 183     task->mark_complete();
 184 
 185     // By convention, the compiling thread is responsible for
 186     // recycling a non-blocking CompileTask.
 187     CompileBroker::free_task(task);
 188   }
 189 }
 190 
 191 
 192 // ------------------------------------------------------------------
 193 // CompileTask::initialize
 194 void CompileTask::initialize(int compile_id,
 195                              methodHandle method,
 196                              int osr_bci,
 197                              int comp_level,
 198                              methodHandle hot_method,
 199                              int hot_count,
 200                              const char* comment,
 201                              bool is_blocking) {
 202   assert(!_lock->is_locked(), "bad locking");
 203 
 204   _compile_id = compile_id;
 205   _method = JNIHandles::make_global(method);
 206   _osr_bci = osr_bci;
 207   _is_blocking = is_blocking;
 208   _comp_level = comp_level;
 209   _num_inlined_bytecodes = 0;
 210 
 211   _is_complete = false;
 212   _is_success = false;
 213   _code_handle = NULL;
 214 
 215   _hot_method = NULL;
 216   _hot_count = hot_count;
 217   _time_queued = 0;  // tidy
 218   _comment = comment;
 219 
 220   if (LogCompilation) {
 221     _time_queued = os::elapsed_counter();
 222     if (hot_method.not_null()) {
 223       if (hot_method == method) {
 224         _hot_method = _method;
 225       } else {
 226         _hot_method = JNIHandles::make_global(hot_method);
 227       }
 228     }
 229   }
 230 
 231   _next = NULL;
 232 }
 233 
 234 // ------------------------------------------------------------------
 235 // CompileTask::code/set_code
 236 nmethod* CompileTask::code() const {
 237   if (_code_handle == NULL)  return NULL;
 238   return _code_handle->code();
 239 }
 240 void CompileTask::set_code(nmethod* nm) {
 241   if (_code_handle == NULL && nm == NULL)  return;
 242   guarantee(_code_handle != NULL, "");
 243   _code_handle->set_code(nm);
 244   if (nm == NULL)  _code_handle = NULL;  // drop the handle also
 245 }
 246 
 247 // ------------------------------------------------------------------
 248 // CompileTask::free
 249 void CompileTask::free() {
 250   set_code(NULL);
 251   assert(!_lock->is_locked(), "Should not be locked when freed");
 252   if (_hot_method != NULL && _hot_method != _method) {
 253     JNIHandles::destroy_global(_hot_method);
 254   }
 255   JNIHandles::destroy_global(_method);
 256 }
 257 
 258 
 259 // ------------------------------------------------------------------
 260 // CompileTask::print
 261 void CompileTask::print() {
 262   tty->print("<CompileTask compile_id=%d ", _compile_id);
 263   tty->print("method=");
 264   ((methodOop)JNIHandles::resolve(_method))->print_name(tty);
 265   tty->print_cr(" osr_bci=%d is_blocking=%s is_complete=%s is_success=%s>",
 266              _osr_bci, bool_to_str(_is_blocking),
 267              bool_to_str(_is_complete), bool_to_str(_is_success));
 268 }
 269 
 270 
 271 // ------------------------------------------------------------------
 272 // CompileTask::print_line_on_error
 273 //
 274 // This function is called by fatal error handler when the thread
 275 // causing troubles is a compiler thread.
 276 //
 277 // Do not grab any lock, do not allocate memory.
 278 //
 279 // Otherwise it's the same as CompileTask::print_line()
 280 //
 281 void CompileTask::print_line_on_error(outputStream* st, char* buf, int buflen) {
 282   // print compiler name
 283   st->print("%s:", CompileBroker::compiler(comp_level())->name());
 284   print_compilation(st);
 285 }
 286 
 287 // ------------------------------------------------------------------
 288 // CompileTask::print_line
 289 void CompileTask::print_line() {
 290   ttyLocker ttyl;  // keep the following output all in one block
 291   // print compiler name if requested
 292   if (CIPrintCompilerName) tty->print("%s:", CompileBroker::compiler(comp_level())->name());
 293   print_compilation();
 294 }
 295 
 296 
 297 // ------------------------------------------------------------------
 298 // CompileTask::print_compilation_impl
 299 void CompileTask::print_compilation_impl(outputStream* st, methodOop method, int compile_id, int comp_level, bool is_osr_method, int osr_bci, bool is_blocking, const char* msg) {
 300   st->print("%7d ", (int) st->time_stamp().milliseconds());  // print timestamp
 301   st->print("%4d ", compile_id);    // print compilation number
 302 
 303   // For unloaded methods the transition to zombie occurs after the
 304   // method is cleared so it's impossible to report accurate
 305   // information for that case.
 306   bool is_synchronized = false;
 307   bool has_exception_handler = false;
 308   bool is_native = false;
 309   if (method != NULL) {
 310     is_synchronized       = method->is_synchronized();
 311     has_exception_handler = method->has_exception_handler();
 312     is_native             = method->is_native();
 313   }
 314   // method attributes
 315   const char compile_type   = is_osr_method                   ? '%' : ' ';
 316   const char sync_char      = is_synchronized                 ? 's' : ' ';
 317   const char exception_char = has_exception_handler           ? '!' : ' ';
 318   const char blocking_char  = is_blocking                     ? 'b' : ' ';
 319   const char native_char    = is_native                       ? 'n' : ' ';
 320 
 321   // print method attributes
 322   st->print("%c%c%c%c%c ", compile_type, sync_char, exception_char, blocking_char, native_char);
 323 
 324   if (TieredCompilation) {
 325     if (comp_level != -1)  st->print("%d ", comp_level);
 326     else                   st->print("- ");
 327   }
 328   st->print("     ");  // more indent
 329 
 330   if (method == NULL) {
 331     st->print("(method)");
 332   } else {
 333     method->print_short_name(st);
 334     if (is_osr_method) {
 335       st->print(" @ %d", osr_bci);
 336     }
 337     st->print(" (%d bytes)", method->code_size());
 338   }
 339 
 340   if (msg != NULL) {
 341     st->print("   %s", msg);
 342   }
 343   st->cr();
 344 }
 345 
 346 // ------------------------------------------------------------------
 347 // CompileTask::print_inlining
 348 void CompileTask::print_inlining(outputStream* st, ciMethod* method, int inline_level, int bci, const char* msg) {
 349   //         1234567
 350   st->print("        ");     // print timestamp
 351   //         1234
 352   st->print("     ");        // print compilation number
 353 
 354   // method attributes
 355   const char sync_char      = method->is_synchronized()        ? 's' : ' ';
 356   const char exception_char = method->has_exception_handlers() ? '!' : ' ';
 357   const char monitors_char  = method->has_monitor_bytecodes()  ? 'm' : ' ';
 358 
 359   // print method attributes
 360   st->print(" %c%c%c  ", sync_char, exception_char, monitors_char);
 361 
 362   if (TieredCompilation) {
 363     st->print("  ");
 364   }
 365   st->print("     ");        // more indent
 366   st->print("    ");         // initial inlining indent
 367 
 368   for (int i = 0; i < inline_level; i++)  st->print("  ");
 369 
 370   st->print("@ %d  ", bci);  // print bci
 371   method->print_short_name(st);
 372   st->print(" (%d bytes)", method->code_size());
 373 
 374   if (msg != NULL) {
 375     st->print("   %s", msg);
 376   }
 377   st->cr();
 378 }
 379 
 380 // ------------------------------------------------------------------
 381 // CompileTask::print_inline_indent
 382 void CompileTask::print_inline_indent(int inline_level, outputStream* st) {
 383   //         1234567
 384   st->print("        ");     // print timestamp
 385   //         1234
 386   st->print("     ");        // print compilation number
 387   //         %s!bn
 388   st->print("      ");       // print method attributes
 389   if (TieredCompilation) {
 390     st->print("  ");
 391   }
 392   st->print("     ");        // more indent
 393   st->print("    ");         // initial inlining indent
 394   for (int i = 0; i < inline_level; i++)  st->print("  ");
 395 }
 396 
 397 // ------------------------------------------------------------------
 398 // CompileTask::print_compilation
 399 void CompileTask::print_compilation(outputStream* st) {
 400   oop rem = JNIHandles::resolve(method_handle());
 401   assert(rem != NULL && rem->is_method(), "must be");
 402   methodOop method = (methodOop) rem;
 403   bool is_osr_method = osr_bci() != InvocationEntryBci;
 404   print_compilation_impl(st, method, compile_id(), comp_level(), is_osr_method, osr_bci(), is_blocking());
 405 }
 406 
 407 // ------------------------------------------------------------------
 408 // CompileTask::log_task
 409 void CompileTask::log_task(xmlStream* log) {
 410   Thread* thread = Thread::current();
 411   methodHandle method(thread,
 412                       (methodOop)JNIHandles::resolve(method_handle()));
 413   ResourceMark rm(thread);
 414 
 415   // <task id='9' method='M' osr_bci='X' level='1' blocking='1' stamp='1.234'>
 416   if (_compile_id != 0)   log->print(" compile_id='%d'", _compile_id);
 417   if (_osr_bci != CompileBroker::standard_entry_bci) {
 418     log->print(" compile_kind='osr'");  // same as nmethod::compile_kind
 419   } // else compile_kind='c2c'
 420   if (!method.is_null())  log->method(method);
 421   if (_osr_bci != CompileBroker::standard_entry_bci) {
 422     log->print(" osr_bci='%d'", _osr_bci);
 423   }
 424   if (_comp_level != CompLevel_highest_tier) {
 425     log->print(" level='%d'", _comp_level);
 426   }
 427   if (_is_blocking) {
 428     log->print(" blocking='1'");
 429   }
 430   log->stamp();
 431 }
 432 
 433 
 434 // ------------------------------------------------------------------
 435 // CompileTask::log_task_queued
 436 void CompileTask::log_task_queued() {
 437   Thread* thread = Thread::current();
 438   ttyLocker ttyl;
 439   ResourceMark rm(thread);
 440 
 441   xtty->begin_elem("task_queued");
 442   log_task(xtty);
 443   if (_comment != NULL) {
 444     xtty->print(" comment='%s'", _comment);
 445   }
 446   if (_hot_method != NULL) {
 447     methodHandle hot(thread,
 448                      (methodOop)JNIHandles::resolve(_hot_method));
 449     methodHandle method(thread,
 450                         (methodOop)JNIHandles::resolve(_method));
 451     if (hot() != method()) {
 452       xtty->method(hot);
 453     }
 454   }
 455   if (_hot_count != 0) {
 456     xtty->print(" hot_count='%d'", _hot_count);
 457   }
 458   xtty->end_elem();
 459 }
 460 
 461 
 462 // ------------------------------------------------------------------
 463 // CompileTask::log_task_start
 464 void CompileTask::log_task_start(CompileLog* log)   {
 465   log->begin_head("task");
 466   log_task(log);
 467   log->end_head();
 468 }
 469 
 470 
 471 // ------------------------------------------------------------------
 472 // CompileTask::log_task_done
 473 void CompileTask::log_task_done(CompileLog* log) {
 474   Thread* thread = Thread::current();
 475   methodHandle method(thread,
 476                       (methodOop)JNIHandles::resolve(method_handle()));
 477   ResourceMark rm(thread);
 478 
 479   // <task_done ... stamp='1.234'>  </task>
 480   nmethod* nm = code();
 481   log->begin_elem("task_done success='%d' nmsize='%d' count='%d'",
 482                   _is_success, nm == NULL ? 0 : nm->content_size(),
 483                   method->invocation_count());
 484   int bec = method->backedge_count();
 485   if (bec != 0)  log->print(" backedge_count='%d'", bec);
 486   // Note:  "_is_complete" is about to be set, but is not.
 487   if (_num_inlined_bytecodes != 0) {
 488     log->print(" inlined_bytes='%d'", _num_inlined_bytecodes);
 489   }
 490   log->stamp();
 491   log->end_elem();
 492   log->tail("task");
 493   log->clear_identities();   // next task will have different CI
 494   if (log->unflushed_count() > 2000) {
 495     log->flush();
 496   }
 497   log->mark_file_end();
 498 }
 499 
 500 
 501 
 502 // ------------------------------------------------------------------
 503 // CompileQueue::add
 504 //
 505 // Add a CompileTask to a CompileQueue
 506 void CompileQueue::add(CompileTask* task) {
 507   assert(lock()->owned_by_self(), "must own lock");
 508 
 509   task->set_next(NULL);
 510   task->set_prev(NULL);
 511 
 512   if (_last == NULL) {
 513     // The compile queue is empty.
 514     assert(_first == NULL, "queue is empty");
 515     _first = task;
 516     _last = task;
 517   } else {
 518     // Append the task to the queue.
 519     assert(_last->next() == NULL, "not last");
 520     _last->set_next(task);
 521     task->set_prev(_last);
 522     _last = task;
 523   }
 524   ++_size;
 525 
 526   // Mark the method as being in the compile queue.
 527   ((methodOop)JNIHandles::resolve(task->method_handle()))->set_queued_for_compilation();
 528 
 529   if (CIPrintCompileQueue) {
 530     print();
 531   }
 532 
 533   if (LogCompilation && xtty != NULL) {
 534     task->log_task_queued();
 535   }
 536 
 537   // Notify CompilerThreads that a task is available.
 538   lock()->notify_all();
 539 }
 540 
 541 // ------------------------------------------------------------------
 542 // CompileQueue::get
 543 //
 544 // Get the next CompileTask from a CompileQueue
 545 CompileTask* CompileQueue::get() {
 546   NMethodSweeper::possibly_sweep();
 547 
 548   MutexLocker locker(lock());
 549   // Wait for an available CompileTask.
 550   while (_first == NULL) {
 551     // There is no work to be done right now.  Wait.
 552     if (UseCodeCacheFlushing && (!CompileBroker::should_compile_new_jobs() || CodeCache::needs_flushing())) {
 553       // During the emergency sweeping periods, wake up and sweep occasionally
 554       bool timedout = lock()->wait(!Mutex::_no_safepoint_check_flag, NmethodSweepCheckInterval*1000);
 555       if (timedout) {
 556         MutexUnlocker ul(lock());
 557         // When otherwise not busy, run nmethod sweeping
 558         NMethodSweeper::possibly_sweep();
 559       }
 560     } else {
 561       // During normal operation no need to wake up on timer
 562       lock()->wait();
 563     }
 564   }
 565   CompileTask* task = CompilationPolicy::policy()->select_task(this);
 566   remove(task);
 567   return task;
 568 }
 569 
 570 void CompileQueue::remove(CompileTask* task)
 571 {
 572    assert(lock()->owned_by_self(), "must own lock");
 573   if (task->prev() != NULL) {
 574     task->prev()->set_next(task->next());
 575   } else {
 576     // max is the first element
 577     assert(task == _first, "Sanity");
 578     _first = task->next();
 579   }
 580 
 581   if (task->next() != NULL) {
 582     task->next()->set_prev(task->prev());
 583   } else {
 584     // max is the last element
 585     assert(task == _last, "Sanity");
 586     _last = task->prev();
 587   }
 588   --_size;
 589 }
 590 
 591 // ------------------------------------------------------------------
 592 // CompileQueue::print
 593 void CompileQueue::print() {
 594   tty->print_cr("Contents of %s", name());
 595   tty->print_cr("----------------------");
 596   CompileTask* task = _first;
 597   while (task != NULL) {
 598     task->print_line();
 599     task = task->next();
 600   }
 601   tty->print_cr("----------------------");
 602 }
 603 
 604 CompilerCounters::CompilerCounters(const char* thread_name, int instance, TRAPS) {
 605 
 606   _current_method[0] = '\0';
 607   _compile_type = CompileBroker::no_compile;
 608 
 609   if (UsePerfData) {
 610     ResourceMark rm;
 611 
 612     // create the thread instance name space string - don't create an
 613     // instance subspace if instance is -1 - keeps the adapterThread
 614     // counters  from having a ".0" namespace.
 615     const char* thread_i = (instance == -1) ? thread_name :
 616                       PerfDataManager::name_space(thread_name, instance);
 617 
 618 
 619     char* name = PerfDataManager::counter_name(thread_i, "method");
 620     _perf_current_method =
 621                PerfDataManager::create_string_variable(SUN_CI, name,
 622                                                        cmname_buffer_length,
 623                                                        _current_method, CHECK);
 624 
 625     name = PerfDataManager::counter_name(thread_i, "type");
 626     _perf_compile_type = PerfDataManager::create_variable(SUN_CI, name,
 627                                                           PerfData::U_None,
 628                                                          (jlong)_compile_type,
 629                                                           CHECK);
 630 
 631     name = PerfDataManager::counter_name(thread_i, "time");
 632     _perf_time = PerfDataManager::create_counter(SUN_CI, name,
 633                                                  PerfData::U_Ticks, CHECK);
 634 
 635     name = PerfDataManager::counter_name(thread_i, "compiles");
 636     _perf_compiles = PerfDataManager::create_counter(SUN_CI, name,
 637                                                      PerfData::U_Events, CHECK);
 638   }
 639 }
 640 
 641 // ------------------------------------------------------------------
 642 // CompileBroker::compilation_init
 643 //
 644 // Initialize the Compilation object
 645 void CompileBroker::compilation_init() {
 646   _last_method_compiled[0] = '\0';
 647 
 648 #ifndef SHARK
 649   // Set the interface to the current compiler(s).
 650   int c1_count = CompilationPolicy::policy()->compiler_count(CompLevel_simple);
 651   int c2_count = CompilationPolicy::policy()->compiler_count(CompLevel_full_optimization);
 652 #ifdef COMPILER1
 653   if (c1_count > 0) {
 654     _compilers[0] = new Compiler();
 655   }
 656 #endif // COMPILER1
 657 
 658 #ifdef COMPILER2
 659   if (c2_count > 0) {
 660     _compilers[1] = new C2Compiler();
 661   }
 662 #endif // COMPILER2
 663 
 664 #else // SHARK
 665   int c1_count = 0;
 666   int c2_count = 1;
 667 
 668   _compilers[1] = new SharkCompiler();
 669 #endif // SHARK
 670 
 671   // Initialize the CompileTask free list
 672   _task_free_list = NULL;
 673 
 674   // Start the CompilerThreads
 675   init_compiler_threads(c1_count, c2_count);
 676   // totalTime performance counter is always created as it is required
 677   // by the implementation of java.lang.management.CompilationMBean.
 678   {
 679     EXCEPTION_MARK;
 680     _perf_total_compilation =
 681                  PerfDataManager::create_counter(JAVA_CI, "totalTime",
 682                                                  PerfData::U_Ticks, CHECK);
 683   }
 684 
 685 
 686   if (UsePerfData) {
 687 
 688     EXCEPTION_MARK;
 689 
 690     // create the jvmstat performance counters
 691     _perf_osr_compilation =
 692                  PerfDataManager::create_counter(SUN_CI, "osrTime",
 693                                                  PerfData::U_Ticks, CHECK);
 694 
 695     _perf_standard_compilation =
 696                  PerfDataManager::create_counter(SUN_CI, "standardTime",
 697                                                  PerfData::U_Ticks, CHECK);
 698 
 699     _perf_total_bailout_count =
 700                  PerfDataManager::create_counter(SUN_CI, "totalBailouts",
 701                                                  PerfData::U_Events, CHECK);
 702 
 703     _perf_total_invalidated_count =
 704                  PerfDataManager::create_counter(SUN_CI, "totalInvalidates",
 705                                                  PerfData::U_Events, CHECK);
 706 
 707     _perf_total_compile_count =
 708                  PerfDataManager::create_counter(SUN_CI, "totalCompiles",
 709                                                  PerfData::U_Events, CHECK);
 710     _perf_total_osr_compile_count =
 711                  PerfDataManager::create_counter(SUN_CI, "osrCompiles",
 712                                                  PerfData::U_Events, CHECK);
 713 
 714     _perf_total_standard_compile_count =
 715                  PerfDataManager::create_counter(SUN_CI, "standardCompiles",
 716                                                  PerfData::U_Events, CHECK);
 717 
 718     _perf_sum_osr_bytes_compiled =
 719                  PerfDataManager::create_counter(SUN_CI, "osrBytes",
 720                                                  PerfData::U_Bytes, CHECK);
 721 
 722     _perf_sum_standard_bytes_compiled =
 723                  PerfDataManager::create_counter(SUN_CI, "standardBytes",
 724                                                  PerfData::U_Bytes, CHECK);
 725 
 726     _perf_sum_nmethod_size =
 727                  PerfDataManager::create_counter(SUN_CI, "nmethodSize",
 728                                                  PerfData::U_Bytes, CHECK);
 729 
 730     _perf_sum_nmethod_code_size =
 731                  PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",
 732                                                  PerfData::U_Bytes, CHECK);
 733 
 734     _perf_last_method =
 735                  PerfDataManager::create_string_variable(SUN_CI, "lastMethod",
 736                                        CompilerCounters::cmname_buffer_length,
 737                                        "", CHECK);
 738 
 739     _perf_last_failed_method =
 740             PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",
 741                                        CompilerCounters::cmname_buffer_length,
 742                                        "", CHECK);
 743 
 744     _perf_last_invalidated_method =
 745         PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",
 746                                      CompilerCounters::cmname_buffer_length,
 747                                      "", CHECK);
 748 
 749     _perf_last_compile_type =
 750              PerfDataManager::create_variable(SUN_CI, "lastType",
 751                                               PerfData::U_None,
 752                                               (jlong)CompileBroker::no_compile,
 753                                               CHECK);
 754 
 755     _perf_last_compile_size =
 756              PerfDataManager::create_variable(SUN_CI, "lastSize",
 757                                               PerfData::U_Bytes,
 758                                               (jlong)CompileBroker::no_compile,
 759                                               CHECK);
 760 
 761 
 762     _perf_last_failed_type =
 763              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 764                                               PerfData::U_None,
 765                                               (jlong)CompileBroker::no_compile,
 766                                               CHECK);
 767 
 768     _perf_last_invalidated_type =
 769          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 770                                           PerfData::U_None,
 771                                           (jlong)CompileBroker::no_compile,
 772                                           CHECK);
 773   }
 774 
 775   _initialized = true;
 776 }
 777 
 778 
 779 
 780 // ------------------------------------------------------------------
 781 // CompileBroker::make_compiler_thread
 782 CompilerThread* CompileBroker::make_compiler_thread(const char* name, CompileQueue* queue, CompilerCounters* counters, TRAPS) {
 783   CompilerThread* compiler_thread = NULL;
 784 
 785   klassOop k =
 786     SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(),
 787                                       true, CHECK_0);
 788   instanceKlassHandle klass (THREAD, k);
 789   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_0);
 790   Handle string = java_lang_String::create_from_str(name, CHECK_0);
 791 
 792   // Initialize thread_oop to put it into the system threadGroup
 793   Handle thread_group (THREAD,  Universe::system_thread_group());
 794   JavaValue result(T_VOID);
 795   JavaCalls::call_special(&result, thread_oop,
 796                        klass,
 797                        vmSymbols::object_initializer_name(),
 798                        vmSymbols::threadgroup_string_void_signature(),
 799                        thread_group,
 800                        string,
 801                        CHECK_0);
 802 
 803   {
 804     MutexLocker mu(Threads_lock, THREAD);
 805     compiler_thread = new CompilerThread(queue, counters);
 806     // At this point the new CompilerThread data-races with this startup
 807     // thread (which I believe is the primoridal thread and NOT the VM
 808     // thread).  This means Java bytecodes being executed at startup can
 809     // queue compile jobs which will run at whatever default priority the
 810     // newly created CompilerThread runs at.
 811 
 812 
 813     // At this point it may be possible that no osthread was created for the
 814     // JavaThread due to lack of memory. We would have to throw an exception
 815     // in that case. However, since this must work and we do not allow
 816     // exceptions anyway, check and abort if this fails.
 817 
 818     if (compiler_thread == NULL || compiler_thread->osthread() == NULL){
 819       vm_exit_during_initialization("java.lang.OutOfMemoryError",
 820                                     "unable to create new native thread");
 821     }
 822 
 823     java_lang_Thread::set_thread(thread_oop(), compiler_thread);
 824 
 825     // Note that this only sets the JavaThread _priority field, which by
 826     // definition is limited to Java priorities and not OS priorities.
 827     // The os-priority is set in the CompilerThread startup code itself
 828     java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
 829     // CLEANUP PRIORITIES: This -if- statement hids a bug whereby the compiler
 830     // threads never have their OS priority set.  The assumption here is to
 831     // enable the Performance group to do flag tuning, figure out a suitable
 832     // CompilerThreadPriority, and then remove this 'if' statement (and
 833     // comment) and unconditionally set the priority.
 834 
 835     // Compiler Threads should be at the highest Priority
 836     if ( CompilerThreadPriority != -1 )
 837       os::set_native_priority( compiler_thread, CompilerThreadPriority );
 838     else
 839       os::set_native_priority( compiler_thread, os::java_to_os_priority[NearMaxPriority]);
 840 
 841       // Note that I cannot call os::set_priority because it expects Java
 842       // priorities and I am *explicitly* using OS priorities so that it's
 843       // possible to set the compiler thread priority higher than any Java
 844       // thread.
 845 
 846     java_lang_Thread::set_daemon(thread_oop());
 847 
 848     compiler_thread->set_threadObj(thread_oop());
 849     Threads::add(compiler_thread);
 850     Thread::start(compiler_thread);
 851   }
 852   // Let go of Threads_lock before yielding
 853   os::yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
 854 
 855   return compiler_thread;
 856 }
 857 
 858 
 859 // ------------------------------------------------------------------
 860 // CompileBroker::init_compiler_threads
 861 //
 862 // Initialize the compilation queue
 863 void CompileBroker::init_compiler_threads(int c1_compiler_count, int c2_compiler_count) {
 864   EXCEPTION_MARK;
 865 #if !defined(ZERO) && !defined(SHARK)
 866   assert(c2_compiler_count > 0 || c1_compiler_count > 0, "No compilers?");
 867 #endif // !ZERO && !SHARK
 868   if (c2_compiler_count > 0) {
 869     _c2_method_queue  = new CompileQueue("C2MethodQueue",  MethodCompileQueue_lock);
 870   }
 871   if (c1_compiler_count > 0) {
 872     _c1_method_queue  = new CompileQueue("C1MethodQueue",  MethodCompileQueue_lock);
 873   }
 874 
 875   int compiler_count = c1_compiler_count + c2_compiler_count;
 876 
 877   _method_threads =
 878     new (ResourceObj::C_HEAP) GrowableArray<CompilerThread*>(compiler_count, true);
 879 
 880   char name_buffer[256];
 881   for (int i = 0; i < c2_compiler_count; i++) {
 882     // Create a name for our thread.
 883     sprintf(name_buffer, "C2 CompilerThread%d", i);
 884     CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);
 885     CompilerThread* new_thread = make_compiler_thread(name_buffer, _c2_method_queue, counters, CHECK);
 886     _method_threads->append(new_thread);
 887   }
 888 
 889   for (int i = c2_compiler_count; i < compiler_count; i++) {
 890     // Create a name for our thread.
 891     sprintf(name_buffer, "C1 CompilerThread%d", i);
 892     CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);
 893     CompilerThread* new_thread = make_compiler_thread(name_buffer, _c1_method_queue, counters, CHECK);
 894     _method_threads->append(new_thread);
 895   }
 896 
 897   if (UsePerfData) {
 898     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes,
 899                                      compiler_count, CHECK);
 900   }
 901 }
 902 
 903 // ------------------------------------------------------------------
 904 // CompileBroker::is_idle
 905 bool CompileBroker::is_idle() {
 906   if (_c2_method_queue != NULL && !_c2_method_queue->is_empty()) {
 907     return false;
 908   } else if (_c1_method_queue != NULL && !_c1_method_queue->is_empty()) {
 909     return false;
 910   } else {
 911     int num_threads = _method_threads->length();
 912     for (int i=0; i<num_threads; i++) {
 913       if (_method_threads->at(i)->task() != NULL) {
 914         return false;
 915       }
 916     }
 917 
 918     // No pending or active compilations.
 919     return true;
 920   }
 921 }
 922 
 923 
 924 // ------------------------------------------------------------------
 925 // CompileBroker::compile_method
 926 //
 927 // Request compilation of a method.
 928 void CompileBroker::compile_method_base(methodHandle method,
 929                                         int osr_bci,
 930                                         int comp_level,
 931                                         methodHandle hot_method,
 932                                         int hot_count,
 933                                         const char* comment,
 934                                         TRAPS) {
 935   // do nothing if compiler thread(s) is not available
 936   if (!_initialized ) {
 937     return;
 938   }
 939 
 940   guarantee(!method->is_abstract(), "cannot compile abstract methods");
 941   assert(method->method_holder()->klass_part()->oop_is_instance(),
 942          "sanity check");
 943   assert(!instanceKlass::cast(method->method_holder())->is_not_initialized(),
 944          "method holder must be initialized");
 945 
 946   if (CIPrintRequests) {
 947     tty->print("request: ");
 948     method->print_short_name(tty);
 949     if (osr_bci != InvocationEntryBci) {
 950       tty->print(" osr_bci: %d", osr_bci);
 951     }
 952     tty->print(" comment: %s count: %d", comment, hot_count);
 953     if (!hot_method.is_null()) {
 954       tty->print(" hot: ");
 955       if (hot_method() != method()) {
 956           hot_method->print_short_name(tty);
 957       } else {
 958         tty->print("yes");
 959       }
 960     }
 961     tty->cr();
 962   }
 963 
 964   // A request has been made for compilation.  Before we do any
 965   // real work, check to see if the method has been compiled
 966   // in the meantime with a definitive result.
 967   if (compilation_is_complete(method, osr_bci, comp_level)) {
 968     return;
 969   }
 970 
 971 #ifndef PRODUCT
 972   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
 973     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
 974       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
 975       return;
 976     }
 977   }
 978 #endif
 979 
 980   // If this method is already in the compile queue, then
 981   // we do not block the current thread.
 982   if (compilation_is_in_queue(method, osr_bci)) {
 983     // We may want to decay our counter a bit here to prevent
 984     // multiple denied requests for compilation.  This is an
 985     // open compilation policy issue. Note: The other possibility,
 986     // in the case that this is a blocking compile request, is to have
 987     // all subsequent blocking requesters wait for completion of
 988     // ongoing compiles. Note that in this case we'll need a protocol
 989     // for freeing the associated compile tasks. [Or we could have
 990     // a single static monitor on which all these waiters sleep.]
 991     return;
 992   }
 993 
 994   // If the requesting thread is holding the pending list lock
 995   // then we just return. We can't risk blocking while holding
 996   // the pending list lock or a 3-way deadlock may occur
 997   // between the reference handler thread, a GC (instigated
 998   // by a compiler thread), and compiled method registration.
 999   if (instanceRefKlass::owns_pending_list_lock(JavaThread::current())) {
1000     return;
1001   }
1002 
1003   // Outputs from the following MutexLocker block:
1004   CompileTask* task     = NULL;
1005   bool         blocking = false;
1006   CompileQueue* queue  = compile_queue(comp_level);
1007 
1008   // Acquire our lock.
1009   {
1010     MutexLocker locker(queue->lock(), THREAD);
1011 
1012     // Make sure the method has not slipped into the queues since
1013     // last we checked; note that those checks were "fast bail-outs".
1014     // Here we need to be more careful, see 14012000 below.
1015     if (compilation_is_in_queue(method, osr_bci)) {
1016       return;
1017     }
1018 
1019     // We need to check again to see if the compilation has
1020     // completed.  A previous compilation may have registered
1021     // some result.
1022     if (compilation_is_complete(method, osr_bci, comp_level)) {
1023       return;
1024     }
1025 
1026     // We now know that this compilation is not pending, complete,
1027     // or prohibited.  Assign a compile_id to this compilation
1028     // and check to see if it is in our [Start..Stop) range.
1029     uint compile_id = assign_compile_id(method, osr_bci);
1030     if (compile_id == 0) {
1031       // The compilation falls outside the allowed range.
1032       return;
1033     }
1034 
1035     // Should this thread wait for completion of the compile?
1036     blocking = is_compile_blocking(method, osr_bci);
1037 
1038     // We will enter the compilation in the queue.
1039     // 14012000: Note that this sets the queued_for_compile bits in
1040     // the target method. We can now reason that a method cannot be
1041     // queued for compilation more than once, as follows:
1042     // Before a thread queues a task for compilation, it first acquires
1043     // the compile queue lock, then checks if the method's queued bits
1044     // are set or it has already been compiled. Thus there can not be two
1045     // instances of a compilation task for the same method on the
1046     // compilation queue. Consider now the case where the compilation
1047     // thread has already removed a task for that method from the queue
1048     // and is in the midst of compiling it. In this case, the
1049     // queued_for_compile bits must be set in the method (and these
1050     // will be visible to the current thread, since the bits were set
1051     // under protection of the compile queue lock, which we hold now.
1052     // When the compilation completes, the compiler thread first sets
1053     // the compilation result and then clears the queued_for_compile
1054     // bits. Neither of these actions are protected by a barrier (or done
1055     // under the protection of a lock), so the only guarantee we have
1056     // (on machines with TSO (Total Store Order)) is that these values
1057     // will update in that order. As a result, the only combinations of
1058     // these bits that the current thread will see are, in temporal order:
1059     // <RESULT, QUEUE> :
1060     //     <0, 1> : in compile queue, but not yet compiled
1061     //     <1, 1> : compiled but queue bit not cleared
1062     //     <1, 0> : compiled and queue bit cleared
1063     // Because we first check the queue bits then check the result bits,
1064     // we are assured that we cannot introduce a duplicate task.
1065     // Note that if we did the tests in the reverse order (i.e. check
1066     // result then check queued bit), we could get the result bit before
1067     // the compilation completed, and the queue bit after the compilation
1068     // completed, and end up introducing a "duplicate" (redundant) task.
1069     // In that case, the compiler thread should first check if a method
1070     // has already been compiled before trying to compile it.
1071     // NOTE: in the event that there are multiple compiler threads and
1072     // there is de-optimization/recompilation, things will get hairy,
1073     // and in that case it's best to protect both the testing (here) of
1074     // these bits, and their updating (here and elsewhere) under a
1075     // common lock.
1076     task = create_compile_task(queue,
1077                                compile_id, method,
1078                                osr_bci, comp_level,
1079                                hot_method, hot_count, comment,
1080                                blocking);
1081   }
1082 
1083   if (blocking) {
1084     wait_for_completion(task);
1085   }
1086 }
1087 
1088 
1089 nmethod* CompileBroker::compile_method(methodHandle method, int osr_bci,
1090                                        int comp_level,
1091                                        methodHandle hot_method, int hot_count,
1092                                        const char* comment, TRAPS) {
1093   // make sure arguments make sense
1094   assert(method->method_holder()->klass_part()->oop_is_instance(), "not an instance method");
1095   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1096   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1097   assert(!instanceKlass::cast(method->method_holder())->is_not_initialized(), "method holder must be initialized");
1098 
1099   if (!TieredCompilation) {
1100     comp_level = CompLevel_highest_tier;
1101   }
1102 
1103   // return quickly if possible
1104 
1105   // lock, make sure that the compilation
1106   // isn't prohibited in a straightforward way.
1107 
1108   if (compiler(comp_level) == NULL || compilation_is_prohibited(method, osr_bci, comp_level)) {
1109     return NULL;
1110   }
1111 
1112   if (osr_bci == InvocationEntryBci) {
1113     // standard compilation
1114     nmethod* method_code = method->code();
1115     if (method_code != NULL) {
1116       if (compilation_is_complete(method, osr_bci, comp_level)) {
1117         return method_code;
1118       }
1119     }
1120     if (method->is_not_compilable(comp_level)) return NULL;
1121 
1122     if (UseCodeCacheFlushing) {
1123       nmethod* saved = CodeCache::find_and_remove_saved_code(method());
1124       if (saved != NULL) {
1125         method->set_code(method, saved);
1126         return saved;
1127       }
1128     }
1129 
1130   } else {
1131     // osr compilation
1132 #ifndef TIERED
1133     // seems like an assert of dubious value
1134     assert(comp_level == CompLevel_highest_tier,
1135            "all OSR compiles are assumed to be at a single compilation lavel");
1136 #endif // TIERED
1137     // We accept a higher level osr method
1138     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1139     if (nm != NULL) return nm;
1140     if (method->is_not_osr_compilable()) return NULL;
1141   }
1142 
1143   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1144   // some prerequisites that are compiler specific
1145   if (compiler(comp_level)->is_c2() || compiler(comp_level)->is_shark()) {
1146     method->constants()->resolve_string_constants(CHECK_0);
1147     // Resolve all classes seen in the signature of the method
1148     // we are compiling.
1149     methodOopDesc::load_signature_classes(method, CHECK_0);
1150   }
1151 
1152   // If the method is native, do the lookup in the thread requesting
1153   // the compilation. Native lookups can load code, which is not
1154   // permitted during compilation.
1155   //
1156   // Note: A native method implies non-osr compilation which is
1157   //       checked with an assertion at the entry of this method.
1158   if (method->is_native()) {
1159     bool in_base_library;
1160     address adr = NativeLookup::lookup(method, in_base_library, THREAD);
1161     if (HAS_PENDING_EXCEPTION) {
1162       // In case of an exception looking up the method, we just forget
1163       // about it. The interpreter will kick-in and throw the exception.
1164       method->set_not_compilable(); // implies is_not_osr_compilable()
1165       CLEAR_PENDING_EXCEPTION;
1166       return NULL;
1167     }
1168     assert(method->has_native_function(), "must have native code by now");
1169   }
1170 
1171   // RedefineClasses() has replaced this method; just return
1172   if (method->is_old()) {
1173     return NULL;
1174   }
1175 
1176   // JVMTI -- post_compile_event requires jmethod_id() that may require
1177   // a lock the compiling thread can not acquire. Prefetch it here.
1178   if (JvmtiExport::should_post_compiled_method_load()) {
1179     method->jmethod_id();
1180   }
1181 
1182   // If the compiler is shut off due to code cache flushing or otherwise,
1183   // fail out now so blocking compiles dont hang the java thread
1184   if (!should_compile_new_jobs() || (UseCodeCacheFlushing && CodeCache::needs_flushing())) {
1185     CompilationPolicy::policy()->delay_compilation(method());
1186     return NULL;
1187   }
1188 
1189   // do the compilation
1190   if (method->is_native()) {
1191     if (!PreferInterpreterNativeStubs) {
1192       // Acquire our lock.
1193       int compile_id;
1194       {
1195         MutexLocker locker(MethodCompileQueue_lock, THREAD);
1196         compile_id = assign_compile_id(method, standard_entry_bci);
1197       }
1198       (void) AdapterHandlerLibrary::create_native_wrapper(method, compile_id);
1199     } else {
1200       return NULL;
1201     }
1202   } else {
1203     compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, comment, CHECK_0);
1204   }
1205 
1206   // return requested nmethod
1207   // We accept a higher level osr method
1208   return osr_bci  == InvocationEntryBci ? method->code() : method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1209 }
1210 
1211 
1212 // ------------------------------------------------------------------
1213 // CompileBroker::compilation_is_complete
1214 //
1215 // See if compilation of this method is already complete.
1216 bool CompileBroker::compilation_is_complete(methodHandle method,
1217                                             int          osr_bci,
1218                                             int          comp_level) {
1219   bool is_osr = (osr_bci != standard_entry_bci);
1220   if (is_osr) {
1221     if (method->is_not_osr_compilable()) {
1222       return true;
1223     } else {
1224       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1225       return (result != NULL);
1226     }
1227   } else {
1228     if (method->is_not_compilable(comp_level)) {
1229       return true;
1230     } else {
1231       nmethod* result = method->code();
1232       if (result == NULL) return false;
1233       return comp_level == result->comp_level();
1234     }
1235   }
1236 }
1237 
1238 
1239 // ------------------------------------------------------------------
1240 // CompileBroker::compilation_is_in_queue
1241 //
1242 // See if this compilation is already requested.
1243 //
1244 // Implementation note: there is only a single "is in queue" bit
1245 // for each method.  This means that the check below is overly
1246 // conservative in the sense that an osr compilation in the queue
1247 // will block a normal compilation from entering the queue (and vice
1248 // versa).  This can be remedied by a full queue search to disambiguate
1249 // cases.  If it is deemed profitible, this may be done.
1250 bool CompileBroker::compilation_is_in_queue(methodHandle method,
1251                                             int          osr_bci) {
1252   return method->queued_for_compilation();
1253 }
1254 
1255 // ------------------------------------------------------------------
1256 // CompileBroker::compilation_is_prohibited
1257 //
1258 // See if this compilation is not allowed.
1259 bool CompileBroker::compilation_is_prohibited(methodHandle method, int osr_bci, int comp_level) {
1260   bool is_native = method->is_native();
1261   // Some compilers may not support the compilation of natives.
1262   if (is_native &&
1263       (!CICompileNatives || !compiler(comp_level)->supports_native())) {
1264     method->set_not_compilable_quietly(comp_level);
1265     return true;
1266   }
1267 
1268   bool is_osr = (osr_bci != standard_entry_bci);
1269   // Some compilers may not support on stack replacement.
1270   if (is_osr &&
1271       (!CICompileOSR || !compiler(comp_level)->supports_osr())) {
1272     method->set_not_osr_compilable();
1273     return true;
1274   }
1275 
1276   // The method may be explicitly excluded by the user.
1277   bool quietly;
1278   if (CompilerOracle::should_exclude(method, quietly)) {
1279     if (!quietly) {
1280       // This does not happen quietly...
1281       ResourceMark rm;
1282       tty->print("### Excluding %s:%s",
1283                  method->is_native() ? "generation of native wrapper" : "compile",
1284                  (method->is_static() ? " static" : ""));
1285       method->print_short_name(tty);
1286       tty->cr();
1287     }
1288     method->set_not_compilable_quietly();
1289   }
1290 
1291   return false;
1292 }
1293 
1294 
1295 // ------------------------------------------------------------------
1296 // CompileBroker::assign_compile_id
1297 //
1298 // Assign a serialized id number to this compilation request.  If the
1299 // number falls out of the allowed range, return a 0.  OSR
1300 // compilations may be numbered separately from regular compilations
1301 // if certain debugging flags are used.
1302 uint CompileBroker::assign_compile_id(methodHandle method, int osr_bci) {
1303   assert(MethodCompileQueue_lock->owner() == Thread::current(),
1304          "must hold the compilation queue lock");
1305   bool is_osr = (osr_bci != standard_entry_bci);
1306   uint id;
1307   if (CICountOSR && is_osr) {
1308     id = ++_osr_compilation_id;
1309     if ((uint)CIStartOSR <= id && id < (uint)CIStopOSR) {
1310       return id;
1311     }
1312   } else {
1313     id = ++_compilation_id;
1314     if ((uint)CIStart <= id && id < (uint)CIStop) {
1315       return id;
1316     }
1317   }
1318 
1319   // Method was not in the appropriate compilation range.
1320   method->set_not_compilable_quietly();
1321   return 0;
1322 }
1323 
1324 
1325 // ------------------------------------------------------------------
1326 // CompileBroker::is_compile_blocking
1327 //
1328 // Should the current thread be blocked until this compilation request
1329 // has been fulfilled?
1330 bool CompileBroker::is_compile_blocking(methodHandle method, int osr_bci) {
1331   assert(!instanceRefKlass::owns_pending_list_lock(JavaThread::current()), "possible deadlock");
1332   return !BackgroundCompilation;
1333 }
1334 
1335 
1336 // ------------------------------------------------------------------
1337 // CompileBroker::preload_classes
1338 void CompileBroker::preload_classes(methodHandle method, TRAPS) {
1339   // Move this code over from c1_Compiler.cpp
1340   ShouldNotReachHere();
1341 }
1342 
1343 
1344 // ------------------------------------------------------------------
1345 // CompileBroker::create_compile_task
1346 //
1347 // Create a CompileTask object representing the current request for
1348 // compilation.  Add this task to the queue.
1349 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,
1350                                               int           compile_id,
1351                                               methodHandle  method,
1352                                               int           osr_bci,
1353                                               int           comp_level,
1354                                               methodHandle  hot_method,
1355                                               int           hot_count,
1356                                               const char*   comment,
1357                                               bool          blocking) {
1358   CompileTask* new_task = allocate_task();
1359   new_task->initialize(compile_id, method, osr_bci, comp_level,
1360                        hot_method, hot_count, comment,
1361                        blocking);
1362   queue->add(new_task);
1363   return new_task;
1364 }
1365 
1366 
1367 // ------------------------------------------------------------------
1368 // CompileBroker::allocate_task
1369 //
1370 // Allocate a CompileTask, from the free list if possible.
1371 CompileTask* CompileBroker::allocate_task() {
1372   MutexLocker locker(CompileTaskAlloc_lock);
1373   CompileTask* task = NULL;
1374   if (_task_free_list != NULL) {
1375     task = _task_free_list;
1376     _task_free_list = task->next();
1377     task->set_next(NULL);
1378   } else {
1379     task = new CompileTask();
1380     task->set_next(NULL);
1381   }
1382   return task;
1383 }
1384 
1385 
1386 // ------------------------------------------------------------------
1387 // CompileBroker::free_task
1388 //
1389 // Add a task to the free list.
1390 void CompileBroker::free_task(CompileTask* task) {
1391   MutexLocker locker(CompileTaskAlloc_lock);
1392   task->free();
1393   task->set_next(_task_free_list);
1394   _task_free_list = task;
1395 }
1396 
1397 
1398 // ------------------------------------------------------------------
1399 // CompileBroker::wait_for_completion
1400 //
1401 // Wait for the given method CompileTask to complete.
1402 void CompileBroker::wait_for_completion(CompileTask* task) {
1403   if (CIPrintCompileQueue) {
1404     tty->print_cr("BLOCKING FOR COMPILE");
1405   }
1406 
1407   assert(task->is_blocking(), "can only wait on blocking task");
1408 
1409   JavaThread *thread = JavaThread::current();
1410   thread->set_blocked_on_compilation(true);
1411 
1412   methodHandle method(thread,
1413                       (methodOop)JNIHandles::resolve(task->method_handle()));
1414   {
1415     MutexLocker waiter(task->lock(), thread);
1416 
1417     while (!task->is_complete())
1418       task->lock()->wait();
1419   }
1420   // It is harmless to check this status without the lock, because
1421   // completion is a stable property (until the task object is recycled).
1422   assert(task->is_complete(), "Compilation should have completed");
1423   assert(task->code_handle() == NULL, "must be reset");
1424 
1425   thread->set_blocked_on_compilation(false);
1426 
1427   // By convention, the waiter is responsible for recycling a
1428   // blocking CompileTask. Since there is only one waiter ever
1429   // waiting on a CompileTask, we know that no one else will
1430   // be using this CompileTask; we can free it.
1431   free_task(task);
1432 }
1433 
1434 // ------------------------------------------------------------------
1435 // CompileBroker::compiler_thread_loop
1436 //
1437 // The main loop run by a CompilerThread.
1438 void CompileBroker::compiler_thread_loop() {
1439   CompilerThread* thread = CompilerThread::current();
1440   CompileQueue* queue = thread->queue();
1441 
1442   // For the thread that initializes the ciObjectFactory
1443   // this resource mark holds all the shared objects
1444   ResourceMark rm;
1445 
1446   // First thread to get here will initialize the compiler interface
1447 
1448   if (!ciObjectFactory::is_initialized()) {
1449     ASSERT_IN_VM;
1450     MutexLocker only_one (CompileThread_lock, thread);
1451     if (!ciObjectFactory::is_initialized()) {
1452       ciObjectFactory::initialize();
1453     }
1454   }
1455 
1456   // Open a log.
1457   if (LogCompilation) {
1458     init_compiler_thread_log();
1459   }
1460   CompileLog* log = thread->log();
1461   if (log != NULL) {
1462     log->begin_elem("start_compile_thread thread='" UINTX_FORMAT "' process='%d'",
1463                     os::current_thread_id(),
1464                     os::current_process_id());
1465     log->stamp();
1466     log->end_elem();
1467   }
1468 
1469   while (true) {
1470     {
1471       // We need this HandleMark to avoid leaking VM handles.
1472       HandleMark hm(thread);
1473 
1474       if (CodeCache::largest_free_block() < CodeCacheMinimumFreeSpace) {
1475         // the code cache is really full
1476         handle_full_code_cache();
1477       } else if (UseCodeCacheFlushing && CodeCache::needs_flushing()) {
1478         // Attempt to start cleaning the code cache while there is still a little headroom
1479         NMethodSweeper::handle_full_code_cache(false);
1480       }
1481 
1482       CompileTask* task = queue->get();
1483 
1484       // Give compiler threads an extra quanta.  They tend to be bursty and
1485       // this helps the compiler to finish up the job.
1486       if( CompilerThreadHintNoPreempt )
1487         os::hint_no_preempt();
1488 
1489       // trace per thread time and compile statistics
1490       CompilerCounters* counters = ((CompilerThread*)thread)->counters();
1491       PerfTraceTimedEvent(counters->time_counter(), counters->compile_counter());
1492 
1493       // Assign the task to the current thread.  Mark this compilation
1494       // thread as active for the profiler.
1495       CompileTaskWrapper ctw(task);
1496       nmethodLocker result_handle;  // (handle for the nmethod produced by this task)
1497       task->set_code_handle(&result_handle);
1498       methodHandle method(thread,
1499                      (methodOop)JNIHandles::resolve(task->method_handle()));
1500 
1501       // Never compile a method if breakpoints are present in it
1502       if (method()->number_of_breakpoints() == 0) {
1503         // Compile the method.
1504         if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1505 #ifdef COMPILER1
1506           // Allow repeating compilations for the purpose of benchmarking
1507           // compile speed. This is not useful for customers.
1508           if (CompilationRepeat != 0) {
1509             int compile_count = CompilationRepeat;
1510             while (compile_count > 0) {
1511               invoke_compiler_on_method(task);
1512               nmethod* nm = method->code();
1513               if (nm != NULL) {
1514                 nm->make_zombie();
1515                 method->clear_code();
1516               }
1517               compile_count--;
1518             }
1519           }
1520 #endif /* COMPILER1 */
1521           invoke_compiler_on_method(task);
1522         } else {
1523           // After compilation is disabled, remove remaining methods from queue
1524           method->clear_queued_for_compilation();
1525         }
1526       }
1527     }
1528   }
1529 }
1530 
1531 
1532 // ------------------------------------------------------------------
1533 // CompileBroker::init_compiler_thread_log
1534 //
1535 // Set up state required by +LogCompilation.
1536 void CompileBroker::init_compiler_thread_log() {
1537     CompilerThread* thread = CompilerThread::current();
1538     char  fileBuf[4*K];
1539     FILE* fp = NULL;
1540     char* file = NULL;
1541     intx thread_id = os::current_thread_id();
1542     for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
1543       const char* dir = (try_temp_dir ? os::get_temp_directory() : NULL);
1544       if (dir == NULL) {
1545         jio_snprintf(fileBuf, sizeof(fileBuf), "hs_c" UINTX_FORMAT "_pid%u.log",
1546                      thread_id, os::current_process_id());
1547       } else {
1548         jio_snprintf(fileBuf, sizeof(fileBuf),
1549                      "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir,
1550                      os::file_separator(), thread_id, os::current_process_id());
1551       }
1552       fp = fopen(fileBuf, "at");
1553       if (fp != NULL) {
1554         file = NEW_C_HEAP_ARRAY(char, strlen(fileBuf)+1);
1555         strcpy(file, fileBuf);
1556         break;
1557       }
1558     }
1559     if (fp == NULL) {
1560       warning("Cannot open log file: %s", fileBuf);
1561     } else {
1562       if (LogCompilation && Verbose)
1563         tty->print_cr("Opening compilation log %s", file);
1564       CompileLog* log = new(ResourceObj::C_HEAP) CompileLog(file, fp, thread_id);
1565       thread->init_log(log);
1566 
1567       if (xtty != NULL) {
1568         ttyLocker ttyl;
1569 
1570         // Record any per thread log files
1571         xtty->elem("thread_logfile thread='%d' filename='%s'", thread_id, file);
1572       }
1573     }
1574 }
1575 
1576 // ------------------------------------------------------------------
1577 // CompileBroker::set_should_block
1578 //
1579 // Set _should_block.
1580 // Call this from the VM, with Threads_lock held and a safepoint requested.
1581 void CompileBroker::set_should_block() {
1582   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
1583   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
1584 #ifndef PRODUCT
1585   if (PrintCompilation && (Verbose || WizardMode))
1586     tty->print_cr("notifying compiler thread pool to block");
1587 #endif
1588   _should_block = true;
1589 }
1590 
1591 // ------------------------------------------------------------------
1592 // CompileBroker::maybe_block
1593 //
1594 // Call this from the compiler at convenient points, to poll for _should_block.
1595 void CompileBroker::maybe_block() {
1596   if (_should_block) {
1597 #ifndef PRODUCT
1598     if (PrintCompilation && (Verbose || WizardMode))
1599       tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", Thread::current());
1600 #endif
1601     ThreadInVMfromNative tivfn(JavaThread::current());
1602   }
1603 }
1604 
1605 
1606 // ------------------------------------------------------------------
1607 // CompileBroker::invoke_compiler_on_method
1608 //
1609 // Compile a method.
1610 //
1611 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
1612   if (PrintCompilation) {
1613     ResourceMark rm;
1614     task->print_line();
1615   }
1616   elapsedTimer time;
1617 
1618   CompilerThread* thread = CompilerThread::current();
1619   ResourceMark rm(thread);
1620 
1621   // Common flags.
1622   uint compile_id = task->compile_id();
1623   int osr_bci = task->osr_bci();
1624   bool is_osr = (osr_bci != standard_entry_bci);
1625   bool should_log = (thread->log() != NULL);
1626   bool should_break = false;
1627   {
1628     // create the handle inside it's own block so it can't
1629     // accidentally be referenced once the thread transitions to
1630     // native.  The NoHandleMark before the transition should catch
1631     // any cases where this occurs in the future.
1632     methodHandle method(thread,
1633                         (methodOop)JNIHandles::resolve(task->method_handle()));
1634     should_break = check_break_at(method, compile_id, is_osr);
1635     if (should_log && !CompilerOracle::should_log(method)) {
1636       should_log = false;
1637     }
1638     assert(!method->is_native(), "no longer compile natives");
1639 
1640     // Save information about this method in case of failure.
1641     set_last_compile(thread, method, is_osr, task->comp_level());
1642 
1643     DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler(task->comp_level()), method);
1644   }
1645 
1646   // Allocate a new set of JNI handles.
1647   push_jni_handle_block();
1648   jobject target_handle = JNIHandles::make_local(thread, JNIHandles::resolve(task->method_handle()));
1649   int compilable = ciEnv::MethodCompilable;
1650   {
1651     int system_dictionary_modification_counter;
1652     {
1653       MutexLocker locker(Compile_lock, thread);
1654       system_dictionary_modification_counter = SystemDictionary::number_of_modifications();
1655     }
1656 
1657     NoHandleMark  nhm;
1658     ThreadToNativeFromVM ttn(thread);
1659 
1660     ciEnv ci_env(task, system_dictionary_modification_counter);
1661     if (should_break) {
1662       ci_env.set_break_at_compile(true);
1663     }
1664     if (should_log) {
1665       ci_env.set_log(thread->log());
1666     }
1667     assert(thread->env() == &ci_env, "set by ci_env");
1668     // The thread-env() field is cleared in ~CompileTaskWrapper.
1669 
1670     // Cache Jvmti state
1671     ci_env.cache_jvmti_state();
1672 
1673     // Cache DTrace flags
1674     ci_env.cache_dtrace_flags();
1675 
1676     ciMethod* target = ci_env.get_method_from_handle(target_handle);
1677 
1678     TraceTime t1("compilation", &time);
1679 
1680     compiler(task->comp_level())->compile_method(&ci_env, target, osr_bci);
1681 
1682     if (!ci_env.failing() && task->code() == NULL) {
1683       //assert(false, "compiler should always document failure");
1684       // The compiler elected, without comment, not to register a result.
1685       // Do not attempt further compilations of this method.
1686       ci_env.record_method_not_compilable("compile failed", !TieredCompilation);
1687     }
1688 
1689     if (ci_env.failing()) {
1690       // Copy this bit to the enclosing block:
1691       compilable = ci_env.compilable();
1692       if (PrintCompilation) {
1693         const char* reason = ci_env.failure_reason();
1694         if (compilable == ciEnv::MethodCompilable_not_at_tier) {
1695             tty->print_cr("%3d   COMPILE SKIPPED: %s (retry at different tier)", compile_id, reason);
1696         } else if (compilable == ciEnv::MethodCompilable_never) {
1697           tty->print_cr("%3d   COMPILE SKIPPED: %s (not retryable)", compile_id, reason);
1698         } else if (compilable == ciEnv::MethodCompilable) {
1699           tty->print_cr("%3d   COMPILE SKIPPED: %s", compile_id, reason);
1700         }
1701       }
1702     } else {
1703       task->mark_success();
1704       task->set_num_inlined_bytecodes(ci_env.num_inlined_bytecodes());
1705     }
1706   }
1707   pop_jni_handle_block();
1708 
1709   methodHandle method(thread,
1710                       (methodOop)JNIHandles::resolve(task->method_handle()));
1711 
1712   DTRACE_METHOD_COMPILE_END_PROBE(compiler(task->comp_level()), method, task->is_success());
1713 
1714   collect_statistics(thread, time, task);
1715 
1716   if (compilable == ciEnv::MethodCompilable_never) {
1717     if (is_osr) {
1718       method->set_not_osr_compilable();
1719     } else {
1720       method->set_not_compilable_quietly();
1721     }
1722   } else if (compilable == ciEnv::MethodCompilable_not_at_tier) {
1723     method->set_not_compilable_quietly(task->comp_level());
1724   }
1725 
1726   // Note that the queued_for_compilation bits are cleared without
1727   // protection of a mutex. [They were set by the requester thread,
1728   // when adding the task to the complie queue -- at which time the
1729   // compile queue lock was held. Subsequently, we acquired the compile
1730   // queue lock to get this task off the compile queue; thus (to belabour
1731   // the point somewhat) our clearing of the bits must be occurring
1732   // only after the setting of the bits. See also 14012000 above.
1733   method->clear_queued_for_compilation();
1734 
1735 #ifdef ASSERT
1736   if (CollectedHeap::fired_fake_oom()) {
1737     // The current compile received a fake OOM during compilation so
1738     // go ahead and exit the VM since the test apparently succeeded
1739     tty->print_cr("*** Shutting down VM after successful fake OOM");
1740     vm_exit(0);
1741   }
1742 #endif
1743 }
1744 
1745 // ------------------------------------------------------------------
1746 // CompileBroker::handle_full_code_cache
1747 //
1748 // The CodeCache is full.  Print out warning and disable compilation or
1749 // try code cache cleaning so compilation can continue later.
1750 void CompileBroker::handle_full_code_cache() {
1751   UseInterpreter = true;
1752   if (UseCompiler || AlwaysCompileLoopMethods ) {
1753     if (xtty != NULL) {
1754       stringStream s;
1755       // Dump code cache state into a buffer before locking the tty,
1756       // because log_state() will use locks causing lock conflicts.
1757       CodeCache::log_state(&s);
1758       // Lock to prevent tearing
1759       ttyLocker ttyl;
1760       xtty->begin_elem("code_cache_full");
1761       xtty->print(s.as_string());
1762       xtty->stamp();
1763       xtty->end_elem();
1764     }
1765     warning("CodeCache is full. Compiler has been disabled.");
1766     warning("Try increasing the code cache size using -XX:ReservedCodeCacheSize=");
1767     CodeCache::print_bounds(tty);
1768 #ifndef PRODUCT
1769     if (CompileTheWorld || ExitOnFullCodeCache) {
1770       before_exit(JavaThread::current());
1771       exit_globals(); // will delete tty
1772       vm_direct_exit(CompileTheWorld ? 0 : 1);
1773     }
1774 #endif
1775     if (UseCodeCacheFlushing) {
1776       NMethodSweeper::handle_full_code_cache(true);
1777     } else {
1778       UseCompiler               = false;
1779       AlwaysCompileLoopMethods  = false;
1780     }
1781   }
1782 }
1783 
1784 // ------------------------------------------------------------------
1785 // CompileBroker::set_last_compile
1786 //
1787 // Record this compilation for debugging purposes.
1788 void CompileBroker::set_last_compile(CompilerThread* thread, methodHandle method, bool is_osr, int comp_level) {
1789   ResourceMark rm;
1790   char* method_name = method->name()->as_C_string();
1791   strncpy(_last_method_compiled, method_name, CompileBroker::name_buffer_length);
1792   char current_method[CompilerCounters::cmname_buffer_length];
1793   size_t maxLen = CompilerCounters::cmname_buffer_length;
1794 
1795   if (UsePerfData) {
1796     const char* class_name = method->method_holder()->klass_part()->name()->as_C_string();
1797 
1798     size_t s1len = strlen(class_name);
1799     size_t s2len = strlen(method_name);
1800 
1801     // check if we need to truncate the string
1802     if (s1len + s2len + 2 > maxLen) {
1803 
1804       // the strategy is to lop off the leading characters of the
1805       // class name and the trailing characters of the method name.
1806 
1807       if (s2len + 2 > maxLen) {
1808         // lop of the entire class name string, let snprintf handle
1809         // truncation of the method name.
1810         class_name += s1len; // null string
1811       }
1812       else {
1813         // lop off the extra characters from the front of the class name
1814         class_name += ((s1len + s2len + 2) - maxLen);
1815       }
1816     }
1817 
1818     jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
1819   }
1820 
1821   if (CICountOSR && is_osr) {
1822     _last_compile_type = osr_compile;
1823   } else {
1824     _last_compile_type = normal_compile;
1825   }
1826   _last_compile_level = comp_level;
1827 
1828   if (UsePerfData) {
1829     CompilerCounters* counters = thread->counters();
1830     counters->set_current_method(current_method);
1831     counters->set_compile_type((jlong)_last_compile_type);
1832   }
1833 }
1834 
1835 
1836 // ------------------------------------------------------------------
1837 // CompileBroker::push_jni_handle_block
1838 //
1839 // Push on a new block of JNI handles.
1840 void CompileBroker::push_jni_handle_block() {
1841   JavaThread* thread = JavaThread::current();
1842 
1843   // Allocate a new block for JNI handles.
1844   // Inlined code from jni_PushLocalFrame()
1845   JNIHandleBlock* java_handles = thread->active_handles();
1846   JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread);
1847   assert(compile_handles != NULL && java_handles != NULL, "should not be NULL");
1848   compile_handles->set_pop_frame_link(java_handles);  // make sure java handles get gc'd.
1849   thread->set_active_handles(compile_handles);
1850 }
1851 
1852 
1853 // ------------------------------------------------------------------
1854 // CompileBroker::pop_jni_handle_block
1855 //
1856 // Pop off the current block of JNI handles.
1857 void CompileBroker::pop_jni_handle_block() {
1858   JavaThread* thread = JavaThread::current();
1859 
1860   // Release our JNI handle block
1861   JNIHandleBlock* compile_handles = thread->active_handles();
1862   JNIHandleBlock* java_handles = compile_handles->pop_frame_link();
1863   thread->set_active_handles(java_handles);
1864   compile_handles->set_pop_frame_link(NULL);
1865   JNIHandleBlock::release_block(compile_handles, thread); // may block
1866 }
1867 
1868 
1869 // ------------------------------------------------------------------
1870 // CompileBroker::check_break_at
1871 //
1872 // Should the compilation break at the current compilation.
1873 bool CompileBroker::check_break_at(methodHandle method, int compile_id, bool is_osr) {
1874   if (CICountOSR && is_osr && (compile_id == CIBreakAtOSR)) {
1875     return true;
1876   } else if( CompilerOracle::should_break_at(method) ) { // break when compiling
1877     return true;
1878   } else {
1879     return (compile_id == CIBreakAt);
1880   }
1881 }
1882 
1883 // ------------------------------------------------------------------
1884 // CompileBroker::collect_statistics
1885 //
1886 // Collect statistics about the compilation.
1887 
1888 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
1889   bool success = task->is_success();
1890   methodHandle method (thread, (methodOop)JNIHandles::resolve(task->method_handle()));
1891   uint compile_id = task->compile_id();
1892   bool is_osr = (task->osr_bci() != standard_entry_bci);
1893   nmethod* code = task->code();
1894   CompilerCounters* counters = thread->counters();
1895 
1896   assert(code == NULL || code->is_locked_by_vm(), "will survive the MutexLocker");
1897   MutexLocker locker(CompileStatistics_lock);
1898 
1899   // _perf variables are production performance counters which are
1900   // updated regardless of the setting of the CITime and CITimeEach flags
1901   //
1902   if (!success) {
1903     _total_bailout_count++;
1904     if (UsePerfData) {
1905       _perf_last_failed_method->set_value(counters->current_method());
1906       _perf_last_failed_type->set_value(counters->compile_type());
1907       _perf_total_bailout_count->inc();
1908     }
1909   } else if (code == NULL) {
1910     if (UsePerfData) {
1911       _perf_last_invalidated_method->set_value(counters->current_method());
1912       _perf_last_invalidated_type->set_value(counters->compile_type());
1913       _perf_total_invalidated_count->inc();
1914     }
1915     _total_invalidated_count++;
1916   } else {
1917     // Compilation succeeded
1918 
1919     // update compilation ticks - used by the implementation of
1920     // java.lang.management.CompilationMBean
1921     _perf_total_compilation->inc(time.ticks());
1922 
1923     if (CITime) {
1924       _t_total_compilation.add(time);
1925       if (is_osr) {
1926         _t_osr_compilation.add(time);
1927         _sum_osr_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
1928       } else {
1929         _t_standard_compilation.add(time);
1930         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
1931       }
1932     }
1933 
1934     if (UsePerfData) {
1935       // save the name of the last method compiled
1936       _perf_last_method->set_value(counters->current_method());
1937       _perf_last_compile_type->set_value(counters->compile_type());
1938       _perf_last_compile_size->set_value(method->code_size() +
1939                                          task->num_inlined_bytecodes());
1940       if (is_osr) {
1941         _perf_osr_compilation->inc(time.ticks());
1942         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
1943       } else {
1944         _perf_standard_compilation->inc(time.ticks());
1945         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
1946       }
1947     }
1948 
1949     if (CITimeEach) {
1950       float bytes_per_sec = 1.0 * (method->code_size() + task->num_inlined_bytecodes()) / time.seconds();
1951       tty->print_cr("%3d   seconds: %f bytes/sec : %f (bytes %d + %d inlined)",
1952                     compile_id, time.seconds(), bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
1953     }
1954 
1955     // Collect counts of successful compilations
1956     _sum_nmethod_size      += code->total_size();
1957     _sum_nmethod_code_size += code->insts_size();
1958     _total_compile_count++;
1959 
1960     if (UsePerfData) {
1961       _perf_sum_nmethod_size->inc(     code->total_size());
1962       _perf_sum_nmethod_code_size->inc(code->insts_size());
1963       _perf_total_compile_count->inc();
1964     }
1965 
1966     if (is_osr) {
1967       if (UsePerfData) _perf_total_osr_compile_count->inc();
1968       _total_osr_compile_count++;
1969     } else {
1970       if (UsePerfData) _perf_total_standard_compile_count->inc();
1971       _total_standard_compile_count++;
1972     }
1973   }
1974   // set the current method for the thread to null
1975   if (UsePerfData) counters->set_current_method("");
1976 }
1977 
1978 
1979 
1980 void CompileBroker::print_times() {
1981   tty->cr();
1982   tty->print_cr("Accumulated compiler times (for compiled methods only)");
1983   tty->print_cr("------------------------------------------------");
1984                //0000000000111111111122222222223333333333444444444455555555556666666666
1985                //0123456789012345678901234567890123456789012345678901234567890123456789
1986   tty->print_cr("  Total compilation time   : %6.3f s", CompileBroker::_t_total_compilation.seconds());
1987   tty->print_cr("    Standard compilation   : %6.3f s, Average : %2.3f",
1988                 CompileBroker::_t_standard_compilation.seconds(),
1989                 CompileBroker::_t_standard_compilation.seconds() / CompileBroker::_total_standard_compile_count);
1990   tty->print_cr("    On stack replacement   : %6.3f s, Average : %2.3f", CompileBroker::_t_osr_compilation.seconds(), CompileBroker::_t_osr_compilation.seconds() / CompileBroker::_total_osr_compile_count);
1991 
1992   if (compiler(CompLevel_simple) != NULL) {
1993     compiler(CompLevel_simple)->print_timers();
1994   }
1995   if (compiler(CompLevel_full_optimization) != NULL) {
1996     compiler(CompLevel_full_optimization)->print_timers();
1997   }
1998   tty->cr();
1999   int tcb = CompileBroker::_sum_osr_bytes_compiled + CompileBroker::_sum_standard_bytes_compiled;
2000   tty->print_cr("  Total compiled bytecodes : %6d bytes", tcb);
2001   tty->print_cr("    Standard compilation   : %6d bytes", CompileBroker::_sum_standard_bytes_compiled);
2002   tty->print_cr("    On stack replacement   : %6d bytes", CompileBroker::_sum_osr_bytes_compiled);
2003   int bps = (int)(tcb / CompileBroker::_t_total_compilation.seconds());
2004   tty->print_cr("  Average compilation speed: %6d bytes/s", bps);
2005   tty->cr();
2006   tty->print_cr("  nmethod code size        : %6d bytes", CompileBroker::_sum_nmethod_code_size);
2007   tty->print_cr("  nmethod total size       : %6d bytes", CompileBroker::_sum_nmethod_size);
2008 }
2009 
2010 
2011 // Debugging output for failure
2012 void CompileBroker::print_last_compile() {
2013   if ( _last_compile_level != CompLevel_none &&
2014        compiler(_last_compile_level) != NULL &&
2015        _last_method_compiled != NULL &&
2016        _last_compile_type != no_compile) {
2017     if (_last_compile_type == osr_compile) {
2018       tty->print_cr("Last parse:  [osr]%d+++(%d) %s",
2019                     _osr_compilation_id, _last_compile_level, _last_method_compiled);
2020     } else {
2021       tty->print_cr("Last parse:  %d+++(%d) %s",
2022                     _compilation_id, _last_compile_level, _last_method_compiled);
2023     }
2024   }
2025 }
2026 
2027 
2028 void CompileBroker::print_compiler_threads_on(outputStream* st) {
2029 #ifndef PRODUCT
2030   st->print_cr("Compiler thread printing unimplemented.");
2031   st->cr();
2032 #endif
2033 }