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