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