< prev index next >

src/hotspot/share/compiler/compileBroker.cpp

Print this page

   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/javaClasses.inline.hpp"
  27 #include "classfile/symbolTable.hpp"
  28 #include "classfile/vmClasses.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "code/codeHeapState.hpp"
  32 #include "code/dependencyContext.hpp"

  33 #include "compiler/compilationLog.hpp"
  34 #include "compiler/compilationMemoryStatistic.hpp"
  35 #include "compiler/compilationPolicy.hpp"
  36 #include "compiler/compileBroker.hpp"

  37 #include "compiler/compileLog.hpp"
  38 #include "compiler/compilerEvent.hpp"
  39 #include "compiler/compilerOracle.hpp"
  40 #include "compiler/directivesParser.hpp"

  41 #include "gc/shared/memAllocator.hpp"
  42 #include "interpreter/linkResolver.hpp"
  43 #include "jvm.h"
  44 #include "jfr/jfrEvents.hpp"
  45 #include "logging/log.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/allocation.inline.hpp"
  48 #include "memory/resourceArea.hpp"
  49 #include "memory/universe.hpp"
  50 #include "oops/methodData.hpp"
  51 #include "oops/method.inline.hpp"
  52 #include "oops/oop.inline.hpp"
  53 #include "prims/jvmtiExport.hpp"
  54 #include "prims/nativeLookup.hpp"
  55 #include "prims/whitebox.hpp"
  56 #include "runtime/atomic.hpp"
  57 #include "runtime/escapeBarrier.hpp"
  58 #include "runtime/globals_extension.hpp"
  59 #include "runtime/handles.inline.hpp"
  60 #include "runtime/init.hpp"
  61 #include "runtime/interfaceSupport.inline.hpp"
  62 #include "runtime/java.hpp"
  63 #include "runtime/javaCalls.hpp"
  64 #include "runtime/jniHandles.inline.hpp"
  65 #include "runtime/os.hpp"
  66 #include "runtime/perfData.hpp"
  67 #include "runtime/safepointVerifiers.hpp"
  68 #include "runtime/sharedRuntime.hpp"
  69 #include "runtime/threads.hpp"
  70 #include "runtime/threadSMR.hpp"
  71 #include "runtime/timerTrace.hpp"
  72 #include "runtime/vframe.inline.hpp"

  73 #include "utilities/debug.hpp"
  74 #include "utilities/dtrace.hpp"
  75 #include "utilities/events.hpp"
  76 #include "utilities/formatBuffer.hpp"
  77 #include "utilities/macros.hpp"

  78 #ifdef COMPILER1
  79 #include "c1/c1_Compiler.hpp"
  80 #endif
  81 #ifdef COMPILER2
  82 #include "opto/c2compiler.hpp"
  83 #endif
  84 #if INCLUDE_JVMCI
  85 #include "jvmci/jvmciEnv.hpp"
  86 #include "jvmci/jvmciRuntime.hpp"
  87 #endif
  88 
  89 #ifdef DTRACE_ENABLED
  90 
  91 // Only bother with this argument setup if dtrace is available
  92 
  93 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
  94   {                                                                      \
  95     Symbol* klass_name = (method)->klass_name();                         \
  96     Symbol* name = (method)->name();                                     \
  97     Symbol* signature = (method)->signature();                           \

 105 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)      \
 106   {                                                                      \
 107     Symbol* klass_name = (method)->klass_name();                         \
 108     Symbol* name = (method)->name();                                     \
 109     Symbol* signature = (method)->signature();                           \
 110     HOTSPOT_METHOD_COMPILE_END(                                          \
 111       (char *) comp_name, strlen(comp_name),                             \
 112       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
 113       (char *) name->bytes(), name->utf8_length(),                       \
 114       (char *) signature->bytes(), signature->utf8_length(), (success)); \
 115   }
 116 
 117 #else //  ndef DTRACE_ENABLED
 118 
 119 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
 120 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
 121 
 122 #endif // ndef DTRACE_ENABLED
 123 
 124 bool CompileBroker::_initialized = false;

 125 volatile bool CompileBroker::_should_block = false;
 126 volatile int  CompileBroker::_print_compilation_warning = 0;
 127 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
 128 
 129 // The installed compiler(s)
 130 AbstractCompiler* CompileBroker::_compilers[2];
 131 
 132 // The maximum numbers of compiler threads to be determined during startup.
 133 int CompileBroker::_c1_count = 0;
 134 int CompileBroker::_c2_count = 0;


 135 
 136 // An array of compiler names as Java String objects
 137 jobject* CompileBroker::_compiler1_objects = nullptr;
 138 jobject* CompileBroker::_compiler2_objects = nullptr;


 139 
 140 CompileLog** CompileBroker::_compiler1_logs = nullptr;
 141 CompileLog** CompileBroker::_compiler2_logs = nullptr;


 142 
 143 // These counters are used to assign an unique ID to each compilation.
 144 volatile jint CompileBroker::_compilation_id     = 0;
 145 volatile jint CompileBroker::_osr_compilation_id = 0;
 146 volatile jint CompileBroker::_native_compilation_id = 0;
 147 
 148 // Performance counters
 149 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
 150 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
 151 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
 152 
 153 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
 154 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
 155 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
 156 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
 157 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
 158 
 159 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
 160 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
 161 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
 162 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
 163 
 164 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
 165 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
 166 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
 167 PerfVariable*       CompileBroker::_perf_last_compile_type = nullptr;
 168 PerfVariable*       CompileBroker::_perf_last_compile_size = nullptr;
 169 PerfVariable*       CompileBroker::_perf_last_failed_type = nullptr;
 170 PerfVariable*       CompileBroker::_perf_last_invalidated_type = nullptr;
 171 
 172 // Timers and counters for generating statistics
 173 elapsedTimer CompileBroker::_t_total_compilation;
 174 elapsedTimer CompileBroker::_t_osr_compilation;
 175 elapsedTimer CompileBroker::_t_standard_compilation;
 176 elapsedTimer CompileBroker::_t_invalidated_compilation;
 177 elapsedTimer CompileBroker::_t_bailedout_compilation;
 178 
 179 uint CompileBroker::_total_bailout_count            = 0;
 180 uint CompileBroker::_total_invalidated_count        = 0;

 181 uint CompileBroker::_total_compile_count            = 0;
 182 uint CompileBroker::_total_osr_compile_count        = 0;
 183 uint CompileBroker::_total_standard_compile_count   = 0;
 184 uint CompileBroker::_total_compiler_stopped_count   = 0;
 185 uint CompileBroker::_total_compiler_restarted_count = 0;
 186 
 187 uint CompileBroker::_sum_osr_bytes_compiled         = 0;
 188 uint CompileBroker::_sum_standard_bytes_compiled    = 0;
 189 uint CompileBroker::_sum_nmethod_size               = 0;
 190 uint CompileBroker::_sum_nmethod_code_size          = 0;
 191 
 192 jlong CompileBroker::_peak_compilation_time        = 0;
 193 
 194 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];


 195 

 196 CompileQueue* CompileBroker::_c2_compile_queue     = nullptr;
 197 CompileQueue* CompileBroker::_c1_compile_queue     = nullptr;


 198 
 199 bool compileBroker_init() {
 200   if (LogEvents) {
 201     CompilationLog::init();
 202   }
 203 
 204   // init directives stack, adding default directive
 205   DirectivesStack::init();
 206 
 207   if (DirectivesParser::has_file()) {
 208     return DirectivesParser::parse_from_flag();
 209   } else if (CompilerDirectivesPrint) {
 210     // Print default directive even when no other was added
 211     DirectivesStack::print(tty);
 212   }
 213 
 214   return true;
 215 }
 216 
 217 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
 218   CompilerThread* thread = CompilerThread::current();
 219   thread->set_task(task);
 220   CompileLog*     log  = thread->log();
 221   if (log != nullptr && !task->is_unloaded())  task->log_task_start(log);
 222 }
 223 
 224 CompileTaskWrapper::~CompileTaskWrapper() {
 225   CompilerThread* thread = CompilerThread::current();
 226   CompileTask* task = thread->task();
 227   CompileLog*  log  = thread->log();

 228   if (log != nullptr && !task->is_unloaded())  task->log_task_done(log);
 229   thread->set_task(nullptr);
 230   thread->set_env(nullptr);
 231   if (task->is_blocking()) {
 232     bool free_task = false;
 233     {
 234       MutexLocker notifier(thread, task->lock());
 235       task->mark_complete();
 236 #if INCLUDE_JVMCI
 237       if (CompileBroker::compiler(task->comp_level())->is_jvmci()) {
 238         if (!task->has_waiter()) {
 239           // The waiting thread timed out and thus did not free the task.
 240           free_task = true;
 241         }
 242         task->set_blocking_jvmci_compile_state(nullptr);
 243       }
 244 #endif
 245       if (!free_task) {
 246         // Notify the waiting thread that the compilation has completed
 247         // so that it can free the task.
 248         task->lock()->notify_all();
 249       }
 250     }
 251     if (free_task) {
 252       // The task can only be freed once the task lock is released.
 253       CompileTask::free(task);
 254     }
 255   } else {
 256     task->mark_complete();
 257 
 258     // By convention, the compiling thread is responsible for
 259     // recycling a non-blocking CompileTask.
 260     CompileTask::free(task);
 261   }
 262 }
 263 
 264 /**
 265  * Check if a CompilerThread can be removed and update count if requested.
 266  */
 267 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
 268   assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
 269   if (!ReduceNumberOfCompilerThreads) return false;
 270 


 271   AbstractCompiler *compiler = ct->compiler();
 272   int compiler_count = compiler->num_compiler_threads();
 273   bool c1 = compiler->is_c1();
 274 
 275   // Keep at least 1 compiler thread of each type.
 276   if (compiler_count < 2) return false;
 277 
 278   // Keep thread alive for at least some time.
 279   if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
 280 
 281 #if INCLUDE_JVMCI
 282   if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 283     // Handles for JVMCI thread objects may get released concurrently.
 284     if (do_it) {
 285       assert(CompileThread_lock->owner() == ct, "must be holding lock");
 286     } else {
 287       // Skip check if it's the last thread and let caller check again.
 288       return true;
 289     }
 290   }

 297     if (do_it) {
 298       assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
 299       compiler->set_num_compiler_threads(compiler_count - 1);
 300 #if INCLUDE_JVMCI
 301       if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 302         // Old j.l.Thread object can die when no longer referenced elsewhere.
 303         JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
 304         _compiler2_objects[compiler_count - 1] = nullptr;
 305       }
 306 #endif
 307     }
 308     return true;
 309   }
 310   return false;
 311 }
 312 
 313 /**
 314  * Add a CompileTask to a CompileQueue.
 315  */
 316 void CompileQueue::add(CompileTask* task) {
 317   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 318 
 319   task->set_next(nullptr);
 320   task->set_prev(nullptr);
 321 
 322   if (_last == nullptr) {
 323     // The compile queue is empty.
 324     assert(_first == nullptr, "queue is empty");
 325     _first = task;
 326     _last = task;
 327   } else {
 328     // Append the task to the queue.
 329     assert(_last->next() == nullptr, "not last");
 330     _last->set_next(task);
 331     task->set_prev(_last);
 332     _last = task;
 333   }
 334   ++_size;
 335   ++_total_added;
 336   if (_size > _peak_size) {
 337     _peak_size = _size;
 338   }
 339 
 340   // Mark the method as being in the compile queue.
 341   task->method()->set_queued_for_compilation();
 342 


 343   if (CIPrintCompileQueue) {
 344     print_tty();
 345   }
 346 
 347   if (LogCompilation && xtty != nullptr) {
 348     task->log_task_queued();
 349   }
 350 








 351   // Notify CompilerThreads that a task is available.
 352   MethodCompileQueue_lock->notify_all();













































 353 }
 354 
 355 /**
 356  * Empties compilation queue by putting all compilation tasks onto
 357  * a freelist. Furthermore, the method wakes up all threads that are
 358  * waiting on a compilation task to finish. This can happen if background
 359  * compilation is disabled.
 360  */
 361 void CompileQueue::free_all() {
 362   MutexLocker mu(MethodCompileQueue_lock);


 363   CompileTask* next = _first;
 364 
 365   // Iterate over all tasks in the compile queue
 366   while (next != nullptr) {
 367     CompileTask* current = next;
 368     next = current->next();
 369     {
 370       // Wake up thread that blocks on the compile task.
 371       MutexLocker ct_lock(current->lock());
 372       current->lock()->notify();
 373     }
 374     // Put the task back on the freelist.
 375     CompileTask::free(current);
 376   }
 377   _first = nullptr;
 378   _last = nullptr;
 379 
 380   // Wake up all threads that block on the queue.
 381   MethodCompileQueue_lock->notify_all();
 382 }
 383 
 384 /**
 385  * Get the next CompileTask from a CompileQueue
 386  */
 387 CompileTask* CompileQueue::get(CompilerThread* thread) {
 388   // save methods from RedefineClasses across safepoint
 389   // across MethodCompileQueue_lock below.
 390   methodHandle save_method;
 391   methodHandle save_hot_method;
 392 
 393   MonitorLocker locker(MethodCompileQueue_lock);




 394   // If _first is null we have no more compile jobs. There are two reasons for
 395   // having no compile jobs: First, we compiled everything we wanted. Second,
 396   // we ran out of code cache so compilation has been disabled. In the latter
 397   // case we perform code cache sweeps to free memory such that we can re-enable
 398   // compilation.
 399   while (_first == nullptr) {
 400     // Exit loop if compilation is disabled forever
 401     if (CompileBroker::is_compilation_disabled_forever()) {
 402       return nullptr;
 403     }
 404 
 405     AbstractCompiler* compiler = thread->compiler();
 406     guarantee(compiler != nullptr, "Compiler object must exist");
 407     compiler->on_empty_queue(this, thread);
 408     if (_first != nullptr) {
 409       // The call to on_empty_queue may have temporarily unlocked the MCQ lock
 410       // so check again whether any tasks were added to the queue.
 411       break;
 412     }
 413 
 414     // If there are no compilation tasks and we can compile new jobs
 415     // (i.e., there is enough free space in the code cache) there is
 416     // no need to invoke the GC.
 417     // We need a timed wait here, since compiler threads can exit if compilation
 418     // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
 419     // is not critical and we do not want idle compiler threads to wake up too often.
 420     locker.wait(5*1000);
 421 




 422     if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
 423       // Still nothing to compile. Give caller a chance to stop this thread.
 424       if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
 425     }
 426   }
 427 
 428   if (CompileBroker::is_compilation_disabled_forever()) {
 429     return nullptr;
 430   }
 431 
 432   CompileTask* task;
 433   {
 434     NoSafepointVerifier nsv;
 435     task = CompilationPolicy::select_task(this);
 436     if (task != nullptr) {
 437       task = task->select_for_compilation();
 438     }
 439   }
 440 
 441   if (task != nullptr) {
 442     // Save method pointers across unlock safepoint.  The task is removed from
 443     // the compilation queue, which is walked during RedefineClasses.
 444     Thread* thread = Thread::current();
 445     save_method = methodHandle(thread, task->method());
 446     save_hot_method = methodHandle(thread, task->hot_method());
 447 
 448     remove(task);
 449   }
 450   purge_stale_tasks(); // may temporarily release MCQ lock
 451   return task;
 452 }
 453 
 454 // Clean & deallocate stale compile tasks.
 455 // Temporarily releases MethodCompileQueue lock.
 456 void CompileQueue::purge_stale_tasks() {
 457   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 458   if (_first_stale != nullptr) {
 459     // Stale tasks are purged when MCQ lock is released,
 460     // but _first_stale updates are protected by MCQ lock.
 461     // Once task processing starts and MCQ lock is released,
 462     // other compiler threads can reuse _first_stale.
 463     CompileTask* head = _first_stale;
 464     _first_stale = nullptr;
 465     {
 466       MutexUnlocker ul(MethodCompileQueue_lock);
 467       for (CompileTask* task = head; task != nullptr; ) {
 468         CompileTask* next_task = task->next();
 469         CompileTaskWrapper ctw(task); // Frees the task
 470         task->set_failure_reason("stale task");
 471         task = next_task;
 472       }
 473     }

 474   }
 475 }
 476 
 477 void CompileQueue::remove(CompileTask* task) {
 478   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 479   if (task->prev() != nullptr) {
 480     task->prev()->set_next(task->next());
 481   } else {
 482     // max is the first element
 483     assert(task == _first, "Sanity");
 484     _first = task->next();
 485   }
 486 
 487   if (task->next() != nullptr) {
 488     task->next()->set_prev(task->prev());
 489   } else {
 490     // max is the last element
 491     assert(task == _last, "Sanity");
 492     _last = task->prev();
 493   }
 494   --_size;
 495   ++_total_removed;
 496 }
 497 
 498 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
 499   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 500   remove(task);
 501 
 502   // Enqueue the task for reclamation (should be done outside MCQ lock)
 503   task->set_next(_first_stale);
 504   task->set_prev(nullptr);
 505   _first_stale = task;
 506 }
 507 
 508 // methods in the compile queue need to be marked as used on the stack
 509 // so that they don't get reclaimed by Redefine Classes
 510 void CompileQueue::mark_on_stack() {
 511   CompileTask* task = _first;
 512   while (task != nullptr) {



 513     task->mark_on_stack();
 514     task = task->next();
 515   }
 516 }
 517 
 518 
 519 CompileQueue* CompileBroker::compile_queue(int comp_level) {
 520   if (is_c2_compile(comp_level)) return _c2_compile_queue;
 521   if (is_c1_compile(comp_level)) return _c1_compile_queue;
 522   return nullptr;
 523 }
 524 
 525 CompileQueue* CompileBroker::c1_compile_queue() {
 526   return _c1_compile_queue;
 527 }
 528 
 529 CompileQueue* CompileBroker::c2_compile_queue() {
 530   return _c2_compile_queue;
 531 }
 532 
 533 void CompileBroker::print_compile_queues(outputStream* st) {
 534   st->print_cr("Current compiles: ");
 535 
 536   char buf[2000];
 537   int buflen = sizeof(buf);
 538   Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
 539 
 540   st->cr();
 541   if (_c1_compile_queue != nullptr) {
 542     _c1_compile_queue->print(st);
 543   }
 544   if (_c2_compile_queue != nullptr) {
 545     _c2_compile_queue->print(st);
 546   }









 547 }
 548 
 549 void CompileQueue::print(outputStream* st) {
 550   assert_locked_or_safepoint(MethodCompileQueue_lock);
 551   st->print_cr("%s:", name());
 552   CompileTask* task = _first;
 553   if (task == nullptr) {
 554     st->print_cr("Empty");
 555   } else {
 556     while (task != nullptr) {
 557       task->print(st, nullptr, true, true);
 558       task = task->next();
 559     }
 560   }
 561   st->cr();
 562 }
 563 
 564 void CompileQueue::print_tty() {
 565   stringStream ss;
 566   // Dump the compile queue into a buffer before locking the tty
 567   print(&ss);
 568   {
 569     ttyLocker ttyl;
 570     tty->print("%s", ss.freeze());

 597       CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
 598     }
 599     first_registration = false;
 600 #endif // COMPILER2
 601   }
 602 }
 603 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
 604 
 605 // ------------------------------------------------------------------
 606 // CompileBroker::compilation_init
 607 //
 608 // Initialize the Compilation object
 609 void CompileBroker::compilation_init(JavaThread* THREAD) {
 610   // No need to initialize compilation system if we do not use it.
 611   if (!UseCompiler) {
 612     return;
 613   }
 614   // Set the interface to the current compiler(s).
 615   _c1_count = CompilationPolicy::c1_count();
 616   _c2_count = CompilationPolicy::c2_count();


 617 
 618 #if INCLUDE_JVMCI
 619   if (EnableJVMCI) {
 620     // This is creating a JVMCICompiler singleton.
 621     JVMCICompiler* jvmci = new JVMCICompiler();
 622 
 623     if (UseJVMCICompiler) {
 624       _compilers[1] = jvmci;
 625       if (FLAG_IS_DEFAULT(JVMCIThreads)) {
 626         if (BootstrapJVMCI) {
 627           // JVMCI will bootstrap so give it more threads
 628           _c2_count = MIN2(32, os::active_processor_count());
 629         }
 630       } else {
 631         _c2_count = JVMCIThreads;
 632       }
 633       if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
 634       } else {
 635 #ifdef COMPILER1
 636         _c1_count = JVMCIHostThreads;
 637 #endif // COMPILER1
 638       }





 639     }
 640   }
 641 #endif // INCLUDE_JVMCI
 642 
 643 #ifdef COMPILER1
 644   if (_c1_count > 0) {
 645     _compilers[0] = new Compiler();
 646   }
 647 #endif // COMPILER1
 648 
 649 #ifdef COMPILER2
 650   if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
 651     if (_c2_count > 0) {
 652       _compilers[1] = new C2Compiler();
 653       // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.
 654       // idToPhase mapping for c2 is in opto/phasetype.hpp
 655       JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)
 656     }
 657   }
 658 #endif // COMPILER2

 753     _perf_last_compile_size =
 754              PerfDataManager::create_variable(SUN_CI, "lastSize",
 755                                               PerfData::U_Bytes,
 756                                               (jlong)CompileBroker::no_compile,
 757                                               CHECK);
 758 
 759 
 760     _perf_last_failed_type =
 761              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 762                                               PerfData::U_None,
 763                                               (jlong)CompileBroker::no_compile,
 764                                               CHECK);
 765 
 766     _perf_last_invalidated_type =
 767          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 768                                           PerfData::U_None,
 769                                           (jlong)CompileBroker::no_compile,
 770                                           CHECK);
 771   }
 772 

 773   _initialized = true;
 774 }
 775 









 776 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 777 // Stress testing. Dedicated threads revert optimizations based on escape analysis concurrently to
 778 // the running java application.  Configured with vm options DeoptimizeObjectsALot*.
 779 class DeoptimizeObjectsALotThread : public JavaThread {
 780 
 781   static void deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS);
 782   void deoptimize_objects_alot_loop_single();
 783   void deoptimize_objects_alot_loop_all();
 784 
 785 public:
 786   DeoptimizeObjectsALotThread() : JavaThread(&deopt_objs_alot_thread_entry) { }
 787 
 788   bool is_hidden_from_external_view() const      { return true; }
 789 };
 790 
 791 // Entry for DeoptimizeObjectsALotThread. The threads are started in
 792 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
 793 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
 794     DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
 795     bool enter_single_loop;

 847   if (java_lang_Thread::thread(thread_oop()) != nullptr) {
 848     assert(type == compiler_t, "should only happen with reused compiler threads");
 849     // The compiler thread hasn't actually exited yet so don't try to reuse it
 850     return nullptr;
 851   }
 852 
 853   JavaThread* new_thread = nullptr;
 854   switch (type) {
 855     case compiler_t:
 856       assert(comp != nullptr, "Compiler instance missing.");
 857       if (!InjectCompilerCreationFailure || comp->num_compiler_threads() == 0) {
 858         CompilerCounters* counters = new CompilerCounters();
 859         new_thread = new CompilerThread(queue, counters);
 860       }
 861       break;
 862 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 863     case deoptimizer_t:
 864       new_thread = new DeoptimizeObjectsALotThread();
 865       break;
 866 #endif // ASSERT



 867     default:
 868       ShouldNotReachHere();
 869   }
 870 
 871   // At this point the new CompilerThread data-races with this startup
 872   // thread (which is the main thread and NOT the VM thread).
 873   // This means Java bytecodes being executed at startup can
 874   // queue compile jobs which will run at whatever default priority the
 875   // newly created CompilerThread runs at.
 876 
 877 
 878   // At this point it may be possible that no osthread was created for the
 879   // JavaThread due to lack of resources. We will handle that failure below.
 880   // Also check new_thread so that static analysis is happy.
 881   if (new_thread != nullptr && new_thread->osthread() != nullptr) {
 882 
 883     if (type == compiler_t) {
 884       CompilerThread::cast(new_thread)->set_compiler(comp);
 885     }
 886 

 926 }
 927 
 928 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
 929   char name_buffer[256];
 930   os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
 931   Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
 932   return JNIHandles::make_global(thread_oop);
 933 }
 934 
 935 static void print_compiler_threads(stringStream& msg) {
 936   if (TraceCompilerThreads) {
 937     tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
 938   }
 939   LogTarget(Debug, jit, thread) lt;
 940   if (lt.is_enabled()) {
 941     LogStream ls(lt);
 942     ls.print_cr("%s", msg.as_string());
 943   }
 944 }
 945 











 946 void CompileBroker::init_compiler_threads() {
 947   // Ensure any exceptions lead to vm_exit_during_initialization.
 948   EXCEPTION_MARK;
 949 #if !defined(ZERO)
 950   assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
 951 #endif // !ZERO
 952   // Initialize the compilation queue
 953   if (_c2_count > 0) {
 954     const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
 955     _c2_compile_queue  = new CompileQueue(name);
 956     _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
 957     _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
 958   }
 959   if (_c1_count > 0) {
 960     _c1_compile_queue  = new CompileQueue("C1 compile queue");
 961     _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
 962     _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
 963   }
 964 


















 965   for (int i = 0; i < _c2_count; i++) {
 966     // Create a name for our thread.
 967     jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
 968     _compiler2_objects[i] = thread_handle;
 969     _compiler2_logs[i] = nullptr;
 970 
 971     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
 972       JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
 973       assert(ct != nullptr, "should have been handled for initial thread");
 974       _compilers[1]->set_num_compiler_threads(i + 1);
 975       if (trace_compiler_threads()) {
 976         ResourceMark rm;
 977         ThreadsListHandle tlh;  // name() depends on the TLH.
 978         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
 979         stringStream msg;
 980         msg.print("Added initial compiler thread %s", ct->name());
 981         print_compiler_threads(msg);
 982       }
 983     }
 984   }
 985 
 986   for (int i = 0; i < _c1_count; i++) {
 987     // Create a name for our thread.
 988     jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
 989     _compiler1_objects[i] = thread_handle;
 990     _compiler1_logs[i] = nullptr;
 991 
 992     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
 993       JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
 994       assert(ct != nullptr, "should have been handled for initial thread");
 995       _compilers[0]->set_num_compiler_threads(i + 1);
 996       if (trace_compiler_threads()) {
 997         ResourceMark rm;
 998         ThreadsListHandle tlh;  // name() depends on the TLH.
 999         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1000         stringStream msg;
1001         msg.print("Added initial compiler thread %s", ct->name());
1002         print_compiler_threads(msg);
1003       }


































1004     }
1005   }
1006 
1007   if (UsePerfData) {
1008     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK);
1009   }
1010 
1011 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1012   if (DeoptimizeObjectsALot) {
1013     // Initialize and start the object deoptimizer threads
1014     const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1015     for (int count = 0; count < total_count; count++) {
1016       Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1017       jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1018       make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1019     }
1020   }
1021 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1022 }
1023 













1024 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1025 
1026   int old_c2_count = 0, new_c2_count = 0, old_c1_count = 0, new_c1_count = 0;
1027   const int c2_tasks_per_thread = 2, c1_tasks_per_thread = 4;
1028 
1029   // Quick check if we already have enough compiler threads without taking the lock.
1030   // Numbers may change concurrently, so we read them again after we have the lock.
1031   if (_c2_compile_queue != nullptr) {
1032     old_c2_count = get_c2_thread_count();
1033     new_c2_count = MIN2(_c2_count, _c2_compile_queue->size() / c2_tasks_per_thread);
1034   }
1035   if (_c1_compile_queue != nullptr) {
1036     old_c1_count = get_c1_thread_count();
1037     new_c1_count = MIN2(_c1_count, _c1_compile_queue->size() / c1_tasks_per_thread);
1038   }
1039   if (new_c2_count <= old_c2_count && new_c1_count <= old_c1_count) return;
1040 
1041   // Now, we do the more expensive operations.
1042   julong free_memory = os::free_memory();
1043   // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).

1126         stringStream msg;
1127         msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)",
1128                   ct->name(), (int)(free_memory/M), (int)(available_cc_p/M));
1129         print_compiler_threads(msg);
1130       }
1131     }
1132   }
1133 
1134   CompileThread_lock->unlock();
1135 }
1136 
1137 
1138 /**
1139  * Set the methods on the stack as on_stack so that redefine classes doesn't
1140  * reclaim them. This method is executed at a safepoint.
1141  */
1142 void CompileBroker::mark_on_stack() {
1143   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1144   // Since we are at a safepoint, we do not need a lock to access
1145   // the compile queues.



1146   if (_c2_compile_queue != nullptr) {
1147     _c2_compile_queue->mark_on_stack();
1148   }
1149   if (_c1_compile_queue != nullptr) {
1150     _c1_compile_queue->mark_on_stack();
1151   }






1152 }
1153 
1154 // ------------------------------------------------------------------
1155 // CompileBroker::compile_method
1156 //
1157 // Request compilation of a method.
1158 void CompileBroker::compile_method_base(const methodHandle& method,
1159                                         int osr_bci,
1160                                         int comp_level,
1161                                         const methodHandle& hot_method,
1162                                         int hot_count,
1163                                         CompileTask::CompileReason compile_reason,

1164                                         bool blocking,
1165                                         Thread* thread) {
1166   guarantee(!method->is_abstract(), "cannot compile abstract methods");
1167   assert(method->method_holder()->is_instance_klass(),
1168          "sanity check");
1169   assert(!method->method_holder()->is_not_initialized(),
1170          "method holder must be initialized");


1171   assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1172 
1173   if (CIPrintRequests) {
1174     tty->print("request: ");
1175     method->print_short_name(tty);
1176     if (osr_bci != InvocationEntryBci) {
1177       tty->print(" osr_bci: %d", osr_bci);
1178     }
1179     tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1180     if (!hot_method.is_null()) {
1181       tty->print(" hot: ");
1182       if (hot_method() != method()) {
1183           hot_method->print_short_name(tty);
1184       } else {
1185         tty->print("yes");
1186       }
1187     }
1188     tty->cr();
1189   }
1190 
1191   // A request has been made for compilation.  Before we do any
1192   // real work, check to see if the method has been compiled
1193   // in the meantime with a definitive result.
1194   if (compilation_is_complete(method, osr_bci, comp_level)) {
1195     return;
1196   }
1197 
1198 #ifndef PRODUCT
1199   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1200     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1201       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
1202       return;
1203     }
1204   }
1205 #endif
1206 
1207   // If this method is already in the compile queue, then
1208   // we do not block the current thread.
1209   if (compilation_is_in_queue(method)) {
1210     // We may want to decay our counter a bit here to prevent
1211     // multiple denied requests for compilation.  This is an
1212     // open compilation policy issue. Note: The other possibility,
1213     // in the case that this is a blocking compile request, is to have
1214     // all subsequent blocking requesters wait for completion of
1215     // ongoing compiles. Note that in this case we'll need a protocol
1216     // for freeing the associated compile tasks. [Or we could have
1217     // a single static monitor on which all these waiters sleep.]
1218     return;
1219   }
1220 
1221   // Tiered policy requires MethodCounters to exist before adding a method to
1222   // the queue. Create if we don't have them yet.
1223   method->get_method_counters(thread);





1224 
1225   // Outputs from the following MutexLocker block:
1226   CompileTask* task     = nullptr;
1227   CompileQueue* queue  = compile_queue(comp_level);








1228 
1229   // Acquire our lock.
1230   {
1231     MutexLocker locker(thread, MethodCompileQueue_lock);
1232 
1233     // Make sure the method has not slipped into the queues since
1234     // last we checked; note that those checks were "fast bail-outs".
1235     // Here we need to be more careful, see 14012000 below.
1236     if (compilation_is_in_queue(method)) {
1237       return;
1238     }
1239 
1240     // We need to check again to see if the compilation has
1241     // completed.  A previous compilation may have registered
1242     // some result.
1243     if (compilation_is_complete(method, osr_bci, comp_level)) {
1244       return;
1245     }
1246 
1247     // We now know that this compilation is not pending, complete,
1248     // or prohibited.  Assign a compile_id to this compilation
1249     // and check to see if it is in our [Start..Stop) range.
1250     int compile_id = assign_compile_id(method, osr_bci);
1251     if (compile_id == 0) {
1252       // The compilation falls outside the allowed range.
1253       return;
1254     }
1255 
1256 #if INCLUDE_JVMCI
1257     if (UseJVMCICompiler && blocking) {
1258       // Don't allow blocking compiles for requests triggered by JVMCI.
1259       if (thread->is_Compiler_thread()) {
1260         blocking = false;
1261       }
1262 
1263       // In libjvmci, JVMCI initialization should not deadlock with other threads

1313     // <RESULT, QUEUE> :
1314     //     <0, 1> : in compile queue, but not yet compiled
1315     //     <1, 1> : compiled but queue bit not cleared
1316     //     <1, 0> : compiled and queue bit cleared
1317     // Because we first check the queue bits then check the result bits,
1318     // we are assured that we cannot introduce a duplicate task.
1319     // Note that if we did the tests in the reverse order (i.e. check
1320     // result then check queued bit), we could get the result bit before
1321     // the compilation completed, and the queue bit after the compilation
1322     // completed, and end up introducing a "duplicate" (redundant) task.
1323     // In that case, the compiler thread should first check if a method
1324     // has already been compiled before trying to compile it.
1325     // NOTE: in the event that there are multiple compiler threads and
1326     // there is de-optimization/recompilation, things will get hairy,
1327     // and in that case it's best to protect both the testing (here) of
1328     // these bits, and their updating (here and elsewhere) under a
1329     // common lock.
1330     task = create_compile_task(queue,
1331                                compile_id, method,
1332                                osr_bci, comp_level,
1333                                hot_method, hot_count, compile_reason,
1334                                blocking);












1335   }
1336 
1337   if (blocking) {
1338     wait_for_completion(task);
1339   }
1340 }
1341 
















1342 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1343                                        int comp_level,
1344                                        const methodHandle& hot_method, int hot_count,

1345                                        CompileTask::CompileReason compile_reason,
1346                                        TRAPS) {
1347   // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1348   if (!_initialized || comp_level == CompLevel_none) {
1349     return nullptr;
1350   }
1351 







1352   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1353   assert(comp != nullptr, "Ensure we have a compiler");
1354 
1355 #if INCLUDE_JVMCI
1356   if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1357     // JVMCI compilation is not yet initializable.
1358     return nullptr;
1359   }
1360 #endif
1361 
1362   DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1363   // CompileBroker::compile_method can trap and can have pending async exception.
1364   nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, directive, THREAD);
1365   DirectivesStack::release(directive);
1366   return nm;
1367 }
1368 
1369 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1370                                          int comp_level,
1371                                          const methodHandle& hot_method, int hot_count,

1372                                          CompileTask::CompileReason compile_reason,
1373                                          DirectiveSet* directive,
1374                                          TRAPS) {
1375 
1376   // make sure arguments make sense
1377   assert(method->method_holder()->is_instance_klass(), "not an instance method");
1378   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1379   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1380   assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");



1381   // return quickly if possible
1382 




1383   // lock, make sure that the compilation
1384   // isn't prohibited in a straightforward way.
1385   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1386   if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1387     return nullptr;
1388   }
1389 
1390   if (osr_bci == InvocationEntryBci) {
1391     // standard compilation
1392     nmethod* method_code = method->code();
1393     if (method_code != nullptr) {
1394       if (compilation_is_complete(method, osr_bci, comp_level)) {
1395         return method_code;
1396       }
1397     }
1398     if (method->is_not_compilable(comp_level)) {
1399       return nullptr;
1400     }
1401   } else {
1402     // osr compilation
1403     // We accept a higher level osr method
1404     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1405     if (nm != nullptr) return nm;
1406     if (method->is_not_osr_compilable(comp_level)) return nullptr;
1407   }
1408 
1409   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1410   // some prerequisites that are compiler specific
1411   if (comp->is_c2() || comp->is_jvmci()) {
1412     InternalOOMEMark iom(THREAD);
1413     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1414     // Resolve all classes seen in the signature of the method
1415     // we are compiling.
1416     Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1417   }
1418 
1419   // If the method is native, do the lookup in the thread requesting
1420   // the compilation. Native lookups can load code, which is not
1421   // permitted during compilation.
1422   //
1423   // Note: A native method implies non-osr compilation which is
1424   //       checked with an assertion at the entry of this method.
1425   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1426     address adr = NativeLookup::lookup(method, THREAD);
1427     if (HAS_PENDING_EXCEPTION) {
1428       // In case of an exception looking up the method, we just forget
1429       // about it. The interpreter will kick-in and throw the exception.
1430       method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1431       CLEAR_PENDING_EXCEPTION;

1470             method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) {
1471         return nullptr;
1472       }
1473 #endif // X86 && !ZERO
1474 
1475       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1476       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1477       //
1478       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1479       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1480       AdapterHandlerLibrary::create_native_wrapper(method);
1481     } else {
1482       return nullptr;
1483     }
1484   } else {
1485     // If the compiler is shut off due to code cache getting full
1486     // fail out now so blocking compiles dont hang the java thread
1487     if (!should_compile_new_jobs()) {
1488       return nullptr;
1489     }
1490     bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles;
1491     compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, is_blocking, THREAD);



1492   }
1493 
1494   // return requested nmethod
1495   // We accept a higher level osr method
1496   if (osr_bci == InvocationEntryBci) {
1497     return method->code();
1498   }
1499   return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1500 }
1501 
1502 
1503 // ------------------------------------------------------------------
1504 // CompileBroker::compilation_is_complete
1505 //
1506 // See if compilation of this method is already complete.
1507 bool CompileBroker::compilation_is_complete(const methodHandle& method,
1508                                             int                 osr_bci,
1509                                             int                 comp_level) {






1510   bool is_osr = (osr_bci != standard_entry_bci);
1511   if (is_osr) {
1512     if (method->is_not_osr_compilable(comp_level)) {
1513       return true;
1514     } else {
1515       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1516       return (result != nullptr);
1517     }
1518   } else {
1519     if (method->is_not_compilable(comp_level)) {
1520       return true;
1521     } else {
1522       nmethod* result = method->code();
1523       if (result == nullptr) return false;
1524       return comp_level == result->comp_level();









1525     }
1526   }
1527 }
1528 
1529 
1530 /**
1531  * See if this compilation is already requested.
1532  *
1533  * Implementation note: there is only a single "is in queue" bit
1534  * for each method.  This means that the check below is overly
1535  * conservative in the sense that an osr compilation in the queue
1536  * will block a normal compilation from entering the queue (and vice
1537  * versa).  This can be remedied by a full queue search to disambiguate
1538  * cases.  If it is deemed profitable, this may be done.
1539  */
1540 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1541   return method->queued_for_compilation();
1542 }
1543 
1544 // ------------------------------------------------------------------

1604     if (CIStart <= id && id < CIStop) {
1605       return id;
1606     }
1607   }
1608 
1609   // Method was not in the appropriate compilation range.
1610   method->set_not_compilable_quietly("Not in requested compile id range");
1611   return 0;
1612 #else
1613   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1614   // only _compilation_id is incremented.
1615   return Atomic::add(&_compilation_id, 1);
1616 #endif
1617 }
1618 
1619 // ------------------------------------------------------------------
1620 // CompileBroker::assign_compile_id_unlocked
1621 //
1622 // Public wrapper for assign_compile_id that acquires the needed locks
1623 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1624   MutexLocker locker(thread, MethodCompileQueue_lock);
1625   return assign_compile_id(method, osr_bci);
1626 }
1627 
1628 // ------------------------------------------------------------------
1629 // CompileBroker::create_compile_task
1630 //
1631 // Create a CompileTask object representing the current request for
1632 // compilation.  Add this task to the queue.
1633 CompileTask* CompileBroker::create_compile_task(CompileQueue*       queue,
1634                                                 int                 compile_id,
1635                                                 const methodHandle& method,
1636                                                 int                 osr_bci,
1637                                                 int                 comp_level,
1638                                                 const methodHandle& hot_method,
1639                                                 int                 hot_count,

1640                                                 CompileTask::CompileReason compile_reason,

1641                                                 bool                blocking) {
1642   CompileTask* new_task = CompileTask::allocate();
1643   new_task->initialize(compile_id, method, osr_bci, comp_level,
1644                        hot_method, hot_count, compile_reason,
1645                        blocking);
1646   queue->add(new_task);
1647   return new_task;
1648 }
1649 
1650 #if INCLUDE_JVMCI
1651 // The number of milliseconds to wait before checking if
1652 // JVMCI compilation has made progress.
1653 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1654 
1655 // The number of JVMCI compilation progress checks that must fail
1656 // before unblocking a thread waiting for a blocking compilation.
1657 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1658 
1659 /**
1660  * Waits for a JVMCI compiler to complete a given task. This thread
1661  * waits until either the task completes or it sees no JVMCI compilation
1662  * progress for N consecutive milliseconds where N is
1663  * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1664  * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1665  *
1666  * @return true if this thread needs to free/recycle the task

1767  */
1768 bool CompileBroker::init_compiler_runtime() {
1769   CompilerThread* thread = CompilerThread::current();
1770   AbstractCompiler* comp = thread->compiler();
1771   // Final sanity check - the compiler object must exist
1772   guarantee(comp != nullptr, "Compiler object must exist");
1773 
1774   {
1775     // Must switch to native to allocate ci_env
1776     ThreadToNativeFromVM ttn(thread);
1777     ciEnv ci_env((CompileTask*)nullptr);
1778     // Cache Jvmti state
1779     ci_env.cache_jvmti_state();
1780     // Cache DTrace flags
1781     ci_env.cache_dtrace_flags();
1782 
1783     // Switch back to VM state to do compiler initialization
1784     ThreadInVMfromNative tv(thread);
1785 
1786     // Perform per-thread and global initializations




1787     comp->initialize();
1788   }
1789 
1790   if (comp->is_failed()) {
1791     disable_compilation_forever();
1792     // If compiler initialization failed, no compiler thread that is specific to a
1793     // particular compiler runtime will ever start to compile methods.
1794     shutdown_compiler_runtime(comp, thread);
1795     return false;
1796   }
1797 
1798   // C1 specific check
1799   if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
1800     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
1801     return false;
1802   }
1803 
1804   return true;
1805 }
1806 
1807 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
1808   BufferBlob* blob = thread->get_buffer_blob();
1809   if (blob != nullptr) {
1810     blob->purge();
1811     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1812     CodeCache::free(blob);
1813   }
1814 }
1815 
1816 /**
1817  * If C1 and/or C2 initialization failed, we shut down all compilation.
1818  * We do this to keep things simple. This can be changed if it ever turns
1819  * out to be a problem.
1820  */
1821 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
1822   free_buffer_blob_if_allocated(thread);
1823 


1824   if (comp->should_perform_shutdown()) {
1825     // There are two reasons for shutting down the compiler
1826     // 1) compiler runtime initialization failed
1827     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
1828     warning("%s initialization failed. Shutting down all compilers", comp->name());
1829 
1830     // Only one thread per compiler runtime object enters here
1831     // Set state to shut down
1832     comp->set_shut_down();
1833 
1834     // Delete all queued compilation tasks to make compiler threads exit faster.
1835     if (_c1_compile_queue != nullptr) {
1836       _c1_compile_queue->free_all();
1837     }
1838 
1839     if (_c2_compile_queue != nullptr) {
1840       _c2_compile_queue->free_all();
1841     }
1842 




1843     // Set flags so that we continue execution with using interpreter only.
1844     UseCompiler    = false;
1845     UseInterpreter = true;
1846 
1847     // We could delete compiler runtimes also. However, there are references to
1848     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
1849     // fail. This can be done later if necessary.
1850   }
1851 }
1852 
1853 /**
1854  * Helper function to create new or reuse old CompileLog.
1855  */
1856 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
1857   if (!LogCompilation) return nullptr;
1858 
1859   AbstractCompiler *compiler = ct->compiler();

1860   bool c1 = compiler->is_c1();
1861   jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;
1862   assert(compiler_objects != nullptr, "must be initialized at this point");
1863   CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;
1864   assert(logs != nullptr, "must be initialized at this point");
1865   int count = c1 ? _c1_count : _c2_count;
1866 





1867   // Find Compiler number by its threadObj.
1868   oop compiler_obj = ct->threadObj();
1869   int compiler_number = 0;
1870   bool found = false;
1871   for (; compiler_number < count; compiler_number++) {
1872     if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
1873       found = true;
1874       break;
1875     }
1876   }
1877   assert(found, "Compiler must exist at this point");
1878 
1879   // Determine pointer for this thread's log.
1880   CompileLog** log_ptr = &logs[compiler_number];
1881 
1882   // Return old one if it exists.
1883   CompileLog* log = *log_ptr;
1884   if (log != nullptr) {
1885     ct->init_log(log);
1886     return log;

1924     log->stamp();
1925     log->end_elem();
1926   }
1927 
1928   // If compiler thread/runtime initialization fails, exit the compiler thread
1929   if (!init_compiler_runtime()) {
1930     return;
1931   }
1932 
1933   thread->start_idle_timer();
1934 
1935   // Poll for new compilation tasks as long as the JVM runs. Compilation
1936   // should only be disabled if something went wrong while initializing the
1937   // compiler runtimes. This, in turn, should not happen. The only known case
1938   // when compiler runtime initialization fails is if there is not enough free
1939   // space in the code cache to generate the necessary stubs, etc.
1940   while (!is_compilation_disabled_forever()) {
1941     // We need this HandleMark to avoid leaking VM handles.
1942     HandleMark hm(thread);
1943 


1944     CompileTask* task = queue->get(thread);

1945     if (task == nullptr) {
1946       if (UseDynamicNumberOfCompilerThreads) {
1947         // Access compiler_count under lock to enforce consistency.
1948         MutexLocker only_one(CompileThread_lock);
1949         if (can_remove(thread, true)) {
1950           if (trace_compiler_threads()) {
1951             ResourceMark rm;
1952             stringStream msg;
1953             msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
1954                       thread->name(), thread->idle_time_millis());
1955             print_compiler_threads(msg);
1956           }
1957 
1958           // Notify compiler that the compiler thread is about to stop
1959           thread->compiler()->stopping_compiler_thread(thread);
1960 
1961           free_buffer_blob_if_allocated(thread);
1962           return; // Stop this thread.
1963         }
1964       }
1965     } else {
1966       // Assign the task to the current thread.  Mark this compilation
1967       // thread as active for the profiler.
1968       // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
1969       // occurs after fetching the compile task off the queue.
1970       CompileTaskWrapper ctw(task);
1971       methodHandle method(thread, task->method());
1972 
1973       // Never compile a method if breakpoints are present in it
1974       if (method()->number_of_breakpoints() == 0) {
1975         // Compile the method.
1976         if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1977           invoke_compiler_on_method(task);
1978           thread->start_idle_timer();
1979         } else {
1980           // After compilation is disabled, remove remaining methods from queue
1981           method->clear_queued_for_compilation();

1982           task->set_failure_reason("compilation is disabled");
1983         }
1984       } else {
1985         task->set_failure_reason("breakpoints are present");
1986       }
1987 
1988       if (UseDynamicNumberOfCompilerThreads) {
1989         possibly_add_compiler_threads(thread);
1990         assert(!thread->has_pending_exception(), "should have been handled");
1991       }
1992     }
1993   }
1994 
1995   // Shut down compiler runtime
1996   shutdown_compiler_runtime(thread->compiler(), thread);
1997 }
1998 
1999 // ------------------------------------------------------------------
2000 // CompileBroker::init_compiler_thread_log
2001 //

2293     }
2294     assert(thread->env() == &ci_env, "set by ci_env");
2295     // The thread-env() field is cleared in ~CompileTaskWrapper.
2296 
2297     // Cache Jvmti state
2298     bool method_is_old = ci_env.cache_jvmti_state();
2299 
2300     // Skip redefined methods
2301     if (method_is_old) {
2302       ci_env.record_method_not_compilable("redefined method", true);
2303     }
2304 
2305     // Cache DTrace flags
2306     ci_env.cache_dtrace_flags();
2307 
2308     ciMethod* target = ci_env.get_method_from_handle(target_handle);
2309 
2310     TraceTime t1("compilation", &time);
2311     EventCompilation event;
2312 

2313     if (comp == nullptr) {
2314       ci_env.record_method_not_compilable("no compiler");
2315     } else if (!ci_env.failing()) {
2316       if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2317         whitebox_lock_compilation();
2318       }
2319       comp->compile_method(&ci_env, target, osr_bci, true, directive);



2320 
2321       /* Repeat compilation without installing code for profiling purposes */
2322       int repeat_compilation_count = directive->RepeatCompilationOption;
2323       while (repeat_compilation_count > 0) {
2324         ResourceMark rm(thread);
2325         task->print_ul("NO CODE INSTALLED");
2326         comp->compile_method(&ci_env, target, osr_bci, false, directive);
2327         repeat_compilation_count--;
2328       }
2329     }
2330 
2331     DirectivesStack::release(directive);
2332 
2333     if (!ci_env.failing() && !task->is_success()) {
2334       assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2335       assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2336       // The compiler elected, without comment, not to register a result.
2337       // Do not attempt further compilations of this method.
2338       ci_env.record_method_not_compilable("compile failed");
2339     }
2340 
2341     // Copy this bit to the enclosing block:
2342     compilable = ci_env.compilable();
2343 
2344     if (ci_env.failing()) {
2345       // Duplicate the failure reason string, so that it outlives ciEnv
2346       failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2347       failure_reason_on_C_heap = true;
2348       retry_message = ci_env.retry_message();
2349       ci_env.report_failure(failure_reason);
2350     }
2351 
2352     if (ci_env.failing()) {
2353       handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2354     }
2355     if (event.should_commit()) {
2356       post_compilation_event(event, task);
2357     }
2358   }
2359 
2360   if (failure_reason != nullptr) {
2361     task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2362     if (CompilationLog::log() != nullptr) {
2363       CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2364     }
2365     if (PrintCompilation) {
2366       FormatBufferResource msg = retry_message != nullptr ?
2367         FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2368         FormatBufferResource("COMPILE SKIPPED: %s",      failure_reason);
2369       task->print(tty, msg);
2370     }
2371   }
2372 


2373   methodHandle method(thread, task->method());
2374 
2375   DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2376 
2377   collect_statistics(thread, time, task);
2378 
2379   if (PrintCompilation && PrintCompilation2) {
2380     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
2381     tty->print("%4d ", compile_id);    // print compilation number
2382     tty->print("%s ", (is_osr ? "%" : " "));
2383     if (task->is_success()) {
2384       tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2385     }
2386     tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2387   }
2388 
2389   Log(compilation, codecache) log;
2390   if (log.is_debug()) {
2391     LogStream ls(log.debug());
2392     codecache_print(&ls, /* detailed= */ false);
2393   }
2394   if (PrintCodeCacheOnCompilation) {
2395     codecache_print(/* detailed= */ false);
2396   }
2397   // Disable compilation, if required.
2398   switch (compilable) {
2399   case ciEnv::MethodCompilable_never:
2400     if (is_osr)
2401       method->set_not_osr_compilable_quietly("MethodCompilable_never");
2402     else
2403       method->set_not_compilable_quietly("MethodCompilable_never");
2404     break;
2405   case ciEnv::MethodCompilable_not_at_tier:
2406     if (is_osr)
2407       method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2408     else
2409       method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2410     break;
2411   }
2412 
2413   // Note that the queued_for_compilation bits are cleared without
2414   // protection of a mutex. [They were set by the requester thread,
2415   // when adding the task to the compile queue -- at which time the
2416   // compile queue lock was held. Subsequently, we acquired the compile
2417   // queue lock to get this task off the compile queue; thus (to belabour
2418   // the point somewhat) our clearing of the bits must be occurring
2419   // only after the setting of the bits. See also 14012000 above.
2420   method->clear_queued_for_compilation();






2421 }
2422 
2423 /**
2424  * The CodeCache is full. Print warning and disable compilation.
2425  * Schedule code cache cleaning so compilation can continue later.
2426  * This function needs to be called only from CodeCache::allocate(),
2427  * since we currently handle a full code cache uniformly.
2428  */
2429 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2430   UseInterpreter = true;
2431   if (UseCompiler || AlwaysCompileLoopMethods ) {
2432     if (xtty != nullptr) {
2433       stringStream s;
2434       // Dump code cache state into a buffer before locking the tty,
2435       // because log_state() will use locks causing lock conflicts.
2436       CodeCache::log_state(&s);
2437       // Lock to prevent tearing
2438       ttyLocker ttyl;
2439       xtty->begin_elem("code_cache_full");
2440       xtty->print("%s", s.freeze());

2513 // CompileBroker::collect_statistics
2514 //
2515 // Collect statistics about the compilation.
2516 
2517 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2518   bool success = task->is_success();
2519   methodHandle method (thread, task->method());
2520   int compile_id = task->compile_id();
2521   bool is_osr = (task->osr_bci() != standard_entry_bci);
2522   const int comp_level = task->comp_level();
2523   CompilerCounters* counters = thread->counters();
2524 
2525   MutexLocker locker(CompileStatistics_lock);
2526 
2527   // _perf variables are production performance counters which are
2528   // updated regardless of the setting of the CITime and CITimeEach flags
2529   //
2530 
2531   // account all time, including bailouts and failures in this counter;
2532   // C1 and C2 counters are counting both successful and unsuccessful compiles
2533   _t_total_compilation.add(time);
2534 
2535   if (!success) {
2536     _total_bailout_count++;
2537     if (UsePerfData) {
2538       _perf_last_failed_method->set_value(counters->current_method());
2539       _perf_last_failed_type->set_value(counters->compile_type());
2540       _perf_total_bailout_count->inc();
2541     }
2542     _t_bailedout_compilation.add(time);











2543   } else if (!task->is_success()) {
2544     if (UsePerfData) {
2545       _perf_last_invalidated_method->set_value(counters->current_method());
2546       _perf_last_invalidated_type->set_value(counters->compile_type());
2547       _perf_total_invalidated_count->inc();
2548     }
2549     _total_invalidated_count++;
2550     _t_invalidated_compilation.add(time);











2551   } else {
2552     // Compilation succeeded
2553 
2554     // update compilation ticks - used by the implementation of
2555     // java.lang.management.CompilationMXBean
2556     _perf_total_compilation->inc(time.ticks());
2557     _peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time;
2558 
2559     if (CITime) {
2560       int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2561       if (is_osr) {
2562         _t_osr_compilation.add(time);
2563         _sum_osr_bytes_compiled += bytes_compiled;
2564       } else {
2565         _t_standard_compilation.add(time);
2566         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2567       }
2568 
2569       // Collect statistic per compilation level
2570       if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {









2571         CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2572         if (is_osr) {
2573           stats->_osr.update(time, bytes_compiled);
2574         } else {
2575           stats->_standard.update(time, bytes_compiled);
2576         }
2577         stats->_nmethods_size += task->nm_total_size();
2578         stats->_nmethods_code_size += task->nm_insts_size();
2579       } else {
2580         assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2581       }
2582 
2583       // Collect statistic per compiler
2584       AbstractCompiler* comp = compiler(comp_level);
2585       if (comp) {
2586         CompilerStatistics* stats = comp->stats();
2587         if (is_osr) {
2588           stats->_osr.update(time, bytes_compiled);
2589         } else {
2590           stats->_standard.update(time, bytes_compiled);
2591         }
2592         stats->_nmethods_size += task->nm_total_size();
2593         stats->_nmethods_code_size += task->nm_insts_size();
2594       } else { // if (!comp)
2595         assert(false, "Compiler object must exist");
2596       }
2597     }
2598 
2599     if (UsePerfData) {
2600       // save the name of the last method compiled
2601       _perf_last_method->set_value(counters->current_method());
2602       _perf_last_compile_type->set_value(counters->compile_type());
2603       _perf_last_compile_size->set_value(method->code_size() +
2604                                          task->num_inlined_bytecodes());
2605       if (is_osr) {
2606         _perf_osr_compilation->inc(time.ticks());
2607         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2608       } else {
2609         _perf_standard_compilation->inc(time.ticks());
2610         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2611       }
2612     }
2613 
2614     if (CITimeEach) {

2637       _total_standard_compile_count++;
2638     }
2639   }
2640   // set the current method for the thread to null
2641   if (UsePerfData) counters->set_current_method("");
2642 }
2643 
2644 const char* CompileBroker::compiler_name(int comp_level) {
2645   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2646   if (comp == nullptr) {
2647     return "no compiler";
2648   } else {
2649     return (comp->name());
2650   }
2651 }
2652 
2653 jlong CompileBroker::total_compilation_ticks() {
2654   return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2655 }
2656 


















2657 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2658   tty->print_cr("  %s {speed: %6.3f bytes/s; standard: %6.3f s, %u bytes, %u methods; osr: %6.3f s, %u bytes, %u methods; nmethods_size: %u bytes; nmethods_code_size: %u bytes}",
2659                 name, stats->bytes_per_second(),
2660                 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2661                 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2662                 stats->_nmethods_size, stats->_nmethods_code_size);
2663 }
2664 












































































































2665 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
2666   if (per_compiler) {
2667     if (aggregate) {
2668       tty->cr();
2669       tty->print_cr("Individual compiler times (for compiled methods only)");
2670       tty->print_cr("------------------------------------------------");
2671       tty->cr();
2672     }
2673     for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
2674       AbstractCompiler* comp = _compilers[i];
2675       if (comp != nullptr) {
2676         print_times(comp->name(), comp->stats());
2677       }
2678     }



2679     if (aggregate) {
2680       tty->cr();
2681       tty->print_cr("Individual compilation Tier times (for compiled methods only)");
2682       tty->print_cr("------------------------------------------------");
2683       tty->cr();
2684     }
2685     char tier_name[256];
2686     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
2687       CompilerStatistics* stats = &_stats_per_level[tier-1];
2688       os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
2689       print_times(tier_name, stats);
2690     }







2691   }
2692 
2693   if (!aggregate) {
2694     return;
2695   }
2696 
2697   elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
2698   elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
2699   elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
2700 
2701   uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
2702   uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
2703 
2704   uint standard_compile_count = CompileBroker::_total_standard_compile_count;
2705   uint osr_compile_count = CompileBroker::_total_osr_compile_count;
2706   uint total_compile_count = CompileBroker::_total_compile_count;
2707   uint total_bailout_count = CompileBroker::_total_bailout_count;
2708   uint total_invalidated_count = CompileBroker::_total_invalidated_count;
2709 
2710   uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;

2712 
2713   tty->cr();
2714   tty->print_cr("Accumulated compiler times");
2715   tty->print_cr("----------------------------------------------------------");
2716                //0000000000111111111122222222223333333333444444444455555555556666666666
2717                //0123456789012345678901234567890123456789012345678901234567890123456789
2718   tty->print_cr("  Total compilation time   : %7.3f s", total_compilation.seconds());
2719   tty->print_cr("    Standard compilation   : %7.3f s, Average : %2.3f s",
2720                 standard_compilation.seconds(),
2721                 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
2722   tty->print_cr("    Bailed out compilation : %7.3f s, Average : %2.3f s",
2723                 CompileBroker::_t_bailedout_compilation.seconds(),
2724                 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
2725   tty->print_cr("    On stack replacement   : %7.3f s, Average : %2.3f s",
2726                 osr_compilation.seconds(),
2727                 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
2728   tty->print_cr("    Invalidated            : %7.3f s, Average : %2.3f s",
2729                 CompileBroker::_t_invalidated_compilation.seconds(),
2730                 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
2731 




2732   AbstractCompiler *comp = compiler(CompLevel_simple);
2733   if (comp != nullptr) {
2734     tty->cr();
2735     comp->print_timers();
2736   }
2737   comp = compiler(CompLevel_full_optimization);
2738   if (comp != nullptr) {
2739     tty->cr();
2740     comp->print_timers();
2741   }





2742 #if INCLUDE_JVMCI
2743   if (EnableJVMCI) {
2744     JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
2745     if (jvmci_comp != nullptr && jvmci_comp != comp) {
2746       tty->cr();
2747       jvmci_comp->print_timers();
2748     }
2749   }
2750 #endif
2751 
2752   tty->cr();
2753   tty->print_cr("  Total compiled methods    : %8u methods", total_compile_count);
2754   tty->print_cr("    Standard compilation    : %8u methods", standard_compile_count);
2755   tty->print_cr("    On stack replacement    : %8u methods", osr_compile_count);
2756   uint tcb = osr_bytes_compiled + standard_bytes_compiled;
2757   tty->print_cr("  Total compiled bytecodes  : %8u bytes", tcb);
2758   tty->print_cr("    Standard compilation    : %8u bytes", standard_bytes_compiled);
2759   tty->print_cr("    On stack replacement    : %8u bytes", osr_bytes_compiled);
2760   double tcs = total_compilation.seconds();
2761   uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);

   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 "cds/aotLinkedClassBulkLoader.hpp"
  27 #include "cds/cdsConfig.hpp"
  28 #include "classfile/javaClasses.inline.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "classfile/vmClasses.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "code/codeHeapState.hpp"
  34 #include "code/dependencyContext.hpp"
  35 #include "code/SCCache.hpp"
  36 #include "compiler/compilationLog.hpp"
  37 #include "compiler/compilationMemoryStatistic.hpp"
  38 #include "compiler/compilationPolicy.hpp"
  39 #include "compiler/compileBroker.hpp"
  40 #include "compiler/compilerDefinitions.inline.hpp"
  41 #include "compiler/compileLog.hpp"
  42 #include "compiler/compilerEvent.hpp"
  43 #include "compiler/compilerOracle.hpp"
  44 #include "compiler/directivesParser.hpp"
  45 #include "compiler/recompilationPolicy.hpp"
  46 #include "gc/shared/memAllocator.hpp"
  47 #include "interpreter/linkResolver.hpp"
  48 #include "jvm.h"
  49 #include "jfr/jfrEvents.hpp"
  50 #include "logging/log.hpp"
  51 #include "logging/logStream.hpp"
  52 #include "memory/allocation.inline.hpp"
  53 #include "memory/resourceArea.hpp"
  54 #include "memory/universe.hpp"
  55 #include "oops/methodData.hpp"
  56 #include "oops/method.inline.hpp"
  57 #include "oops/oop.inline.hpp"
  58 #include "prims/jvmtiExport.hpp"
  59 #include "prims/nativeLookup.hpp"
  60 #include "prims/whitebox.hpp"
  61 #include "runtime/atomic.hpp"
  62 #include "runtime/escapeBarrier.hpp"
  63 #include "runtime/globals_extension.hpp"
  64 #include "runtime/handles.inline.hpp"
  65 #include "runtime/init.hpp"
  66 #include "runtime/interfaceSupport.inline.hpp"
  67 #include "runtime/java.hpp"
  68 #include "runtime/javaCalls.hpp"
  69 #include "runtime/jniHandles.inline.hpp"
  70 #include "runtime/os.hpp"
  71 #include "runtime/perfData.hpp"
  72 #include "runtime/safepointVerifiers.hpp"
  73 #include "runtime/sharedRuntime.hpp"
  74 #include "runtime/threads.hpp"
  75 #include "runtime/threadSMR.inline.hpp"
  76 #include "runtime/timerTrace.hpp"
  77 #include "runtime/vframe.inline.hpp"
  78 #include "services/management.hpp"
  79 #include "utilities/debug.hpp"
  80 #include "utilities/dtrace.hpp"
  81 #include "utilities/events.hpp"
  82 #include "utilities/formatBuffer.hpp"
  83 #include "utilities/macros.hpp"
  84 #include "utilities/nonblockingQueue.inline.hpp"
  85 #ifdef COMPILER1
  86 #include "c1/c1_Compiler.hpp"
  87 #endif
  88 #ifdef COMPILER2
  89 #include "opto/c2compiler.hpp"
  90 #endif
  91 #if INCLUDE_JVMCI
  92 #include "jvmci/jvmciEnv.hpp"
  93 #include "jvmci/jvmciRuntime.hpp"
  94 #endif
  95 
  96 #ifdef DTRACE_ENABLED
  97 
  98 // Only bother with this argument setup if dtrace is available
  99 
 100 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
 101   {                                                                      \
 102     Symbol* klass_name = (method)->klass_name();                         \
 103     Symbol* name = (method)->name();                                     \
 104     Symbol* signature = (method)->signature();                           \

 112 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)      \
 113   {                                                                      \
 114     Symbol* klass_name = (method)->klass_name();                         \
 115     Symbol* name = (method)->name();                                     \
 116     Symbol* signature = (method)->signature();                           \
 117     HOTSPOT_METHOD_COMPILE_END(                                          \
 118       (char *) comp_name, strlen(comp_name),                             \
 119       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
 120       (char *) name->bytes(), name->utf8_length(),                       \
 121       (char *) signature->bytes(), signature->utf8_length(), (success)); \
 122   }
 123 
 124 #else //  ndef DTRACE_ENABLED
 125 
 126 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
 127 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
 128 
 129 #endif // ndef DTRACE_ENABLED
 130 
 131 bool CompileBroker::_initialized = false;
 132 bool CompileBroker::_replay_initialized = false;
 133 volatile bool CompileBroker::_should_block = false;
 134 volatile int  CompileBroker::_print_compilation_warning = 0;
 135 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
 136 
 137 // The installed compiler(s)
 138 AbstractCompiler* CompileBroker::_compilers[3];
 139 
 140 // The maximum numbers of compiler threads to be determined during startup.
 141 int CompileBroker::_c1_count = 0;
 142 int CompileBroker::_c2_count = 0;
 143 int CompileBroker::_c3_count = 0;
 144 int CompileBroker::_sc_count = 0;
 145 
 146 // An array of compiler names as Java String objects
 147 jobject* CompileBroker::_compiler1_objects = nullptr;
 148 jobject* CompileBroker::_compiler2_objects = nullptr;
 149 jobject* CompileBroker::_compiler3_objects = nullptr;
 150 jobject* CompileBroker::_sc_objects = nullptr;
 151 
 152 CompileLog** CompileBroker::_compiler1_logs = nullptr;
 153 CompileLog** CompileBroker::_compiler2_logs = nullptr;
 154 CompileLog** CompileBroker::_compiler3_logs = nullptr;
 155 CompileLog** CompileBroker::_sc_logs = nullptr;
 156 
 157 // These counters are used to assign an unique ID to each compilation.
 158 volatile jint CompileBroker::_compilation_id     = 0;
 159 volatile jint CompileBroker::_osr_compilation_id = 0;
 160 volatile jint CompileBroker::_native_compilation_id = 0;
 161 
 162 // Performance counters
 163 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
 164 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
 165 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
 166 
 167 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
 168 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
 169 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
 170 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
 171 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
 172 
 173 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
 174 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
 175 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
 176 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
 177 
 178 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
 179 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
 180 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
 181 PerfVariable*       CompileBroker::_perf_last_compile_type = nullptr;
 182 PerfVariable*       CompileBroker::_perf_last_compile_size = nullptr;
 183 PerfVariable*       CompileBroker::_perf_last_failed_type = nullptr;
 184 PerfVariable*       CompileBroker::_perf_last_invalidated_type = nullptr;
 185 
 186 // Timers and counters for generating statistics
 187 elapsedTimer CompileBroker::_t_total_compilation;
 188 elapsedTimer CompileBroker::_t_osr_compilation;
 189 elapsedTimer CompileBroker::_t_standard_compilation;
 190 elapsedTimer CompileBroker::_t_invalidated_compilation;
 191 elapsedTimer CompileBroker::_t_bailedout_compilation;
 192 
 193 uint CompileBroker::_total_bailout_count            = 0;
 194 uint CompileBroker::_total_invalidated_count        = 0;
 195 uint CompileBroker::_total_not_entrant_count        = 0;
 196 uint CompileBroker::_total_compile_count            = 0;
 197 uint CompileBroker::_total_osr_compile_count        = 0;
 198 uint CompileBroker::_total_standard_compile_count   = 0;
 199 uint CompileBroker::_total_compiler_stopped_count   = 0;
 200 uint CompileBroker::_total_compiler_restarted_count = 0;
 201 
 202 uint CompileBroker::_sum_osr_bytes_compiled         = 0;
 203 uint CompileBroker::_sum_standard_bytes_compiled    = 0;
 204 uint CompileBroker::_sum_nmethod_size               = 0;
 205 uint CompileBroker::_sum_nmethod_code_size          = 0;
 206 
 207 jlong CompileBroker::_peak_compilation_time        = 0;
 208 
 209 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];
 210 CompilerStatistics CompileBroker::_scc_stats;
 211 CompilerStatistics CompileBroker::_scc_stats_per_level[CompLevel_full_optimization + 1];
 212 
 213 CompileQueue* CompileBroker::_c3_compile_queue     = nullptr;
 214 CompileQueue* CompileBroker::_c2_compile_queue     = nullptr;
 215 CompileQueue* CompileBroker::_c1_compile_queue     = nullptr;
 216 CompileQueue* CompileBroker::_sc1_compile_queue    = nullptr;
 217 CompileQueue* CompileBroker::_sc2_compile_queue    = nullptr;
 218 
 219 bool compileBroker_init() {
 220   if (LogEvents) {
 221     CompilationLog::init();
 222   }
 223 
 224   // init directives stack, adding default directive
 225   DirectivesStack::init();
 226 
 227   if (DirectivesParser::has_file()) {
 228     return DirectivesParser::parse_from_flag();
 229   } else if (CompilerDirectivesPrint) {
 230     // Print default directive even when no other was added
 231     DirectivesStack::print(tty);
 232   }
 233 
 234   return true;
 235 }
 236 
 237 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
 238   CompilerThread* thread = CompilerThread::current();
 239   thread->set_task(task);
 240   CompileLog*     log  = thread->log();
 241   if (log != nullptr && !task->is_unloaded())  task->log_task_start(log);
 242 }
 243 
 244 CompileTaskWrapper::~CompileTaskWrapper() {
 245   CompilerThread* thread = CompilerThread::current();
 246   CompileTask* task = thread->task();
 247   CompileLog*  log  = thread->log();
 248   AbstractCompiler* comp = thread->compiler();
 249   if (log != nullptr && !task->is_unloaded())  task->log_task_done(log);
 250   thread->set_task(nullptr);
 251   thread->set_env(nullptr);
 252   if (task->is_blocking()) {
 253     bool free_task = false;
 254     {
 255       MutexLocker notifier(thread, task->lock());
 256       task->mark_complete();
 257 #if INCLUDE_JVMCI
 258       if (comp->is_jvmci()) {
 259         if (!task->has_waiter()) {
 260           // The waiting thread timed out and thus did not free the task.
 261           free_task = true;
 262         }
 263         task->set_blocking_jvmci_compile_state(nullptr);
 264       }
 265 #endif
 266       if (!free_task) {
 267         // Notify the waiting thread that the compilation has completed
 268         // so that it can free the task.
 269         task->lock()->notify_all();
 270       }
 271     }
 272     if (free_task) {
 273       // The task can only be freed once the task lock is released.
 274       CompileTask::free(task);
 275     }
 276   } else {
 277     task->mark_complete();
 278 
 279     // By convention, the compiling thread is responsible for
 280     // recycling a non-blocking CompileTask.
 281     CompileTask::free(task);
 282   }
 283 }
 284 
 285 /**
 286  * Check if a CompilerThread can be removed and update count if requested.
 287  */
 288 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
 289   assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
 290   if (!ReduceNumberOfCompilerThreads) return false;
 291 
 292   if (RecompilationPolicy::have_recompilation_work()) return false;
 293 
 294   AbstractCompiler *compiler = ct->compiler();
 295   int compiler_count = compiler->num_compiler_threads();
 296   bool c1 = compiler->is_c1();
 297 
 298   // Keep at least 1 compiler thread of each type.
 299   if (compiler_count < 2) return false;
 300 
 301   // Keep thread alive for at least some time.
 302   if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
 303 
 304 #if INCLUDE_JVMCI
 305   if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 306     // Handles for JVMCI thread objects may get released concurrently.
 307     if (do_it) {
 308       assert(CompileThread_lock->owner() == ct, "must be holding lock");
 309     } else {
 310       // Skip check if it's the last thread and let caller check again.
 311       return true;
 312     }
 313   }

 320     if (do_it) {
 321       assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
 322       compiler->set_num_compiler_threads(compiler_count - 1);
 323 #if INCLUDE_JVMCI
 324       if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 325         // Old j.l.Thread object can die when no longer referenced elsewhere.
 326         JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
 327         _compiler2_objects[compiler_count - 1] = nullptr;
 328       }
 329 #endif
 330     }
 331     return true;
 332   }
 333   return false;
 334 }
 335 
 336 /**
 337  * Add a CompileTask to a CompileQueue.
 338  */
 339 void CompileQueue::add(CompileTask* task) {
 340   assert(_lock->owned_by_self(), "must own lock");
 341 
 342   task->set_next(nullptr);
 343   task->set_prev(nullptr);
 344 
 345   if (_last == nullptr) {
 346     // The compile queue is empty.
 347     assert(_first == nullptr, "queue is empty");
 348     _first = task;
 349     _last = task;
 350   } else {
 351     // Append the task to the queue.
 352     assert(_last->next() == nullptr, "not last");
 353     _last->set_next(task);
 354     task->set_prev(_last);
 355     _last = task;
 356   }
 357   ++_size;
 358   ++_total_added;
 359   if (_size > _peak_size) {
 360     _peak_size = _size;
 361   }
 362 
 363   // Mark the method as being in the compile queue.
 364   task->method()->set_queued_for_compilation();
 365 
 366   task->mark_queued(os::elapsed_counter());
 367 
 368   if (CIPrintCompileQueue) {
 369     print_tty();
 370   }
 371 
 372   if (LogCompilation && xtty != nullptr) {
 373     task->log_task_queued();
 374   }
 375 
 376   if (TrainingData::need_data() &&
 377       !CDSConfig::is_dumping_final_static_archive()) { // FIXME: !!! MetaspaceShared::preload_and_dump() temporarily enables RecordTraining !!!
 378     CompileTrainingData* tdata = CompileTrainingData::make(task);
 379     if (tdata != nullptr) {
 380       task->set_training_data(tdata);
 381     }
 382   }
 383 
 384   // Notify CompilerThreads that a task is available.
 385   _lock->notify_all();
 386 }
 387 
 388 void CompileQueue::add_pending(CompileTask* task) {
 389   assert(_lock->owned_by_self() == false, "must NOT own lock");
 390   assert(UseLockFreeCompileQueues, "");
 391   task->method()->set_queued_for_compilation();
 392   _queue.push(*task);
 393   // FIXME: additional coordination needed? e.g., is it possible for compiler thread to block w/o processing pending tasks?
 394   if (is_empty()) {
 395     MutexLocker ml(_lock);
 396     _lock->notify_all();
 397   }
 398 }
 399 
 400 static bool process_pending(CompileTask* task) {
 401 //  guarantee(task->method()->queued_for_compilation(), "");
 402   if (task->is_unloaded()) {
 403     return true; // unloaded
 404   }
 405   task->method()->set_queued_for_compilation(); // FIXME
 406   if (task->method()->pending_queue_processed()) {
 407     return true; // already queued
 408   }
 409   // Mark the method as being in the compile queue.
 410   task->method()->set_pending_queue_processed();
 411   if (CompileBroker::compilation_is_complete(task->method(), task->osr_bci(), task->comp_level(),
 412                                              task->requires_online_compilation(), task->compile_reason())) {
 413     return true; // already compiled
 414   }
 415   return false; // active
 416 }
 417 
 418 void CompileQueue::transfer_pending() {
 419   assert(_lock->owned_by_self(), "must own lock");
 420   while (!_queue.empty()) {
 421     CompileTask* task = _queue.pop();
 422     bool is_stale = process_pending(task);
 423     if (is_stale) {
 424       task->set_next(_first_stale);
 425       task->set_prev(nullptr);
 426       _first_stale = task;
 427     } else {
 428       add(task);
 429     }
 430   }
 431 }
 432 
 433 /**
 434  * Empties compilation queue by putting all compilation tasks onto
 435  * a freelist. Furthermore, the method wakes up all threads that are
 436  * waiting on a compilation task to finish. This can happen if background
 437  * compilation is disabled.
 438  */
 439 void CompileQueue::free_all() {
 440   MutexLocker mu(_lock);
 441   transfer_pending();
 442 
 443   CompileTask* next = _first;
 444 
 445   // Iterate over all tasks in the compile queue
 446   while (next != nullptr) {
 447     CompileTask* current = next;
 448     next = current->next();
 449     {
 450       // Wake up thread that blocks on the compile task.
 451       MutexLocker ct_lock(current->lock());
 452       current->lock()->notify();
 453     }
 454     // Put the task back on the freelist.
 455     CompileTask::free(current);
 456   }
 457   _first = nullptr;
 458   _last = nullptr;
 459 
 460   // Wake up all threads that block on the queue.
 461   _lock->notify_all();
 462 }
 463 
 464 /**
 465  * Get the next CompileTask from a CompileQueue
 466  */
 467 CompileTask* CompileQueue::get(CompilerThread* thread) {
 468   // save methods from RedefineClasses across safepoint
 469   // across compile queue lock below.
 470   methodHandle save_method;
 471   methodHandle save_hot_method;
 472 
 473   MonitorLocker locker(_lock);
 474   transfer_pending();
 475 
 476   RecompilationPolicy::sample_load_average();
 477 
 478   // If _first is null we have no more compile jobs. There are two reasons for
 479   // having no compile jobs: First, we compiled everything we wanted. Second,
 480   // we ran out of code cache so compilation has been disabled. In the latter
 481   // case we perform code cache sweeps to free memory such that we can re-enable
 482   // compilation.
 483   while (_first == nullptr) {
 484     // Exit loop if compilation is disabled forever
 485     if (CompileBroker::is_compilation_disabled_forever()) {
 486       return nullptr;
 487     }
 488 
 489     AbstractCompiler* compiler = thread->compiler();
 490     guarantee(compiler != nullptr, "Compiler object must exist");
 491     compiler->on_empty_queue(this, thread);
 492     if (_first != nullptr) {
 493       // The call to on_empty_queue may have temporarily unlocked the MCQ lock
 494       // so check again whether any tasks were added to the queue.
 495       break;
 496     }
 497 
 498     // If there are no compilation tasks and we can compile new jobs
 499     // (i.e., there is enough free space in the code cache) there is
 500     // no need to invoke the GC.
 501     // We need a timed wait here, since compiler threads can exit if compilation
 502     // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
 503     // is not critical and we do not want idle compiler threads to wake up too often.
 504     locker.wait(5*1000);
 505 
 506     transfer_pending(); // reacquired lock
 507 
 508     if (RecompilationPolicy::have_recompilation_work()) return nullptr;
 509 
 510     if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
 511       // Still nothing to compile. Give caller a chance to stop this thread.
 512       if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
 513     }
 514   }
 515 
 516   if (CompileBroker::is_compilation_disabled_forever()) {
 517     return nullptr;
 518   }
 519 
 520   CompileTask* task;
 521   {
 522     NoSafepointVerifier nsv;
 523     task = CompilationPolicy::select_task(this, thread);
 524     if (task != nullptr) {
 525       task = task->select_for_compilation();
 526     }
 527   }
 528 
 529   if (task != nullptr) {
 530     // Save method pointers across unlock safepoint.  The task is removed from
 531     // the compilation queue, which is walked during RedefineClasses.
 532     Thread* thread = Thread::current();
 533     save_method = methodHandle(thread, task->method());
 534     save_hot_method = methodHandle(thread, task->hot_method());
 535 
 536     remove(task);
 537   }
 538   purge_stale_tasks(); // may temporarily release MCQ lock
 539   return task;
 540 }
 541 
 542 // Clean & deallocate stale compile tasks.
 543 // Temporarily releases MethodCompileQueue lock.
 544 void CompileQueue::purge_stale_tasks() {
 545   assert(_lock->owned_by_self(), "must own lock");
 546   if (_first_stale != nullptr) {
 547     // Stale tasks are purged when MCQ lock is released,
 548     // but _first_stale updates are protected by MCQ lock.
 549     // Once task processing starts and MCQ lock is released,
 550     // other compiler threads can reuse _first_stale.
 551     CompileTask* head = _first_stale;
 552     _first_stale = nullptr;
 553     {
 554       MutexUnlocker ul(_lock);
 555       for (CompileTask* task = head; task != nullptr; ) {
 556         CompileTask* next_task = task->next();
 557         CompileTaskWrapper ctw(task); // Frees the task
 558         task->set_failure_reason("stale task");
 559         task = next_task;
 560       }
 561     }
 562     transfer_pending(); // transfer pending after reacquiring MCQ lock
 563   }
 564 }
 565 
 566 void CompileQueue::remove(CompileTask* task) {
 567   assert(_lock->owned_by_self(), "must own lock");
 568   if (task->prev() != nullptr) {
 569     task->prev()->set_next(task->next());
 570   } else {
 571     // max is the first element
 572     assert(task == _first, "Sanity");
 573     _first = task->next();
 574   }
 575 
 576   if (task->next() != nullptr) {
 577     task->next()->set_prev(task->prev());
 578   } else {
 579     // max is the last element
 580     assert(task == _last, "Sanity");
 581     _last = task->prev();
 582   }
 583   --_size;
 584   ++_total_removed;
 585 }
 586 
 587 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
 588   assert(_lock->owned_by_self(), "must own lock");
 589   remove(task);
 590 
 591   // Enqueue the task for reclamation (should be done outside MCQ lock)
 592   task->set_next(_first_stale);
 593   task->set_prev(nullptr);
 594   _first_stale = task;
 595 }
 596 
 597 // methods in the compile queue need to be marked as used on the stack
 598 // so that they don't get reclaimed by Redefine Classes
 599 void CompileQueue::mark_on_stack() {
 600   for (CompileTask* task = _first; task != nullptr; task = task->next()) {
 601     task->mark_on_stack();
 602   }
 603   for (CompileTask* task = _queue.first(); !_queue.is_end(task); task = task->next()) {
 604     assert(task != nullptr, "");
 605     task->mark_on_stack();

 606   }
 607 }
 608 
 609 
 610 CompileQueue* CompileBroker::compile_queue(int comp_level, bool is_scc) {
 611   if (is_c2_compile(comp_level)) return ((is_scc  && (_sc_count > 0)) ? _sc2_compile_queue : _c2_compile_queue);
 612   if (is_c1_compile(comp_level)) return ((is_scc && (_sc_count > 0)) ? _sc1_compile_queue : _c1_compile_queue);
 613   return nullptr;
 614 }
 615 
 616 CompileQueue* CompileBroker::c1_compile_queue() {
 617   return _c1_compile_queue;
 618 }
 619 
 620 CompileQueue* CompileBroker::c2_compile_queue() {
 621   return _c2_compile_queue;
 622 }
 623 
 624 void CompileBroker::print_compile_queues(outputStream* st) {
 625   st->print_cr("Current compiles: ");
 626 
 627   char buf[2000];
 628   int buflen = sizeof(buf);
 629   Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
 630 
 631   st->cr();
 632   if (_c1_compile_queue != nullptr) {
 633     _c1_compile_queue->print(st);
 634   }
 635   if (_c2_compile_queue != nullptr) {
 636     _c2_compile_queue->print(st);
 637   }
 638   if (_c3_compile_queue != nullptr) {
 639     _c3_compile_queue->print(st);
 640   }
 641   if (_sc1_compile_queue != nullptr) {
 642     _sc1_compile_queue->print(st);
 643   }
 644   if (_sc2_compile_queue != nullptr) {
 645     _sc2_compile_queue->print(st);
 646   }
 647 }
 648 
 649 void CompileQueue::print(outputStream* st) {
 650   assert_locked_or_safepoint(_lock);
 651   st->print_cr("%s:", name());
 652   CompileTask* task = _first;
 653   if (task == nullptr) {
 654     st->print_cr("Empty");
 655   } else {
 656     while (task != nullptr) {
 657       task->print(st, nullptr, true, true);
 658       task = task->next();
 659     }
 660   }
 661   st->cr();
 662 }
 663 
 664 void CompileQueue::print_tty() {
 665   stringStream ss;
 666   // Dump the compile queue into a buffer before locking the tty
 667   print(&ss);
 668   {
 669     ttyLocker ttyl;
 670     tty->print("%s", ss.freeze());

 697       CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
 698     }
 699     first_registration = false;
 700 #endif // COMPILER2
 701   }
 702 }
 703 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
 704 
 705 // ------------------------------------------------------------------
 706 // CompileBroker::compilation_init
 707 //
 708 // Initialize the Compilation object
 709 void CompileBroker::compilation_init(JavaThread* THREAD) {
 710   // No need to initialize compilation system if we do not use it.
 711   if (!UseCompiler) {
 712     return;
 713   }
 714   // Set the interface to the current compiler(s).
 715   _c1_count = CompilationPolicy::c1_count();
 716   _c2_count = CompilationPolicy::c2_count();
 717   _c3_count = CompilationPolicy::c3_count();
 718   _sc_count = CompilationPolicy::sc_count();
 719 
 720 #if INCLUDE_JVMCI
 721   if (EnableJVMCI) {
 722     // This is creating a JVMCICompiler singleton.
 723     JVMCICompiler* jvmci = new JVMCICompiler();
 724 
 725     if (UseJVMCICompiler) {
 726       _compilers[1] = jvmci;
 727       if (FLAG_IS_DEFAULT(JVMCIThreads)) {
 728         if (BootstrapJVMCI) {
 729           // JVMCI will bootstrap so give it more threads
 730           _c2_count = MIN2(32, os::active_processor_count());
 731         }
 732       } else {
 733         _c2_count = JVMCIThreads;
 734       }
 735       if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
 736       } else {
 737 #ifdef COMPILER1
 738         _c1_count = JVMCIHostThreads;
 739 #endif // COMPILER1
 740       }
 741 #ifdef COMPILER2
 742       if (SCCache::is_on() && (_c3_count > 0)) {
 743         _compilers[2] = new C2Compiler();
 744       }
 745 #endif
 746     }
 747   }
 748 #endif // INCLUDE_JVMCI
 749 
 750 #ifdef COMPILER1
 751   if (_c1_count > 0) {
 752     _compilers[0] = new Compiler();
 753   }
 754 #endif // COMPILER1
 755 
 756 #ifdef COMPILER2
 757   if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
 758     if (_c2_count > 0) {
 759       _compilers[1] = new C2Compiler();
 760       // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.
 761       // idToPhase mapping for c2 is in opto/phasetype.hpp
 762       JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)
 763     }
 764   }
 765 #endif // COMPILER2

 860     _perf_last_compile_size =
 861              PerfDataManager::create_variable(SUN_CI, "lastSize",
 862                                               PerfData::U_Bytes,
 863                                               (jlong)CompileBroker::no_compile,
 864                                               CHECK);
 865 
 866 
 867     _perf_last_failed_type =
 868              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 869                                               PerfData::U_None,
 870                                               (jlong)CompileBroker::no_compile,
 871                                               CHECK);
 872 
 873     _perf_last_invalidated_type =
 874          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 875                                           PerfData::U_None,
 876                                           (jlong)CompileBroker::no_compile,
 877                                           CHECK);
 878   }
 879 
 880   log_info(scc, init)("CompileBroker is initialized");
 881   _initialized = true;
 882 }
 883 
 884 Handle CompileBroker::create_thread_oop(const char* name, TRAPS) {
 885   Handle thread_oop = JavaThread::create_system_thread_object(name, CHECK_NH);
 886   return thread_oop;
 887 }
 888 
 889 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
 890   CompilationPolicy::replay_training_at_init_loop(thread);
 891 }
 892 
 893 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 894 // Stress testing. Dedicated threads revert optimizations based on escape analysis concurrently to
 895 // the running java application.  Configured with vm options DeoptimizeObjectsALot*.
 896 class DeoptimizeObjectsALotThread : public JavaThread {
 897 
 898   static void deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS);
 899   void deoptimize_objects_alot_loop_single();
 900   void deoptimize_objects_alot_loop_all();
 901 
 902 public:
 903   DeoptimizeObjectsALotThread() : JavaThread(&deopt_objs_alot_thread_entry) { }
 904 
 905   bool is_hidden_from_external_view() const      { return true; }
 906 };
 907 
 908 // Entry for DeoptimizeObjectsALotThread. The threads are started in
 909 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
 910 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
 911     DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
 912     bool enter_single_loop;

 964   if (java_lang_Thread::thread(thread_oop()) != nullptr) {
 965     assert(type == compiler_t, "should only happen with reused compiler threads");
 966     // The compiler thread hasn't actually exited yet so don't try to reuse it
 967     return nullptr;
 968   }
 969 
 970   JavaThread* new_thread = nullptr;
 971   switch (type) {
 972     case compiler_t:
 973       assert(comp != nullptr, "Compiler instance missing.");
 974       if (!InjectCompilerCreationFailure || comp->num_compiler_threads() == 0) {
 975         CompilerCounters* counters = new CompilerCounters();
 976         new_thread = new CompilerThread(queue, counters);
 977       }
 978       break;
 979 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 980     case deoptimizer_t:
 981       new_thread = new DeoptimizeObjectsALotThread();
 982       break;
 983 #endif // ASSERT
 984     case training_replay_t:
 985       new_thread = new TrainingReplayThread();
 986       break;
 987     default:
 988       ShouldNotReachHere();
 989   }
 990 
 991   // At this point the new CompilerThread data-races with this startup
 992   // thread (which is the main thread and NOT the VM thread).
 993   // This means Java bytecodes being executed at startup can
 994   // queue compile jobs which will run at whatever default priority the
 995   // newly created CompilerThread runs at.
 996 
 997 
 998   // At this point it may be possible that no osthread was created for the
 999   // JavaThread due to lack of resources. We will handle that failure below.
1000   // Also check new_thread so that static analysis is happy.
1001   if (new_thread != nullptr && new_thread->osthread() != nullptr) {
1002 
1003     if (type == compiler_t) {
1004       CompilerThread::cast(new_thread)->set_compiler(comp);
1005     }
1006 

1046 }
1047 
1048 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
1049   char name_buffer[256];
1050   os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
1051   Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
1052   return JNIHandles::make_global(thread_oop);
1053 }
1054 
1055 static void print_compiler_threads(stringStream& msg) {
1056   if (TraceCompilerThreads) {
1057     tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
1058   }
1059   LogTarget(Debug, jit, thread) lt;
1060   if (lt.is_enabled()) {
1061     LogStream ls(lt);
1062     ls.print_cr("%s", msg.as_string());
1063   }
1064 }
1065 
1066 static void print_compiler_thread(JavaThread *ct) {
1067   if (trace_compiler_threads()) {
1068     ResourceMark rm;
1069     ThreadsListHandle tlh;  // name() depends on the TLH.
1070     assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1071     stringStream msg;
1072     msg.print("Added initial compiler thread %s", ct->name());
1073     print_compiler_threads(msg);
1074   }
1075 }
1076 
1077 void CompileBroker::init_compiler_threads() {
1078   // Ensure any exceptions lead to vm_exit_during_initialization.
1079   EXCEPTION_MARK;
1080 #if !defined(ZERO)
1081   assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
1082 #endif // !ZERO
1083   // Initialize the compilation queue
1084   if (_c2_count > 0) {
1085     const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
1086     _c2_compile_queue  = new CompileQueue(name, MethodCompileQueueC2_lock);
1087     _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
1088     _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
1089   }
1090   if (_c1_count > 0) {
1091     _c1_compile_queue  = new CompileQueue("C1 compile queue", MethodCompileQueueC1_lock);
1092     _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
1093     _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
1094   }
1095 
1096   if (_c3_count > 0) {
1097     const char* name = "C2 compile queue";
1098     _c3_compile_queue  = new CompileQueue(name, MethodCompileQueueC3_lock);
1099     _compiler3_objects = NEW_C_HEAP_ARRAY(jobject, _c3_count, mtCompiler);
1100     _compiler3_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c3_count, mtCompiler);
1101   }
1102   if (_sc_count > 0) {
1103     if (_c1_count > 0) { // C1 is present
1104       _sc1_compile_queue  = new CompileQueue("C1 SC compile queue", MethodCompileQueueSC1_lock);
1105     }
1106     if (_c2_count > 0) { // C2 is present
1107       _sc2_compile_queue  = new CompileQueue("C2 SC compile queue", MethodCompileQueueSC2_lock);
1108     }
1109     _sc_objects = NEW_C_HEAP_ARRAY(jobject, _sc_count, mtCompiler);
1110     _sc_logs = NEW_C_HEAP_ARRAY(CompileLog*, _sc_count, mtCompiler);
1111   }
1112   char name_buffer[256];
1113 
1114   for (int i = 0; i < _c2_count; i++) {
1115     // Create a name for our thread.
1116     jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
1117     _compiler2_objects[i] = thread_handle;
1118     _compiler2_logs[i] = nullptr;
1119 
1120     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1121       JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
1122       assert(ct != nullptr, "should have been handled for initial thread");
1123       _compilers[1]->set_num_compiler_threads(i + 1);
1124       print_compiler_thread(ct);







1125     }
1126   }
1127 
1128   for (int i = 0; i < _c1_count; i++) {
1129     // Create a name for our thread.
1130     jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
1131     _compiler1_objects[i] = thread_handle;
1132     _compiler1_logs[i] = nullptr;
1133 
1134     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1135       JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1136       assert(ct != nullptr, "should have been handled for initial thread");
1137       _compilers[0]->set_num_compiler_threads(i + 1);
1138       print_compiler_thread(ct);
1139     }
1140   }
1141 
1142   for (int i = 0; i < _c3_count; i++) {
1143     // Create a name for our thread.
1144     os::snprintf_checked(name_buffer, sizeof(name_buffer), "C2 CompilerThread%d", i);
1145     Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1146     jobject thread_handle = JNIHandles::make_global(thread_oop);
1147     _compiler3_objects[i] = thread_handle;
1148     _compiler3_logs[i] = nullptr;
1149 
1150     JavaThread *ct = make_thread(compiler_t, thread_handle, _c3_compile_queue, _compilers[2], THREAD);
1151     assert(ct != nullptr, "should have been handled for initial thread");
1152     _compilers[2]->set_num_compiler_threads(i + 1);
1153     print_compiler_thread(ct);
1154   }
1155 
1156   if (_sc_count > 0) {
1157     int i = 0;
1158     if (_c1_count > 0) { // C1 is present
1159       os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d SC CompilerThread", 1);
1160       Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1161       jobject thread_handle = JNIHandles::make_global(thread_oop);
1162       _sc_objects[i] = thread_handle;
1163       _sc_logs[i] = nullptr;
1164       i++;
1165 
1166       JavaThread *ct = make_thread(compiler_t, thread_handle, _sc1_compile_queue, _compilers[0], THREAD);
1167       assert(ct != nullptr, "should have been handled for initial thread");
1168       print_compiler_thread(ct);
1169     }
1170     if (_c2_count > 0) { // C2 is present
1171       os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d SC CompilerThread", 2);
1172       Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1173       jobject thread_handle = JNIHandles::make_global(thread_oop);
1174       _sc_objects[i] = thread_handle;
1175       _sc_logs[i] = nullptr;
1176 
1177       JavaThread *ct = make_thread(compiler_t, thread_handle, _sc2_compile_queue, _compilers[1], THREAD);
1178       assert(ct != nullptr, "should have been handled for initial thread");
1179       print_compiler_thread(ct);
1180     }
1181   }
1182 
1183   if (UsePerfData) {
1184     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count + _c3_count, CHECK);
1185   }
1186 
1187 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1188   if (DeoptimizeObjectsALot) {
1189     // Initialize and start the object deoptimizer threads
1190     const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1191     for (int count = 0; count < total_count; count++) {
1192       Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1193       jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1194       make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1195     }
1196   }
1197 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1198 }
1199 
1200 void CompileBroker::init_training_replay() {
1201   // Ensure any exceptions lead to vm_exit_during_initialization.
1202   EXCEPTION_MARK;
1203   if (TrainingData::have_data()) {
1204     if (UseConcurrentTrainingReplay) {
1205       Handle thread_oop = create_thread_oop("Training replay thread", CHECK);
1206       jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1207       make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1208     }
1209     _replay_initialized = true;
1210   }
1211 }
1212 
1213 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1214 
1215   int old_c2_count = 0, new_c2_count = 0, old_c1_count = 0, new_c1_count = 0;
1216   const int c2_tasks_per_thread = 2, c1_tasks_per_thread = 4;
1217 
1218   // Quick check if we already have enough compiler threads without taking the lock.
1219   // Numbers may change concurrently, so we read them again after we have the lock.
1220   if (_c2_compile_queue != nullptr) {
1221     old_c2_count = get_c2_thread_count();
1222     new_c2_count = MIN2(_c2_count, _c2_compile_queue->size() / c2_tasks_per_thread);
1223   }
1224   if (_c1_compile_queue != nullptr) {
1225     old_c1_count = get_c1_thread_count();
1226     new_c1_count = MIN2(_c1_count, _c1_compile_queue->size() / c1_tasks_per_thread);
1227   }
1228   if (new_c2_count <= old_c2_count && new_c1_count <= old_c1_count) return;
1229 
1230   // Now, we do the more expensive operations.
1231   julong free_memory = os::free_memory();
1232   // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).

1315         stringStream msg;
1316         msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)",
1317                   ct->name(), (int)(free_memory/M), (int)(available_cc_p/M));
1318         print_compiler_threads(msg);
1319       }
1320     }
1321   }
1322 
1323   CompileThread_lock->unlock();
1324 }
1325 
1326 
1327 /**
1328  * Set the methods on the stack as on_stack so that redefine classes doesn't
1329  * reclaim them. This method is executed at a safepoint.
1330  */
1331 void CompileBroker::mark_on_stack() {
1332   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1333   // Since we are at a safepoint, we do not need a lock to access
1334   // the compile queues.
1335   if (_c3_compile_queue != nullptr) {
1336     _c3_compile_queue->mark_on_stack();
1337   }
1338   if (_c2_compile_queue != nullptr) {
1339     _c2_compile_queue->mark_on_stack();
1340   }
1341   if (_c1_compile_queue != nullptr) {
1342     _c1_compile_queue->mark_on_stack();
1343   }
1344   if (_sc1_compile_queue != nullptr) {
1345     _sc1_compile_queue->mark_on_stack();
1346   }
1347   if (_sc2_compile_queue != nullptr) {
1348     _sc2_compile_queue->mark_on_stack();
1349   }
1350 }
1351 
1352 // ------------------------------------------------------------------
1353 // CompileBroker::compile_method
1354 //
1355 // Request compilation of a method.
1356 void CompileBroker::compile_method_base(const methodHandle& method,
1357                                         int osr_bci,
1358                                         int comp_level,
1359                                         const methodHandle& hot_method,
1360                                         int hot_count,
1361                                         CompileTask::CompileReason compile_reason,
1362                                         bool requires_online_compilation,
1363                                         bool blocking,
1364                                         Thread* thread) {
1365   guarantee(!method->is_abstract(), "cannot compile abstract methods");
1366   assert(method->method_holder()->is_instance_klass(),
1367          "sanity check");
1368   assert(!method->method_holder()->is_not_initialized()   ||
1369          compile_reason == CompileTask::Reason_Preload    ||
1370          compile_reason == CompileTask::Reason_Precompile ||
1371          compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1372   assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1373 
1374   if (CIPrintRequests) {
1375     tty->print("request: ");
1376     method->print_short_name(tty);
1377     if (osr_bci != InvocationEntryBci) {
1378       tty->print(" osr_bci: %d", osr_bci);
1379     }
1380     tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1381     if (!hot_method.is_null()) {
1382       tty->print(" hot: ");
1383       if (hot_method() != method()) {
1384           hot_method->print_short_name(tty);
1385       } else {
1386         tty->print("yes");
1387       }
1388     }
1389     tty->cr();
1390   }
1391 
1392   // A request has been made for compilation.  Before we do any
1393   // real work, check to see if the method has been compiled
1394   // in the meantime with a definitive result.
1395   if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1396     return;
1397   }
1398 
1399 #ifndef PRODUCT
1400   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1401     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1402       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
1403       return;
1404     }
1405   }
1406 #endif
1407 
1408   // If this method is already in the compile queue, then
1409   // we do not block the current thread.
1410   if (compilation_is_in_queue(method)) {
1411     // We may want to decay our counter a bit here to prevent
1412     // multiple denied requests for compilation.  This is an
1413     // open compilation policy issue. Note: The other possibility,
1414     // in the case that this is a blocking compile request, is to have
1415     // all subsequent blocking requesters wait for completion of
1416     // ongoing compiles. Note that in this case we'll need a protocol
1417     // for freeing the associated compile tasks. [Or we could have
1418     // a single static monitor on which all these waiters sleep.]
1419     return;
1420   }
1421 
1422   // Tiered policy requires MethodCounters to exist before adding a method to
1423   // the queue. Create if we don't have them yet.
1424   if (compile_reason != CompileTask::Reason_Preload) {
1425     method->get_method_counters(thread);
1426   }
1427 
1428   SCCEntry* scc_entry = find_scc_entry(method, osr_bci, comp_level, compile_reason, requires_online_compilation);
1429   bool is_scc = (scc_entry != nullptr);
1430 
1431   // Outputs from the following MutexLocker block:
1432   CompileTask* task = nullptr;
1433   CompileQueue* queue;
1434 #if INCLUDE_JVMCI
1435   if (is_c2_compile(comp_level) && compiler2()->is_jvmci() && compiler3() != nullptr &&
1436       ((JVMCICompiler*)compiler2())->force_comp_at_level_simple(method)) {
1437     assert(_c3_compile_queue != nullptr, "sanity");
1438     queue = _c3_compile_queue; // JVMCI compiler's methods compilation
1439   } else
1440 #endif
1441   queue = compile_queue(comp_level, is_scc);
1442 
1443   // Acquire our lock.
1444   {
1445     ConditionalMutexLocker locker(thread, queue->lock(), !UseLockFreeCompileQueues);
1446 
1447     // Make sure the method has not slipped into the queues since
1448     // last we checked; note that those checks were "fast bail-outs".
1449     // Here we need to be more careful, see 14012000 below.
1450     if (compilation_is_in_queue(method)) {
1451       return;
1452     }
1453 
1454     // We need to check again to see if the compilation has
1455     // completed.  A previous compilation may have registered
1456     // some result.
1457     if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1458       return;
1459     }
1460 
1461     // We now know that this compilation is not pending, complete,
1462     // or prohibited.  Assign a compile_id to this compilation
1463     // and check to see if it is in our [Start..Stop) range.
1464     int compile_id = assign_compile_id(method, osr_bci);
1465     if (compile_id == 0) {
1466       // The compilation falls outside the allowed range.
1467       return;
1468     }
1469 
1470 #if INCLUDE_JVMCI
1471     if (UseJVMCICompiler && blocking) {
1472       // Don't allow blocking compiles for requests triggered by JVMCI.
1473       if (thread->is_Compiler_thread()) {
1474         blocking = false;
1475       }
1476 
1477       // In libjvmci, JVMCI initialization should not deadlock with other threads

1527     // <RESULT, QUEUE> :
1528     //     <0, 1> : in compile queue, but not yet compiled
1529     //     <1, 1> : compiled but queue bit not cleared
1530     //     <1, 0> : compiled and queue bit cleared
1531     // Because we first check the queue bits then check the result bits,
1532     // we are assured that we cannot introduce a duplicate task.
1533     // Note that if we did the tests in the reverse order (i.e. check
1534     // result then check queued bit), we could get the result bit before
1535     // the compilation completed, and the queue bit after the compilation
1536     // completed, and end up introducing a "duplicate" (redundant) task.
1537     // In that case, the compiler thread should first check if a method
1538     // has already been compiled before trying to compile it.
1539     // NOTE: in the event that there are multiple compiler threads and
1540     // there is de-optimization/recompilation, things will get hairy,
1541     // and in that case it's best to protect both the testing (here) of
1542     // these bits, and their updating (here and elsewhere) under a
1543     // common lock.
1544     task = create_compile_task(queue,
1545                                compile_id, method,
1546                                osr_bci, comp_level,
1547                                hot_method, hot_count, scc_entry, compile_reason,
1548                                requires_online_compilation, blocking);
1549 
1550     if (task->is_scc() && (_sc_count > 0)) {
1551       // Put it on SC queue
1552       queue = is_c1_compile(comp_level) ? _sc1_compile_queue : _sc2_compile_queue;
1553     }
1554 
1555     if (UseLockFreeCompileQueues) {
1556       assert(queue->lock()->owned_by_self() == false, "");
1557       queue->add_pending(task);
1558     } else {
1559       queue->add(task);
1560     }
1561   }
1562 
1563   if (blocking) {
1564     wait_for_completion(task);
1565   }
1566 }
1567 
1568 SCCEntry* CompileBroker::find_scc_entry(const methodHandle& method, int osr_bci, int comp_level,
1569                                         CompileTask::CompileReason compile_reason,
1570                                         bool requires_online_compilation) {
1571   SCCEntry* scc_entry = nullptr;
1572   if (osr_bci == InvocationEntryBci && !requires_online_compilation && SCCache::is_on_for_read()) {
1573     // Check for cached code.
1574     if (compile_reason == CompileTask::Reason_Preload) {
1575       scc_entry = method->scc_entry();
1576       assert(scc_entry != nullptr && scc_entry->for_preload(), "sanity");
1577     } else {
1578       scc_entry = SCCache::find_code_entry(method, comp_level);
1579     }
1580   }
1581   return scc_entry;
1582 }
1583 
1584 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1585                                        int comp_level,
1586                                        const methodHandle& hot_method, int hot_count,
1587                                        bool requires_online_compilation,
1588                                        CompileTask::CompileReason compile_reason,
1589                                        TRAPS) {
1590   // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1591   if (!_initialized || comp_level == CompLevel_none) {
1592     return nullptr;
1593   }
1594 
1595 #if INCLUDE_JVMCI
1596   if (EnableJVMCI && UseJVMCICompiler &&
1597       comp_level == CompLevel_full_optimization && !AOTLinkedClassBulkLoader::class_preloading_finished()) {
1598     return nullptr;
1599   }
1600 #endif
1601 
1602   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1603   assert(comp != nullptr, "Ensure we have a compiler");
1604 
1605 #if INCLUDE_JVMCI
1606   if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1607     // JVMCI compilation is not yet initializable.
1608     return nullptr;
1609   }
1610 #endif
1611 
1612   DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1613   // CompileBroker::compile_method can trap and can have pending async exception.
1614   nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, requires_online_compilation, compile_reason, directive, THREAD);
1615   DirectivesStack::release(directive);
1616   return nm;
1617 }
1618 
1619 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1620                                          int comp_level,
1621                                          const methodHandle& hot_method, int hot_count,
1622                                          bool requires_online_compilation,
1623                                          CompileTask::CompileReason compile_reason,
1624                                          DirectiveSet* directive,
1625                                          TRAPS) {
1626 
1627   // make sure arguments make sense
1628   assert(method->method_holder()->is_instance_klass(), "not an instance method");
1629   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1630   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1631   assert(!method->method_holder()->is_not_initialized()   ||
1632          compile_reason == CompileTask::Reason_Preload    ||
1633          compile_reason == CompileTask::Reason_Precompile ||
1634          compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1635   // return quickly if possible
1636 
1637   if (PrecompileOnlyAndExit && !CompileTask::reason_is_precompiled(compile_reason)) {
1638     return nullptr;
1639   }
1640 
1641   // lock, make sure that the compilation
1642   // isn't prohibited in a straightforward way.
1643   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1644   if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1645     return nullptr;
1646   }
1647 
1648   if (osr_bci == InvocationEntryBci) {
1649     // standard compilation
1650     nmethod* method_code = method->code();
1651     if (method_code != nullptr) {
1652       if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1653         return method_code;
1654       }
1655     }
1656     if (method->is_not_compilable(comp_level)) {
1657       return nullptr;
1658     }
1659   } else {
1660     // osr compilation
1661     // We accept a higher level osr method
1662     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1663     if (nm != nullptr) return nm;
1664     if (method->is_not_osr_compilable(comp_level)) return nullptr;
1665   }
1666 
1667   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1668   // some prerequisites that are compiler specific
1669   if (compile_reason != CompileTask::Reason_Preload && (comp->is_c2() || comp->is_jvmci())) {
1670     InternalOOMEMark iom(THREAD);
1671     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1672     // Resolve all classes seen in the signature of the method
1673     // we are compiling.
1674     Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1675   }
1676 
1677   // If the method is native, do the lookup in the thread requesting
1678   // the compilation. Native lookups can load code, which is not
1679   // permitted during compilation.
1680   //
1681   // Note: A native method implies non-osr compilation which is
1682   //       checked with an assertion at the entry of this method.
1683   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1684     address adr = NativeLookup::lookup(method, THREAD);
1685     if (HAS_PENDING_EXCEPTION) {
1686       // In case of an exception looking up the method, we just forget
1687       // about it. The interpreter will kick-in and throw the exception.
1688       method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1689       CLEAR_PENDING_EXCEPTION;

1728             method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) {
1729         return nullptr;
1730       }
1731 #endif // X86 && !ZERO
1732 
1733       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1734       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1735       //
1736       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1737       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1738       AdapterHandlerLibrary::create_native_wrapper(method);
1739     } else {
1740       return nullptr;
1741     }
1742   } else {
1743     // If the compiler is shut off due to code cache getting full
1744     // fail out now so blocking compiles dont hang the java thread
1745     if (!should_compile_new_jobs()) {
1746       return nullptr;
1747     }
1748     bool is_blocking = ReplayCompiles                                             ||
1749                        !directive->BackgroundCompilationOption                    ||
1750                        (compile_reason == CompileTask::Reason_Precompile)         ||
1751                        (compile_reason == CompileTask::Reason_PrecompileForPreload);
1752 	  compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, requires_online_compilation, is_blocking, THREAD);
1753   }
1754 
1755   // return requested nmethod
1756   // We accept a higher level osr method
1757   if (osr_bci == InvocationEntryBci) {
1758     return method->code();
1759   }
1760   return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1761 }
1762 
1763 
1764 // ------------------------------------------------------------------
1765 // CompileBroker::compilation_is_complete
1766 //
1767 // See if compilation of this method is already complete.
1768 bool CompileBroker::compilation_is_complete(Method*                    method,
1769                                             int                        osr_bci,
1770                                             int                        comp_level,
1771                                             bool                       online_only,
1772                                             CompileTask::CompileReason compile_reason) {
1773   if (compile_reason == CompileTask::Reason_Precompile ||
1774       compile_reason == CompileTask::Reason_PrecompileForPreload) {
1775     return false; // FIXME: any restrictions?
1776   }
1777   bool is_osr = (osr_bci != standard_entry_bci);
1778   if (is_osr) {
1779     if (method->is_not_osr_compilable(comp_level)) {
1780       return true;
1781     } else {
1782       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1783       return (result != nullptr);
1784     }
1785   } else {
1786     if (method->is_not_compilable(comp_level)) {
1787       return true;
1788     } else {
1789       nmethod* result = method->code();
1790       if (result == nullptr) {
1791         return false;
1792       }
1793       if (online_only && result->is_scc()) {
1794         return false;
1795       }
1796       bool same_level = (comp_level == result->comp_level());
1797       if (result->has_clinit_barriers()) {
1798         return !same_level; // Allow replace preloaded code with new code of the same level
1799       }
1800       return same_level;
1801     }
1802   }
1803 }
1804 
1805 
1806 /**
1807  * See if this compilation is already requested.
1808  *
1809  * Implementation note: there is only a single "is in queue" bit
1810  * for each method.  This means that the check below is overly
1811  * conservative in the sense that an osr compilation in the queue
1812  * will block a normal compilation from entering the queue (and vice
1813  * versa).  This can be remedied by a full queue search to disambiguate
1814  * cases.  If it is deemed profitable, this may be done.
1815  */
1816 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1817   return method->queued_for_compilation();
1818 }
1819 
1820 // ------------------------------------------------------------------

1880     if (CIStart <= id && id < CIStop) {
1881       return id;
1882     }
1883   }
1884 
1885   // Method was not in the appropriate compilation range.
1886   method->set_not_compilable_quietly("Not in requested compile id range");
1887   return 0;
1888 #else
1889   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1890   // only _compilation_id is incremented.
1891   return Atomic::add(&_compilation_id, 1);
1892 #endif
1893 }
1894 
1895 // ------------------------------------------------------------------
1896 // CompileBroker::assign_compile_id_unlocked
1897 //
1898 // Public wrapper for assign_compile_id that acquires the needed locks
1899 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {

1900   return assign_compile_id(method, osr_bci);
1901 }
1902 
1903 // ------------------------------------------------------------------
1904 // CompileBroker::create_compile_task
1905 //
1906 // Create a CompileTask object representing the current request for
1907 // compilation.  Add this task to the queue.
1908 CompileTask* CompileBroker::create_compile_task(CompileQueue*       queue,
1909                                                 int                 compile_id,
1910                                                 const methodHandle& method,
1911                                                 int                 osr_bci,
1912                                                 int                 comp_level,
1913                                                 const methodHandle& hot_method,
1914                                                 int                 hot_count,
1915                                                 SCCEntry*           scc_entry,
1916                                                 CompileTask::CompileReason compile_reason,
1917                                                 bool                requires_online_compilation,
1918                                                 bool                blocking) {
1919   CompileTask* new_task = CompileTask::allocate();
1920   new_task->initialize(compile_id, method, osr_bci, comp_level,
1921                        hot_method, hot_count, scc_entry, compile_reason, queue,
1922                        requires_online_compilation, blocking);

1923   return new_task;
1924 }
1925 
1926 #if INCLUDE_JVMCI
1927 // The number of milliseconds to wait before checking if
1928 // JVMCI compilation has made progress.
1929 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1930 
1931 // The number of JVMCI compilation progress checks that must fail
1932 // before unblocking a thread waiting for a blocking compilation.
1933 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1934 
1935 /**
1936  * Waits for a JVMCI compiler to complete a given task. This thread
1937  * waits until either the task completes or it sees no JVMCI compilation
1938  * progress for N consecutive milliseconds where N is
1939  * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1940  * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1941  *
1942  * @return true if this thread needs to free/recycle the task

2043  */
2044 bool CompileBroker::init_compiler_runtime() {
2045   CompilerThread* thread = CompilerThread::current();
2046   AbstractCompiler* comp = thread->compiler();
2047   // Final sanity check - the compiler object must exist
2048   guarantee(comp != nullptr, "Compiler object must exist");
2049 
2050   {
2051     // Must switch to native to allocate ci_env
2052     ThreadToNativeFromVM ttn(thread);
2053     ciEnv ci_env((CompileTask*)nullptr);
2054     // Cache Jvmti state
2055     ci_env.cache_jvmti_state();
2056     // Cache DTrace flags
2057     ci_env.cache_dtrace_flags();
2058 
2059     // Switch back to VM state to do compiler initialization
2060     ThreadInVMfromNative tv(thread);
2061 
2062     // Perform per-thread and global initializations
2063     {
2064       MutexLocker only_one (thread, CompileThread_lock);
2065       SCCache::init_table();
2066     }
2067     comp->initialize();
2068   }
2069 
2070   if (comp->is_failed()) {
2071     disable_compilation_forever();
2072     // If compiler initialization failed, no compiler thread that is specific to a
2073     // particular compiler runtime will ever start to compile methods.
2074     shutdown_compiler_runtime(comp, thread);
2075     return false;
2076   }
2077 
2078   // C1 specific check
2079   if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
2080     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
2081     return false;
2082   }
2083 
2084   return true;
2085 }
2086 
2087 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
2088   BufferBlob* blob = thread->get_buffer_blob();
2089   if (blob != nullptr) {
2090     blob->purge();
2091     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2092     CodeCache::free(blob);
2093   }
2094 }
2095 
2096 /**
2097  * If C1 and/or C2 initialization failed, we shut down all compilation.
2098  * We do this to keep things simple. This can be changed if it ever turns
2099  * out to be a problem.
2100  */
2101 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
2102   free_buffer_blob_if_allocated(thread);
2103 
2104   log_info(compilation)("shutdown_compiler_runtime: " INTPTR_FORMAT, p2i(thread));
2105 
2106   if (comp->should_perform_shutdown()) {
2107     // There are two reasons for shutting down the compiler
2108     // 1) compiler runtime initialization failed
2109     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
2110     warning("%s initialization failed. Shutting down all compilers", comp->name());
2111 
2112     // Only one thread per compiler runtime object enters here
2113     // Set state to shut down
2114     comp->set_shut_down();
2115 
2116     // Delete all queued compilation tasks to make compiler threads exit faster.
2117     if (_c1_compile_queue != nullptr) {
2118       _c1_compile_queue->free_all();
2119     }
2120 
2121     if (_c2_compile_queue != nullptr) {
2122       _c2_compile_queue->free_all();
2123     }
2124 
2125     if (_c3_compile_queue != nullptr) {
2126       _c3_compile_queue->free_all();
2127     }
2128 
2129     // Set flags so that we continue execution with using interpreter only.
2130     UseCompiler    = false;
2131     UseInterpreter = true;
2132 
2133     // We could delete compiler runtimes also. However, there are references to
2134     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
2135     // fail. This can be done later if necessary.
2136   }
2137 }
2138 
2139 /**
2140  * Helper function to create new or reuse old CompileLog.
2141  */
2142 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
2143   if (!LogCompilation) return nullptr;
2144 
2145   AbstractCompiler *compiler = ct->compiler();
2146   bool jvmci = JVMCI_ONLY( compiler->is_jvmci() ||) false;
2147   bool c1 = compiler->is_c1();
2148   jobject* compiler_objects = c1 ? _compiler1_objects : (_c3_count == 0 ? _compiler2_objects : (jvmci ? _compiler2_objects : _compiler3_objects));
2149   assert(compiler_objects != nullptr, "must be initialized at this point");
2150   CompileLog** logs = c1 ? _compiler1_logs : (_c3_count == 0 ? _compiler2_logs : (jvmci ? _compiler2_logs : _compiler3_logs));
2151   assert(logs != nullptr, "must be initialized at this point");
2152   int count = c1 ? _c1_count : (_c3_count == 0 ? _c2_count : (jvmci ? _c2_count : _c3_count));
2153 
2154   if (ct->queue() == _sc1_compile_queue || ct->queue() == _sc2_compile_queue) {
2155     compiler_objects = _sc_objects;
2156     logs  = _sc_logs;
2157     count = _sc_count;
2158   }
2159   // Find Compiler number by its threadObj.
2160   oop compiler_obj = ct->threadObj();
2161   int compiler_number = 0;
2162   bool found = false;
2163   for (; compiler_number < count; compiler_number++) {
2164     if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
2165       found = true;
2166       break;
2167     }
2168   }
2169   assert(found, "Compiler must exist at this point");
2170 
2171   // Determine pointer for this thread's log.
2172   CompileLog** log_ptr = &logs[compiler_number];
2173 
2174   // Return old one if it exists.
2175   CompileLog* log = *log_ptr;
2176   if (log != nullptr) {
2177     ct->init_log(log);
2178     return log;

2216     log->stamp();
2217     log->end_elem();
2218   }
2219 
2220   // If compiler thread/runtime initialization fails, exit the compiler thread
2221   if (!init_compiler_runtime()) {
2222     return;
2223   }
2224 
2225   thread->start_idle_timer();
2226 
2227   // Poll for new compilation tasks as long as the JVM runs. Compilation
2228   // should only be disabled if something went wrong while initializing the
2229   // compiler runtimes. This, in turn, should not happen. The only known case
2230   // when compiler runtime initialization fails is if there is not enough free
2231   // space in the code cache to generate the necessary stubs, etc.
2232   while (!is_compilation_disabled_forever()) {
2233     // We need this HandleMark to avoid leaking VM handles.
2234     HandleMark hm(thread);
2235 
2236     RecompilationPolicy::recompilation_step(RecompilationWorkUnitSize, thread);
2237 
2238     CompileTask* task = queue->get(thread);
2239 
2240     if (task == nullptr) {
2241       if (UseDynamicNumberOfCompilerThreads) {
2242         // Access compiler_count under lock to enforce consistency.
2243         MutexLocker only_one(CompileThread_lock);
2244         if (can_remove(thread, true)) {
2245           if (trace_compiler_threads()) {
2246             ResourceMark rm;
2247             stringStream msg;
2248             msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
2249                       thread->name(), thread->idle_time_millis());
2250             print_compiler_threads(msg);
2251           }
2252 
2253           // Notify compiler that the compiler thread is about to stop
2254           thread->compiler()->stopping_compiler_thread(thread);
2255 
2256           free_buffer_blob_if_allocated(thread);
2257           return; // Stop this thread.
2258         }
2259       }
2260     } else {
2261       // Assign the task to the current thread.  Mark this compilation
2262       // thread as active for the profiler.
2263       // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
2264       // occurs after fetching the compile task off the queue.
2265       CompileTaskWrapper ctw(task);
2266       methodHandle method(thread, task->method());
2267 
2268       // Never compile a method if breakpoints are present in it
2269       if (method()->number_of_breakpoints() == 0) {
2270         // Compile the method.
2271         if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
2272           invoke_compiler_on_method(task);
2273           thread->start_idle_timer();
2274         } else {
2275           // After compilation is disabled, remove remaining methods from queue
2276           method->clear_queued_for_compilation();
2277           method->set_pending_queue_processed(false);
2278           task->set_failure_reason("compilation is disabled");
2279         }
2280       } else {
2281         task->set_failure_reason("breakpoints are present");
2282       }
2283 
2284       if (UseDynamicNumberOfCompilerThreads) {
2285         possibly_add_compiler_threads(thread);
2286         assert(!thread->has_pending_exception(), "should have been handled");
2287       }
2288     }
2289   }
2290 
2291   // Shut down compiler runtime
2292   shutdown_compiler_runtime(thread->compiler(), thread);
2293 }
2294 
2295 // ------------------------------------------------------------------
2296 // CompileBroker::init_compiler_thread_log
2297 //

2589     }
2590     assert(thread->env() == &ci_env, "set by ci_env");
2591     // The thread-env() field is cleared in ~CompileTaskWrapper.
2592 
2593     // Cache Jvmti state
2594     bool method_is_old = ci_env.cache_jvmti_state();
2595 
2596     // Skip redefined methods
2597     if (method_is_old) {
2598       ci_env.record_method_not_compilable("redefined method", true);
2599     }
2600 
2601     // Cache DTrace flags
2602     ci_env.cache_dtrace_flags();
2603 
2604     ciMethod* target = ci_env.get_method_from_handle(target_handle);
2605 
2606     TraceTime t1("compilation", &time);
2607     EventCompilation event;
2608 
2609     bool install_code = true;
2610     if (comp == nullptr) {
2611       ci_env.record_method_not_compilable("no compiler");
2612     } else if (!ci_env.failing()) {
2613       if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2614         whitebox_lock_compilation();
2615       }
2616       if (StoreCachedCode && task->is_precompiled()) {
2617         install_code = false; // not suitable in the current context
2618       }
2619       comp->compile_method(&ci_env, target, osr_bci, install_code, directive);
2620 
2621       /* Repeat compilation without installing code for profiling purposes */
2622       int repeat_compilation_count = directive->RepeatCompilationOption;
2623       while (repeat_compilation_count > 0) {
2624         ResourceMark rm(thread);
2625         task->print_ul("NO CODE INSTALLED");
2626         comp->compile_method(&ci_env, target, osr_bci, false, directive);
2627         repeat_compilation_count--;
2628       }
2629     }
2630 
2631     DirectivesStack::release(directive);
2632 
2633     if (!ci_env.failing() && !task->is_success() && install_code) {
2634       assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2635       assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2636       // The compiler elected, without comment, not to register a result.
2637       // Do not attempt further compilations of this method.
2638       ci_env.record_method_not_compilable("compile failed");
2639     }
2640 
2641     // Copy this bit to the enclosing block:
2642     compilable = ci_env.compilable();
2643 
2644     if (ci_env.failing()) {
2645       // Duplicate the failure reason string, so that it outlives ciEnv
2646       failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2647       failure_reason_on_C_heap = true;
2648       retry_message = ci_env.retry_message();
2649       ci_env.report_failure(failure_reason);
2650     }
2651 
2652     if (ci_env.failing()) {
2653       handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2654     }
2655     if (event.should_commit()) {
2656       post_compilation_event(event, task);
2657     }
2658   }
2659 
2660   if (failure_reason != nullptr) {
2661     task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2662     if (CompilationLog::log() != nullptr) {
2663       CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2664     }
2665     if (PrintCompilation) {
2666       FormatBufferResource msg = retry_message != nullptr ?
2667         FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2668         FormatBufferResource("COMPILE SKIPPED: %s",      failure_reason);
2669       task->print(tty, msg);
2670     }
2671   }
2672 
2673   task->mark_finished(os::elapsed_counter());
2674 
2675   methodHandle method(thread, task->method());
2676 
2677   DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2678 
2679   collect_statistics(thread, time, task);
2680 
2681   if (PrintCompilation && PrintCompilation2) {
2682     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
2683     tty->print("%4d ", compile_id);    // print compilation number
2684     tty->print("%s ", (is_osr ? "%" : (task->is_scc() ? "A" : " ")));
2685     if (task->is_success()) {
2686       tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2687     }
2688     tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2689   }
2690 
2691   Log(compilation, codecache) log;
2692   if (log.is_debug()) {
2693     LogStream ls(log.debug());
2694     codecache_print(&ls, /* detailed= */ false);
2695   }
2696   if (PrintCodeCacheOnCompilation) {
2697     codecache_print(/* detailed= */ false);
2698   }
2699   // Disable compilation, if required.
2700   switch (compilable) {
2701   case ciEnv::MethodCompilable_never:
2702     if (is_osr)
2703       method->set_not_osr_compilable_quietly("MethodCompilable_never");
2704     else
2705       method->set_not_compilable_quietly("MethodCompilable_never");
2706     break;
2707   case ciEnv::MethodCompilable_not_at_tier:
2708     if (is_osr)
2709       method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2710     else
2711       method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2712     break;
2713   }
2714 
2715   // Note that the queued_for_compilation bits are cleared without
2716   // protection of a mutex. [They were set by the requester thread,
2717   // when adding the task to the compile queue -- at which time the
2718   // compile queue lock was held. Subsequently, we acquired the compile
2719   // queue lock to get this task off the compile queue; thus (to belabour
2720   // the point somewhat) our clearing of the bits must be occurring
2721   // only after the setting of the bits. See also 14012000 above.
2722   method->clear_queued_for_compilation();
2723   method->set_pending_queue_processed(false);
2724 
2725   if (PrintCompilation) {
2726     ResourceMark rm;
2727     task->print_tty();
2728   }
2729 }
2730 
2731 /**
2732  * The CodeCache is full. Print warning and disable compilation.
2733  * Schedule code cache cleaning so compilation can continue later.
2734  * This function needs to be called only from CodeCache::allocate(),
2735  * since we currently handle a full code cache uniformly.
2736  */
2737 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2738   UseInterpreter = true;
2739   if (UseCompiler || AlwaysCompileLoopMethods ) {
2740     if (xtty != nullptr) {
2741       stringStream s;
2742       // Dump code cache state into a buffer before locking the tty,
2743       // because log_state() will use locks causing lock conflicts.
2744       CodeCache::log_state(&s);
2745       // Lock to prevent tearing
2746       ttyLocker ttyl;
2747       xtty->begin_elem("code_cache_full");
2748       xtty->print("%s", s.freeze());

2821 // CompileBroker::collect_statistics
2822 //
2823 // Collect statistics about the compilation.
2824 
2825 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2826   bool success = task->is_success();
2827   methodHandle method (thread, task->method());
2828   int compile_id = task->compile_id();
2829   bool is_osr = (task->osr_bci() != standard_entry_bci);
2830   const int comp_level = task->comp_level();
2831   CompilerCounters* counters = thread->counters();
2832 
2833   MutexLocker locker(CompileStatistics_lock);
2834 
2835   // _perf variables are production performance counters which are
2836   // updated regardless of the setting of the CITime and CITimeEach flags
2837   //
2838 
2839   // account all time, including bailouts and failures in this counter;
2840   // C1 and C2 counters are counting both successful and unsuccessful compiles
2841   _t_total_compilation.add(&time);
2842 
2843   if (!success) {
2844     _total_bailout_count++;
2845     if (UsePerfData) {
2846       _perf_last_failed_method->set_value(counters->current_method());
2847       _perf_last_failed_type->set_value(counters->compile_type());
2848       _perf_total_bailout_count->inc();
2849     }
2850     _t_bailedout_compilation.add(&time);
2851 
2852     if (CITime || log_is_enabled(Info, init)) {
2853       CompilerStatistics* stats = nullptr;
2854       if (task->is_scc()) {
2855         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2856         stats = &_scc_stats_per_level[level];
2857       } else {
2858         stats = &_stats_per_level[comp_level-1];
2859       }
2860       stats->_bailout.update(time, 0);
2861     }
2862   } else if (!task->is_success()) {
2863     if (UsePerfData) {
2864       _perf_last_invalidated_method->set_value(counters->current_method());
2865       _perf_last_invalidated_type->set_value(counters->compile_type());
2866       _perf_total_invalidated_count->inc();
2867     }
2868     _total_invalidated_count++;
2869     _t_invalidated_compilation.add(&time);
2870 
2871     if (CITime || log_is_enabled(Info, init)) {
2872       CompilerStatistics* stats = nullptr;
2873       if (task->is_scc()) {
2874         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2875         stats = &_scc_stats_per_level[level];
2876       } else {
2877         stats = &_stats_per_level[comp_level-1];
2878       }
2879       stats->_invalidated.update(time, 0);
2880     }
2881   } else {
2882     // Compilation succeeded
2883 
2884     // update compilation ticks - used by the implementation of
2885     // java.lang.management.CompilationMXBean
2886     _perf_total_compilation->inc(time.ticks());
2887     _peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time;
2888 
2889     if (CITime || log_is_enabled(Info, init)) {
2890       int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2891       if (is_osr) {
2892         _t_osr_compilation.add(&time);
2893         _sum_osr_bytes_compiled += bytes_compiled;
2894       } else {
2895         _t_standard_compilation.add(&time);
2896         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2897       }
2898 
2899       // Collect statistic per compilation level
2900       if (task->is_scc()) {
2901         _scc_stats._standard.update(time, bytes_compiled);
2902         _scc_stats._nmethods_size += task->nm_total_size();
2903         _scc_stats._nmethods_code_size += task->nm_insts_size();
2904         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2905         CompilerStatistics* stats = &_scc_stats_per_level[level];
2906         stats->_standard.update(time, bytes_compiled);
2907         stats->_nmethods_size += task->nm_total_size();
2908         stats->_nmethods_code_size += task->nm_insts_size();
2909       } else if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2910         CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2911         if (is_osr) {
2912           stats->_osr.update(time, bytes_compiled);
2913         } else {
2914           stats->_standard.update(time, bytes_compiled);
2915         }
2916         stats->_nmethods_size += task->nm_total_size();
2917         stats->_nmethods_code_size += task->nm_insts_size();
2918       } else {
2919         assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2920       }
2921 
2922       // Collect statistic per compiler
2923       AbstractCompiler* comp = task->compiler();
2924       if (comp && !task->is_scc()) {
2925         CompilerStatistics* stats = comp->stats();
2926         if (is_osr) {
2927           stats->_osr.update(time, bytes_compiled);
2928         } else {
2929           stats->_standard.update(time, bytes_compiled);
2930         }
2931         stats->_nmethods_size += task->nm_total_size();
2932         stats->_nmethods_code_size += task->nm_insts_size();
2933       } else if (!task->is_scc()) { // if (!comp)
2934         assert(false, "Compiler object must exist");
2935       }
2936     }
2937 
2938     if (UsePerfData) {
2939       // save the name of the last method compiled
2940       _perf_last_method->set_value(counters->current_method());
2941       _perf_last_compile_type->set_value(counters->compile_type());
2942       _perf_last_compile_size->set_value(method->code_size() +
2943                                          task->num_inlined_bytecodes());
2944       if (is_osr) {
2945         _perf_osr_compilation->inc(time.ticks());
2946         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2947       } else {
2948         _perf_standard_compilation->inc(time.ticks());
2949         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2950       }
2951     }
2952 
2953     if (CITimeEach) {

2976       _total_standard_compile_count++;
2977     }
2978   }
2979   // set the current method for the thread to null
2980   if (UsePerfData) counters->set_current_method("");
2981 }
2982 
2983 const char* CompileBroker::compiler_name(int comp_level) {
2984   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2985   if (comp == nullptr) {
2986     return "no compiler";
2987   } else {
2988     return (comp->name());
2989   }
2990 }
2991 
2992 jlong CompileBroker::total_compilation_ticks() {
2993   return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2994 }
2995 
2996 void CompileBroker::log_not_entrant(nmethod* nm) {
2997   _total_not_entrant_count++;
2998   if (CITime || log_is_enabled(Info, init)) {
2999     CompilerStatistics* stats = nullptr;
3000     int level = nm->comp_level();
3001     if (nm->is_scc()) {
3002       if (nm->preloaded()) {
3003         assert(level == CompLevel_full_optimization, "%d", level);
3004         level = CompLevel_full_optimization + 1;
3005       }
3006       stats = &_scc_stats_per_level[level - 1];
3007     } else {
3008       stats = &_stats_per_level[level - 1];
3009     }
3010     stats->_made_not_entrant._count++;
3011   }
3012 }
3013 
3014 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
3015   tty->print_cr("  %s {speed: %6.3f bytes/s; standard: %6.3f s, %u bytes, %u methods; osr: %6.3f s, %u bytes, %u methods; nmethods_size: %u bytes; nmethods_code_size: %u bytes}",
3016                 name, stats->bytes_per_second(),
3017                 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
3018                 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
3019                 stats->_nmethods_size, stats->_nmethods_code_size);
3020 }
3021 
3022 static void print_helper(outputStream* st, const char* name, CompilerStatistics::Data data, bool print_time = true) {
3023   if (data._count > 0) {
3024     st->print("; %s: %4u methods", name, data._count);
3025     if (print_time) {
3026       st->print(" (in %.3fs)", data._time.seconds());
3027     }
3028   }
3029 }
3030 
3031 static void print_tier_helper(outputStream* st, const char* prefix, int tier, CompilerStatistics* stats) {
3032   st->print("    %s%d: %5u methods", prefix, tier, stats->_standard._count);
3033   if (stats->_standard._count > 0) {
3034     st->print(" (in %.3fs)", stats->_standard._time.seconds());
3035   }
3036   print_helper(st, "osr",     stats->_osr);
3037   print_helper(st, "bailout", stats->_bailout);
3038   print_helper(st, "invalid", stats->_invalidated);
3039   print_helper(st, "not_entrant", stats->_made_not_entrant, false);
3040   st->cr();
3041 }
3042 
3043 static void print_queue_info(outputStream* st, CompileQueue* queue) {
3044   if (queue != nullptr) {
3045     MutexLocker ml(queue->lock());
3046 
3047     uint  total_cnt = 0;
3048     uint active_cnt = 0;
3049     for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3050       guarantee(jt != nullptr, "");
3051       if (jt->is_Compiler_thread()) {
3052         CompilerThread* ct = (CompilerThread*)jt;
3053 
3054         guarantee(ct != nullptr, "");
3055         if (ct->queue() == queue) {
3056           ++total_cnt;
3057           CompileTask* task = ct->task();
3058           if (task != nullptr) {
3059             ++active_cnt;
3060           }
3061         }
3062       }
3063     }
3064 
3065     st->print("  %s (%d active / %d total threads): %u tasks",
3066               queue->name(), active_cnt, total_cnt, queue->size());
3067     if (queue->size() > 0) {
3068       uint counts[] = {0, 0, 0, 0, 0}; // T1 ... T5
3069       for (CompileTask* task = queue->first(); task != nullptr; task = task->next()) {
3070         int tier = task->comp_level();
3071         if (task->is_scc() && task->preload()) {
3072           assert(tier == CompLevel_full_optimization, "%d", tier);
3073           tier = CompLevel_full_optimization + 1;
3074         }
3075         counts[tier-1]++;
3076       }
3077       st->print(":");
3078       for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3079         uint cnt = counts[tier-1];
3080         if (cnt > 0) {
3081           st->print(" T%d: %u tasks;", tier, cnt);
3082         }
3083       }
3084     }
3085     st->cr();
3086 
3087 //    for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3088 //      guarantee(jt != nullptr, "");
3089 //      if (jt->is_Compiler_thread()) {
3090 //        CompilerThread* ct = (CompilerThread*)jt;
3091 //
3092 //        guarantee(ct != nullptr, "");
3093 //        if (ct->queue() == queue) {
3094 //          ResourceMark rm;
3095 //          CompileTask* task = ct->task();
3096 //          st->print("    %s: ", ct->name_raw());
3097 //          if (task != nullptr) {
3098 //            task->print(st, nullptr, true /*short_form*/, false /*cr*/);
3099 //          }
3100 //          st->cr();
3101 //        }
3102 //      }
3103 //    }
3104   }
3105 }
3106 void CompileBroker::print_statistics_on(outputStream* st) {
3107   st->print_cr("  Total: %u methods; %u bailouts, %u invalidated, %u non_entrant",
3108                _total_compile_count, _total_bailout_count, _total_invalidated_count, _total_not_entrant_count);
3109   for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3110     print_tier_helper(st, "Tier", tier, &_stats_per_level[tier-1]);
3111   }
3112   st->cr();
3113 
3114   if (LoadCachedCode || StoreCachedCode) {
3115     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3116       if (tier != CompLevel_full_profile) {
3117         print_tier_helper(st, "SC T", tier, &_scc_stats_per_level[tier - 1]);
3118       }
3119     }
3120     st->cr();
3121   }
3122 
3123   print_queue_info(st, _c1_compile_queue);
3124   print_queue_info(st, _c2_compile_queue);
3125   print_queue_info(st, _c3_compile_queue);
3126   print_queue_info(st, _sc1_compile_queue);
3127   print_queue_info(st, _sc2_compile_queue);
3128 }
3129 
3130 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
3131   if (per_compiler) {
3132     if (aggregate) {
3133       tty->cr();
3134       tty->print_cr("[%dms] Individual compiler times (for compiled methods only)", (int)tty->time_stamp().milliseconds());
3135       tty->print_cr("------------------------------------------------");
3136       tty->cr();
3137     }
3138     for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
3139       AbstractCompiler* comp = _compilers[i];
3140       if (comp != nullptr) {
3141         print_times(comp->name(), comp->stats());
3142       }
3143     }
3144     if (_scc_stats._standard._count > 0) {
3145       print_times("SC", &_scc_stats);
3146     }
3147     if (aggregate) {
3148       tty->cr();
3149       tty->print_cr("Individual compilation Tier times (for compiled methods only)");
3150       tty->print_cr("------------------------------------------------");
3151       tty->cr();
3152     }
3153     char tier_name[256];
3154     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3155       CompilerStatistics* stats = &_stats_per_level[tier-1];
3156       os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
3157       print_times(tier_name, stats);
3158     }
3159     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3160       CompilerStatistics* stats = &_scc_stats_per_level[tier-1];
3161       if (stats->_standard._bytes > 0) {
3162         os::snprintf_checked(tier_name, sizeof(tier_name), "SC T%d", tier);
3163         print_times(tier_name, stats);
3164       }
3165     }
3166   }
3167 
3168   if (!aggregate) {
3169     return;
3170   }
3171 
3172   elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
3173   elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
3174   elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
3175 
3176   uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
3177   uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
3178 
3179   uint standard_compile_count = CompileBroker::_total_standard_compile_count;
3180   uint osr_compile_count = CompileBroker::_total_osr_compile_count;
3181   uint total_compile_count = CompileBroker::_total_compile_count;
3182   uint total_bailout_count = CompileBroker::_total_bailout_count;
3183   uint total_invalidated_count = CompileBroker::_total_invalidated_count;
3184 
3185   uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;

3187 
3188   tty->cr();
3189   tty->print_cr("Accumulated compiler times");
3190   tty->print_cr("----------------------------------------------------------");
3191                //0000000000111111111122222222223333333333444444444455555555556666666666
3192                //0123456789012345678901234567890123456789012345678901234567890123456789
3193   tty->print_cr("  Total compilation time   : %7.3f s", total_compilation.seconds());
3194   tty->print_cr("    Standard compilation   : %7.3f s, Average : %2.3f s",
3195                 standard_compilation.seconds(),
3196                 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
3197   tty->print_cr("    Bailed out compilation : %7.3f s, Average : %2.3f s",
3198                 CompileBroker::_t_bailedout_compilation.seconds(),
3199                 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
3200   tty->print_cr("    On stack replacement   : %7.3f s, Average : %2.3f s",
3201                 osr_compilation.seconds(),
3202                 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
3203   tty->print_cr("    Invalidated            : %7.3f s, Average : %2.3f s",
3204                 CompileBroker::_t_invalidated_compilation.seconds(),
3205                 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
3206 
3207   if (StoreCachedCode || LoadCachedCode) { // Check flags because SC cache could be closed already
3208     tty->cr();
3209     SCCache::print_timers_on(tty);
3210   }
3211   AbstractCompiler *comp = compiler(CompLevel_simple);
3212   if (comp != nullptr) {
3213     tty->cr();
3214     comp->print_timers();
3215   }
3216   comp = compiler(CompLevel_full_optimization);
3217   if (comp != nullptr) {
3218     tty->cr();
3219     comp->print_timers();
3220   }
3221   comp = _compilers[2];
3222   if (comp != nullptr) {
3223     tty->cr();
3224     comp->print_timers();
3225   }
3226 #if INCLUDE_JVMCI
3227   if (EnableJVMCI) {
3228     JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
3229     if (jvmci_comp != nullptr && jvmci_comp != comp) {
3230       tty->cr();
3231       jvmci_comp->print_timers();
3232     }
3233   }
3234 #endif
3235 
3236   tty->cr();
3237   tty->print_cr("  Total compiled methods    : %8u methods", total_compile_count);
3238   tty->print_cr("    Standard compilation    : %8u methods", standard_compile_count);
3239   tty->print_cr("    On stack replacement    : %8u methods", osr_compile_count);
3240   uint tcb = osr_bytes_compiled + standard_bytes_compiled;
3241   tty->print_cr("  Total compiled bytecodes  : %8u bytes", tcb);
3242   tty->print_cr("    Standard compilation    : %8u bytes", standard_bytes_compiled);
3243   tty->print_cr("    On stack replacement    : %8u bytes", osr_bytes_compiled);
3244   double tcs = total_compilation.seconds();
3245   uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);
< prev index next >