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