1 /*
   2  * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/cdsConfig.hpp"
  27 #include "cds/classPreloader.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 "gc/shared/memAllocator.hpp"
  46 #include "interpreter/linkResolver.hpp"
  47 #include "jvm.h"
  48 #include "jfr/jfrEvents.hpp"
  49 #include "logging/log.hpp"
  50 #include "logging/logStream.hpp"
  51 #include "memory/allocation.inline.hpp"
  52 #include "memory/resourceArea.hpp"
  53 #include "memory/universe.hpp"
  54 #include "oops/methodData.hpp"
  55 #include "oops/method.inline.hpp"
  56 #include "oops/oop.inline.hpp"
  57 #include "prims/jvmtiExport.hpp"
  58 #include "prims/nativeLookup.hpp"
  59 #include "prims/whitebox.hpp"
  60 #include "runtime/atomic.hpp"
  61 #include "runtime/escapeBarrier.hpp"
  62 #include "runtime/globals_extension.hpp"
  63 #include "runtime/handles.inline.hpp"
  64 #include "runtime/init.hpp"
  65 #include "runtime/interfaceSupport.inline.hpp"
  66 #include "runtime/java.hpp"
  67 #include "runtime/javaCalls.hpp"
  68 #include "runtime/jniHandles.inline.hpp"
  69 #include "runtime/os.hpp"
  70 #include "runtime/perfData.hpp"
  71 #include "runtime/safepointVerifiers.hpp"
  72 #include "runtime/sharedRuntime.hpp"
  73 #include "runtime/threads.hpp"
  74 #include "runtime/threadSMR.inline.hpp"
  75 #include "runtime/timerTrace.hpp"
  76 #include "runtime/vframe.inline.hpp"
  77 #include "services/management.hpp"
  78 #include "utilities/debug.hpp"
  79 #include "utilities/dtrace.hpp"
  80 #include "utilities/events.hpp"
  81 #include "utilities/formatBuffer.hpp"
  82 #include "utilities/macros.hpp"
  83 #include "utilities/nonblockingQueue.inline.hpp"
  84 #ifdef COMPILER1
  85 #include "c1/c1_Compiler.hpp"
  86 #endif
  87 #ifdef COMPILER2
  88 #include "opto/c2compiler.hpp"
  89 #endif
  90 #if INCLUDE_JVMCI
  91 #include "jvmci/jvmciEnv.hpp"
  92 #include "jvmci/jvmciRuntime.hpp"
  93 #endif
  94 
  95 #ifdef DTRACE_ENABLED
  96 
  97 // Only bother with this argument setup if dtrace is available
  98 
  99 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
 100   {                                                                      \
 101     Symbol* klass_name = (method)->klass_name();                         \
 102     Symbol* name = (method)->name();                                     \
 103     Symbol* signature = (method)->signature();                           \
 104     HOTSPOT_METHOD_COMPILE_BEGIN(                                        \
 105       (char *) comp_name, strlen(comp_name),                             \
 106       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
 107       (char *) name->bytes(), name->utf8_length(),                       \
 108       (char *) signature->bytes(), signature->utf8_length());            \
 109   }
 110 
 111 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)      \
 112   {                                                                      \
 113     Symbol* klass_name = (method)->klass_name();                         \
 114     Symbol* name = (method)->name();                                     \
 115     Symbol* signature = (method)->signature();                           \
 116     HOTSPOT_METHOD_COMPILE_END(                                          \
 117       (char *) comp_name, strlen(comp_name),                             \
 118       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
 119       (char *) name->bytes(), name->utf8_length(),                       \
 120       (char *) signature->bytes(), signature->utf8_length(), (success)); \
 121   }
 122 
 123 #else //  ndef DTRACE_ENABLED
 124 
 125 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
 126 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
 127 
 128 #endif // ndef DTRACE_ENABLED
 129 
 130 bool CompileBroker::_initialized = false;
 131 bool CompileBroker::_replay_initialized = false;
 132 volatile bool CompileBroker::_should_block = false;
 133 volatile int  CompileBroker::_print_compilation_warning = 0;
 134 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
 135 
 136 // The installed compiler(s)
 137 AbstractCompiler* CompileBroker::_compilers[3];
 138 
 139 // The maximum numbers of compiler threads to be determined during startup.
 140 int CompileBroker::_c1_count = 0;
 141 int CompileBroker::_c2_count = 0;
 142 int CompileBroker::_c3_count = 0;
 143 int CompileBroker::_sc_count = 0;
 144 
 145 // An array of compiler names as Java String objects
 146 jobject* CompileBroker::_compiler1_objects = nullptr;
 147 jobject* CompileBroker::_compiler2_objects = nullptr;
 148 jobject* CompileBroker::_compiler3_objects = nullptr;
 149 jobject* CompileBroker::_sc_objects = nullptr;
 150 
 151 CompileLog** CompileBroker::_compiler1_logs = nullptr;
 152 CompileLog** CompileBroker::_compiler2_logs = nullptr;
 153 CompileLog** CompileBroker::_compiler3_logs = nullptr;
 154 CompileLog** CompileBroker::_sc_logs = nullptr;
 155 
 156 // These counters are used to assign an unique ID to each compilation.
 157 volatile jint CompileBroker::_compilation_id     = 0;
 158 volatile jint CompileBroker::_osr_compilation_id = 0;
 159 volatile jint CompileBroker::_native_compilation_id = 0;
 160 
 161 // Performance counters
 162 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
 163 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
 164 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
 165 
 166 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
 167 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
 168 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
 169 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
 170 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
 171 
 172 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
 173 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
 174 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
 175 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
 176 
 177 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
 178 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
 179 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
 180 PerfVariable*       CompileBroker::_perf_last_compile_type = nullptr;
 181 PerfVariable*       CompileBroker::_perf_last_compile_size = nullptr;
 182 PerfVariable*       CompileBroker::_perf_last_failed_type = nullptr;
 183 PerfVariable*       CompileBroker::_perf_last_invalidated_type = nullptr;
 184 
 185 // Timers and counters for generating statistics
 186 elapsedTimer CompileBroker::_t_total_compilation;
 187 elapsedTimer CompileBroker::_t_osr_compilation;
 188 elapsedTimer CompileBroker::_t_standard_compilation;
 189 elapsedTimer CompileBroker::_t_invalidated_compilation;
 190 elapsedTimer CompileBroker::_t_bailedout_compilation;
 191 
 192 uint CompileBroker::_total_bailout_count            = 0;
 193 uint CompileBroker::_total_invalidated_count        = 0;
 194 uint CompileBroker::_total_not_entrant_count        = 0;
 195 uint CompileBroker::_total_compile_count            = 0;
 196 uint CompileBroker::_total_osr_compile_count        = 0;
 197 uint CompileBroker::_total_standard_compile_count   = 0;
 198 uint CompileBroker::_total_compiler_stopped_count   = 0;
 199 uint CompileBroker::_total_compiler_restarted_count = 0;
 200 
 201 uint CompileBroker::_sum_osr_bytes_compiled         = 0;
 202 uint CompileBroker::_sum_standard_bytes_compiled    = 0;
 203 uint CompileBroker::_sum_nmethod_size               = 0;
 204 uint CompileBroker::_sum_nmethod_code_size          = 0;
 205 
 206 jlong CompileBroker::_peak_compilation_time        = 0;
 207 
 208 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];
 209 CompilerStatistics CompileBroker::_scc_stats;
 210 CompilerStatistics CompileBroker::_scc_stats_per_level[CompLevel_full_optimization + 1];
 211 
 212 CompileQueue* CompileBroker::_c3_compile_queue     = nullptr;
 213 CompileQueue* CompileBroker::_c2_compile_queue     = nullptr;
 214 CompileQueue* CompileBroker::_c1_compile_queue     = nullptr;
 215 CompileQueue* CompileBroker::_sc1_compile_queue    = nullptr;
 216 CompileQueue* CompileBroker::_sc2_compile_queue    = nullptr;
 217 
 218 bool compileBroker_init() {
 219   if (LogEvents) {
 220     CompilationLog::init();
 221   }
 222 
 223   // init directives stack, adding default directive
 224   DirectivesStack::init();
 225 
 226   if (DirectivesParser::has_file()) {
 227     return DirectivesParser::parse_from_flag();
 228   } else if (CompilerDirectivesPrint) {
 229     // Print default directive even when no other was added
 230     DirectivesStack::print(tty);
 231   }
 232 
 233   return true;
 234 }
 235 
 236 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
 237   CompilerThread* thread = CompilerThread::current();
 238   thread->set_task(task);
 239   CompileLog*     log  = thread->log();
 240   if (log != nullptr && !task->is_unloaded())  task->log_task_start(log);
 241 }
 242 
 243 CompileTaskWrapper::~CompileTaskWrapper() {
 244   CompilerThread* thread = CompilerThread::current();
 245   CompileTask* task = thread->task();
 246   CompileLog*  log  = thread->log();
 247   AbstractCompiler* comp = thread->compiler();
 248   if (log != nullptr && !task->is_unloaded())  task->log_task_done(log);
 249   thread->set_task(nullptr);
 250   thread->set_env(nullptr);
 251   if (task->is_blocking()) {
 252     bool free_task = false;
 253     {
 254       MutexLocker notifier(thread, task->lock());
 255       task->mark_complete();
 256 #if INCLUDE_JVMCI
 257       if (comp->is_jvmci()) {
 258         if (!task->has_waiter()) {
 259           // The waiting thread timed out and thus did not free the task.
 260           free_task = true;
 261         }
 262         task->set_blocking_jvmci_compile_state(nullptr);
 263       }
 264 #endif
 265       if (!free_task) {
 266         // Notify the waiting thread that the compilation has completed
 267         // so that it can free the task.
 268         task->lock()->notify_all();
 269       }
 270     }
 271     if (free_task) {
 272       // The task can only be freed once the task lock is released.
 273       CompileTask::free(task);
 274     }
 275   } else {
 276     task->mark_complete();
 277 
 278     // By convention, the compiling thread is responsible for
 279     // recycling a non-blocking CompileTask.
 280     CompileTask::free(task);
 281   }
 282 }
 283 
 284 /**
 285  * Check if a CompilerThread can be removed and update count if requested.
 286  */
 287 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
 288   assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
 289   if (!ReduceNumberOfCompilerThreads) return false;
 290 
 291   if (CompilationPolicy::have_recompilation_work()) return false;
 292 
 293   AbstractCompiler *compiler = ct->compiler();
 294   int compiler_count = compiler->num_compiler_threads();
 295   bool c1 = compiler->is_c1();
 296 
 297   // Keep at least 1 compiler thread of each type.
 298   if (compiler_count < 2) return false;
 299 
 300   // Keep thread alive for at least some time.
 301   if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
 302 
 303 #if INCLUDE_JVMCI
 304   if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 305     // Handles for JVMCI thread objects may get released concurrently.
 306     if (do_it) {
 307       assert(CompileThread_lock->owner() == ct, "must be holding lock");
 308     } else {
 309       // Skip check if it's the last thread and let caller check again.
 310       return true;
 311     }
 312   }
 313 #endif
 314 
 315   // We only allow the last compiler thread of each type to get removed.
 316   jobject last_compiler = c1 ? compiler1_object(compiler_count - 1)
 317                              : compiler2_object(compiler_count - 1);
 318   if (ct->threadObj() == JNIHandles::resolve_non_null(last_compiler)) {
 319     if (do_it) {
 320       assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
 321       compiler->set_num_compiler_threads(compiler_count - 1);
 322 #if INCLUDE_JVMCI
 323       if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 324         // Old j.l.Thread object can die when no longer referenced elsewhere.
 325         JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
 326         _compiler2_objects[compiler_count - 1] = nullptr;
 327       }
 328 #endif
 329     }
 330     return true;
 331   }
 332   return false;
 333 }
 334 
 335 /**
 336  * Add a CompileTask to a CompileQueue.
 337  */
 338 void CompileQueue::add(CompileTask* task) {
 339   assert(_lock->owned_by_self(), "must own lock");
 340 
 341   task->set_next(nullptr);
 342   task->set_prev(nullptr);
 343 
 344   if (_last == nullptr) {
 345     // The compile queue is empty.
 346     assert(_first == nullptr, "queue is empty");
 347     _first = task;
 348     _last = task;
 349   } else {
 350     // Append the task to the queue.
 351     assert(_last->next() == nullptr, "not last");
 352     _last->set_next(task);
 353     task->set_prev(_last);
 354     _last = task;
 355   }
 356   ++_size;
 357   ++_total_added;
 358   if (_size > _peak_size) {
 359     _peak_size = _size;
 360   }
 361 
 362   // Mark the method as being in the compile queue.
 363   task->method()->set_queued_for_compilation();
 364 
 365   task->mark_queued(os::elapsed_counter());
 366 
 367   if (CIPrintCompileQueue) {
 368     print_tty();
 369   }
 370 
 371   if (LogCompilation && xtty != nullptr) {
 372     task->log_task_queued();
 373   }
 374 
 375   if (TrainingData::need_data() &&
 376       !CDSConfig::is_dumping_final_static_archive()) { // FIXME: !!! MetaspaceShared::preload_and_dump() temporarily enables RecordTraining !!!
 377     CompileTrainingData* tdata = CompileTrainingData::make(task);
 378     if (tdata != nullptr) {
 379       tdata->record_compilation_queued(task);
 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   CompilationPolicy::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 (CompilationPolicy::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 ? _sc2_compile_queue : _c2_compile_queue);
 612   if (is_c1_compile(comp_level)) return (is_scc ? _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());
 671   }
 672 }
 673 
 674 CompilerCounters::CompilerCounters() {
 675   _current_method[0] = '\0';
 676   _compile_type = CompileBroker::no_compile;
 677 }
 678 
 679 #if INCLUDE_JFR && COMPILER2_OR_JVMCI
 680 // It appends new compiler phase names to growable array phase_names(a new CompilerPhaseType mapping
 681 // in compiler/compilerEvent.cpp) and registers it with its serializer.
 682 //
 683 // c2 uses explicit CompilerPhaseType idToPhase mapping in opto/phasetype.hpp,
 684 // so if c2 is used, it should be always registered first.
 685 // This function is called during vm initialization.
 686 static void register_jfr_phasetype_serializer(CompilerType compiler_type) {
 687   ResourceMark rm;
 688   static bool first_registration = true;
 689   if (compiler_type == compiler_jvmci) {
 690     CompilerEvent::PhaseEvent::get_phase_id("NOT_A_PHASE_NAME", false, false, false);
 691     first_registration = false;
 692 #ifdef COMPILER2
 693   } else if (compiler_type == compiler_c2) {
 694     assert(first_registration, "invariant"); // c2 must be registered first.
 695     for (int i = 0; i < PHASE_NUM_TYPES; i++) {
 696       const char* phase_name = CompilerPhaseTypeHelper::to_description((CompilerPhaseType) i);
 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
 766 
 767 #if INCLUDE_JVMCI
 768    // Register after c2 registration.
 769    // JVMCI CompilerPhaseType idToPhase mapping is dynamic.
 770    if (EnableJVMCI) {
 771      JFR_ONLY(register_jfr_phasetype_serializer(compiler_jvmci);)
 772    }
 773 #endif // INCLUDE_JVMCI
 774 
 775   if (CompilerOracle::should_collect_memstat()) {
 776     CompilationMemoryStatistic::initialize();
 777   }
 778 
 779   // Start the compiler thread(s)
 780   init_compiler_threads();
 781   // totalTime performance counter is always created as it is required
 782   // by the implementation of java.lang.management.CompilationMXBean.
 783   {
 784     // Ensure OOM leads to vm_exit_during_initialization.
 785     EXCEPTION_MARK;
 786     _perf_total_compilation =
 787                  PerfDataManager::create_counter(JAVA_CI, "totalTime",
 788                                                  PerfData::U_Ticks, CHECK);
 789   }
 790 
 791   if (UsePerfData) {
 792 
 793     EXCEPTION_MARK;
 794 
 795     // create the jvmstat performance counters
 796     _perf_osr_compilation =
 797                  PerfDataManager::create_counter(SUN_CI, "osrTime",
 798                                                  PerfData::U_Ticks, CHECK);
 799 
 800     _perf_standard_compilation =
 801                  PerfDataManager::create_counter(SUN_CI, "standardTime",
 802                                                  PerfData::U_Ticks, CHECK);
 803 
 804     _perf_total_bailout_count =
 805                  PerfDataManager::create_counter(SUN_CI, "totalBailouts",
 806                                                  PerfData::U_Events, CHECK);
 807 
 808     _perf_total_invalidated_count =
 809                  PerfDataManager::create_counter(SUN_CI, "totalInvalidates",
 810                                                  PerfData::U_Events, CHECK);
 811 
 812     _perf_total_compile_count =
 813                  PerfDataManager::create_counter(SUN_CI, "totalCompiles",
 814                                                  PerfData::U_Events, CHECK);
 815     _perf_total_osr_compile_count =
 816                  PerfDataManager::create_counter(SUN_CI, "osrCompiles",
 817                                                  PerfData::U_Events, CHECK);
 818 
 819     _perf_total_standard_compile_count =
 820                  PerfDataManager::create_counter(SUN_CI, "standardCompiles",
 821                                                  PerfData::U_Events, CHECK);
 822 
 823     _perf_sum_osr_bytes_compiled =
 824                  PerfDataManager::create_counter(SUN_CI, "osrBytes",
 825                                                  PerfData::U_Bytes, CHECK);
 826 
 827     _perf_sum_standard_bytes_compiled =
 828                  PerfDataManager::create_counter(SUN_CI, "standardBytes",
 829                                                  PerfData::U_Bytes, CHECK);
 830 
 831     _perf_sum_nmethod_size =
 832                  PerfDataManager::create_counter(SUN_CI, "nmethodSize",
 833                                                  PerfData::U_Bytes, CHECK);
 834 
 835     _perf_sum_nmethod_code_size =
 836                  PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",
 837                                                  PerfData::U_Bytes, CHECK);
 838 
 839     _perf_last_method =
 840                  PerfDataManager::create_string_variable(SUN_CI, "lastMethod",
 841                                        CompilerCounters::cmname_buffer_length,
 842                                        "", CHECK);
 843 
 844     _perf_last_failed_method =
 845             PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",
 846                                        CompilerCounters::cmname_buffer_length,
 847                                        "", CHECK);
 848 
 849     _perf_last_invalidated_method =
 850         PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",
 851                                      CompilerCounters::cmname_buffer_length,
 852                                      "", CHECK);
 853 
 854     _perf_last_compile_type =
 855              PerfDataManager::create_variable(SUN_CI, "lastType",
 856                                               PerfData::U_None,
 857                                               (jlong)CompileBroker::no_compile,
 858                                               CHECK);
 859 
 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;
 913     {
 914       MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
 915       static int single_thread_count = 0;
 916       enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
 917     }
 918     if (enter_single_loop) {
 919       dt->deoptimize_objects_alot_loop_single();
 920     } else {
 921       dt->deoptimize_objects_alot_loop_all();
 922     }
 923   }
 924 
 925 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
 926 // barrier targets a single thread which is selected round robin.
 927 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_single() {
 928   HandleMark hm(this);
 929   while (true) {
 930     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *deoptee_thread = jtiwh.next(); ) {
 931       { // Begin new scope for escape barrier
 932         HandleMarkCleaner hmc(this);
 933         ResourceMark rm(this);
 934         EscapeBarrier eb(true, this, deoptee_thread);
 935         eb.deoptimize_objects(100);
 936       }
 937       // Now sleep after the escape barriers destructor resumed deoptee_thread.
 938       sleep(DeoptimizeObjectsALotInterval);
 939     }
 940   }
 941 }
 942 
 943 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
 944 // barrier targets all java threads in the vm at once.
 945 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_all() {
 946   HandleMark hm(this);
 947   while (true) {
 948     { // Begin new scope for escape barrier
 949       HandleMarkCleaner hmc(this);
 950       ResourceMark rm(this);
 951       EscapeBarrier eb(true, this);
 952       eb.deoptimize_objects_all_threads();
 953     }
 954     // Now sleep after the escape barriers destructor resumed the java threads.
 955     sleep(DeoptimizeObjectsALotInterval);
 956   }
 957 }
 958 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
 959 
 960 
 961 JavaThread* CompileBroker::make_thread(ThreadType type, jobject thread_handle, CompileQueue* queue, AbstractCompiler* comp, JavaThread* THREAD) {
 962   Handle thread_oop(THREAD, JNIHandles::resolve_non_null(thread_handle));
 963 
 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 
1007     // Note that we cannot call os::set_priority because it expects Java
1008     // priorities and we are *explicitly* using OS priorities so that it's
1009     // possible to set the compiler thread priority higher than any Java
1010     // thread.
1011 
1012     int native_prio = CompilerThreadPriority;
1013     if (native_prio == -1) {
1014       if (UseCriticalCompilerThreadPriority) {
1015         native_prio = os::java_to_os_priority[CriticalPriority];
1016       } else {
1017         native_prio = os::java_to_os_priority[NearMaxPriority];
1018       }
1019     }
1020     os::set_native_priority(new_thread, native_prio);
1021 
1022     // Note that this only sets the JavaThread _priority field, which by
1023     // definition is limited to Java priorities and not OS priorities.
1024     JavaThread::start_internal_daemon(THREAD, new_thread, thread_oop, NearMaxPriority);
1025 
1026   } else { // osthread initialization failure
1027     if (UseDynamicNumberOfCompilerThreads && type == compiler_t
1028         && comp->num_compiler_threads() > 0) {
1029       // The new thread is not known to Thread-SMR yet so we can just delete.
1030       delete new_thread;
1031       return nullptr;
1032     } else {
1033       vm_exit_during_initialization("java.lang.OutOfMemoryError",
1034                                     os::native_thread_creation_failed_msg());
1035     }
1036   }
1037 
1038   os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
1039 
1040   return new_thread;
1041 }
1042 
1043 static bool trace_compiler_threads() {
1044   LogTarget(Debug, jit, thread) lt;
1045   return TraceCompilerThreads || lt.is_enabled();
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   julong free_memory = os::free_memory();
1216   // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).
1217   size_t available_cc_np  = CodeCache::unallocated_capacity(CodeBlobType::MethodNonProfiled),
1218          available_cc_p   = CodeCache::unallocated_capacity(CodeBlobType::MethodProfiled);
1219 
1220   // Only do attempt to start additional threads if the lock is free.
1221   if (!CompileThread_lock->try_lock()) return;
1222 
1223   if (_c2_compile_queue != nullptr) {
1224     int old_c2_count = _compilers[1]->num_compiler_threads();
1225     int new_c2_count = MIN4(_c2_count,
1226         _c2_compile_queue->size() / 2,
1227         (int)(free_memory / (200*M)),
1228         (int)(available_cc_np / (128*K)));
1229 
1230     for (int i = old_c2_count; i < new_c2_count; i++) {
1231 #if INCLUDE_JVMCI
1232       if (UseJVMCICompiler && !UseJVMCINativeLibrary && _compiler2_objects[i] == nullptr) {
1233         // Native compiler threads as used in C1/C2 can reuse the j.l.Thread objects as their
1234         // existence is completely hidden from the rest of the VM (and those compiler threads can't
1235         // call Java code to do the creation anyway).
1236         //
1237         // For pure Java JVMCI we have to create new j.l.Thread objects as they are visible and we
1238         // can see unexpected thread lifecycle transitions if we bind them to new JavaThreads.  For
1239         // native library JVMCI it's preferred to use the C1/C2 strategy as this avoids unnecessary
1240         // coupling with Java.
1241         if (!THREAD->can_call_java()) break;
1242         char name_buffer[256];
1243         os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", _compilers[1]->name(), i);
1244         Handle thread_oop;
1245         {
1246           // We have to give up the lock temporarily for the Java calls.
1247           MutexUnlocker mu(CompileThread_lock);
1248           thread_oop = JavaThread::create_system_thread_object(name_buffer, THREAD);
1249         }
1250         if (HAS_PENDING_EXCEPTION) {
1251           if (trace_compiler_threads()) {
1252             ResourceMark rm;
1253             stringStream msg;
1254             msg.print_cr("JVMCI compiler thread creation failed:");
1255             PENDING_EXCEPTION->print_on(&msg);
1256             print_compiler_threads(msg);
1257           }
1258           CLEAR_PENDING_EXCEPTION;
1259           break;
1260         }
1261         // Check if another thread has beaten us during the Java calls.
1262         if (_compilers[1]->num_compiler_threads() != i) break;
1263         jobject thread_handle = JNIHandles::make_global(thread_oop);
1264         assert(compiler2_object(i) == nullptr, "Old one must be released!");
1265         _compiler2_objects[i] = thread_handle;
1266       }
1267 #endif
1268       guarantee(compiler2_object(i) != nullptr, "Thread oop must exist");
1269       JavaThread *ct = make_thread(compiler_t, compiler2_object(i), _c2_compile_queue, _compilers[1], THREAD);
1270       if (ct == nullptr) break;
1271       _compilers[1]->set_num_compiler_threads(i + 1);
1272       if (trace_compiler_threads()) {
1273         ResourceMark rm;
1274         ThreadsListHandle tlh;  // name() depends on the TLH.
1275         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1276         stringStream msg;
1277         msg.print("Added compiler thread %s (free memory: %dMB, available non-profiled code cache: %dMB)",
1278                   ct->name(), (int)(free_memory/M), (int)(available_cc_np/M));
1279         print_compiler_threads(msg);
1280       }
1281     }
1282   }
1283 
1284   if (_c1_compile_queue != nullptr) {
1285     int old_c1_count = _compilers[0]->num_compiler_threads();
1286     int new_c1_count = MIN4(_c1_count,
1287         _c1_compile_queue->size() / 4,
1288         (int)(free_memory / (100*M)),
1289         (int)(available_cc_p / (128*K)));
1290 
1291     for (int i = old_c1_count; i < new_c1_count; i++) {
1292       JavaThread *ct = make_thread(compiler_t, compiler1_object(i), _c1_compile_queue, _compilers[0], THREAD);
1293       if (ct == nullptr) break;
1294       _compilers[0]->set_num_compiler_threads(i + 1);
1295       if (trace_compiler_threads()) {
1296         ResourceMark rm;
1297         ThreadsListHandle tlh;  // name() depends on the TLH.
1298         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1299         stringStream msg;
1300         msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)",
1301                   ct->name(), (int)(free_memory/M), (int)(available_cc_p/M));
1302         print_compiler_threads(msg);
1303       }
1304     }
1305   }
1306 
1307   CompileThread_lock->unlock();
1308 }
1309 
1310 
1311 /**
1312  * Set the methods on the stack as on_stack so that redefine classes doesn't
1313  * reclaim them. This method is executed at a safepoint.
1314  */
1315 void CompileBroker::mark_on_stack() {
1316   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1317   // Since we are at a safepoint, we do not need a lock to access
1318   // the compile queues.
1319   if (_c3_compile_queue != nullptr) {
1320     _c3_compile_queue->mark_on_stack();
1321   }
1322   if (_c2_compile_queue != nullptr) {
1323     _c2_compile_queue->mark_on_stack();
1324   }
1325   if (_c1_compile_queue != nullptr) {
1326     _c1_compile_queue->mark_on_stack();
1327   }
1328   if (_sc1_compile_queue != nullptr) {
1329     _sc1_compile_queue->mark_on_stack();
1330   }
1331   if (_sc2_compile_queue != nullptr) {
1332     _sc2_compile_queue->mark_on_stack();
1333   }
1334 }
1335 
1336 // ------------------------------------------------------------------
1337 // CompileBroker::compile_method
1338 //
1339 // Request compilation of a method.
1340 void CompileBroker::compile_method_base(const methodHandle& method,
1341                                         int osr_bci,
1342                                         int comp_level,
1343                                         const methodHandle& hot_method,
1344                                         int hot_count,
1345                                         CompileTask::CompileReason compile_reason,
1346                                         bool requires_online_compilation,
1347                                         bool blocking,
1348                                         Thread* thread) {
1349   guarantee(!method->is_abstract(), "cannot compile abstract methods");
1350   assert(method->method_holder()->is_instance_klass(),
1351          "sanity check");
1352   assert(!method->method_holder()->is_not_initialized()   ||
1353          compile_reason == CompileTask::Reason_Preload    ||
1354          compile_reason == CompileTask::Reason_Precompile ||
1355          compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1356   assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1357 
1358   if (CIPrintRequests) {
1359     tty->print("request: ");
1360     method->print_short_name(tty);
1361     if (osr_bci != InvocationEntryBci) {
1362       tty->print(" osr_bci: %d", osr_bci);
1363     }
1364     tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1365     if (!hot_method.is_null()) {
1366       tty->print(" hot: ");
1367       if (hot_method() != method()) {
1368           hot_method->print_short_name(tty);
1369       } else {
1370         tty->print("yes");
1371       }
1372     }
1373     tty->cr();
1374   }
1375 
1376   // A request has been made for compilation.  Before we do any
1377   // real work, check to see if the method has been compiled
1378   // in the meantime with a definitive result.
1379   if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1380     return;
1381   }
1382 
1383 #ifndef PRODUCT
1384   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1385     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1386       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
1387       return;
1388     }
1389   }
1390 #endif
1391 
1392   // If this method is already in the compile queue, then
1393   // we do not block the current thread.
1394   if (compilation_is_in_queue(method)) {
1395     // We may want to decay our counter a bit here to prevent
1396     // multiple denied requests for compilation.  This is an
1397     // open compilation policy issue. Note: The other possibility,
1398     // in the case that this is a blocking compile request, is to have
1399     // all subsequent blocking requesters wait for completion of
1400     // ongoing compiles. Note that in this case we'll need a protocol
1401     // for freeing the associated compile tasks. [Or we could have
1402     // a single static monitor on which all these waiters sleep.]
1403     return;
1404   }
1405 
1406   // Tiered policy requires MethodCounters to exist before adding a method to
1407   // the queue. Create if we don't have them yet.
1408   if (compile_reason != CompileTask::Reason_Preload) {
1409     method->get_method_counters(thread);
1410   }
1411 
1412   SCCEntry* scc_entry = find_scc_entry(method, osr_bci, comp_level, compile_reason, requires_online_compilation);
1413   bool is_scc = (scc_entry != nullptr);
1414 
1415   // Outputs from the following MutexLocker block:
1416   CompileTask* task = nullptr;
1417   CompileQueue* queue;
1418 #if INCLUDE_JVMCI
1419   if (is_c2_compile(comp_level) && compiler2()->is_jvmci() && compiler3() != nullptr &&
1420       ((JVMCICompiler*)compiler2())->force_comp_at_level_simple(method)) {
1421     assert(_c3_compile_queue != nullptr, "sanity");
1422     queue = _c3_compile_queue; // JVMCI compiler's methods compilation
1423   } else
1424 #endif
1425   queue = compile_queue(comp_level, is_scc);
1426 
1427   // Acquire our lock.
1428   {
1429     ConditionalMutexLocker locker(thread, queue->lock(), !UseLockFreeCompileQueues);
1430 
1431     // Make sure the method has not slipped into the queues since
1432     // last we checked; note that those checks were "fast bail-outs".
1433     // Here we need to be more careful, see 14012000 below.
1434     if (compilation_is_in_queue(method)) {
1435       return;
1436     }
1437 
1438     // We need to check again to see if the compilation has
1439     // completed.  A previous compilation may have registered
1440     // some result.
1441     if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1442       return;
1443     }
1444 
1445     // We now know that this compilation is not pending, complete,
1446     // or prohibited.  Assign a compile_id to this compilation
1447     // and check to see if it is in our [Start..Stop) range.
1448     int compile_id = assign_compile_id(method, osr_bci);
1449     if (compile_id == 0) {
1450       // The compilation falls outside the allowed range.
1451       return;
1452     }
1453 
1454 #if INCLUDE_JVMCI
1455     if (UseJVMCICompiler && blocking) {
1456       // Don't allow blocking compiles for requests triggered by JVMCI.
1457       if (thread->is_Compiler_thread()) {
1458         blocking = false;
1459       }
1460 
1461       // In libjvmci, JVMCI initialization should not deadlock with other threads
1462       if (!UseJVMCINativeLibrary) {
1463         // Don't allow blocking compiles if inside a class initializer or while performing class loading
1464         vframeStream vfst(JavaThread::cast(thread));
1465         for (; !vfst.at_end(); vfst.next()) {
1466           if (vfst.method()->is_static_initializer() ||
1467               (vfst.method()->method_holder()->is_subclass_of(vmClasses::ClassLoader_klass()) &&
1468                   vfst.method()->name() == vmSymbols::loadClass_name())) {
1469             blocking = false;
1470             break;
1471           }
1472         }
1473 
1474         // Don't allow blocking compilation requests to JVMCI
1475         // if JVMCI itself is not yet initialized
1476         if (!JVMCI::is_compiler_initialized() && compiler(comp_level)->is_jvmci()) {
1477           blocking = false;
1478         }
1479       }
1480 
1481       // Don't allow blocking compilation requests if we are in JVMCIRuntime::shutdown
1482       // to avoid deadlock between compiler thread(s) and threads run at shutdown
1483       // such as the DestroyJavaVM thread.
1484       if (JVMCI::in_shutdown()) {
1485         blocking = false;
1486       }
1487     }
1488 #endif // INCLUDE_JVMCI
1489 
1490     // We will enter the compilation in the queue.
1491     // 14012000: Note that this sets the queued_for_compile bits in
1492     // the target method. We can now reason that a method cannot be
1493     // queued for compilation more than once, as follows:
1494     // Before a thread queues a task for compilation, it first acquires
1495     // the compile queue lock, then checks if the method's queued bits
1496     // are set or it has already been compiled. Thus there can not be two
1497     // instances of a compilation task for the same method on the
1498     // compilation queue. Consider now the case where the compilation
1499     // thread has already removed a task for that method from the queue
1500     // and is in the midst of compiling it. In this case, the
1501     // queued_for_compile bits must be set in the method (and these
1502     // will be visible to the current thread, since the bits were set
1503     // under protection of the compile queue lock, which we hold now.
1504     // When the compilation completes, the compiler thread first sets
1505     // the compilation result and then clears the queued_for_compile
1506     // bits. Neither of these actions are protected by a barrier (or done
1507     // under the protection of a lock), so the only guarantee we have
1508     // (on machines with TSO (Total Store Order)) is that these values
1509     // will update in that order. As a result, the only combinations of
1510     // these bits that the current thread will see are, in temporal order:
1511     // <RESULT, QUEUE> :
1512     //     <0, 1> : in compile queue, but not yet compiled
1513     //     <1, 1> : compiled but queue bit not cleared
1514     //     <1, 0> : compiled and queue bit cleared
1515     // Because we first check the queue bits then check the result bits,
1516     // we are assured that we cannot introduce a duplicate task.
1517     // Note that if we did the tests in the reverse order (i.e. check
1518     // result then check queued bit), we could get the result bit before
1519     // the compilation completed, and the queue bit after the compilation
1520     // completed, and end up introducing a "duplicate" (redundant) task.
1521     // In that case, the compiler thread should first check if a method
1522     // has already been compiled before trying to compile it.
1523     // NOTE: in the event that there are multiple compiler threads and
1524     // there is de-optimization/recompilation, things will get hairy,
1525     // and in that case it's best to protect both the testing (here) of
1526     // these bits, and their updating (here and elsewhere) under a
1527     // common lock.
1528     task = create_compile_task(queue,
1529                                compile_id, method,
1530                                osr_bci, comp_level,
1531                                hot_method, hot_count, scc_entry, compile_reason,
1532                                requires_online_compilation, blocking);
1533 
1534     if (task->is_scc() && (_sc_count > 0)) {
1535       // Put it on SC queue
1536       queue = is_c1_compile(comp_level) ? _sc1_compile_queue : _sc2_compile_queue;
1537     }
1538 
1539     if (UseLockFreeCompileQueues) {
1540       assert(queue->lock()->owned_by_self() == false, "");
1541       queue->add_pending(task);
1542     } else {
1543       queue->add(task);
1544     }
1545   }
1546 
1547   if (blocking) {
1548     wait_for_completion(task);
1549   }
1550 }
1551 
1552 SCCEntry* CompileBroker::find_scc_entry(const methodHandle& method, int osr_bci, int comp_level,
1553                                         CompileTask::CompileReason compile_reason,
1554                                         bool requires_online_compilation) {
1555   SCCEntry* scc_entry = nullptr;
1556   if (_sc_count > 0 && osr_bci == InvocationEntryBci && !requires_online_compilation && SCCache::is_on_for_read()) {
1557     // Check for cached code.
1558     if (compile_reason == CompileTask::Reason_Preload) {
1559       scc_entry = method->scc_entry();
1560       assert(scc_entry != nullptr && scc_entry->for_preload(), "sanity");
1561     } else {
1562       scc_entry = SCCache::find_code_entry(method, comp_level);
1563     }
1564   }
1565   return scc_entry;
1566 }
1567 
1568 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1569                                        int comp_level,
1570                                        const methodHandle& hot_method, int hot_count,
1571                                        bool requires_online_compilation,
1572                                        CompileTask::CompileReason compile_reason,
1573                                        TRAPS) {
1574   // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1575   if (!_initialized || comp_level == CompLevel_none) {
1576     return nullptr;
1577   }
1578 
1579 #if INCLUDE_JVMCI
1580   if (EnableJVMCI && UseJVMCICompiler &&
1581       comp_level == CompLevel_full_optimization && !ClassPreloader::class_preloading_finished()) {
1582     return nullptr;
1583   }
1584 #endif
1585 
1586   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1587   assert(comp != nullptr, "Ensure we have a compiler");
1588 
1589 #if INCLUDE_JVMCI
1590   if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1591     // JVMCI compilation is not yet initializable.
1592     return nullptr;
1593   }
1594 #endif
1595 
1596   DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1597   // CompileBroker::compile_method can trap and can have pending async exception.
1598   nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, requires_online_compilation, compile_reason, directive, THREAD);
1599   DirectivesStack::release(directive);
1600   return nm;
1601 }
1602 
1603 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1604                                          int comp_level,
1605                                          const methodHandle& hot_method, int hot_count,
1606                                          bool requires_online_compilation,
1607                                          CompileTask::CompileReason compile_reason,
1608                                          DirectiveSet* directive,
1609                                          TRAPS) {
1610 
1611   // make sure arguments make sense
1612   assert(method->method_holder()->is_instance_klass(), "not an instance method");
1613   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1614   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1615   assert(!method->method_holder()->is_not_initialized()   ||
1616          compile_reason == CompileTask::Reason_Preload    ||
1617          compile_reason == CompileTask::Reason_Precompile ||
1618          compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1619   // return quickly if possible
1620 
1621   if (PrecompileOnlyAndExit && !CompileTask::reason_is_precompiled(compile_reason)) {
1622     return nullptr;
1623   }
1624 
1625   // lock, make sure that the compilation
1626   // isn't prohibited in a straightforward way.
1627   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1628   if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1629     return nullptr;
1630   }
1631 
1632   if (osr_bci == InvocationEntryBci) {
1633     // standard compilation
1634     nmethod* method_code = method->code();
1635     if (method_code != nullptr) {
1636       if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1637         return method_code;
1638       }
1639     }
1640     if (method->is_not_compilable(comp_level)) {
1641       return nullptr;
1642     }
1643   } else {
1644     // osr compilation
1645     // We accept a higher level osr method
1646     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1647     if (nm != nullptr) return nm;
1648     if (method->is_not_osr_compilable(comp_level)) return nullptr;
1649   }
1650 
1651   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1652   // some prerequisites that are compiler specific
1653   if (compile_reason != CompileTask::Reason_Preload && (comp->is_c2() || comp->is_jvmci())) {
1654     InternalOOMEMark iom(THREAD);
1655     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1656     // Resolve all classes seen in the signature of the method
1657     // we are compiling.
1658     Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1659   }
1660 
1661   // If the method is native, do the lookup in the thread requesting
1662   // the compilation. Native lookups can load code, which is not
1663   // permitted during compilation.
1664   //
1665   // Note: A native method implies non-osr compilation which is
1666   //       checked with an assertion at the entry of this method.
1667   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1668     address adr = NativeLookup::lookup(method, THREAD);
1669     if (HAS_PENDING_EXCEPTION) {
1670       // In case of an exception looking up the method, we just forget
1671       // about it. The interpreter will kick-in and throw the exception.
1672       method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1673       CLEAR_PENDING_EXCEPTION;
1674       return nullptr;
1675     }
1676     assert(method->has_native_function(), "must have native code by now");
1677   }
1678 
1679   // RedefineClasses() has replaced this method; just return
1680   if (method->is_old()) {
1681     return nullptr;
1682   }
1683 
1684   // JVMTI -- post_compile_event requires jmethod_id() that may require
1685   // a lock the compiling thread can not acquire. Prefetch it here.
1686   if (JvmtiExport::should_post_compiled_method_load()) {
1687     method->jmethod_id();
1688   }
1689 
1690   // do the compilation
1691   if (method->is_native()) {
1692     if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1693 #if defined(X86) && !defined(ZERO)
1694       // The following native methods:
1695       //
1696       // java.lang.Float.intBitsToFloat
1697       // java.lang.Float.floatToRawIntBits
1698       // java.lang.Double.longBitsToDouble
1699       // java.lang.Double.doubleToRawLongBits
1700       //
1701       // are called through the interpreter even if interpreter native stubs
1702       // are not preferred (i.e., calling through adapter handlers is preferred).
1703       // The reason is that on x86_32 signaling NaNs (sNaNs) are not preserved
1704       // if the version of the methods from the native libraries is called.
1705       // As the interpreter and the C2-intrinsified version of the methods preserves
1706       // sNaNs, that would result in an inconsistent way of handling of sNaNs.
1707       if ((UseSSE >= 1 &&
1708           (method->intrinsic_id() == vmIntrinsics::_intBitsToFloat ||
1709            method->intrinsic_id() == vmIntrinsics::_floatToRawIntBits)) ||
1710           (UseSSE >= 2 &&
1711            (method->intrinsic_id() == vmIntrinsics::_longBitsToDouble ||
1712             method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) {
1713         return nullptr;
1714       }
1715 #endif // X86 && !ZERO
1716 
1717       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1718       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1719       //
1720       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1721       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1722       AdapterHandlerLibrary::create_native_wrapper(method);
1723     } else {
1724       return nullptr;
1725     }
1726   } else {
1727     // If the compiler is shut off due to code cache getting full
1728     // fail out now so blocking compiles dont hang the java thread
1729     if (!should_compile_new_jobs()) {
1730       return nullptr;
1731     }
1732     bool is_blocking = ReplayCompiles                                             ||
1733                        !directive->BackgroundCompilationOption                    ||
1734                        (compile_reason == CompileTask::Reason_Precompile)         ||
1735                        (compile_reason == CompileTask::Reason_PrecompileForPreload);
1736 	  compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, requires_online_compilation, is_blocking, THREAD);
1737   }
1738 
1739   // return requested nmethod
1740   // We accept a higher level osr method
1741   if (osr_bci == InvocationEntryBci) {
1742     return method->code();
1743   }
1744   return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1745 }
1746 
1747 
1748 // ------------------------------------------------------------------
1749 // CompileBroker::compilation_is_complete
1750 //
1751 // See if compilation of this method is already complete.
1752 bool CompileBroker::compilation_is_complete(Method*                    method,
1753                                             int                        osr_bci,
1754                                             int                        comp_level,
1755                                             bool                       online_only,
1756                                             CompileTask::CompileReason compile_reason) {
1757   if (compile_reason == CompileTask::Reason_Precompile ||
1758       compile_reason == CompileTask::Reason_PrecompileForPreload) {
1759     return false; // FIXME: any restrictions?
1760   }
1761   bool is_osr = (osr_bci != standard_entry_bci);
1762   if (is_osr) {
1763     if (method->is_not_osr_compilable(comp_level)) {
1764       return true;
1765     } else {
1766       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1767       return (result != nullptr);
1768     }
1769   } else {
1770     if (method->is_not_compilable(comp_level)) {
1771       return true;
1772     } else {
1773       nmethod* result = method->code();
1774       if (result == nullptr) {
1775         return false;
1776       }
1777       if (online_only && result->is_scc()) {
1778         return false;
1779       }
1780       bool same_level = (comp_level == result->comp_level());
1781       if (result->has_clinit_barriers()) {
1782         return !same_level; // Allow replace preloaded code with new code of the same level
1783       }
1784       return same_level;
1785     }
1786   }
1787 }
1788 
1789 
1790 /**
1791  * See if this compilation is already requested.
1792  *
1793  * Implementation note: there is only a single "is in queue" bit
1794  * for each method.  This means that the check below is overly
1795  * conservative in the sense that an osr compilation in the queue
1796  * will block a normal compilation from entering the queue (and vice
1797  * versa).  This can be remedied by a full queue search to disambiguate
1798  * cases.  If it is deemed profitable, this may be done.
1799  */
1800 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1801   return method->queued_for_compilation();
1802 }
1803 
1804 // ------------------------------------------------------------------
1805 // CompileBroker::compilation_is_prohibited
1806 //
1807 // See if this compilation is not allowed.
1808 bool CompileBroker::compilation_is_prohibited(const methodHandle& method, int osr_bci, int comp_level, bool excluded) {
1809   bool is_native = method->is_native();
1810   // Some compilers may not support the compilation of natives.
1811   AbstractCompiler *comp = compiler(comp_level);
1812   if (is_native && (!CICompileNatives || comp == nullptr)) {
1813     method->set_not_compilable_quietly("native methods not supported", comp_level);
1814     return true;
1815   }
1816 
1817   bool is_osr = (osr_bci != standard_entry_bci);
1818   // Some compilers may not support on stack replacement.
1819   if (is_osr && (!CICompileOSR || comp == nullptr)) {
1820     method->set_not_osr_compilable("OSR not supported", comp_level);
1821     return true;
1822   }
1823 
1824   // The method may be explicitly excluded by the user.
1825   double scale;
1826   if (excluded || (CompilerOracle::has_option_value(method, CompileCommandEnum::CompileThresholdScaling, scale) && scale == 0)) {
1827     bool quietly = CompilerOracle::be_quiet();
1828     if (PrintCompilation && !quietly) {
1829       // This does not happen quietly...
1830       ResourceMark rm;
1831       tty->print("### Excluding %s:%s",
1832                  method->is_native() ? "generation of native wrapper" : "compile",
1833                  (method->is_static() ? " static" : ""));
1834       method->print_short_name(tty);
1835       tty->cr();
1836     }
1837     method->set_not_compilable("excluded by CompileCommand", comp_level, !quietly);
1838   }
1839 
1840   return false;
1841 }
1842 
1843 /**
1844  * Generate serialized IDs for compilation requests. If certain debugging flags are used
1845  * and the ID is not within the specified range, the method is not compiled and 0 is returned.
1846  * The function also allows to generate separate compilation IDs for OSR compilations.
1847  */
1848 int CompileBroker::assign_compile_id(const methodHandle& method, int osr_bci) {
1849 #ifdef ASSERT
1850   bool is_osr = (osr_bci != standard_entry_bci);
1851   int id;
1852   if (method->is_native()) {
1853     assert(!is_osr, "can't be osr");
1854     // Adapters, native wrappers and method handle intrinsics
1855     // should be generated always.
1856     return Atomic::add(CICountNative ? &_native_compilation_id : &_compilation_id, 1);
1857   } else if (CICountOSR && is_osr) {
1858     id = Atomic::add(&_osr_compilation_id, 1);
1859     if (CIStartOSR <= id && id < CIStopOSR) {
1860       return id;
1861     }
1862   } else {
1863     id = Atomic::add(&_compilation_id, 1);
1864     if (CIStart <= id && id < CIStop) {
1865       return id;
1866     }
1867   }
1868 
1869   // Method was not in the appropriate compilation range.
1870   method->set_not_compilable_quietly("Not in requested compile id range");
1871   return 0;
1872 #else
1873   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1874   // only _compilation_id is incremented.
1875   return Atomic::add(&_compilation_id, 1);
1876 #endif
1877 }
1878 
1879 // ------------------------------------------------------------------
1880 // CompileBroker::assign_compile_id_unlocked
1881 //
1882 // Public wrapper for assign_compile_id that acquires the needed locks
1883 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1884   return assign_compile_id(method, osr_bci);
1885 }
1886 
1887 // ------------------------------------------------------------------
1888 // CompileBroker::create_compile_task
1889 //
1890 // Create a CompileTask object representing the current request for
1891 // compilation.  Add this task to the queue.
1892 CompileTask* CompileBroker::create_compile_task(CompileQueue*       queue,
1893                                                 int                 compile_id,
1894                                                 const methodHandle& method,
1895                                                 int                 osr_bci,
1896                                                 int                 comp_level,
1897                                                 const methodHandle& hot_method,
1898                                                 int                 hot_count,
1899                                                 SCCEntry*           scc_entry,
1900                                                 CompileTask::CompileReason compile_reason,
1901                                                 bool                requires_online_compilation,
1902                                                 bool                blocking) {
1903   CompileTask* new_task = CompileTask::allocate();
1904   new_task->initialize(compile_id, method, osr_bci, comp_level,
1905                        hot_method, hot_count, scc_entry, compile_reason, queue,
1906                        requires_online_compilation, blocking);
1907   return new_task;
1908 }
1909 
1910 #if INCLUDE_JVMCI
1911 // The number of milliseconds to wait before checking if
1912 // JVMCI compilation has made progress.
1913 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1914 
1915 // The number of JVMCI compilation progress checks that must fail
1916 // before unblocking a thread waiting for a blocking compilation.
1917 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1918 
1919 /**
1920  * Waits for a JVMCI compiler to complete a given task. This thread
1921  * waits until either the task completes or it sees no JVMCI compilation
1922  * progress for N consecutive milliseconds where N is
1923  * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1924  * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1925  *
1926  * @return true if this thread needs to free/recycle the task
1927  */
1928 bool CompileBroker::wait_for_jvmci_completion(JVMCICompiler* jvmci, CompileTask* task, JavaThread* thread) {
1929   assert(UseJVMCICompiler, "sanity");
1930   MonitorLocker ml(thread, task->lock());
1931   int progress_wait_attempts = 0;
1932   jint thread_jvmci_compilation_ticks = 0;
1933   jint global_jvmci_compilation_ticks = jvmci->global_compilation_ticks();
1934   while (!task->is_complete() && !is_compilation_disabled_forever() &&
1935          ml.wait(JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE)) {
1936     JVMCICompileState* jvmci_compile_state = task->blocking_jvmci_compile_state();
1937 
1938     bool progress;
1939     if (jvmci_compile_state != nullptr) {
1940       jint ticks = jvmci_compile_state->compilation_ticks();
1941       progress = (ticks - thread_jvmci_compilation_ticks) != 0;
1942       JVMCI_event_1("waiting on compilation %d [ticks=%d]", task->compile_id(), ticks);
1943       thread_jvmci_compilation_ticks = ticks;
1944     } else {
1945       // Still waiting on JVMCI compiler queue. This thread may be holding a lock
1946       // that all JVMCI compiler threads are blocked on. We use the global JVMCI
1947       // compilation ticks to determine whether JVMCI compilation
1948       // is still making progress through the JVMCI compiler queue.
1949       jint ticks = jvmci->global_compilation_ticks();
1950       progress = (ticks - global_jvmci_compilation_ticks) != 0;
1951       JVMCI_event_1("waiting on compilation %d to be queued [ticks=%d]", task->compile_id(), ticks);
1952       global_jvmci_compilation_ticks = ticks;
1953     }
1954 
1955     if (!progress) {
1956       if (++progress_wait_attempts == JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS) {
1957         if (PrintCompilation) {
1958           task->print(tty, "wait for blocking compilation timed out");
1959         }
1960         JVMCI_event_1("waiting on compilation %d timed out", task->compile_id());
1961         break;
1962       }
1963     } else {
1964       progress_wait_attempts = 0;
1965     }
1966   }
1967   task->clear_waiter();
1968   return task->is_complete();
1969 }
1970 #endif
1971 
1972 /**
1973  *  Wait for the compilation task to complete.
1974  */
1975 void CompileBroker::wait_for_completion(CompileTask* task) {
1976   if (CIPrintCompileQueue) {
1977     ttyLocker ttyl;
1978     tty->print_cr("BLOCKING FOR COMPILE");
1979   }
1980 
1981   assert(task->is_blocking(), "can only wait on blocking task");
1982 
1983   JavaThread* thread = JavaThread::current();
1984 
1985   methodHandle method(thread, task->method());
1986   bool free_task;
1987 #if INCLUDE_JVMCI
1988   AbstractCompiler* comp = compiler(task->comp_level());
1989   if (!UseJVMCINativeLibrary && comp->is_jvmci() && !task->should_wait_for_compilation()) {
1990     // It may return before compilation is completed.
1991     // Note that libjvmci should not pre-emptively unblock
1992     // a thread waiting for a compilation as it does not call
1993     // Java code and so is not deadlock prone like jarjvmci.
1994     free_task = wait_for_jvmci_completion((JVMCICompiler*) comp, task, thread);
1995   } else
1996 #endif
1997   {
1998     MonitorLocker ml(thread, task->lock());
1999     free_task = true;
2000     while (!task->is_complete() && !is_compilation_disabled_forever()) {
2001       ml.wait();
2002     }
2003   }
2004 
2005   if (free_task) {
2006     if (is_compilation_disabled_forever()) {
2007       CompileTask::free(task);
2008       return;
2009     }
2010 
2011     // It is harmless to check this status without the lock, because
2012     // completion is a stable property (until the task object is recycled).
2013     assert(task->is_complete(), "Compilation should have completed");
2014 
2015     // By convention, the waiter is responsible for recycling a
2016     // blocking CompileTask. Since there is only one waiter ever
2017     // waiting on a CompileTask, we know that no one else will
2018     // be using this CompileTask; we can free it.
2019     CompileTask::free(task);
2020   }
2021 }
2022 
2023 /**
2024  * Initialize compiler thread(s) + compiler object(s). The postcondition
2025  * of this function is that the compiler runtimes are initialized and that
2026  * compiler threads can start compiling.
2027  */
2028 bool CompileBroker::init_compiler_runtime() {
2029   CompilerThread* thread = CompilerThread::current();
2030   AbstractCompiler* comp = thread->compiler();
2031   // Final sanity check - the compiler object must exist
2032   guarantee(comp != nullptr, "Compiler object must exist");
2033 
2034   {
2035     // Must switch to native to allocate ci_env
2036     ThreadToNativeFromVM ttn(thread);
2037     ciEnv ci_env((CompileTask*)nullptr);
2038     // Cache Jvmti state
2039     ci_env.cache_jvmti_state();
2040     // Cache DTrace flags
2041     ci_env.cache_dtrace_flags();
2042 
2043     // Switch back to VM state to do compiler initialization
2044     ThreadInVMfromNative tv(thread);
2045 
2046     // Perform per-thread and global initializations
2047     {
2048       MutexLocker only_one (thread, CompileThread_lock);
2049       SCCache::init_table();
2050     }
2051     comp->initialize();
2052   }
2053 
2054   if (comp->is_failed()) {
2055     disable_compilation_forever();
2056     // If compiler initialization failed, no compiler thread that is specific to a
2057     // particular compiler runtime will ever start to compile methods.
2058     shutdown_compiler_runtime(comp, thread);
2059     return false;
2060   }
2061 
2062   // C1 specific check
2063   if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
2064     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
2065     return false;
2066   }
2067 
2068   return true;
2069 }
2070 
2071 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
2072   BufferBlob* blob = thread->get_buffer_blob();
2073   if (blob != nullptr) {
2074     blob->purge();
2075     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2076     CodeCache::free(blob);
2077   }
2078 }
2079 
2080 /**
2081  * If C1 and/or C2 initialization failed, we shut down all compilation.
2082  * We do this to keep things simple. This can be changed if it ever turns
2083  * out to be a problem.
2084  */
2085 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
2086   free_buffer_blob_if_allocated(thread);
2087 
2088   log_info(compilation)("shutdown_compiler_runtime: " INTPTR_FORMAT, p2i(thread));
2089 
2090   if (comp->should_perform_shutdown()) {
2091     // There are two reasons for shutting down the compiler
2092     // 1) compiler runtime initialization failed
2093     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
2094     warning("%s initialization failed. Shutting down all compilers", comp->name());
2095 
2096     // Only one thread per compiler runtime object enters here
2097     // Set state to shut down
2098     comp->set_shut_down();
2099 
2100     // Delete all queued compilation tasks to make compiler threads exit faster.
2101     if (_c1_compile_queue != nullptr) {
2102       _c1_compile_queue->free_all();
2103     }
2104 
2105     if (_c2_compile_queue != nullptr) {
2106       _c2_compile_queue->free_all();
2107     }
2108 
2109     if (_c3_compile_queue != nullptr) {
2110       _c3_compile_queue->free_all();
2111     }
2112 
2113     // Set flags so that we continue execution with using interpreter only.
2114     UseCompiler    = false;
2115     UseInterpreter = true;
2116 
2117     // We could delete compiler runtimes also. However, there are references to
2118     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
2119     // fail. This can be done later if necessary.
2120   }
2121 }
2122 
2123 /**
2124  * Helper function to create new or reuse old CompileLog.
2125  */
2126 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
2127   if (!LogCompilation) return nullptr;
2128 
2129   AbstractCompiler *compiler = ct->compiler();
2130   bool jvmci = JVMCI_ONLY( compiler->is_jvmci() ||) false;
2131   bool c1 = compiler->is_c1();
2132   jobject* compiler_objects = c1 ? _compiler1_objects : (_c3_count == 0 ? _compiler2_objects : (jvmci ? _compiler2_objects : _compiler3_objects));
2133   assert(compiler_objects != nullptr, "must be initialized at this point");
2134   CompileLog** logs = c1 ? _compiler1_logs : (_c3_count == 0 ? _compiler2_logs : (jvmci ? _compiler2_logs : _compiler3_logs));
2135   assert(logs != nullptr, "must be initialized at this point");
2136   int count = c1 ? _c1_count : (_c3_count == 0 ? _c2_count : (jvmci ? _c2_count : _c3_count));
2137 
2138   if (ct->queue() == _sc1_compile_queue || ct->queue() == _sc2_compile_queue) {
2139     compiler_objects = _sc_objects;
2140     logs  = _sc_logs;
2141     count = _sc_count;
2142   }
2143   // Find Compiler number by its threadObj.
2144   oop compiler_obj = ct->threadObj();
2145   int compiler_number = 0;
2146   bool found = false;
2147   for (; compiler_number < count; compiler_number++) {
2148     if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
2149       found = true;
2150       break;
2151     }
2152   }
2153   assert(found, "Compiler must exist at this point");
2154 
2155   // Determine pointer for this thread's log.
2156   CompileLog** log_ptr = &logs[compiler_number];
2157 
2158   // Return old one if it exists.
2159   CompileLog* log = *log_ptr;
2160   if (log != nullptr) {
2161     ct->init_log(log);
2162     return log;
2163   }
2164 
2165   // Create a new one and remember it.
2166   init_compiler_thread_log();
2167   log = ct->log();
2168   *log_ptr = log;
2169   return log;
2170 }
2171 
2172 // ------------------------------------------------------------------
2173 // CompileBroker::compiler_thread_loop
2174 //
2175 // The main loop run by a CompilerThread.
2176 void CompileBroker::compiler_thread_loop() {
2177   CompilerThread* thread = CompilerThread::current();
2178   CompileQueue* queue = thread->queue();
2179   // For the thread that initializes the ciObjectFactory
2180   // this resource mark holds all the shared objects
2181   ResourceMark rm;
2182 
2183   // First thread to get here will initialize the compiler interface
2184 
2185   {
2186     ASSERT_IN_VM;
2187     MutexLocker only_one (thread, CompileThread_lock);
2188     if (!ciObjectFactory::is_initialized()) {
2189       ciObjectFactory::initialize();
2190     }
2191   }
2192 
2193   // Open a log.
2194   CompileLog* log = get_log(thread);
2195   if (log != nullptr) {
2196     log->begin_elem("start_compile_thread name='%s' thread='" UINTX_FORMAT "' process='%d'",
2197                     thread->name(),
2198                     os::current_thread_id(),
2199                     os::current_process_id());
2200     log->stamp();
2201     log->end_elem();
2202   }
2203 
2204   // If compiler thread/runtime initialization fails, exit the compiler thread
2205   if (!init_compiler_runtime()) {
2206     return;
2207   }
2208 
2209   thread->start_idle_timer();
2210 
2211   // Poll for new compilation tasks as long as the JVM runs. Compilation
2212   // should only be disabled if something went wrong while initializing the
2213   // compiler runtimes. This, in turn, should not happen. The only known case
2214   // when compiler runtime initialization fails is if there is not enough free
2215   // space in the code cache to generate the necessary stubs, etc.
2216   while (!is_compilation_disabled_forever()) {
2217     // We need this HandleMark to avoid leaking VM handles.
2218     HandleMark hm(thread);
2219 
2220     CompilationPolicy::recompilation_step(RecompilationWorkUnitSize, thread);
2221 
2222     CompileTask* task = queue->get(thread);
2223 
2224     if (task == nullptr) {
2225       if (UseDynamicNumberOfCompilerThreads) {
2226         // Access compiler_count under lock to enforce consistency.
2227         MutexLocker only_one(CompileThread_lock);
2228         if (can_remove(thread, true)) {
2229           if (trace_compiler_threads()) {
2230             ResourceMark rm;
2231             stringStream msg;
2232             msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
2233                       thread->name(), thread->idle_time_millis());
2234             print_compiler_threads(msg);
2235           }
2236 
2237           // Notify compiler that the compiler thread is about to stop
2238           thread->compiler()->stopping_compiler_thread(thread);
2239 
2240           free_buffer_blob_if_allocated(thread);
2241           return; // Stop this thread.
2242         }
2243       }
2244     } else {
2245       // Assign the task to the current thread.  Mark this compilation
2246       // thread as active for the profiler.
2247       // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
2248       // occurs after fetching the compile task off the queue.
2249       CompileTaskWrapper ctw(task);
2250       methodHandle method(thread, task->method());
2251 
2252       // Never compile a method if breakpoints are present in it
2253       if (method()->number_of_breakpoints() == 0) {
2254         // Compile the method.
2255         if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
2256           invoke_compiler_on_method(task);
2257           thread->start_idle_timer();
2258         } else {
2259           // After compilation is disabled, remove remaining methods from queue
2260           method->clear_queued_for_compilation();
2261           method->set_pending_queue_processed(false);
2262           task->set_failure_reason("compilation is disabled");
2263         }
2264       } else {
2265         task->set_failure_reason("breakpoints are present");
2266       }
2267 
2268       if (UseDynamicNumberOfCompilerThreads) {
2269         possibly_add_compiler_threads(thread);
2270         assert(!thread->has_pending_exception(), "should have been handled");
2271       }
2272     }
2273   }
2274 
2275   // Shut down compiler runtime
2276   shutdown_compiler_runtime(thread->compiler(), thread);
2277 }
2278 
2279 // ------------------------------------------------------------------
2280 // CompileBroker::init_compiler_thread_log
2281 //
2282 // Set up state required by +LogCompilation.
2283 void CompileBroker::init_compiler_thread_log() {
2284     CompilerThread* thread = CompilerThread::current();
2285     char  file_name[4*K];
2286     FILE* fp = nullptr;
2287     intx thread_id = os::current_thread_id();
2288     for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
2289       const char* dir = (try_temp_dir ? os::get_temp_directory() : nullptr);
2290       if (dir == nullptr) {
2291         jio_snprintf(file_name, sizeof(file_name), "hs_c" UINTX_FORMAT "_pid%u.log",
2292                      thread_id, os::current_process_id());
2293       } else {
2294         jio_snprintf(file_name, sizeof(file_name),
2295                      "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir,
2296                      os::file_separator(), thread_id, os::current_process_id());
2297       }
2298 
2299       fp = os::fopen(file_name, "wt");
2300       if (fp != nullptr) {
2301         if (LogCompilation && Verbose) {
2302           tty->print_cr("Opening compilation log %s", file_name);
2303         }
2304         CompileLog* log = new(mtCompiler) CompileLog(file_name, fp, thread_id);
2305         if (log == nullptr) {
2306           fclose(fp);
2307           return;
2308         }
2309         thread->init_log(log);
2310 
2311         if (xtty != nullptr) {
2312           ttyLocker ttyl;
2313           // Record any per thread log files
2314           xtty->elem("thread_logfile thread='" INTX_FORMAT "' filename='%s'", thread_id, file_name);
2315         }
2316         return;
2317       }
2318     }
2319     warning("Cannot open log file: %s", file_name);
2320 }
2321 
2322 void CompileBroker::log_metaspace_failure() {
2323   const char* message = "some methods may not be compiled because metaspace "
2324                         "is out of memory";
2325   if (CompilationLog::log() != nullptr) {
2326     CompilationLog::log()->log_metaspace_failure(message);
2327   }
2328   if (PrintCompilation) {
2329     tty->print_cr("COMPILE PROFILING SKIPPED: %s", message);
2330   }
2331 }
2332 
2333 
2334 // ------------------------------------------------------------------
2335 // CompileBroker::set_should_block
2336 //
2337 // Set _should_block.
2338 // Call this from the VM, with Threads_lock held and a safepoint requested.
2339 void CompileBroker::set_should_block() {
2340   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
2341   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
2342 #ifndef PRODUCT
2343   if (PrintCompilation && (Verbose || WizardMode))
2344     tty->print_cr("notifying compiler thread pool to block");
2345 #endif
2346   _should_block = true;
2347 }
2348 
2349 // ------------------------------------------------------------------
2350 // CompileBroker::maybe_block
2351 //
2352 // Call this from the compiler at convenient points, to poll for _should_block.
2353 void CompileBroker::maybe_block() {
2354   if (_should_block) {
2355 #ifndef PRODUCT
2356     if (PrintCompilation && (Verbose || WizardMode))
2357       tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current()));
2358 #endif
2359     ThreadInVMfromNative tivfn(JavaThread::current());
2360   }
2361 }
2362 
2363 // wrapper for CodeCache::print_summary()
2364 static void codecache_print(bool detailed)
2365 {
2366   stringStream s;
2367   // Dump code cache  into a buffer before locking the tty,
2368   {
2369     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2370     CodeCache::print_summary(&s, detailed);
2371   }
2372   ttyLocker ttyl;
2373   tty->print("%s", s.freeze());
2374 }
2375 
2376 // wrapper for CodeCache::print_summary() using outputStream
2377 static void codecache_print(outputStream* out, bool detailed) {
2378   stringStream s;
2379 
2380   // Dump code cache into a buffer
2381   {
2382     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2383     CodeCache::print_summary(&s, detailed);
2384   }
2385 
2386   char* remaining_log = s.as_string();
2387   while (*remaining_log != '\0') {
2388     char* eol = strchr(remaining_log, '\n');
2389     if (eol == nullptr) {
2390       out->print_cr("%s", remaining_log);
2391       remaining_log = remaining_log + strlen(remaining_log);
2392     } else {
2393       *eol = '\0';
2394       out->print_cr("%s", remaining_log);
2395       remaining_log = eol + 1;
2396     }
2397   }
2398 }
2399 
2400 void CompileBroker::handle_compile_error(CompilerThread* thread, CompileTask* task, ciEnv* ci_env,
2401                                          int compilable, const char* failure_reason) {
2402   if (!AbortVMOnCompilationFailure) {
2403     return;
2404   }
2405   if (compilable == ciEnv::MethodCompilable_not_at_tier) {
2406     fatal("Not compilable at tier %d: %s", task->comp_level(), failure_reason);
2407   }
2408   if (compilable == ciEnv::MethodCompilable_never) {
2409     fatal("Never compilable: %s", failure_reason);
2410   }
2411 }
2412 
2413 static void post_compilation_event(EventCompilation& event, CompileTask* task) {
2414   assert(task != nullptr, "invariant");
2415   CompilerEvent::CompilationEvent::post(event,
2416                                         task->compile_id(),
2417                                         task->compiler()->type(),
2418                                         task->method(),
2419                                         task->comp_level(),
2420                                         task->is_success(),
2421                                         task->osr_bci() != CompileBroker::standard_entry_bci,
2422                                         task->nm_total_size(),
2423                                         task->num_inlined_bytecodes(),
2424                                         task->arena_bytes());
2425 }
2426 
2427 int DirectivesStack::_depth = 0;
2428 CompilerDirectives* DirectivesStack::_top = nullptr;
2429 CompilerDirectives* DirectivesStack::_bottom = nullptr;
2430 
2431 // Acquires Compilation_lock and waits for it to be notified
2432 // as long as WhiteBox::compilation_locked is true.
2433 static void whitebox_lock_compilation() {
2434   MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2435   while (WhiteBox::compilation_locked) {
2436     locker.wait();
2437   }
2438 }
2439 
2440 // ------------------------------------------------------------------
2441 // CompileBroker::invoke_compiler_on_method
2442 //
2443 // Compile a method.
2444 //
2445 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2446   task->print_ul();
2447   elapsedTimer time;
2448 
2449   DirectiveSet* directive = task->directive();
2450   if (directive->PrintCompilationOption) {
2451     ResourceMark rm;
2452     task->print_tty();
2453   }
2454 
2455   CompilerThread* thread = CompilerThread::current();
2456   ResourceMark rm(thread);
2457 
2458   if (CompilationLog::log() != nullptr) {
2459     CompilationLog::log()->log_compile(thread, task);
2460   }
2461 
2462   // Common flags.
2463   int compile_id = task->compile_id();
2464   int osr_bci = task->osr_bci();
2465   bool is_osr = (osr_bci != standard_entry_bci);
2466   bool should_log = (thread->log() != nullptr);
2467   bool should_break = false;
2468   const int task_level = task->comp_level();
2469   AbstractCompiler* comp = task->compiler();
2470   CompileTrainingData* tdata = task->training_data();
2471   assert(tdata == nullptr || TrainingData::need_data() ||
2472          CDSConfig::is_dumping_preimage_static_archive(), ""); // FIXME: MetaspaceShared::preload_and_dump() messes with RecordTraining flag
2473   {
2474     // create the handle inside it's own block so it can't
2475     // accidentally be referenced once the thread transitions to
2476     // native.  The NoHandleMark before the transition should catch
2477     // any cases where this occurs in the future.
2478     methodHandle method(thread, task->method());
2479 
2480     assert(!method->is_native(), "no longer compile natives");
2481 
2482     // Update compile information when using perfdata.
2483     if (UsePerfData) {
2484       update_compile_perf_data(thread, method, is_osr);
2485     }
2486 
2487     DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2488   }
2489 
2490   if (tdata != nullptr) {
2491     tdata->record_compilation_start(task);
2492   }
2493 
2494   should_break = directive->BreakAtCompileOption || task->check_break_at_flags();
2495   if (should_log && !directive->LogOption) {
2496     should_log = false;
2497   }
2498 
2499   // Allocate a new set of JNI handles.
2500   JNIHandleMark jhm(thread);
2501   Method* target_handle = task->method();
2502   int compilable = ciEnv::MethodCompilable;
2503   const char* failure_reason = nullptr;
2504   bool failure_reason_on_C_heap = false;
2505   const char* retry_message = nullptr;
2506 
2507 #if INCLUDE_JVMCI
2508   if (UseJVMCICompiler && comp != nullptr && comp->is_jvmci()) {
2509     JVMCICompiler* jvmci = (JVMCICompiler*) comp;
2510 
2511     TraceTime t1("compilation", &time);
2512     EventCompilation event;
2513     JVMCICompileState compile_state(task, jvmci);
2514     JVMCIRuntime *runtime = nullptr;
2515 
2516     if (JVMCI::in_shutdown()) {
2517       failure_reason = "in JVMCI shutdown";
2518       retry_message = "not retryable";
2519       compilable = ciEnv::MethodCompilable_never;
2520     } else if (compile_state.target_method_is_old()) {
2521       // Skip redefined methods
2522       failure_reason = "redefined method";
2523       retry_message = "not retryable";
2524       compilable = ciEnv::MethodCompilable_never;
2525     } else {
2526       JVMCIEnv env(thread, &compile_state, __FILE__, __LINE__);
2527       if (env.init_error() != JNI_OK) {
2528         const char* msg = env.init_error_msg();
2529         failure_reason = os::strdup(err_msg("Error attaching to libjvmci (err: %d, %s)",
2530                                     env.init_error(), msg == nullptr ? "unknown" : msg), mtJVMCI);
2531         bool reason_on_C_heap = true;
2532         // In case of JNI_ENOMEM, there's a good chance a subsequent attempt to create libjvmci or attach to it
2533         // might succeed. Other errors most likely indicate a non-recoverable error in the JVMCI runtime.
2534         bool retryable = env.init_error() == JNI_ENOMEM;
2535         compile_state.set_failure(retryable, failure_reason, reason_on_C_heap);
2536       }
2537       if (failure_reason == nullptr) {
2538         if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2539           // Must switch to native to block
2540           ThreadToNativeFromVM ttn(thread);
2541           whitebox_lock_compilation();
2542         }
2543         methodHandle method(thread, target_handle);
2544         runtime = env.runtime();
2545         runtime->compile_method(&env, jvmci, method, osr_bci);
2546 
2547         failure_reason = compile_state.failure_reason();
2548         failure_reason_on_C_heap = compile_state.failure_reason_on_C_heap();
2549         if (!compile_state.retryable()) {
2550           retry_message = "not retryable";
2551           compilable = ciEnv::MethodCompilable_not_at_tier;
2552         }
2553         if (!task->is_success()) {
2554           assert(failure_reason != nullptr, "must specify failure_reason");
2555         }
2556       }
2557     }
2558     if (!task->is_success() && !JVMCI::in_shutdown()) {
2559       handle_compile_error(thread, task, nullptr, compilable, failure_reason);
2560     }
2561     if (event.should_commit()) {
2562       post_compilation_event(event, task);
2563     }
2564 
2565     if (runtime != nullptr) {
2566       runtime->post_compile(thread);
2567     }
2568   } else
2569 #endif // INCLUDE_JVMCI
2570   {
2571     NoHandleMark  nhm;
2572     ThreadToNativeFromVM ttn(thread);
2573 
2574     ciEnv ci_env(task);
2575     if (should_break) {
2576       ci_env.set_break_at_compile(true);
2577     }
2578     if (should_log) {
2579       ci_env.set_log(thread->log());
2580     }
2581     assert(thread->env() == &ci_env, "set by ci_env");
2582     // The thread-env() field is cleared in ~CompileTaskWrapper.
2583 
2584     // Cache Jvmti state
2585     bool method_is_old = ci_env.cache_jvmti_state();
2586 
2587     // Skip redefined methods
2588     if (method_is_old) {
2589       ci_env.record_method_not_compilable("redefined method", true);
2590     }
2591 
2592     // Cache DTrace flags
2593     ci_env.cache_dtrace_flags();
2594 
2595     ciMethod* target = ci_env.get_method_from_handle(target_handle);
2596 
2597     TraceTime t1("compilation", &time);
2598     EventCompilation event;
2599 
2600     bool install_code = true;
2601     if (comp == nullptr) {
2602       ci_env.record_method_not_compilable("no compiler");
2603     } else if (!ci_env.failing()) {
2604       if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2605         whitebox_lock_compilation();
2606       }
2607       if (StoreCachedCode && task->is_precompiled()) {
2608         install_code = false; // not suitable in the current context
2609       }
2610       comp->compile_method(&ci_env, target, osr_bci, install_code, directive);
2611 
2612       /* Repeat compilation without installing code for profiling purposes */
2613       int repeat_compilation_count = directive->RepeatCompilationOption;
2614       while (repeat_compilation_count > 0) {
2615         ResourceMark rm(thread);
2616         task->print_ul("NO CODE INSTALLED");
2617         comp->compile_method(&ci_env, target, osr_bci, false, directive);
2618         repeat_compilation_count--;
2619       }
2620     }
2621 
2622     DirectivesStack::release(directive);
2623 
2624     if (!ci_env.failing() && !task->is_success() && install_code) {
2625       assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2626       assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2627       // The compiler elected, without comment, not to register a result.
2628       // Do not attempt further compilations of this method.
2629       ci_env.record_method_not_compilable("compile failed");
2630     }
2631 
2632     // Copy this bit to the enclosing block:
2633     compilable = ci_env.compilable();
2634 
2635     if (ci_env.failing()) {
2636       // Duplicate the failure reason string, so that it outlives ciEnv
2637       failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2638       failure_reason_on_C_heap = true;
2639       retry_message = ci_env.retry_message();
2640       ci_env.report_failure(failure_reason);
2641     }
2642 
2643     if (ci_env.failing()) {
2644       handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2645     }
2646     if (event.should_commit()) {
2647       post_compilation_event(event, task);
2648     }
2649   }
2650 
2651   if (failure_reason != nullptr) {
2652     task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2653     if (CompilationLog::log() != nullptr) {
2654       CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2655     }
2656     if (PrintCompilation) {
2657       FormatBufferResource msg = retry_message != nullptr ?
2658         FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2659         FormatBufferResource("COMPILE SKIPPED: %s",      failure_reason);
2660       task->print(tty, msg);
2661     }
2662   }
2663 
2664   if (tdata != nullptr) {
2665     tdata->record_compilation_end(task);
2666   }
2667 
2668   methodHandle method(thread, task->method());
2669 
2670   DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2671 
2672   collect_statistics(thread, time, task);
2673 
2674   if (PrintCompilation && PrintCompilation2) {
2675     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
2676     tty->print("%4d ", compile_id);    // print compilation number
2677     tty->print("%s ", (is_osr ? "%" : (task->is_scc() ? "A" : " ")));
2678     if (task->is_success()) {
2679       tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2680     }
2681     tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2682   }
2683 
2684   Log(compilation, codecache) log;
2685   if (log.is_debug()) {
2686     LogStream ls(log.debug());
2687     codecache_print(&ls, /* detailed= */ false);
2688   }
2689   if (PrintCodeCacheOnCompilation) {
2690     codecache_print(/* detailed= */ false);
2691   }
2692   // Disable compilation, if required.
2693   switch (compilable) {
2694   case ciEnv::MethodCompilable_never:
2695     if (is_osr)
2696       method->set_not_osr_compilable_quietly("MethodCompilable_never");
2697     else
2698       method->set_not_compilable_quietly("MethodCompilable_never");
2699     break;
2700   case ciEnv::MethodCompilable_not_at_tier:
2701     if (is_osr)
2702       method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2703     else
2704       method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2705     break;
2706   }
2707 
2708   // Note that the queued_for_compilation bits are cleared without
2709   // protection of a mutex. [They were set by the requester thread,
2710   // when adding the task to the compile queue -- at which time the
2711   // compile queue lock was held. Subsequently, we acquired the compile
2712   // queue lock to get this task off the compile queue; thus (to belabour
2713   // the point somewhat) our clearing of the bits must be occurring
2714   // only after the setting of the bits. See also 14012000 above.
2715   method->clear_queued_for_compilation();
2716   method->set_pending_queue_processed(false);
2717 }
2718 
2719 /**
2720  * The CodeCache is full. Print warning and disable compilation.
2721  * Schedule code cache cleaning so compilation can continue later.
2722  * This function needs to be called only from CodeCache::allocate(),
2723  * since we currently handle a full code cache uniformly.
2724  */
2725 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2726   UseInterpreter = true;
2727   if (UseCompiler || AlwaysCompileLoopMethods ) {
2728     if (xtty != nullptr) {
2729       stringStream s;
2730       // Dump code cache state into a buffer before locking the tty,
2731       // because log_state() will use locks causing lock conflicts.
2732       CodeCache::log_state(&s);
2733       // Lock to prevent tearing
2734       ttyLocker ttyl;
2735       xtty->begin_elem("code_cache_full");
2736       xtty->print("%s", s.freeze());
2737       xtty->stamp();
2738       xtty->end_elem();
2739     }
2740 
2741 #ifndef PRODUCT
2742     if (ExitOnFullCodeCache) {
2743       codecache_print(/* detailed= */ true);
2744       before_exit(JavaThread::current());
2745       exit_globals(); // will delete tty
2746       vm_direct_exit(1);
2747     }
2748 #endif
2749     if (UseCodeCacheFlushing) {
2750       // Since code cache is full, immediately stop new compiles
2751       if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) {
2752         log_info(codecache)("Code cache is full - disabling compilation");
2753       }
2754     } else {
2755       disable_compilation_forever();
2756     }
2757 
2758     CodeCache::report_codemem_full(code_blob_type, should_print_compiler_warning());
2759   }
2760 }
2761 
2762 // ------------------------------------------------------------------
2763 // CompileBroker::update_compile_perf_data
2764 //
2765 // Record this compilation for debugging purposes.
2766 void CompileBroker::update_compile_perf_data(CompilerThread* thread, const methodHandle& method, bool is_osr) {
2767   ResourceMark rm;
2768   char* method_name = method->name()->as_C_string();
2769   char current_method[CompilerCounters::cmname_buffer_length];
2770   size_t maxLen = CompilerCounters::cmname_buffer_length;
2771 
2772   const char* class_name = method->method_holder()->name()->as_C_string();
2773 
2774   size_t s1len = strlen(class_name);
2775   size_t s2len = strlen(method_name);
2776 
2777   // check if we need to truncate the string
2778   if (s1len + s2len + 2 > maxLen) {
2779 
2780     // the strategy is to lop off the leading characters of the
2781     // class name and the trailing characters of the method name.
2782 
2783     if (s2len + 2 > maxLen) {
2784       // lop of the entire class name string, let snprintf handle
2785       // truncation of the method name.
2786       class_name += s1len; // null string
2787     }
2788     else {
2789       // lop off the extra characters from the front of the class name
2790       class_name += ((s1len + s2len + 2) - maxLen);
2791     }
2792   }
2793 
2794   jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
2795 
2796   int last_compile_type = normal_compile;
2797   if (CICountOSR && is_osr) {
2798     last_compile_type = osr_compile;
2799   } else if (CICountNative && method->is_native()) {
2800     last_compile_type = native_compile;
2801   }
2802 
2803   CompilerCounters* counters = thread->counters();
2804   counters->set_current_method(current_method);
2805   counters->set_compile_type((jlong) last_compile_type);
2806 }
2807 
2808 // ------------------------------------------------------------------
2809 // CompileBroker::collect_statistics
2810 //
2811 // Collect statistics about the compilation.
2812 
2813 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2814   bool success = task->is_success();
2815   methodHandle method (thread, task->method());
2816   int compile_id = task->compile_id();
2817   bool is_osr = (task->osr_bci() != standard_entry_bci);
2818   const int comp_level = task->comp_level();
2819   CompilerCounters* counters = thread->counters();
2820 
2821   MutexLocker locker(CompileStatistics_lock);
2822 
2823   // _perf variables are production performance counters which are
2824   // updated regardless of the setting of the CITime and CITimeEach flags
2825   //
2826 
2827   // account all time, including bailouts and failures in this counter;
2828   // C1 and C2 counters are counting both successful and unsuccessful compiles
2829   _t_total_compilation.add(&time);
2830 
2831   if (!success) {
2832     _total_bailout_count++;
2833     if (UsePerfData) {
2834       _perf_last_failed_method->set_value(counters->current_method());
2835       _perf_last_failed_type->set_value(counters->compile_type());
2836       _perf_total_bailout_count->inc();
2837     }
2838     _t_bailedout_compilation.add(&time);
2839 
2840     if (CITime || log_is_enabled(Info, init)) {
2841       CompilerStatistics* stats = nullptr;
2842       if (task->is_scc()) {
2843         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2844         stats = &_scc_stats_per_level[level];
2845       } else {
2846         stats = &_stats_per_level[comp_level-1];
2847       }
2848       stats->_bailout.update(time, 0);
2849     }
2850   } else if (!task->is_success()) {
2851     if (UsePerfData) {
2852       _perf_last_invalidated_method->set_value(counters->current_method());
2853       _perf_last_invalidated_type->set_value(counters->compile_type());
2854       _perf_total_invalidated_count->inc();
2855     }
2856     _total_invalidated_count++;
2857     _t_invalidated_compilation.add(&time);
2858 
2859     if (CITime || log_is_enabled(Info, init)) {
2860       CompilerStatistics* stats = nullptr;
2861       if (task->is_scc()) {
2862         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2863         stats = &_scc_stats_per_level[level];
2864       } else {
2865         stats = &_stats_per_level[comp_level-1];
2866       }
2867       stats->_invalidated.update(time, 0);
2868     }
2869   } else {
2870     // Compilation succeeded
2871 
2872     // update compilation ticks - used by the implementation of
2873     // java.lang.management.CompilationMXBean
2874     _perf_total_compilation->inc(time.ticks());
2875     _peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time;
2876 
2877     if (CITime || log_is_enabled(Info, init)) {
2878       int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2879       if (is_osr) {
2880         _t_osr_compilation.add(&time);
2881         _sum_osr_bytes_compiled += bytes_compiled;
2882       } else {
2883         _t_standard_compilation.add(&time);
2884         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2885       }
2886 
2887       // Collect statistic per compilation level
2888       if (task->is_scc()) {
2889         _scc_stats._standard.update(time, bytes_compiled);
2890         _scc_stats._nmethods_size += task->nm_total_size();
2891         _scc_stats._nmethods_code_size += task->nm_insts_size();
2892         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2893         CompilerStatistics* stats = &_scc_stats_per_level[level];
2894         stats->_standard.update(time, bytes_compiled);
2895         stats->_nmethods_size += task->nm_total_size();
2896         stats->_nmethods_code_size += task->nm_insts_size();
2897       } else if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2898         CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2899         if (is_osr) {
2900           stats->_osr.update(time, bytes_compiled);
2901         } else {
2902           stats->_standard.update(time, bytes_compiled);
2903         }
2904         stats->_nmethods_size += task->nm_total_size();
2905         stats->_nmethods_code_size += task->nm_insts_size();
2906       } else {
2907         assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2908       }
2909 
2910       // Collect statistic per compiler
2911       AbstractCompiler* comp = task->compiler();
2912       if (comp && !task->is_scc()) {
2913         CompilerStatistics* stats = comp->stats();
2914         if (is_osr) {
2915           stats->_osr.update(time, bytes_compiled);
2916         } else {
2917           stats->_standard.update(time, bytes_compiled);
2918         }
2919         stats->_nmethods_size += task->nm_total_size();
2920         stats->_nmethods_code_size += task->nm_insts_size();
2921       } else if (!task->is_scc()) { // if (!comp)
2922         assert(false, "Compiler object must exist");
2923       }
2924     }
2925 
2926     if (UsePerfData) {
2927       // save the name of the last method compiled
2928       _perf_last_method->set_value(counters->current_method());
2929       _perf_last_compile_type->set_value(counters->compile_type());
2930       _perf_last_compile_size->set_value(method->code_size() +
2931                                          task->num_inlined_bytecodes());
2932       if (is_osr) {
2933         _perf_osr_compilation->inc(time.ticks());
2934         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2935       } else {
2936         _perf_standard_compilation->inc(time.ticks());
2937         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2938       }
2939     }
2940 
2941     if (CITimeEach) {
2942       double compile_time = time.seconds();
2943       double bytes_per_sec = compile_time == 0.0 ? 0.0 : (double)(method->code_size() + task->num_inlined_bytecodes()) / compile_time;
2944       tty->print_cr("%3d   seconds: %6.3f bytes/sec : %f (bytes %d + %d inlined)",
2945                     compile_id, compile_time, bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
2946     }
2947 
2948     // Collect counts of successful compilations
2949     _sum_nmethod_size      += task->nm_total_size();
2950     _sum_nmethod_code_size += task->nm_insts_size();
2951     _total_compile_count++;
2952 
2953     if (UsePerfData) {
2954       _perf_sum_nmethod_size->inc(     task->nm_total_size());
2955       _perf_sum_nmethod_code_size->inc(task->nm_insts_size());
2956       _perf_total_compile_count->inc();
2957     }
2958 
2959     if (is_osr) {
2960       if (UsePerfData) _perf_total_osr_compile_count->inc();
2961       _total_osr_compile_count++;
2962     } else {
2963       if (UsePerfData) _perf_total_standard_compile_count->inc();
2964       _total_standard_compile_count++;
2965     }
2966   }
2967   // set the current method for the thread to null
2968   if (UsePerfData) counters->set_current_method("");
2969 }
2970 
2971 const char* CompileBroker::compiler_name(int comp_level) {
2972   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2973   if (comp == nullptr) {
2974     return "no compiler";
2975   } else {
2976     return (comp->name());
2977   }
2978 }
2979 
2980 jlong CompileBroker::total_compilation_ticks() {
2981   return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2982 }
2983 
2984 void CompileBroker::log_not_entrant(nmethod* nm) {
2985   _total_not_entrant_count++;
2986   if (CITime || log_is_enabled(Info, init)) {
2987     CompilerStatistics* stats = nullptr;
2988     int level = nm->comp_level();
2989     if (nm->is_scc()) {
2990       if (nm->preloaded()) {
2991         assert(level == CompLevel_full_optimization, "%d", level);
2992         level = CompLevel_full_optimization + 1;
2993       }
2994       stats = &_scc_stats_per_level[level - 1];
2995     } else {
2996       stats = &_stats_per_level[level - 1];
2997     }
2998     stats->_made_not_entrant._count++;
2999   }
3000 }
3001 
3002 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
3003   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}",
3004                 name, stats->bytes_per_second(),
3005                 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
3006                 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
3007                 stats->_nmethods_size, stats->_nmethods_code_size);
3008 }
3009 
3010 static void print_helper(outputStream* st, const char* name, CompilerStatistics::Data data, bool print_time = true) {
3011   if (data._count > 0) {
3012     st->print("; %s: %4u methods", name, data._count);
3013     if (print_time) {
3014       st->print(" (in %.3fs)", data._time.seconds());
3015     }
3016   }
3017 }
3018 
3019 static void print_tier_helper(outputStream* st, const char* prefix, int tier, CompilerStatistics* stats) {
3020   st->print("    %s%d: %5u methods", prefix, tier, stats->_standard._count);
3021   if (stats->_standard._count > 0) {
3022     st->print(" (in %.3fs)", stats->_standard._time.seconds());
3023   }
3024   print_helper(st, "osr",     stats->_osr);
3025   print_helper(st, "bailout", stats->_bailout);
3026   print_helper(st, "invalid", stats->_invalidated);
3027   print_helper(st, "not_entrant", stats->_made_not_entrant, false);
3028   st->cr();
3029 }
3030 
3031 static void print_queue_info(outputStream* st, CompileQueue* queue) {
3032   if (queue != nullptr) {
3033     MutexLocker ml(queue->lock());
3034 
3035     uint  total_cnt = 0;
3036     uint active_cnt = 0;
3037     for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3038       guarantee(jt != nullptr, "");
3039       if (jt->is_Compiler_thread()) {
3040         CompilerThread* ct = (CompilerThread*)jt;
3041 
3042         guarantee(ct != nullptr, "");
3043         if (ct->queue() == queue) {
3044           ++total_cnt;
3045           CompileTask* task = ct->task();
3046           if (task != nullptr) {
3047             ++active_cnt;
3048           }
3049         }
3050       }
3051     }
3052 
3053     st->print("  %s (%d active / %d total threads): %u tasks",
3054               queue->name(), active_cnt, total_cnt, queue->size());
3055     if (queue->size() > 0) {
3056       uint counts[] = {0, 0, 0, 0, 0}; // T1 ... T5
3057       for (CompileTask* task = queue->first(); task != nullptr; task = task->next()) {
3058         int tier = task->comp_level();
3059         if (task->is_scc() && task->preload()) {
3060           assert(tier == CompLevel_full_optimization, "%d", tier);
3061           tier = CompLevel_full_optimization + 1;
3062         }
3063         counts[tier-1]++;
3064       }
3065       st->print(":");
3066       for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3067         uint cnt = counts[tier-1];
3068         if (cnt > 0) {
3069           st->print(" T%d: %u tasks;", tier, cnt);
3070         }
3071       }
3072     }
3073     st->cr();
3074 
3075 //    for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3076 //      guarantee(jt != nullptr, "");
3077 //      if (jt->is_Compiler_thread()) {
3078 //        CompilerThread* ct = (CompilerThread*)jt;
3079 //
3080 //        guarantee(ct != nullptr, "");
3081 //        if (ct->queue() == queue) {
3082 //          ResourceMark rm;
3083 //          CompileTask* task = ct->task();
3084 //          st->print("    %s: ", ct->name_raw());
3085 //          if (task != nullptr) {
3086 //            task->print(st, nullptr, true /*short_form*/, false /*cr*/);
3087 //          }
3088 //          st->cr();
3089 //        }
3090 //      }
3091 //    }
3092   }
3093 }
3094 void CompileBroker::print_statistics_on(outputStream* st) {
3095   st->print_cr("  Total: %u methods; %u bailouts, %u invalidated, %u non_entrant",
3096                _total_compile_count, _total_bailout_count, _total_invalidated_count, _total_not_entrant_count);
3097   for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3098     print_tier_helper(st, "Tier", tier, &_stats_per_level[tier-1]);
3099   }
3100   st->cr();
3101 
3102   if (LoadCachedCode || StoreCachedCode) {
3103     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3104       if (tier != CompLevel_full_profile) {
3105         print_tier_helper(st, "SC T", tier, &_scc_stats_per_level[tier - 1]);
3106       }
3107     }
3108     st->cr();
3109   }
3110 
3111   print_queue_info(st, _c1_compile_queue);
3112   print_queue_info(st, _c2_compile_queue);
3113   print_queue_info(st, _c3_compile_queue);
3114   print_queue_info(st, _sc1_compile_queue);
3115   print_queue_info(st, _sc2_compile_queue);
3116 }
3117 
3118 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
3119   if (per_compiler) {
3120     if (aggregate) {
3121       tty->cr();
3122       tty->print_cr("[%dms] Individual compiler times (for compiled methods only)", (int)tty->time_stamp().milliseconds());
3123       tty->print_cr("------------------------------------------------");
3124       tty->cr();
3125     }
3126     for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
3127       AbstractCompiler* comp = _compilers[i];
3128       if (comp != nullptr) {
3129         print_times(comp->name(), comp->stats());
3130       }
3131     }
3132     if (_scc_stats._standard._count > 0) {
3133       print_times("SC", &_scc_stats);
3134     }
3135     if (aggregate) {
3136       tty->cr();
3137       tty->print_cr("Individual compilation Tier times (for compiled methods only)");
3138       tty->print_cr("------------------------------------------------");
3139       tty->cr();
3140     }
3141     char tier_name[256];
3142     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3143       CompilerStatistics* stats = &_stats_per_level[tier-1];
3144       os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
3145       print_times(tier_name, stats);
3146     }
3147     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3148       CompilerStatistics* stats = &_scc_stats_per_level[tier-1];
3149       if (stats->_standard._bytes > 0) {
3150         os::snprintf_checked(tier_name, sizeof(tier_name), "SC T%d", tier);
3151         print_times(tier_name, stats);
3152       }
3153     }
3154   }
3155 
3156   if (!aggregate) {
3157     return;
3158   }
3159 
3160   elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
3161   elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
3162   elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
3163 
3164   uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
3165   uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
3166 
3167   uint standard_compile_count = CompileBroker::_total_standard_compile_count;
3168   uint osr_compile_count = CompileBroker::_total_osr_compile_count;
3169   uint total_compile_count = CompileBroker::_total_compile_count;
3170   uint total_bailout_count = CompileBroker::_total_bailout_count;
3171   uint total_invalidated_count = CompileBroker::_total_invalidated_count;
3172 
3173   uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;
3174   uint nmethods_size = CompileBroker::_sum_nmethod_size;
3175 
3176   tty->cr();
3177   tty->print_cr("Accumulated compiler times");
3178   tty->print_cr("----------------------------------------------------------");
3179                //0000000000111111111122222222223333333333444444444455555555556666666666
3180                //0123456789012345678901234567890123456789012345678901234567890123456789
3181   tty->print_cr("  Total compilation time   : %7.3f s", total_compilation.seconds());
3182   tty->print_cr("    Standard compilation   : %7.3f s, Average : %2.3f s",
3183                 standard_compilation.seconds(),
3184                 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
3185   tty->print_cr("    Bailed out compilation : %7.3f s, Average : %2.3f s",
3186                 CompileBroker::_t_bailedout_compilation.seconds(),
3187                 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
3188   tty->print_cr("    On stack replacement   : %7.3f s, Average : %2.3f s",
3189                 osr_compilation.seconds(),
3190                 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
3191   tty->print_cr("    Invalidated            : %7.3f s, Average : %2.3f s",
3192                 CompileBroker::_t_invalidated_compilation.seconds(),
3193                 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
3194 
3195   if (StoreCachedCode || LoadCachedCode) { // Check flags because SC cache could be closed already
3196     tty->cr();
3197     SCCache::print_timers_on(tty);
3198   }
3199   AbstractCompiler *comp = compiler(CompLevel_simple);
3200   if (comp != nullptr) {
3201     tty->cr();
3202     comp->print_timers();
3203   }
3204   comp = compiler(CompLevel_full_optimization);
3205   if (comp != nullptr) {
3206     tty->cr();
3207     comp->print_timers();
3208   }
3209   comp = _compilers[2];
3210   if (comp != nullptr) {
3211     tty->cr();
3212     comp->print_timers();
3213   }
3214 #if INCLUDE_JVMCI
3215   if (EnableJVMCI) {
3216     JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
3217     if (jvmci_comp != nullptr && jvmci_comp != comp) {
3218       tty->cr();
3219       jvmci_comp->print_timers();
3220     }
3221   }
3222 #endif
3223 
3224   tty->cr();
3225   tty->print_cr("  Total compiled methods    : %8u methods", total_compile_count);
3226   tty->print_cr("    Standard compilation    : %8u methods", standard_compile_count);
3227   tty->print_cr("    On stack replacement    : %8u methods", osr_compile_count);
3228   uint tcb = osr_bytes_compiled + standard_bytes_compiled;
3229   tty->print_cr("  Total compiled bytecodes  : %8u bytes", tcb);
3230   tty->print_cr("    Standard compilation    : %8u bytes", standard_bytes_compiled);
3231   tty->print_cr("    On stack replacement    : %8u bytes", osr_bytes_compiled);
3232   double tcs = total_compilation.seconds();
3233   uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);
3234   tty->print_cr("  Average compilation speed : %8u bytes/s", bps);
3235   tty->cr();
3236   tty->print_cr("  nmethod code size         : %8u bytes", nmethods_code_size);
3237   tty->print_cr("  nmethod total size        : %8u bytes", nmethods_size);
3238 }
3239 
3240 // Print general/accumulated JIT information.
3241 void CompileBroker::print_info(outputStream *out) {
3242   if (out == nullptr) out = tty;
3243   out->cr();
3244   out->print_cr("======================");
3245   out->print_cr("   General JIT info   ");
3246   out->print_cr("======================");
3247   out->cr();
3248   out->print_cr("            JIT is : %7s",     should_compile_new_jobs() ? "on" : "off");
3249   out->print_cr("  Compiler threads : %7d",     (int)CICompilerCount);
3250   out->cr();
3251   out->print_cr("CodeCache overview");
3252   out->print_cr("--------------------------------------------------------");
3253   out->cr();
3254   out->print_cr("         Reserved size : " SIZE_FORMAT_W(7) " KB", CodeCache::max_capacity() / K);
3255   out->print_cr("        Committed size : " SIZE_FORMAT_W(7) " KB", CodeCache::capacity() / K);
3256   out->print_cr("  Unallocated capacity : " SIZE_FORMAT_W(7) " KB", CodeCache::unallocated_capacity() / K);
3257   out->cr();
3258 }
3259 
3260 // Note: tty_lock must not be held upon entry to this function.
3261 //       Print functions called from herein do "micro-locking" on tty_lock.
3262 //       That's a tradeoff which keeps together important blocks of output.
3263 //       At the same time, continuous tty_lock hold time is kept in check,
3264 //       preventing concurrently printing threads from stalling a long time.
3265 void CompileBroker::print_heapinfo(outputStream* out, const char* function, size_t granularity) {
3266   TimeStamp ts_total;
3267   TimeStamp ts_global;
3268   TimeStamp ts;
3269 
3270   bool allFun = !strcmp(function, "all");
3271   bool aggregate = !strcmp(function, "aggregate") || !strcmp(function, "analyze") || allFun;
3272   bool usedSpace = !strcmp(function, "UsedSpace") || allFun;
3273   bool freeSpace = !strcmp(function, "FreeSpace") || allFun;
3274   bool methodCount = !strcmp(function, "MethodCount") || allFun;
3275   bool methodSpace = !strcmp(function, "MethodSpace") || allFun;
3276   bool methodAge = !strcmp(function, "MethodAge") || allFun;
3277   bool methodNames = !strcmp(function, "MethodNames") || allFun;
3278   bool discard = !strcmp(function, "discard") || allFun;
3279 
3280   if (out == nullptr) {
3281     out = tty;
3282   }
3283 
3284   if (!(aggregate || usedSpace || freeSpace || methodCount || methodSpace || methodAge || methodNames || discard)) {
3285     out->print_cr("\n__ CodeHeapStateAnalytics: Function %s is not supported", function);
3286     out->cr();
3287     return;
3288   }
3289 
3290   ts_total.update(); // record starting point
3291 
3292   if (aggregate) {
3293     print_info(out);
3294   }
3295 
3296   // We hold the CodeHeapStateAnalytics_lock all the time, from here until we leave this function.
3297   // That prevents other threads from destroying (making inconsistent) our view on the CodeHeap.
3298   // When we request individual parts of the analysis via the jcmd interface, it is possible
3299   // that in between another thread (another jcmd user or the vm running into CodeCache OOM)
3300   // updated the aggregated data. We will then see a modified, but again consistent, view
3301   // on the CodeHeap. That's a tolerable tradeoff we have to accept because we can't hold
3302   // a lock across user interaction.
3303 
3304   // We should definitely acquire this lock before acquiring Compile_lock and CodeCache_lock.
3305   // CodeHeapStateAnalytics_lock may be held by a concurrent thread for a long time,
3306   // leading to an unnecessarily long hold time of the other locks we acquired before.
3307   ts.update(); // record starting point
3308   MutexLocker mu0(CodeHeapStateAnalytics_lock, Mutex::_safepoint_check_flag);
3309   out->print_cr("\n__ CodeHeapStateAnalytics lock wait took %10.3f seconds _________\n", ts.seconds());
3310 
3311   // Holding the CodeCache_lock protects from concurrent alterations of the CodeCache.
3312   // Unfortunately, such protection is not sufficient:
3313   // When a new nmethod is created via ciEnv::register_method(), the
3314   // Compile_lock is taken first. After some initializations,
3315   // nmethod::new_nmethod() takes over, grabbing the CodeCache_lock
3316   // immediately (after finalizing the oop references). To lock out concurrent
3317   // modifiers, we have to grab both locks as well in the described sequence.
3318   //
3319   // If we serve an "allFun" call, it is beneficial to hold CodeCache_lock and Compile_lock
3320   // for the entire duration of aggregation and printing. That makes sure we see
3321   // a consistent picture and do not run into issues caused by concurrent alterations.
3322   bool should_take_Compile_lock   = !SafepointSynchronize::is_at_safepoint() &&
3323                                     !Compile_lock->owned_by_self();
3324   bool should_take_CodeCache_lock = !SafepointSynchronize::is_at_safepoint() &&
3325                                     !CodeCache_lock->owned_by_self();
3326   bool take_global_lock_1   =  allFun && should_take_Compile_lock;
3327   bool take_global_lock_2   =  allFun && should_take_CodeCache_lock;
3328   bool take_function_lock_1 = !allFun && should_take_Compile_lock;
3329   bool take_function_lock_2 = !allFun && should_take_CodeCache_lock;
3330   bool take_global_locks    = take_global_lock_1 || take_global_lock_2;
3331   bool take_function_locks  = take_function_lock_1 || take_function_lock_2;
3332 
3333   ts_global.update(); // record starting point
3334 
3335   ConditionalMutexLocker mu1(Compile_lock, take_global_lock_1, Mutex::_safepoint_check_flag);
3336   ConditionalMutexLocker mu2(CodeCache_lock, take_global_lock_2, Mutex::_no_safepoint_check_flag);
3337   if (take_global_locks) {
3338     out->print_cr("\n__ Compile & CodeCache (global) lock wait took %10.3f seconds _________\n", ts_global.seconds());
3339     ts_global.update(); // record starting point
3340   }
3341 
3342   if (aggregate) {
3343     ts.update(); // record starting point
3344     ConditionalMutexLocker mu11(Compile_lock, take_function_lock_1,  Mutex::_safepoint_check_flag);
3345     ConditionalMutexLocker mu22(CodeCache_lock, take_function_lock_2, Mutex::_no_safepoint_check_flag);
3346     if (take_function_locks) {
3347       out->print_cr("\n__ Compile & CodeCache (function) lock wait took %10.3f seconds _________\n", ts.seconds());
3348     }
3349 
3350     ts.update(); // record starting point
3351     CodeCache::aggregate(out, granularity);
3352     if (take_function_locks) {
3353       out->print_cr("\n__ Compile & CodeCache (function) lock hold took %10.3f seconds _________\n", ts.seconds());
3354     }
3355   }
3356 
3357   if (usedSpace) CodeCache::print_usedSpace(out);
3358   if (freeSpace) CodeCache::print_freeSpace(out);
3359   if (methodCount) CodeCache::print_count(out);
3360   if (methodSpace) CodeCache::print_space(out);
3361   if (methodAge) CodeCache::print_age(out);
3362   if (methodNames) {
3363     if (allFun) {
3364       // print_names() can only be used safely if the locks have been continuously held
3365       // since aggregation begin. That is true only for function "all".
3366       CodeCache::print_names(out);
3367     } else {
3368       out->print_cr("\nCodeHeapStateAnalytics: Function 'MethodNames' is only available as part of function 'all'");
3369     }
3370   }
3371   if (discard) CodeCache::discard(out);
3372 
3373   if (take_global_locks) {
3374     out->print_cr("\n__ Compile & CodeCache (global) lock hold took %10.3f seconds _________\n", ts_global.seconds());
3375   }
3376   out->print_cr("\n__ CodeHeapStateAnalytics total duration %10.3f seconds _________\n", ts_total.seconds());
3377 }