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