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