1 /*
   2  * Copyright (c) 1999, 2025, 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 "cds/cdsConfig.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "classfile/symbolTable.hpp"
  28 #include "classfile/vmClasses.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "code/codeHeapState.hpp"
  32 #include "code/dependencyContext.hpp"
  33 #include "compiler/compilationLog.hpp"
  34 #include "compiler/compilationMemoryStatistic.hpp"
  35 #include "compiler/compilationPolicy.hpp"
  36 #include "compiler/compileBroker.hpp"
  37 #include "compiler/compileLog.hpp"
  38 #include "compiler/compilerEvent.hpp"
  39 #include "compiler/compilerOracle.hpp"
  40 #include "compiler/directivesParser.hpp"
  41 #include "gc/shared/memAllocator.hpp"
  42 #include "interpreter/linkResolver.hpp"
  43 #include "jfr/jfrEvents.hpp"
  44 #include "jvm.h"
  45 #include "logging/log.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/allocation.inline.hpp"
  48 #include "memory/resourceArea.hpp"
  49 #include "memory/universe.hpp"
  50 #include "oops/method.inline.hpp"
  51 #include "oops/methodData.hpp"
  52 #include "oops/oop.inline.hpp"
  53 #include "prims/jvmtiExport.hpp"
  54 #include "prims/nativeLookup.hpp"
  55 #include "prims/whitebox.hpp"
  56 #include "runtime/atomic.hpp"
  57 #include "runtime/escapeBarrier.hpp"
  58 #include "runtime/globals_extension.hpp"
  59 #include "runtime/handles.inline.hpp"
  60 #include "runtime/init.hpp"
  61 #include "runtime/interfaceSupport.inline.hpp"
  62 #include "runtime/java.hpp"
  63 #include "runtime/javaCalls.hpp"
  64 #include "runtime/jniHandles.inline.hpp"
  65 #include "runtime/os.hpp"
  66 #include "runtime/perfData.hpp"
  67 #include "runtime/safepointVerifiers.hpp"
  68 #include "runtime/sharedRuntime.hpp"
  69 #include "runtime/threads.hpp"
  70 #include "runtime/threadSMR.hpp"
  71 #include "runtime/timerTrace.hpp"
  72 #include "runtime/vframe.inline.hpp"
  73 #include "utilities/debug.hpp"
  74 #include "utilities/dtrace.hpp"
  75 #include "utilities/events.hpp"
  76 #include "utilities/formatBuffer.hpp"
  77 #include "utilities/macros.hpp"
  78 #ifdef COMPILER1
  79 #include "c1/c1_Compiler.hpp"
  80 #endif
  81 #ifdef COMPILER2
  82 #include "opto/c2compiler.hpp"
  83 #endif
  84 #if INCLUDE_JVMCI
  85 #include "jvmci/jvmciEnv.hpp"
  86 #include "jvmci/jvmciRuntime.hpp"
  87 #endif
  88 
  89 #ifdef DTRACE_ENABLED
  90 
  91 // Only bother with this argument setup if dtrace is available
  92 
  93 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
  94   {                                                                      \
  95     Symbol* klass_name = (method)->klass_name();                         \
  96     Symbol* name = (method)->name();                                     \
  97     Symbol* signature = (method)->signature();                           \
  98     HOTSPOT_METHOD_COMPILE_BEGIN(                                        \
  99       (char *) comp_name, strlen(comp_name),                             \
 100       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
 101       (char *) name->bytes(), name->utf8_length(),                       \
 102       (char *) signature->bytes(), signature->utf8_length());            \
 103   }
 104 
 105 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)      \
 106   {                                                                      \
 107     Symbol* klass_name = (method)->klass_name();                         \
 108     Symbol* name = (method)->name();                                     \
 109     Symbol* signature = (method)->signature();                           \
 110     HOTSPOT_METHOD_COMPILE_END(                                          \
 111       (char *) comp_name, strlen(comp_name),                             \
 112       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
 113       (char *) name->bytes(), name->utf8_length(),                       \
 114       (char *) signature->bytes(), signature->utf8_length(), (success)); \
 115   }
 116 
 117 #else //  ndef DTRACE_ENABLED
 118 
 119 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
 120 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
 121 
 122 #endif // ndef DTRACE_ENABLED
 123 
 124 bool CompileBroker::_initialized = false;
 125 volatile bool CompileBroker::_should_block = false;
 126 volatile int  CompileBroker::_print_compilation_warning = 0;
 127 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
 128 
 129 // The installed compiler(s)
 130 AbstractCompiler* CompileBroker::_compilers[2];
 131 
 132 // The maximum numbers of compiler threads to be determined during startup.
 133 int CompileBroker::_c1_count = 0;
 134 int CompileBroker::_c2_count = 0;
 135 
 136 // An array of compiler names as Java String objects
 137 jobject* CompileBroker::_compiler1_objects = nullptr;
 138 jobject* CompileBroker::_compiler2_objects = nullptr;
 139 
 140 CompileLog** CompileBroker::_compiler1_logs = nullptr;
 141 CompileLog** CompileBroker::_compiler2_logs = nullptr;
 142 
 143 // These counters are used to assign an unique ID to each compilation.
 144 volatile jint CompileBroker::_compilation_id     = 0;
 145 volatile jint CompileBroker::_osr_compilation_id = 0;
 146 volatile jint CompileBroker::_native_compilation_id = 0;
 147 
 148 // Performance counters
 149 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
 150 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
 151 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
 152 
 153 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
 154 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
 155 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
 156 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
 157 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
 158 
 159 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
 160 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
 161 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
 162 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
 163 
 164 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
 165 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
 166 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
 167 PerfVariable*       CompileBroker::_perf_last_compile_type = nullptr;
 168 PerfVariable*       CompileBroker::_perf_last_compile_size = nullptr;
 169 PerfVariable*       CompileBroker::_perf_last_failed_type = nullptr;
 170 PerfVariable*       CompileBroker::_perf_last_invalidated_type = nullptr;
 171 
 172 // Timers and counters for generating statistics
 173 elapsedTimer CompileBroker::_t_total_compilation;
 174 elapsedTimer CompileBroker::_t_osr_compilation;
 175 elapsedTimer CompileBroker::_t_standard_compilation;
 176 elapsedTimer CompileBroker::_t_invalidated_compilation;
 177 elapsedTimer CompileBroker::_t_bailedout_compilation;
 178 
 179 uint CompileBroker::_total_bailout_count            = 0;
 180 uint CompileBroker::_total_invalidated_count        = 0;
 181 uint CompileBroker::_total_compile_count            = 0;
 182 uint CompileBroker::_total_osr_compile_count        = 0;
 183 uint CompileBroker::_total_standard_compile_count   = 0;
 184 uint CompileBroker::_total_compiler_stopped_count   = 0;
 185 uint CompileBroker::_total_compiler_restarted_count = 0;
 186 
 187 uint CompileBroker::_sum_osr_bytes_compiled         = 0;
 188 uint CompileBroker::_sum_standard_bytes_compiled    = 0;
 189 uint CompileBroker::_sum_nmethod_size               = 0;
 190 uint CompileBroker::_sum_nmethod_code_size          = 0;
 191 
 192 jlong CompileBroker::_peak_compilation_time        = 0;
 193 
 194 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];
 195 
 196 CompileQueue* CompileBroker::_c2_compile_queue     = nullptr;
 197 CompileQueue* CompileBroker::_c1_compile_queue     = nullptr;
 198 
 199 bool compileBroker_init() {
 200   if (LogEvents) {
 201     CompilationLog::init();
 202   }
 203 
 204   // init directives stack, adding default directive
 205   DirectivesStack::init();
 206 
 207   if (DirectivesParser::has_file()) {
 208     return DirectivesParser::parse_from_flag();
 209   } else if (CompilerDirectivesPrint) {
 210     // Print default directive even when no other was added
 211     DirectivesStack::print(tty);
 212   }
 213 
 214   return true;
 215 }
 216 
 217 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
 218   CompilerThread* thread = CompilerThread::current();
 219   thread->set_task(task);
 220   CompileLog*     log  = thread->log();
 221   thread->timeout()->arm();
 222   if (log != nullptr && !task->is_unloaded())  task->log_task_start(log);
 223 }
 224 
 225 CompileTaskWrapper::~CompileTaskWrapper() {
 226   CompilerThread* thread = CompilerThread::current();
 227   CompileTask* task = thread->task();
 228   CompileLog*  log  = thread->log();
 229   if (log != nullptr && !task->is_unloaded())  task->log_task_done(log);
 230   thread->set_task(nullptr);
 231   thread->set_env(nullptr);
 232   thread->timeout()->disarm();
 233   if (task->is_blocking()) {
 234     bool free_task = false;
 235     {
 236       MutexLocker notifier(thread, CompileTaskWait_lock);
 237       task->mark_complete();
 238 #if INCLUDE_JVMCI
 239       if (CompileBroker::compiler(task->comp_level())->is_jvmci()) {
 240         if (!task->has_waiter()) {
 241           // The waiting thread timed out and thus did not delete the task.
 242           free_task = true;
 243         }
 244         task->set_blocking_jvmci_compile_state(nullptr);
 245       }
 246 #endif
 247       if (!free_task) {
 248         // Notify the waiting thread that the compilation has completed
 249         // so that it can free the task.
 250         CompileTaskWait_lock->notify_all();
 251       }
 252     }
 253     if (free_task) {
 254       // The task can only be deleted once the task lock is released.
 255       delete task;
 256     }
 257   } else {
 258     task->mark_complete();
 259 
 260     // By convention, the compiling thread is responsible for deleting
 261     // a non-blocking CompileTask.
 262     delete task;
 263   }
 264 }
 265 
 266 /**
 267  * Check if a CompilerThread can be removed and update count if requested.
 268  */
 269 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
 270   assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
 271   if (!ReduceNumberOfCompilerThreads) return false;
 272 
 273   AbstractCompiler *compiler = ct->compiler();
 274   int compiler_count = compiler->num_compiler_threads();
 275   bool c1 = compiler->is_c1();
 276 
 277   // Keep at least 1 compiler thread of each type.
 278   if (compiler_count < 2) return false;
 279 
 280   // Keep thread alive for at least some time.
 281   if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
 282 
 283 #if INCLUDE_JVMCI
 284   if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 285     // Handles for JVMCI thread objects may get released concurrently.
 286     if (do_it) {
 287       assert(CompileThread_lock->owner() == ct, "must be holding lock");
 288     } else {
 289       // Skip check if it's the last thread and let caller check again.
 290       return true;
 291     }
 292   }
 293 #endif
 294 
 295   // We only allow the last compiler thread of each type to get removed.
 296   jobject last_compiler = c1 ? compiler1_object(compiler_count - 1)
 297                              : compiler2_object(compiler_count - 1);
 298   if (ct->threadObj() == JNIHandles::resolve_non_null(last_compiler)) {
 299     if (do_it) {
 300       assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
 301       compiler->set_num_compiler_threads(compiler_count - 1);
 302 #if INCLUDE_JVMCI
 303       if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 304         // Old j.l.Thread object can die when no longer referenced elsewhere.
 305         JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
 306         _compiler2_objects[compiler_count - 1] = nullptr;
 307       }
 308 #endif
 309     }
 310     return true;
 311   }
 312   return false;
 313 }
 314 
 315 /**
 316  * Add a CompileTask to a CompileQueue.
 317  */
 318 void CompileQueue::add(CompileTask* task) {
 319   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 320 
 321   task->set_next(nullptr);
 322   task->set_prev(nullptr);
 323 
 324   if (_last == nullptr) {
 325     // The compile queue is empty.
 326     assert(_first == nullptr, "queue is empty");
 327     _first = task;
 328     _last = task;
 329   } else {
 330     // Append the task to the queue.
 331     assert(_last->next() == nullptr, "not last");
 332     _last->set_next(task);
 333     task->set_prev(_last);
 334     _last = task;
 335   }
 336   ++_size;
 337   ++_total_added;
 338   if (_size > _peak_size) {
 339     _peak_size = _size;
 340   }
 341 
 342   // Mark the method as being in the compile queue.
 343   task->method()->set_queued_for_compilation();
 344 
 345   if (CIPrintCompileQueue) {
 346     print_tty();
 347   }
 348 
 349   if (LogCompilation && xtty != nullptr) {
 350     task->log_task_queued();
 351   }
 352 
 353   if (TrainingData::need_data() && !CDSConfig::is_dumping_final_static_archive()) {
 354     CompileTrainingData* ctd = CompileTrainingData::make(task);
 355     if (ctd != nullptr) {
 356       task->set_training_data(ctd);
 357     }
 358   }
 359 
 360   // Notify CompilerThreads that a task is available.
 361   MethodCompileQueue_lock->notify_all();
 362 }
 363 
 364 /**
 365  * Empties compilation queue by deleting all compilation tasks.
 366  * Furthermore, the method wakes up all threads that are waiting
 367  * on a compilation task to finish. This can happen if background
 368  * compilation is disabled.
 369  */
 370 void CompileQueue::delete_all() {
 371   MutexLocker mu(MethodCompileQueue_lock);
 372   CompileTask* current = _first;
 373 
 374   // Iterate over all tasks in the compile queue
 375   while (current != nullptr) {
 376     CompileTask* next = current->next();
 377     if (!current->is_blocking()) {
 378       // Non-blocking task. No one is waiting for it, delete it now.
 379       delete current;
 380     } else {
 381       // Blocking task. By convention, it is the waiters responsibility
 382       // to delete the task. We cannot delete it here, because we do not
 383       // coordinate with waiters. We will notify the waiters later.
 384     }
 385     current = next;
 386   }
 387   _first = nullptr;
 388   _last = nullptr;
 389 
 390   // Wake up all blocking task waiters to deal with remaining blocking
 391   // tasks. This is not a performance sensitive path, so we do this
 392   // unconditionally to simplify coding/testing.
 393   {
 394     MonitorLocker ml(Thread::current(), CompileTaskWait_lock);
 395     ml.notify_all();
 396   }
 397 
 398   // Wake up all threads that block on the queue.
 399   MethodCompileQueue_lock->notify_all();
 400 }
 401 
 402 /**
 403  * Get the next CompileTask from a CompileQueue
 404  */
 405 CompileTask* CompileQueue::get(CompilerThread* thread) {
 406   // save methods from RedefineClasses across safepoint
 407   // across MethodCompileQueue_lock below.
 408   methodHandle save_method;
 409 
 410   MonitorLocker locker(MethodCompileQueue_lock);
 411   // If _first is null we have no more compile jobs. There are two reasons for
 412   // having no compile jobs: First, we compiled everything we wanted. Second,
 413   // we ran out of code cache so compilation has been disabled. In the latter
 414   // case we perform code cache sweeps to free memory such that we can re-enable
 415   // compilation.
 416   while (_first == nullptr) {
 417     // Exit loop if compilation is disabled forever
 418     if (CompileBroker::is_compilation_disabled_forever()) {
 419       return nullptr;
 420     }
 421 
 422     AbstractCompiler* compiler = thread->compiler();
 423     guarantee(compiler != nullptr, "Compiler object must exist");
 424     compiler->on_empty_queue(this, thread);
 425     if (_first != nullptr) {
 426       // The call to on_empty_queue may have temporarily unlocked the MCQ lock
 427       // so check again whether any tasks were added to the queue.
 428       break;
 429     }
 430 
 431     // If there are no compilation tasks and we can compile new jobs
 432     // (i.e., there is enough free space in the code cache) there is
 433     // no need to invoke the GC.
 434     // We need a timed wait here, since compiler threads can exit if compilation
 435     // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
 436     // is not critical and we do not want idle compiler threads to wake up too often.
 437     locker.wait(5*1000);
 438 
 439     if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
 440       // Still nothing to compile. Give caller a chance to stop this thread.
 441       if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
 442     }
 443   }
 444 
 445   if (CompileBroker::is_compilation_disabled_forever()) {
 446     return nullptr;
 447   }
 448 
 449   CompileTask* task;
 450   {
 451     NoSafepointVerifier nsv;
 452     task = CompilationPolicy::select_task(this, thread);
 453     if (task != nullptr) {
 454       task = task->select_for_compilation();
 455     }
 456   }
 457 
 458   if (task != nullptr) {
 459     // Save method pointers across unlock safepoint.  The task is removed from
 460     // the compilation queue, which is walked during RedefineClasses.
 461     Thread* thread = Thread::current();
 462     save_method = methodHandle(thread, task->method());
 463 
 464     remove(task);
 465   }
 466   purge_stale_tasks(); // may temporarily release MCQ lock
 467   return task;
 468 }
 469 
 470 // Clean & deallocate stale compile tasks.
 471 // Temporarily releases MethodCompileQueue lock.
 472 void CompileQueue::purge_stale_tasks() {
 473   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 474   if (_first_stale != nullptr) {
 475     // Stale tasks are purged when MCQ lock is released,
 476     // but _first_stale updates are protected by MCQ lock.
 477     // Once task processing starts and MCQ lock is released,
 478     // other compiler threads can reuse _first_stale.
 479     CompileTask* head = _first_stale;
 480     _first_stale = nullptr;
 481     {
 482       MutexUnlocker ul(MethodCompileQueue_lock);
 483       for (CompileTask* task = head; task != nullptr; ) {
 484         CompileTask* next_task = task->next();
 485         task->set_next(nullptr);
 486         CompileTaskWrapper ctw(task); // Frees the task
 487         task->set_failure_reason("stale task");
 488         task = next_task;
 489       }
 490     }
 491   }
 492 }
 493 
 494 void CompileQueue::remove(CompileTask* task) {
 495   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 496   if (task->prev() != nullptr) {
 497     task->prev()->set_next(task->next());
 498   } else {
 499     // max is the first element
 500     assert(task == _first, "Sanity");
 501     _first = task->next();
 502   }
 503 
 504   if (task->next() != nullptr) {
 505     task->next()->set_prev(task->prev());
 506   } else {
 507     // max is the last element
 508     assert(task == _last, "Sanity");
 509     _last = task->prev();
 510   }
 511   task->set_next(nullptr);
 512   task->set_prev(nullptr);
 513   --_size;
 514   ++_total_removed;
 515 }
 516 
 517 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
 518   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 519   remove(task);
 520 
 521   // Enqueue the task for reclamation (should be done outside MCQ lock)
 522   task->set_next(_first_stale);
 523   task->set_prev(nullptr);
 524   _first_stale = task;
 525 }
 526 
 527 // methods in the compile queue need to be marked as used on the stack
 528 // so that they don't get reclaimed by Redefine Classes
 529 void CompileQueue::mark_on_stack() {
 530   CompileTask* task = _first;
 531   while (task != nullptr) {
 532     task->mark_on_stack();
 533     task = task->next();
 534   }
 535 }
 536 
 537 
 538 CompileQueue* CompileBroker::compile_queue(int comp_level) {
 539   if (is_c2_compile(comp_level)) return _c2_compile_queue;
 540   if (is_c1_compile(comp_level)) return _c1_compile_queue;
 541   return nullptr;
 542 }
 543 
 544 CompileQueue* CompileBroker::c1_compile_queue() {
 545   return _c1_compile_queue;
 546 }
 547 
 548 CompileQueue* CompileBroker::c2_compile_queue() {
 549   return _c2_compile_queue;
 550 }
 551 
 552 void CompileBroker::print_compile_queues(outputStream* st) {
 553   st->print_cr("Current compiles: ");
 554 
 555   char buf[2000];
 556   int buflen = sizeof(buf);
 557   Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
 558 
 559   st->cr();
 560   if (_c1_compile_queue != nullptr) {
 561     _c1_compile_queue->print(st);
 562   }
 563   if (_c2_compile_queue != nullptr) {
 564     _c2_compile_queue->print(st);
 565   }
 566 }
 567 
 568 void CompileQueue::print(outputStream* st) {
 569   assert_locked_or_safepoint(MethodCompileQueue_lock);
 570   st->print_cr("%s:", name());
 571   CompileTask* task = _first;
 572   if (task == nullptr) {
 573     st->print_cr("Empty");
 574   } else {
 575     while (task != nullptr) {
 576       task->print(st, nullptr, true, true);
 577       task = task->next();
 578     }
 579   }
 580   st->cr();
 581 }
 582 
 583 void CompileQueue::print_tty() {
 584   stringStream ss;
 585   // Dump the compile queue into a buffer before locking the tty
 586   print(&ss);
 587   {
 588     ttyLocker ttyl;
 589     tty->print("%s", ss.freeze());
 590   }
 591 }
 592 
 593 CompilerCounters::CompilerCounters() {
 594   _current_method[0] = '\0';
 595   _compile_type = CompileBroker::no_compile;
 596 }
 597 
 598 #if INCLUDE_JFR && COMPILER2_OR_JVMCI
 599 // It appends new compiler phase names to growable array phase_names(a new CompilerPhaseType mapping
 600 // in compiler/compilerEvent.cpp) and registers it with its serializer.
 601 //
 602 // c2 uses explicit CompilerPhaseType idToPhase mapping in opto/phasetype.hpp,
 603 // so if c2 is used, it should be always registered first.
 604 // This function is called during vm initialization.
 605 static void register_jfr_phasetype_serializer(CompilerType compiler_type) {
 606   ResourceMark rm;
 607   static bool first_registration = true;
 608   if (compiler_type == compiler_jvmci) {
 609     CompilerEvent::PhaseEvent::get_phase_id("NOT_A_PHASE_NAME", false, false, false);
 610     first_registration = false;
 611 #ifdef COMPILER2
 612   } else if (compiler_type == compiler_c2) {
 613     assert(first_registration, "invariant"); // c2 must be registered first.
 614     for (int i = 0; i < PHASE_NUM_TYPES; i++) {
 615       const char* phase_name = CompilerPhaseTypeHelper::to_description((CompilerPhaseType) i);
 616       CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
 617     }
 618     first_registration = false;
 619 #endif // COMPILER2
 620   }
 621 }
 622 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
 623 
 624 // ------------------------------------------------------------------
 625 // CompileBroker::compilation_init
 626 //
 627 // Initialize the Compilation object
 628 void CompileBroker::compilation_init(JavaThread* THREAD) {
 629   // No need to initialize compilation system if we do not use it.
 630   if (!UseCompiler) {
 631     return;
 632   }
 633   // Set the interface to the current compiler(s).
 634   _c1_count = CompilationPolicy::c1_count();
 635   _c2_count = CompilationPolicy::c2_count();
 636 
 637 #if INCLUDE_JVMCI
 638   if (EnableJVMCI) {
 639     // This is creating a JVMCICompiler singleton.
 640     JVMCICompiler* jvmci = new JVMCICompiler();
 641 
 642     if (UseJVMCICompiler) {
 643       _compilers[1] = jvmci;
 644       if (FLAG_IS_DEFAULT(JVMCIThreads)) {
 645         if (BootstrapJVMCI) {
 646           // JVMCI will bootstrap so give it more threads
 647           _c2_count = MIN2(32, os::active_processor_count());
 648         }
 649       } else {
 650         _c2_count = JVMCIThreads;
 651       }
 652       if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
 653       } else {
 654 #ifdef COMPILER1
 655         _c1_count = JVMCIHostThreads;
 656 #endif // COMPILER1
 657       }
 658     }
 659   }
 660 #endif // INCLUDE_JVMCI
 661 
 662 #ifdef COMPILER1
 663   if (_c1_count > 0) {
 664     _compilers[0] = new Compiler();
 665   }
 666 #endif // COMPILER1
 667 
 668 #ifdef COMPILER2
 669   if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
 670     if (_c2_count > 0) {
 671       _compilers[1] = new C2Compiler();
 672       // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.
 673       // idToPhase mapping for c2 is in opto/phasetype.hpp
 674       JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)
 675     }
 676   }
 677 #endif // COMPILER2
 678 
 679 #if INCLUDE_JVMCI
 680    // Register after c2 registration.
 681    // JVMCI CompilerPhaseType idToPhase mapping is dynamic.
 682    if (EnableJVMCI) {
 683      JFR_ONLY(register_jfr_phasetype_serializer(compiler_jvmci);)
 684    }
 685 #endif // INCLUDE_JVMCI
 686 
 687   if (CompilerOracle::should_collect_memstat()) {
 688     CompilationMemoryStatistic::initialize();
 689   }
 690 
 691   // Start the compiler thread(s)
 692   init_compiler_threads();
 693   // totalTime performance counter is always created as it is required
 694   // by the implementation of java.lang.management.CompilationMXBean.
 695   {
 696     // Ensure OOM leads to vm_exit_during_initialization.
 697     EXCEPTION_MARK;
 698     _perf_total_compilation =
 699                  PerfDataManager::create_counter(JAVA_CI, "totalTime",
 700                                                  PerfData::U_Ticks, CHECK);
 701   }
 702 
 703   if (UsePerfData) {
 704 
 705     EXCEPTION_MARK;
 706 
 707     // create the jvmstat performance counters
 708     _perf_osr_compilation =
 709                  PerfDataManager::create_counter(SUN_CI, "osrTime",
 710                                                  PerfData::U_Ticks, CHECK);
 711 
 712     _perf_standard_compilation =
 713                  PerfDataManager::create_counter(SUN_CI, "standardTime",
 714                                                  PerfData::U_Ticks, CHECK);
 715 
 716     _perf_total_bailout_count =
 717                  PerfDataManager::create_counter(SUN_CI, "totalBailouts",
 718                                                  PerfData::U_Events, CHECK);
 719 
 720     _perf_total_invalidated_count =
 721                  PerfDataManager::create_counter(SUN_CI, "totalInvalidates",
 722                                                  PerfData::U_Events, CHECK);
 723 
 724     _perf_total_compile_count =
 725                  PerfDataManager::create_counter(SUN_CI, "totalCompiles",
 726                                                  PerfData::U_Events, CHECK);
 727     _perf_total_osr_compile_count =
 728                  PerfDataManager::create_counter(SUN_CI, "osrCompiles",
 729                                                  PerfData::U_Events, CHECK);
 730 
 731     _perf_total_standard_compile_count =
 732                  PerfDataManager::create_counter(SUN_CI, "standardCompiles",
 733                                                  PerfData::U_Events, CHECK);
 734 
 735     _perf_sum_osr_bytes_compiled =
 736                  PerfDataManager::create_counter(SUN_CI, "osrBytes",
 737                                                  PerfData::U_Bytes, CHECK);
 738 
 739     _perf_sum_standard_bytes_compiled =
 740                  PerfDataManager::create_counter(SUN_CI, "standardBytes",
 741                                                  PerfData::U_Bytes, CHECK);
 742 
 743     _perf_sum_nmethod_size =
 744                  PerfDataManager::create_counter(SUN_CI, "nmethodSize",
 745                                                  PerfData::U_Bytes, CHECK);
 746 
 747     _perf_sum_nmethod_code_size =
 748                  PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",
 749                                                  PerfData::U_Bytes, CHECK);
 750 
 751     _perf_last_method =
 752                  PerfDataManager::create_string_variable(SUN_CI, "lastMethod",
 753                                        CompilerCounters::cmname_buffer_length,
 754                                        "", CHECK);
 755 
 756     _perf_last_failed_method =
 757             PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",
 758                                        CompilerCounters::cmname_buffer_length,
 759                                        "", CHECK);
 760 
 761     _perf_last_invalidated_method =
 762         PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",
 763                                      CompilerCounters::cmname_buffer_length,
 764                                      "", CHECK);
 765 
 766     _perf_last_compile_type =
 767              PerfDataManager::create_variable(SUN_CI, "lastType",
 768                                               PerfData::U_None,
 769                                               (jlong)CompileBroker::no_compile,
 770                                               CHECK);
 771 
 772     _perf_last_compile_size =
 773              PerfDataManager::create_variable(SUN_CI, "lastSize",
 774                                               PerfData::U_Bytes,
 775                                               (jlong)CompileBroker::no_compile,
 776                                               CHECK);
 777 
 778 
 779     _perf_last_failed_type =
 780              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 781                                               PerfData::U_None,
 782                                               (jlong)CompileBroker::no_compile,
 783                                               CHECK);
 784 
 785     _perf_last_invalidated_type =
 786          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 787                                           PerfData::U_None,
 788                                           (jlong)CompileBroker::no_compile,
 789                                           CHECK);
 790   }
 791 
 792   _initialized = true;
 793 }
 794 
 795 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
 796   CompilationPolicy::replay_training_at_init_loop(thread);
 797 }
 798 
 799 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 800 // Entry for DeoptimizeObjectsALotThread. The threads are started in
 801 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
 802 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
 803     DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
 804     bool enter_single_loop;
 805     {
 806       MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
 807       static int single_thread_count = 0;
 808       enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
 809     }
 810     if (enter_single_loop) {
 811       dt->deoptimize_objects_alot_loop_single();
 812     } else {
 813       dt->deoptimize_objects_alot_loop_all();
 814     }
 815   }
 816 
 817 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
 818 // barrier targets a single thread which is selected round robin.
 819 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_single() {
 820   HandleMark hm(this);
 821   while (true) {
 822     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *deoptee_thread = jtiwh.next(); ) {
 823       { // Begin new scope for escape barrier
 824         HandleMarkCleaner hmc(this);
 825         ResourceMark rm(this);
 826         EscapeBarrier eb(true, this, deoptee_thread);
 827         eb.deoptimize_objects(100);
 828       }
 829       // Now sleep after the escape barriers destructor resumed deoptee_thread.
 830       sleep(DeoptimizeObjectsALotInterval);
 831     }
 832   }
 833 }
 834 
 835 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
 836 // barrier targets all java threads in the vm at once.
 837 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_all() {
 838   HandleMark hm(this);
 839   while (true) {
 840     { // Begin new scope for escape barrier
 841       HandleMarkCleaner hmc(this);
 842       ResourceMark rm(this);
 843       EscapeBarrier eb(true, this);
 844       eb.deoptimize_objects_all_threads();
 845     }
 846     // Now sleep after the escape barriers destructor resumed the java threads.
 847     sleep(DeoptimizeObjectsALotInterval);
 848   }
 849 }
 850 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
 851 
 852 
 853 JavaThread* CompileBroker::make_thread(ThreadType type, jobject thread_handle, CompileQueue* queue, AbstractCompiler* comp, JavaThread* THREAD) {
 854   Handle thread_oop(THREAD, JNIHandles::resolve_non_null(thread_handle));
 855 
 856   if (java_lang_Thread::thread(thread_oop()) != nullptr) {
 857     assert(type == compiler_t, "should only happen with reused compiler threads");
 858     // The compiler thread hasn't actually exited yet so don't try to reuse it
 859     return nullptr;
 860   }
 861 
 862   JavaThread* new_thread = nullptr;
 863   switch (type) {
 864     case compiler_t:
 865       assert(comp != nullptr, "Compiler instance missing.");
 866       if (!InjectCompilerCreationFailure || comp->num_compiler_threads() == 0) {
 867         CompilerCounters* counters = new CompilerCounters();
 868         new_thread = new CompilerThread(queue, counters);
 869       }
 870       break;
 871 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 872     case deoptimizer_t:
 873       new_thread = new DeoptimizeObjectsALotThread();
 874       break;
 875 #endif // ASSERT
 876     case training_replay_t:
 877       new_thread = new TrainingReplayThread();
 878       break;
 879     default:
 880       ShouldNotReachHere();
 881   }
 882 
 883   // At this point the new CompilerThread data-races with this startup
 884   // thread (which is the main thread and NOT the VM thread).
 885   // This means Java bytecodes being executed at startup can
 886   // queue compile jobs which will run at whatever default priority the
 887   // newly created CompilerThread runs at.
 888 
 889 
 890   // At this point it may be possible that no osthread was created for the
 891   // JavaThread due to lack of resources. We will handle that failure below.
 892   // Also check new_thread so that static analysis is happy.
 893   if (new_thread != nullptr && new_thread->osthread() != nullptr) {
 894 
 895     if (type == compiler_t) {
 896       CompilerThread::cast(new_thread)->set_compiler(comp);
 897     }
 898 
 899     // Note that we cannot call os::set_priority because it expects Java
 900     // priorities and we are *explicitly* using OS priorities so that it's
 901     // possible to set the compiler thread priority higher than any Java
 902     // thread.
 903 
 904     int native_prio = CompilerThreadPriority;
 905     if (native_prio == -1) {
 906       if (UseCriticalCompilerThreadPriority) {
 907         native_prio = os::java_to_os_priority[CriticalPriority];
 908       } else {
 909         native_prio = os::java_to_os_priority[NearMaxPriority];
 910       }
 911     }
 912     os::set_native_priority(new_thread, native_prio);
 913 
 914     // Note that this only sets the JavaThread _priority field, which by
 915     // definition is limited to Java priorities and not OS priorities.
 916     JavaThread::start_internal_daemon(THREAD, new_thread, thread_oop, NearMaxPriority);
 917 
 918   } else { // osthread initialization failure
 919     if (UseDynamicNumberOfCompilerThreads && type == compiler_t
 920         && comp->num_compiler_threads() > 0) {
 921       // The new thread is not known to Thread-SMR yet so we can just delete.
 922       delete new_thread;
 923       return nullptr;
 924     } else {
 925       vm_exit_during_initialization("java.lang.OutOfMemoryError",
 926                                     os::native_thread_creation_failed_msg());
 927     }
 928   }
 929 
 930   os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
 931 
 932   return new_thread;
 933 }
 934 
 935 static bool trace_compiler_threads() {
 936   LogTarget(Debug, jit, thread) lt;
 937   return TraceCompilerThreads || lt.is_enabled();
 938 }
 939 
 940 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
 941   char name_buffer[256];
 942   os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
 943   Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
 944   return JNIHandles::make_global(thread_oop);
 945 }
 946 
 947 static void print_compiler_threads(stringStream& msg) {
 948   if (TraceCompilerThreads) {
 949     tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
 950   }
 951   LogTarget(Debug, jit, thread) lt;
 952   if (lt.is_enabled()) {
 953     LogStream ls(lt);
 954     ls.print_cr("%s", msg.as_string());
 955   }
 956 }
 957 
 958 void CompileBroker::init_compiler_threads() {
 959   // Ensure any exceptions lead to vm_exit_during_initialization.
 960   EXCEPTION_MARK;
 961 #if !defined(ZERO)
 962   assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
 963 #endif // !ZERO
 964   // Initialize the compilation queue
 965   if (_c2_count > 0) {
 966     const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
 967     _c2_compile_queue  = new CompileQueue(name);
 968     _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
 969     _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
 970   }
 971   if (_c1_count > 0) {
 972     _c1_compile_queue  = new CompileQueue("C1 compile queue");
 973     _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
 974     _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
 975   }
 976 
 977   for (int i = 0; i < _c2_count; i++) {
 978     // Create a name for our thread.
 979     jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
 980     _compiler2_objects[i] = thread_handle;
 981     _compiler2_logs[i] = nullptr;
 982 
 983     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
 984       JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
 985       assert(ct != nullptr, "should have been handled for initial thread");
 986       _compilers[1]->set_num_compiler_threads(i + 1);
 987       if (trace_compiler_threads()) {
 988         ResourceMark rm;
 989         ThreadsListHandle tlh;  // name() depends on the TLH.
 990         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
 991         stringStream msg;
 992         msg.print("Added initial compiler thread %s", ct->name());
 993         print_compiler_threads(msg);
 994       }
 995     }
 996   }
 997 
 998   for (int i = 0; i < _c1_count; i++) {
 999     // Create a name for our thread.
1000     jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
1001     _compiler1_objects[i] = thread_handle;
1002     _compiler1_logs[i] = nullptr;
1003 
1004     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1005       JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1006       assert(ct != nullptr, "should have been handled for initial thread");
1007       _compilers[0]->set_num_compiler_threads(i + 1);
1008       if (trace_compiler_threads()) {
1009         ResourceMark rm;
1010         ThreadsListHandle tlh;  // name() depends on the TLH.
1011         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1012         stringStream msg;
1013         msg.print("Added initial compiler thread %s", ct->name());
1014         print_compiler_threads(msg);
1015       }
1016     }
1017   }
1018 
1019   if (UsePerfData) {
1020     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK);
1021   }
1022 
1023 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1024   if (DeoptimizeObjectsALot) {
1025     // Initialize and start the object deoptimizer threads
1026     const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1027     for (int count = 0; count < total_count; count++) {
1028       Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1029       jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1030       make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1031     }
1032   }
1033 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1034 }
1035 
1036 void CompileBroker::init_training_replay() {
1037   // Ensure any exceptions lead to vm_exit_during_initialization.
1038   EXCEPTION_MARK;
1039   if (TrainingData::have_data()) {
1040     Handle thread_oop = JavaThread::create_system_thread_object("Training replay thread", CHECK);
1041     jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1042     make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1043   }
1044 }
1045 
1046 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1047 
1048   int old_c2_count = 0, new_c2_count = 0, old_c1_count = 0, new_c1_count = 0;
1049   const int c2_tasks_per_thread = 2, c1_tasks_per_thread = 4;
1050 
1051   // Quick check if we already have enough compiler threads without taking the lock.
1052   // Numbers may change concurrently, so we read them again after we have the lock.
1053   if (_c2_compile_queue != nullptr) {
1054     old_c2_count = get_c2_thread_count();
1055     new_c2_count = MIN2(_c2_count, _c2_compile_queue->size() / c2_tasks_per_thread);
1056   }
1057   if (_c1_compile_queue != nullptr) {
1058     old_c1_count = get_c1_thread_count();
1059     new_c1_count = MIN2(_c1_count, _c1_compile_queue->size() / c1_tasks_per_thread);
1060   }
1061   if (new_c2_count <= old_c2_count && new_c1_count <= old_c1_count) return;
1062 
1063   // Now, we do the more expensive operations.
1064   size_t free_memory = 0;
1065   // Return value ignored - defaulting to 0 on failure.
1066   (void)os::free_memory(free_memory);
1067   // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).
1068   size_t available_cc_np = CodeCache::unallocated_capacity(CodeBlobType::MethodNonProfiled),
1069          available_cc_p  = CodeCache::unallocated_capacity(CodeBlobType::MethodProfiled);
1070 
1071   // Only attempt to start additional threads if the lock is free.
1072   if (!CompileThread_lock->try_lock()) return;
1073 
1074   if (_c2_compile_queue != nullptr) {
1075     old_c2_count = get_c2_thread_count();
1076     new_c2_count = MIN4(_c2_count,
1077         _c2_compile_queue->size() / c2_tasks_per_thread,
1078         (int)(free_memory / (200*M)),
1079         (int)(available_cc_np / (128*K)));
1080 
1081     for (int i = old_c2_count; i < new_c2_count; i++) {
1082 #if INCLUDE_JVMCI
1083       if (UseJVMCICompiler && !UseJVMCINativeLibrary && _compiler2_objects[i] == nullptr) {
1084         // Native compiler threads as used in C1/C2 can reuse the j.l.Thread objects as their
1085         // existence is completely hidden from the rest of the VM (and those compiler threads can't
1086         // call Java code to do the creation anyway).
1087         //
1088         // For pure Java JVMCI we have to create new j.l.Thread objects as they are visible and we
1089         // can see unexpected thread lifecycle transitions if we bind them to new JavaThreads.  For
1090         // native library JVMCI it's preferred to use the C1/C2 strategy as this avoids unnecessary
1091         // coupling with Java.
1092         if (!THREAD->can_call_java()) break;
1093         char name_buffer[256];
1094         os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", _compilers[1]->name(), i);
1095         Handle thread_oop;
1096         {
1097           // We have to give up the lock temporarily for the Java calls.
1098           MutexUnlocker mu(CompileThread_lock);
1099           thread_oop = JavaThread::create_system_thread_object(name_buffer, THREAD);
1100         }
1101         if (HAS_PENDING_EXCEPTION) {
1102           if (trace_compiler_threads()) {
1103             ResourceMark rm;
1104             stringStream msg;
1105             msg.print_cr("JVMCI compiler thread creation failed:");
1106             PENDING_EXCEPTION->print_on(&msg);
1107             print_compiler_threads(msg);
1108           }
1109           CLEAR_PENDING_EXCEPTION;
1110           break;
1111         }
1112         // Check if another thread has beaten us during the Java calls.
1113         if (get_c2_thread_count() != i) break;
1114         jobject thread_handle = JNIHandles::make_global(thread_oop);
1115         assert(compiler2_object(i) == nullptr, "Old one must be released!");
1116         _compiler2_objects[i] = thread_handle;
1117       }
1118 #endif
1119       guarantee(compiler2_object(i) != nullptr, "Thread oop must exist");
1120       JavaThread *ct = make_thread(compiler_t, compiler2_object(i), _c2_compile_queue, _compilers[1], THREAD);
1121       if (ct == nullptr) break;
1122       _compilers[1]->set_num_compiler_threads(i + 1);
1123       if (trace_compiler_threads()) {
1124         ResourceMark rm;
1125         ThreadsListHandle tlh;  // name() depends on the TLH.
1126         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1127         stringStream msg;
1128         msg.print("Added compiler thread %s (free memory: %dMB, available non-profiled code cache: %dMB)",
1129                   ct->name(), (int)(free_memory/M), (int)(available_cc_np/M));
1130         print_compiler_threads(msg);
1131       }
1132     }
1133   }
1134 
1135   if (_c1_compile_queue != nullptr) {
1136     old_c1_count = get_c1_thread_count();
1137     new_c1_count = MIN4(_c1_count,
1138         _c1_compile_queue->size() / c1_tasks_per_thread,
1139         (int)(free_memory / (100*M)),
1140         (int)(available_cc_p / (128*K)));
1141 
1142     for (int i = old_c1_count; i < new_c1_count; i++) {
1143       JavaThread *ct = make_thread(compiler_t, compiler1_object(i), _c1_compile_queue, _compilers[0], THREAD);
1144       if (ct == nullptr) break;
1145       _compilers[0]->set_num_compiler_threads(i + 1);
1146       if (trace_compiler_threads()) {
1147         ResourceMark rm;
1148         ThreadsListHandle tlh;  // name() depends on the TLH.
1149         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1150         stringStream msg;
1151         msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)",
1152                   ct->name(), (int)(free_memory/M), (int)(available_cc_p/M));
1153         print_compiler_threads(msg);
1154       }
1155     }
1156   }
1157 
1158   CompileThread_lock->unlock();
1159 }
1160 
1161 
1162 /**
1163  * Set the methods on the stack as on_stack so that redefine classes doesn't
1164  * reclaim them. This method is executed at a safepoint.
1165  */
1166 void CompileBroker::mark_on_stack() {
1167   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1168   // Since we are at a safepoint, we do not need a lock to access
1169   // the compile queues.
1170   if (_c2_compile_queue != nullptr) {
1171     _c2_compile_queue->mark_on_stack();
1172   }
1173   if (_c1_compile_queue != nullptr) {
1174     _c1_compile_queue->mark_on_stack();
1175   }
1176 }
1177 
1178 // ------------------------------------------------------------------
1179 // CompileBroker::compile_method
1180 //
1181 // Request compilation of a method.
1182 void CompileBroker::compile_method_base(const methodHandle& method,
1183                                         int osr_bci,
1184                                         int comp_level,
1185                                         int hot_count,
1186                                         CompileTask::CompileReason compile_reason,
1187                                         bool blocking,
1188                                         Thread* thread) {
1189   guarantee(!method->is_abstract(), "cannot compile abstract methods");
1190   assert(method->method_holder()->is_instance_klass(),
1191          "sanity check");
1192   assert(!method->method_holder()->is_not_initialized(),
1193          "method holder must be initialized");
1194   assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1195 
1196   if (CIPrintRequests) {
1197     tty->print("request: ");
1198     method->print_short_name(tty);
1199     if (osr_bci != InvocationEntryBci) {
1200       tty->print(" osr_bci: %d", osr_bci);
1201     }
1202     tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1203     if (hot_count > 0) {
1204       tty->print(" hot: yes");
1205     }
1206     tty->cr();
1207   }
1208 
1209   // A request has been made for compilation.  Before we do any
1210   // real work, check to see if the method has been compiled
1211   // in the meantime with a definitive result.
1212   if (compilation_is_complete(method, osr_bci, comp_level)) {
1213     return;
1214   }
1215 
1216 #ifndef PRODUCT
1217   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1218     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1219       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
1220       return;
1221     }
1222   }
1223 #endif
1224 
1225   // If this method is already in the compile queue, then
1226   // we do not block the current thread.
1227   if (compilation_is_in_queue(method)) {
1228     // We may want to decay our counter a bit here to prevent
1229     // multiple denied requests for compilation.  This is an
1230     // open compilation policy issue. Note: The other possibility,
1231     // in the case that this is a blocking compile request, is to have
1232     // all subsequent blocking requesters wait for completion of
1233     // ongoing compiles. Note that in this case we'll need a protocol
1234     // for freeing the associated compile tasks. [Or we could have
1235     // a single static monitor on which all these waiters sleep.]
1236     return;
1237   }
1238 
1239   // Tiered policy requires MethodCounters to exist before adding a method to
1240   // the queue. Create if we don't have them yet.
1241   method->get_method_counters(thread);
1242 
1243   // Outputs from the following MutexLocker block:
1244   CompileTask* task     = nullptr;
1245   CompileQueue* queue  = compile_queue(comp_level);
1246 
1247   // Acquire our lock.
1248   {
1249     MutexLocker locker(thread, MethodCompileQueue_lock);
1250 
1251     // Make sure the method has not slipped into the queues since
1252     // last we checked; note that those checks were "fast bail-outs".
1253     // Here we need to be more careful, see 14012000 below.
1254     if (compilation_is_in_queue(method)) {
1255       return;
1256     }
1257 
1258     // We need to check again to see if the compilation has
1259     // completed.  A previous compilation may have registered
1260     // some result.
1261     if (compilation_is_complete(method, osr_bci, comp_level)) {
1262       return;
1263     }
1264 
1265     // We now know that this compilation is not pending, complete,
1266     // or prohibited.  Assign a compile_id to this compilation
1267     // and check to see if it is in our [Start..Stop) range.
1268     int compile_id = assign_compile_id(method, osr_bci);
1269     if (compile_id == 0) {
1270       // The compilation falls outside the allowed range.
1271       return;
1272     }
1273 
1274 #if INCLUDE_JVMCI
1275     if (UseJVMCICompiler && blocking) {
1276       // Don't allow blocking compiles for requests triggered by JVMCI.
1277       if (thread->is_Compiler_thread()) {
1278         blocking = false;
1279       }
1280 
1281       // In libjvmci, JVMCI initialization should not deadlock with other threads
1282       if (!UseJVMCINativeLibrary) {
1283         // Don't allow blocking compiles if inside a class initializer or while performing class loading
1284         vframeStream vfst(JavaThread::cast(thread));
1285         for (; !vfst.at_end(); vfst.next()) {
1286           if (vfst.method()->is_static_initializer() ||
1287               (vfst.method()->method_holder()->is_subclass_of(vmClasses::ClassLoader_klass()) &&
1288                   vfst.method()->name() == vmSymbols::loadClass_name())) {
1289             blocking = false;
1290             break;
1291           }
1292         }
1293 
1294         // Don't allow blocking compilation requests to JVMCI
1295         // if JVMCI itself is not yet initialized
1296         if (!JVMCI::is_compiler_initialized() && compiler(comp_level)->is_jvmci()) {
1297           blocking = false;
1298         }
1299       }
1300 
1301       // Don't allow blocking compilation requests if we are in JVMCIRuntime::shutdown
1302       // to avoid deadlock between compiler thread(s) and threads run at shutdown
1303       // such as the DestroyJavaVM thread.
1304       if (JVMCI::in_shutdown()) {
1305         blocking = false;
1306       }
1307     }
1308 #endif // INCLUDE_JVMCI
1309 
1310     // We will enter the compilation in the queue.
1311     // 14012000: Note that this sets the queued_for_compile bits in
1312     // the target method. We can now reason that a method cannot be
1313     // queued for compilation more than once, as follows:
1314     // Before a thread queues a task for compilation, it first acquires
1315     // the compile queue lock, then checks if the method's queued bits
1316     // are set or it has already been compiled. Thus there can not be two
1317     // instances of a compilation task for the same method on the
1318     // compilation queue. Consider now the case where the compilation
1319     // thread has already removed a task for that method from the queue
1320     // and is in the midst of compiling it. In this case, the
1321     // queued_for_compile bits must be set in the method (and these
1322     // will be visible to the current thread, since the bits were set
1323     // under protection of the compile queue lock, which we hold now.
1324     // When the compilation completes, the compiler thread first sets
1325     // the compilation result and then clears the queued_for_compile
1326     // bits. Neither of these actions are protected by a barrier (or done
1327     // under the protection of a lock), so the only guarantee we have
1328     // (on machines with TSO (Total Store Order)) is that these values
1329     // will update in that order. As a result, the only combinations of
1330     // these bits that the current thread will see are, in temporal order:
1331     // <RESULT, QUEUE> :
1332     //     <0, 1> : in compile queue, but not yet compiled
1333     //     <1, 1> : compiled but queue bit not cleared
1334     //     <1, 0> : compiled and queue bit cleared
1335     // Because we first check the queue bits then check the result bits,
1336     // we are assured that we cannot introduce a duplicate task.
1337     // Note that if we did the tests in the reverse order (i.e. check
1338     // result then check queued bit), we could get the result bit before
1339     // the compilation completed, and the queue bit after the compilation
1340     // completed, and end up introducing a "duplicate" (redundant) task.
1341     // In that case, the compiler thread should first check if a method
1342     // has already been compiled before trying to compile it.
1343     // NOTE: in the event that there are multiple compiler threads and
1344     // there is de-optimization/recompilation, things will get hairy,
1345     // and in that case it's best to protect both the testing (here) of
1346     // these bits, and their updating (here and elsewhere) under a
1347     // common lock.
1348     task = create_compile_task(queue,
1349                                compile_id, method,
1350                                osr_bci, comp_level,
1351                                hot_count, compile_reason,
1352                                blocking);
1353   }
1354 
1355   if (blocking) {
1356     wait_for_completion(task);
1357   }
1358 }
1359 
1360 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1361                                        int comp_level,
1362                                        int hot_count,
1363                                        CompileTask::CompileReason compile_reason,
1364                                        TRAPS) {
1365   // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1366   if (!_initialized || comp_level == CompLevel_none) {
1367     return nullptr;
1368   }
1369 
1370   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1371   assert(comp != nullptr, "Ensure we have a compiler");
1372 
1373 #if INCLUDE_JVMCI
1374   if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1375     // JVMCI compilation is not yet initializable.
1376     return nullptr;
1377   }
1378 #endif
1379 
1380   DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1381   // CompileBroker::compile_method can trap and can have pending async exception.
1382   nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_count, compile_reason, directive, THREAD);
1383   DirectivesStack::release(directive);
1384   return nm;
1385 }
1386 
1387 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1388                                          int comp_level,
1389                                          int hot_count,
1390                                          CompileTask::CompileReason compile_reason,
1391                                          DirectiveSet* directive,
1392                                          TRAPS) {
1393 
1394   // make sure arguments make sense
1395   assert(method->method_holder()->is_instance_klass(), "not an instance method");
1396   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1397   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1398   assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");
1399   // return quickly if possible
1400 
1401   // lock, make sure that the compilation
1402   // isn't prohibited in a straightforward way.
1403   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1404   if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1405     return nullptr;
1406   }
1407 
1408   if (osr_bci == InvocationEntryBci) {
1409     // standard compilation
1410     nmethod* method_code = method->code();
1411     if (method_code != nullptr) {
1412       if (compilation_is_complete(method, osr_bci, comp_level)) {
1413         return method_code;
1414       }
1415     }
1416     if (method->is_not_compilable(comp_level)) {
1417       return nullptr;
1418     }
1419   } else {
1420     // osr compilation
1421     // We accept a higher level osr method
1422     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1423     if (nm != nullptr) return nm;
1424     if (method->is_not_osr_compilable(comp_level)) return nullptr;
1425   }
1426 
1427   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1428   // some prerequisites that are compiler specific
1429   if (comp->is_c2() || comp->is_jvmci()) {
1430     InternalOOMEMark iom(THREAD);
1431     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1432     // Resolve all classes seen in the signature of the method
1433     // we are compiling.
1434     Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1435   }
1436 
1437   // If the method is native, do the lookup in the thread requesting
1438   // the compilation. Native lookups can load code, which is not
1439   // permitted during compilation.
1440   //
1441   // Note: A native method implies non-osr compilation which is
1442   //       checked with an assertion at the entry of this method.
1443   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1444     address adr = NativeLookup::lookup(method, THREAD);
1445     if (HAS_PENDING_EXCEPTION) {
1446       // In case of an exception looking up the method, we just forget
1447       // about it. The interpreter will kick-in and throw the exception.
1448       method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1449       CLEAR_PENDING_EXCEPTION;
1450       return nullptr;
1451     }
1452     assert(method->has_native_function(), "must have native code by now");
1453   }
1454 
1455   // RedefineClasses() has replaced this method; just return
1456   if (method->is_old()) {
1457     return nullptr;
1458   }
1459 
1460   // JVMTI -- post_compile_event requires jmethod_id() that may require
1461   // a lock the compiling thread can not acquire. Prefetch it here.
1462   if (JvmtiExport::should_post_compiled_method_load()) {
1463     method->jmethod_id();
1464   }
1465 
1466   // do the compilation
1467   if (method->is_native()) {
1468     if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1469       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1470       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1471       //
1472       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1473       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1474       AdapterHandlerLibrary::create_native_wrapper(method);
1475     } else {
1476       return nullptr;
1477     }
1478   } else {
1479     // If the compiler is shut off due to code cache getting full
1480     // fail out now so blocking compiles dont hang the java thread
1481     if (!should_compile_new_jobs()) {
1482       return nullptr;
1483     }
1484     bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles;
1485     compile_method_base(method, osr_bci, comp_level, hot_count, compile_reason, is_blocking, THREAD);
1486   }
1487 
1488   // return requested nmethod
1489   // We accept a higher level osr method
1490   if (osr_bci == InvocationEntryBci) {
1491     return method->code();
1492   }
1493   return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1494 }
1495 
1496 
1497 // ------------------------------------------------------------------
1498 // CompileBroker::compilation_is_complete
1499 //
1500 // See if compilation of this method is already complete.
1501 bool CompileBroker::compilation_is_complete(const methodHandle& method,
1502                                             int                 osr_bci,
1503                                             int                 comp_level) {
1504   bool is_osr = (osr_bci != standard_entry_bci);
1505   if (is_osr) {
1506     if (method->is_not_osr_compilable(comp_level)) {
1507       return true;
1508     } else {
1509       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1510       return (result != nullptr);
1511     }
1512   } else {
1513     if (method->is_not_compilable(comp_level)) {
1514       return true;
1515     } else {
1516       nmethod* result = method->code();
1517       if (result == nullptr) return false;
1518       return comp_level == result->comp_level();
1519     }
1520   }
1521 }
1522 
1523 
1524 /**
1525  * See if this compilation is already requested.
1526  *
1527  * Implementation note: there is only a single "is in queue" bit
1528  * for each method.  This means that the check below is overly
1529  * conservative in the sense that an osr compilation in the queue
1530  * will block a normal compilation from entering the queue (and vice
1531  * versa).  This can be remedied by a full queue search to disambiguate
1532  * cases.  If it is deemed profitable, this may be done.
1533  */
1534 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1535   return method->queued_for_compilation();
1536 }
1537 
1538 // ------------------------------------------------------------------
1539 // CompileBroker::compilation_is_prohibited
1540 //
1541 // See if this compilation is not allowed.
1542 bool CompileBroker::compilation_is_prohibited(const methodHandle& method, int osr_bci, int comp_level, bool excluded) {
1543   bool is_native = method->is_native();
1544   // Some compilers may not support the compilation of natives.
1545   AbstractCompiler *comp = compiler(comp_level);
1546   if (is_native && (!CICompileNatives || comp == nullptr)) {
1547     method->set_not_compilable_quietly("native methods not supported", comp_level);
1548     return true;
1549   }
1550 
1551   bool is_osr = (osr_bci != standard_entry_bci);
1552   // Some compilers may not support on stack replacement.
1553   if (is_osr && (!CICompileOSR || comp == nullptr)) {
1554     method->set_not_osr_compilable("OSR not supported", comp_level);
1555     return true;
1556   }
1557 
1558   // The method may be explicitly excluded by the user.
1559   double scale;
1560   if (excluded || (CompilerOracle::has_option_value(method, CompileCommandEnum::CompileThresholdScaling, scale) && scale == 0)) {
1561     bool quietly = CompilerOracle::be_quiet();
1562     if (PrintCompilation && !quietly) {
1563       // This does not happen quietly...
1564       ResourceMark rm;
1565       tty->print("### Excluding %s:%s",
1566                  method->is_native() ? "generation of native wrapper" : "compile",
1567                  (method->is_static() ? " static" : ""));
1568       method->print_short_name(tty);
1569       tty->cr();
1570     }
1571     method->set_not_compilable("excluded by CompileCommand", comp_level, !quietly);
1572   }
1573 
1574   return false;
1575 }
1576 
1577 /**
1578  * Generate serialized IDs for compilation requests. If certain debugging flags are used
1579  * and the ID is not within the specified range, the method is not compiled and 0 is returned.
1580  * The function also allows to generate separate compilation IDs for OSR compilations.
1581  */
1582 int CompileBroker::assign_compile_id(const methodHandle& method, int osr_bci) {
1583 #ifdef ASSERT
1584   bool is_osr = (osr_bci != standard_entry_bci);
1585   int id;
1586   if (method->is_native()) {
1587     assert(!is_osr, "can't be osr");
1588     // Adapters, native wrappers and method handle intrinsics
1589     // should be generated always.
1590     return Atomic::add(CICountNative ? &_native_compilation_id : &_compilation_id, 1);
1591   } else if (CICountOSR && is_osr) {
1592     id = Atomic::add(&_osr_compilation_id, 1);
1593     if (CIStartOSR <= id && id < CIStopOSR) {
1594       return id;
1595     }
1596   } else {
1597     id = Atomic::add(&_compilation_id, 1);
1598     if (CIStart <= id && id < CIStop) {
1599       return id;
1600     }
1601   }
1602 
1603   // Method was not in the appropriate compilation range.
1604   method->set_not_compilable_quietly("Not in requested compile id range");
1605   return 0;
1606 #else
1607   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1608   // only _compilation_id is incremented.
1609   return Atomic::add(&_compilation_id, 1);
1610 #endif
1611 }
1612 
1613 // ------------------------------------------------------------------
1614 // CompileBroker::assign_compile_id_unlocked
1615 //
1616 // Public wrapper for assign_compile_id that acquires the needed locks
1617 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1618   MutexLocker locker(thread, MethodCompileQueue_lock);
1619   return assign_compile_id(method, osr_bci);
1620 }
1621 
1622 // ------------------------------------------------------------------
1623 // CompileBroker::create_compile_task
1624 //
1625 // Create a CompileTask object representing the current request for
1626 // compilation.  Add this task to the queue.
1627 CompileTask* CompileBroker::create_compile_task(CompileQueue*       queue,
1628                                                 int                 compile_id,
1629                                                 const methodHandle& method,
1630                                                 int                 osr_bci,
1631                                                 int                 comp_level,
1632                                                 int                 hot_count,
1633                                                 CompileTask::CompileReason compile_reason,
1634                                                 bool                blocking) {
1635   CompileTask* new_task = new CompileTask(compile_id, method, osr_bci, comp_level,
1636                                           hot_count, compile_reason, blocking);
1637   queue->add(new_task);
1638   return new_task;
1639 }
1640 
1641 #if INCLUDE_JVMCI
1642 // The number of milliseconds to wait before checking if
1643 // JVMCI compilation has made progress.
1644 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1645 
1646 // The number of JVMCI compilation progress checks that must fail
1647 // before unblocking a thread waiting for a blocking compilation.
1648 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1649 
1650 /**
1651  * Waits for a JVMCI compiler to complete a given task. This thread
1652  * waits until either the task completes or it sees no JVMCI compilation
1653  * progress for N consecutive milliseconds where N is
1654  * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1655  * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1656  *
1657  * @return true if this thread needs to delete the task
1658  */
1659 bool CompileBroker::wait_for_jvmci_completion(JVMCICompiler* jvmci, CompileTask* task, JavaThread* thread) {
1660   assert(UseJVMCICompiler, "sanity");
1661   MonitorLocker ml(thread, CompileTaskWait_lock);
1662   int progress_wait_attempts = 0;
1663   jint thread_jvmci_compilation_ticks = 0;
1664   jint global_jvmci_compilation_ticks = jvmci->global_compilation_ticks();
1665   while (!task->is_complete() && !is_compilation_disabled_forever() &&
1666          ml.wait(JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE)) {
1667     JVMCICompileState* jvmci_compile_state = task->blocking_jvmci_compile_state();
1668 
1669     bool progress;
1670     if (jvmci_compile_state != nullptr) {
1671       jint ticks = jvmci_compile_state->compilation_ticks();
1672       progress = (ticks - thread_jvmci_compilation_ticks) != 0;
1673       JVMCI_event_1("waiting on compilation %d [ticks=%d]", task->compile_id(), ticks);
1674       thread_jvmci_compilation_ticks = ticks;
1675     } else {
1676       // Still waiting on JVMCI compiler queue. This thread may be holding a lock
1677       // that all JVMCI compiler threads are blocked on. We use the global JVMCI
1678       // compilation ticks to determine whether JVMCI compilation
1679       // is still making progress through the JVMCI compiler queue.
1680       jint ticks = jvmci->global_compilation_ticks();
1681       progress = (ticks - global_jvmci_compilation_ticks) != 0;
1682       JVMCI_event_1("waiting on compilation %d to be queued [ticks=%d]", task->compile_id(), ticks);
1683       global_jvmci_compilation_ticks = ticks;
1684     }
1685 
1686     if (!progress) {
1687       if (++progress_wait_attempts == JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS) {
1688         if (PrintCompilation) {
1689           task->print(tty, "wait for blocking compilation timed out");
1690         }
1691         JVMCI_event_1("waiting on compilation %d timed out", task->compile_id());
1692         break;
1693       }
1694     } else {
1695       progress_wait_attempts = 0;
1696     }
1697   }
1698   task->clear_waiter();
1699   return task->is_complete();
1700 }
1701 #endif
1702 
1703 /**
1704  *  Wait for the compilation task to complete.
1705  */
1706 void CompileBroker::wait_for_completion(CompileTask* task) {
1707   if (CIPrintCompileQueue) {
1708     ttyLocker ttyl;
1709     tty->print_cr("BLOCKING FOR COMPILE");
1710   }
1711 
1712   assert(task->is_blocking(), "can only wait on blocking task");
1713 
1714   JavaThread* thread = JavaThread::current();
1715 
1716   methodHandle method(thread, task->method());
1717   bool free_task;
1718 #if INCLUDE_JVMCI
1719   AbstractCompiler* comp = compiler(task->comp_level());
1720   if (!UseJVMCINativeLibrary && comp->is_jvmci() && !task->should_wait_for_compilation()) {
1721     // It may return before compilation is completed.
1722     // Note that libjvmci should not pre-emptively unblock
1723     // a thread waiting for a compilation as it does not call
1724     // Java code and so is not deadlock prone like jarjvmci.
1725     free_task = wait_for_jvmci_completion((JVMCICompiler*) comp, task, thread);
1726   } else
1727 #endif
1728   {
1729     free_task = true;
1730     // Wait until the task is complete or compilation is shut down.
1731     MonitorLocker ml(thread, CompileTaskWait_lock);
1732     while (!task->is_complete() && !is_compilation_disabled_forever()) {
1733       ml.wait();
1734     }
1735   }
1736 
1737   // It is harmless to check this status without the lock, because
1738   // completion is a stable property.
1739   if (!task->is_complete()) {
1740     // Task is not complete, likely because we are exiting for compilation
1741     // shutdown. The task can still be reached through the queue, or executed
1742     // by some compiler thread. There is no coordination with either MCQ lock
1743     // holders or compilers, therefore we cannot delete the task.
1744     //
1745     // This will leave task allocated, which leaks it. At this (degraded) point,
1746     // it is less risky to abandon the task, rather than attempting a more
1747     // complicated deletion protocol.
1748     free_task = false;
1749   }
1750 
1751   if (free_task) {
1752     assert(task->is_complete(), "Compilation should have completed");
1753     assert(task->next() == nullptr && task->prev() == nullptr,
1754            "Completed task should not be in the queue");
1755 
1756     // By convention, the waiter is responsible for deleting a
1757     // blocking CompileTask. Since there is only one waiter ever
1758     // waiting on a CompileTask, we know that no one else will
1759     // be using this CompileTask; we can delete it.
1760     delete task;
1761   }
1762 }
1763 
1764 void CompileBroker::wait_for_no_active_tasks() {
1765   CompileTask::wait_for_no_active_tasks();
1766 }
1767 
1768 /**
1769  * Initialize compiler thread(s) + compiler object(s). The postcondition
1770  * of this function is that the compiler runtimes are initialized and that
1771  * compiler threads can start compiling.
1772  */
1773 bool CompileBroker::init_compiler_runtime() {
1774   CompilerThread* thread = CompilerThread::current();
1775   AbstractCompiler* comp = thread->compiler();
1776   // Final sanity check - the compiler object must exist
1777   guarantee(comp != nullptr, "Compiler object must exist");
1778 
1779   {
1780     // Must switch to native to allocate ci_env
1781     ThreadToNativeFromVM ttn(thread);
1782     ciEnv ci_env((CompileTask*)nullptr);
1783     // Cache Jvmti state
1784     ci_env.cache_jvmti_state();
1785     // Cache DTrace flags
1786     ci_env.cache_dtrace_flags();
1787 
1788     // Switch back to VM state to do compiler initialization
1789     ThreadInVMfromNative tv(thread);
1790 
1791     // Perform per-thread and global initializations
1792     comp->initialize();
1793   }
1794 
1795   if (comp->is_failed()) {
1796     disable_compilation_forever();
1797     // If compiler initialization failed, no compiler thread that is specific to a
1798     // particular compiler runtime will ever start to compile methods.
1799     shutdown_compiler_runtime(comp, thread);
1800     return false;
1801   }
1802 
1803   // C1 specific check
1804   if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
1805     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
1806     return false;
1807   }
1808 
1809   return true;
1810 }
1811 
1812 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
1813   BufferBlob* blob = thread->get_buffer_blob();
1814   if (blob != nullptr) {
1815     blob->purge();
1816     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1817     CodeCache::free(blob);
1818   }
1819 }
1820 
1821 /**
1822  * If C1 and/or C2 initialization failed, we shut down all compilation.
1823  * We do this to keep things simple. This can be changed if it ever turns
1824  * out to be a problem.
1825  */
1826 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
1827   free_buffer_blob_if_allocated(thread);
1828 
1829   if (comp->should_perform_shutdown()) {
1830     // There are two reasons for shutting down the compiler
1831     // 1) compiler runtime initialization failed
1832     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
1833     warning("%s initialization failed. Shutting down all compilers", comp->name());
1834 
1835     // Only one thread per compiler runtime object enters here
1836     // Set state to shut down
1837     comp->set_shut_down();
1838 
1839     // Delete all queued compilation tasks to make compiler threads exit faster.
1840     if (_c1_compile_queue != nullptr) {
1841       _c1_compile_queue->delete_all();
1842     }
1843 
1844     if (_c2_compile_queue != nullptr) {
1845       _c2_compile_queue->delete_all();
1846     }
1847 
1848     // Set flags so that we continue execution with using interpreter only.
1849     UseCompiler    = false;
1850     UseInterpreter = true;
1851 
1852     // We could delete compiler runtimes also. However, there are references to
1853     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
1854     // fail. This can be done later if necessary.
1855   }
1856 }
1857 
1858 /**
1859  * Helper function to create new or reuse old CompileLog.
1860  */
1861 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
1862   if (!LogCompilation) return nullptr;
1863 
1864   AbstractCompiler *compiler = ct->compiler();
1865   bool c1 = compiler->is_c1();
1866   jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;
1867   assert(compiler_objects != nullptr, "must be initialized at this point");
1868   CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;
1869   assert(logs != nullptr, "must be initialized at this point");
1870   int count = c1 ? _c1_count : _c2_count;
1871 
1872   // Find Compiler number by its threadObj.
1873   oop compiler_obj = ct->threadObj();
1874   int compiler_number = 0;
1875   bool found = false;
1876   for (; compiler_number < count; compiler_number++) {
1877     if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
1878       found = true;
1879       break;
1880     }
1881   }
1882   assert(found, "Compiler must exist at this point");
1883 
1884   // Determine pointer for this thread's log.
1885   CompileLog** log_ptr = &logs[compiler_number];
1886 
1887   // Return old one if it exists.
1888   CompileLog* log = *log_ptr;
1889   if (log != nullptr) {
1890     ct->init_log(log);
1891     return log;
1892   }
1893 
1894   // Create a new one and remember it.
1895   init_compiler_thread_log();
1896   log = ct->log();
1897   *log_ptr = log;
1898   return log;
1899 }
1900 
1901 // ------------------------------------------------------------------
1902 // CompileBroker::compiler_thread_loop
1903 //
1904 // The main loop run by a CompilerThread.
1905 void CompileBroker::compiler_thread_loop() {
1906   CompilerThread* thread = CompilerThread::current();
1907   CompileQueue* queue = thread->queue();
1908   // For the thread that initializes the ciObjectFactory
1909   // this resource mark holds all the shared objects
1910   ResourceMark rm;
1911 
1912   // First thread to get here will initialize the compiler interface
1913 
1914   {
1915     ASSERT_IN_VM;
1916     MutexLocker only_one (thread, CompileThread_lock);
1917     if (!ciObjectFactory::is_initialized()) {
1918       ciObjectFactory::initialize();
1919     }
1920   }
1921 
1922   // Open a log.
1923   CompileLog* log = get_log(thread);
1924   if (log != nullptr) {
1925     log->begin_elem("start_compile_thread name='%s' thread='%zu' process='%d'",
1926                     thread->name(),
1927                     os::current_thread_id(),
1928                     os::current_process_id());
1929     log->stamp();
1930     log->end_elem();
1931   }
1932 
1933   if (!thread->init_compilation_timeout()) {
1934     return;
1935   }
1936 
1937   // If compiler thread/runtime initialization fails, exit the compiler thread
1938   if (!init_compiler_runtime()) {
1939     return;
1940   }
1941 
1942   thread->start_idle_timer();
1943 
1944   // Poll for new compilation tasks as long as the JVM runs. Compilation
1945   // should only be disabled if something went wrong while initializing the
1946   // compiler runtimes. This, in turn, should not happen. The only known case
1947   // when compiler runtime initialization fails is if there is not enough free
1948   // space in the code cache to generate the necessary stubs, etc.
1949   while (!is_compilation_disabled_forever()) {
1950     // We need this HandleMark to avoid leaking VM handles.
1951     HandleMark hm(thread);
1952 
1953     CompileTask* task = queue->get(thread);
1954     if (task == nullptr) {
1955       if (UseDynamicNumberOfCompilerThreads) {
1956         // Access compiler_count under lock to enforce consistency.
1957         MutexLocker only_one(CompileThread_lock);
1958         if (can_remove(thread, true)) {
1959           if (trace_compiler_threads()) {
1960             ResourceMark rm;
1961             stringStream msg;
1962             msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
1963                       thread->name(), thread->idle_time_millis());
1964             print_compiler_threads(msg);
1965           }
1966 
1967           // Notify compiler that the compiler thread is about to stop
1968           thread->compiler()->stopping_compiler_thread(thread);
1969 
1970           free_buffer_blob_if_allocated(thread);
1971           return; // Stop this thread.
1972         }
1973       }
1974     } else {
1975       // Assign the task to the current thread.  Mark this compilation
1976       // thread as active for the profiler.
1977       // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
1978       // occurs after fetching the compile task off the queue.
1979       CompileTaskWrapper ctw(task);
1980       methodHandle method(thread, task->method());
1981 
1982       // Never compile a method if breakpoints are present in it
1983       if (method()->number_of_breakpoints() == 0) {
1984         // Compile the method.
1985         if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1986           invoke_compiler_on_method(task);
1987           thread->start_idle_timer();
1988         } else {
1989           // After compilation is disabled, remove remaining methods from queue
1990           method->clear_queued_for_compilation();
1991           task->set_failure_reason("compilation is disabled");
1992         }
1993       } else {
1994         task->set_failure_reason("breakpoints are present");
1995       }
1996 
1997       if (UseDynamicNumberOfCompilerThreads) {
1998         possibly_add_compiler_threads(thread);
1999         assert(!thread->has_pending_exception(), "should have been handled");
2000       }
2001     }
2002   }
2003 
2004   // Shut down compiler runtime
2005   shutdown_compiler_runtime(thread->compiler(), thread);
2006 }
2007 
2008 // ------------------------------------------------------------------
2009 // CompileBroker::init_compiler_thread_log
2010 //
2011 // Set up state required by +LogCompilation.
2012 void CompileBroker::init_compiler_thread_log() {
2013     CompilerThread* thread = CompilerThread::current();
2014     char  file_name[4*K];
2015     FILE* fp = nullptr;
2016     intx thread_id = os::current_thread_id();
2017     for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
2018       const char* dir = (try_temp_dir ? os::get_temp_directory() : nullptr);
2019       if (dir == nullptr) {
2020         jio_snprintf(file_name, sizeof(file_name), "hs_c%zu_pid%u.log",
2021                      thread_id, os::current_process_id());
2022       } else {
2023         jio_snprintf(file_name, sizeof(file_name),
2024                      "%s%shs_c%zu_pid%u.log", dir,
2025                      os::file_separator(), thread_id, os::current_process_id());
2026       }
2027 
2028       fp = os::fopen(file_name, "wt");
2029       if (fp != nullptr) {
2030         if (LogCompilation && Verbose) {
2031           tty->print_cr("Opening compilation log %s", file_name);
2032         }
2033         CompileLog* log = new(mtCompiler) CompileLog(file_name, fp, thread_id);
2034         if (log == nullptr) {
2035           fclose(fp);
2036           return;
2037         }
2038         thread->init_log(log);
2039 
2040         if (xtty != nullptr) {
2041           ttyLocker ttyl;
2042           // Record any per thread log files
2043           xtty->elem("thread_logfile thread='%zd' filename='%s'", thread_id, file_name);
2044         }
2045         return;
2046       }
2047     }
2048     warning("Cannot open log file: %s", file_name);
2049 }
2050 
2051 void CompileBroker::log_metaspace_failure() {
2052   const char* message = "some methods may not be compiled because metaspace "
2053                         "is out of memory";
2054   if (CompilationLog::log() != nullptr) {
2055     CompilationLog::log()->log_metaspace_failure(message);
2056   }
2057   if (PrintCompilation) {
2058     tty->print_cr("COMPILE PROFILING SKIPPED: %s", message);
2059   }
2060 }
2061 
2062 
2063 // ------------------------------------------------------------------
2064 // CompileBroker::set_should_block
2065 //
2066 // Set _should_block.
2067 // Call this from the VM, with Threads_lock held and a safepoint requested.
2068 void CompileBroker::set_should_block() {
2069   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
2070   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
2071 #ifndef PRODUCT
2072   if (PrintCompilation && (Verbose || WizardMode))
2073     tty->print_cr("notifying compiler thread pool to block");
2074 #endif
2075   _should_block = true;
2076 }
2077 
2078 // ------------------------------------------------------------------
2079 // CompileBroker::maybe_block
2080 //
2081 // Call this from the compiler at convenient points, to poll for _should_block.
2082 void CompileBroker::maybe_block() {
2083   if (_should_block) {
2084 #ifndef PRODUCT
2085     if (PrintCompilation && (Verbose || WizardMode))
2086       tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current()));
2087 #endif
2088     // If we are executing a task during the request to block, report the task
2089     // before disappearing.
2090     CompilerThread* thread = CompilerThread::current();
2091     if (thread != nullptr) {
2092       CompileTask* task = thread->task();
2093       if (task != nullptr) {
2094         if (PrintCompilation) {
2095           task->print(tty, "blocked");
2096         }
2097         task->print_ul("blocked");
2098       }
2099     }
2100     // Go to VM state and block for final VM shutdown safepoint.
2101     ThreadInVMfromNative tivfn(JavaThread::current());
2102     assert(false, "Should never unblock from TIVNM entry");
2103   }
2104 }
2105 
2106 // wrapper for CodeCache::print_summary()
2107 static void codecache_print(bool detailed)
2108 {
2109   stringStream s;
2110   // Dump code cache  into a buffer before locking the tty,
2111   {
2112     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2113     CodeCache::print_summary(&s, detailed);
2114   }
2115   ttyLocker ttyl;
2116   tty->print("%s", s.freeze());
2117 }
2118 
2119 // wrapper for CodeCache::print_summary() using outputStream
2120 static void codecache_print(outputStream* out, bool detailed) {
2121   stringStream s;
2122 
2123   // Dump code cache into a buffer
2124   {
2125     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2126     CodeCache::print_summary(&s, detailed);
2127   }
2128 
2129   char* remaining_log = s.as_string();
2130   while (*remaining_log != '\0') {
2131     char* eol = strchr(remaining_log, '\n');
2132     if (eol == nullptr) {
2133       out->print_cr("%s", remaining_log);
2134       remaining_log = remaining_log + strlen(remaining_log);
2135     } else {
2136       *eol = '\0';
2137       out->print_cr("%s", remaining_log);
2138       remaining_log = eol + 1;
2139     }
2140   }
2141 }
2142 
2143 void CompileBroker::handle_compile_error(CompilerThread* thread, CompileTask* task, ciEnv* ci_env,
2144                                          int compilable, const char* failure_reason) {
2145   if (!AbortVMOnCompilationFailure) {
2146     return;
2147   }
2148   if (compilable == ciEnv::MethodCompilable_not_at_tier) {
2149     fatal("Not compilable at tier %d: %s", task->comp_level(), failure_reason);
2150   }
2151   if (compilable == ciEnv::MethodCompilable_never) {
2152     fatal("Never compilable: %s", failure_reason);
2153   }
2154 }
2155 
2156 static void post_compilation_event(EventCompilation& event, CompileTask* task) {
2157   assert(task != nullptr, "invariant");
2158   CompilerEvent::CompilationEvent::post(event,
2159                                         task->compile_id(),
2160                                         task->compiler()->type(),
2161                                         task->method(),
2162                                         task->comp_level(),
2163                                         task->is_success(),
2164                                         task->osr_bci() != CompileBroker::standard_entry_bci,
2165                                         task->nm_total_size(),
2166                                         task->num_inlined_bytecodes(),
2167                                         task->arena_bytes());
2168 }
2169 
2170 int DirectivesStack::_depth = 0;
2171 CompilerDirectives* DirectivesStack::_top = nullptr;
2172 CompilerDirectives* DirectivesStack::_bottom = nullptr;
2173 
2174 // Acquires Compilation_lock and waits for it to be notified
2175 // as long as WhiteBox::compilation_locked is true.
2176 static void whitebox_lock_compilation() {
2177   MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2178   while (WhiteBox::compilation_locked) {
2179     locker.wait();
2180   }
2181 }
2182 
2183 // ------------------------------------------------------------------
2184 // CompileBroker::invoke_compiler_on_method
2185 //
2186 // Compile a method.
2187 //
2188 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2189   task->print_ul();
2190   elapsedTimer time;
2191 
2192   DirectiveSet* directive = task->directive();
2193   if (directive->PrintCompilationOption) {
2194     ResourceMark rm;
2195     task->print_tty();
2196   }
2197 
2198   CompilerThread* thread = CompilerThread::current();
2199   ResourceMark rm(thread);
2200 
2201   if (CompilationLog::log() != nullptr) {
2202     CompilationLog::log()->log_compile(thread, task);
2203   }
2204 
2205   // Common flags.
2206   int compile_id = task->compile_id();
2207   int osr_bci = task->osr_bci();
2208   bool is_osr = (osr_bci != standard_entry_bci);
2209   bool should_log = (thread->log() != nullptr);
2210   bool should_break = false;
2211   const int task_level = task->comp_level();
2212   AbstractCompiler* comp = task->compiler();
2213   {
2214     // create the handle inside it's own block so it can't
2215     // accidentally be referenced once the thread transitions to
2216     // native.  The NoHandleMark before the transition should catch
2217     // any cases where this occurs in the future.
2218     methodHandle method(thread, task->method());
2219 
2220     assert(!method->is_native(), "no longer compile natives");
2221 
2222     // Update compile information when using perfdata.
2223     if (UsePerfData) {
2224       update_compile_perf_data(thread, method, is_osr);
2225     }
2226 
2227     DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2228   }
2229 
2230   should_break = directive->BreakAtCompileOption || task->check_break_at_flags();
2231   if (should_log && !directive->LogOption) {
2232     should_log = false;
2233   }
2234 
2235   // Allocate a new set of JNI handles.
2236   JNIHandleMark jhm(thread);
2237   Method* target_handle = task->method();
2238   int compilable = ciEnv::MethodCompilable;
2239   const char* failure_reason = nullptr;
2240   bool failure_reason_on_C_heap = false;
2241   const char* retry_message = nullptr;
2242 
2243 #if INCLUDE_JVMCI
2244   if (UseJVMCICompiler && comp != nullptr && comp->is_jvmci()) {
2245     JVMCICompiler* jvmci = (JVMCICompiler*) comp;
2246 
2247     TraceTime t1("compilation", &time);
2248     EventCompilation event;
2249     JVMCICompileState compile_state(task, jvmci);
2250     JVMCIRuntime *runtime = nullptr;
2251 
2252     if (JVMCI::in_shutdown()) {
2253       failure_reason = "in JVMCI shutdown";
2254       retry_message = "not retryable";
2255       compilable = ciEnv::MethodCompilable_never;
2256     } else if (compile_state.target_method_is_old()) {
2257       // Skip redefined methods
2258       failure_reason = "redefined method";
2259       retry_message = "not retryable";
2260       compilable = ciEnv::MethodCompilable_never;
2261     } else {
2262       JVMCIEnv env(thread, &compile_state, __FILE__, __LINE__);
2263       if (env.init_error() != JNI_OK) {
2264         const char* msg = env.init_error_msg();
2265         failure_reason = os::strdup(err_msg("Error attaching to libjvmci (err: %d, %s)",
2266                                     env.init_error(), msg == nullptr ? "unknown" : msg), mtJVMCI);
2267         bool reason_on_C_heap = true;
2268         // In case of JNI_ENOMEM, there's a good chance a subsequent attempt to create libjvmci or attach to it
2269         // might succeed. Other errors most likely indicate a non-recoverable error in the JVMCI runtime.
2270         bool retryable = env.init_error() == JNI_ENOMEM;
2271         compile_state.set_failure(retryable, failure_reason, reason_on_C_heap);
2272       }
2273       if (failure_reason == nullptr) {
2274         if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2275           // Must switch to native to block
2276           ThreadToNativeFromVM ttn(thread);
2277           whitebox_lock_compilation();
2278         }
2279         methodHandle method(thread, target_handle);
2280         runtime = env.runtime();
2281         runtime->compile_method(&env, jvmci, method, osr_bci);
2282 
2283         failure_reason = compile_state.failure_reason();
2284         failure_reason_on_C_heap = compile_state.failure_reason_on_C_heap();
2285         if (!compile_state.retryable()) {
2286           retry_message = "not retryable";
2287           compilable = ciEnv::MethodCompilable_not_at_tier;
2288         }
2289         if (!task->is_success()) {
2290           assert(failure_reason != nullptr, "must specify failure_reason");
2291         }
2292       }
2293     }
2294     if (!task->is_success() && !JVMCI::in_shutdown()) {
2295       handle_compile_error(thread, task, nullptr, compilable, failure_reason);
2296     }
2297     if (event.should_commit()) {
2298       post_compilation_event(event, task);
2299     }
2300 
2301     if (runtime != nullptr) {
2302       runtime->post_compile(thread);
2303     }
2304   } else
2305 #endif // INCLUDE_JVMCI
2306   {
2307     NoHandleMark  nhm;
2308     ThreadToNativeFromVM ttn(thread);
2309 
2310     ciEnv ci_env(task);
2311     if (should_break) {
2312       ci_env.set_break_at_compile(true);
2313     }
2314     if (should_log) {
2315       ci_env.set_log(thread->log());
2316     }
2317     assert(thread->env() == &ci_env, "set by ci_env");
2318     // The thread-env() field is cleared in ~CompileTaskWrapper.
2319 
2320     // Cache Jvmti state
2321     bool method_is_old = ci_env.cache_jvmti_state();
2322 
2323     // Skip redefined methods
2324     if (method_is_old) {
2325       ci_env.record_method_not_compilable("redefined method", true);
2326     }
2327 
2328     // Cache DTrace flags
2329     ci_env.cache_dtrace_flags();
2330 
2331     ciMethod* target = ci_env.get_method_from_handle(target_handle);
2332 
2333     TraceTime t1("compilation", &time);
2334     EventCompilation event;
2335 
2336     if (comp == nullptr) {
2337       ci_env.record_method_not_compilable("no compiler");
2338     } else if (!ci_env.failing()) {
2339       if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2340         whitebox_lock_compilation();
2341       }
2342       comp->compile_method(&ci_env, target, osr_bci, true, directive);
2343 
2344       /* Repeat compilation without installing code for profiling purposes */
2345       int repeat_compilation_count = directive->RepeatCompilationOption;
2346       while (repeat_compilation_count > 0) {
2347         ResourceMark rm(thread);
2348         task->print_ul("NO CODE INSTALLED");
2349         comp->compile_method(&ci_env, target, osr_bci, false, directive);
2350         repeat_compilation_count--;
2351       }
2352     }
2353 
2354 
2355     if (!ci_env.failing() && !task->is_success()) {
2356       assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2357       assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2358       // The compiler elected, without comment, not to register a result.
2359       // Do not attempt further compilations of this method.
2360       ci_env.record_method_not_compilable("compile failed");
2361     }
2362 
2363     // Copy this bit to the enclosing block:
2364     compilable = ci_env.compilable();
2365 
2366     if (ci_env.failing()) {
2367       // Duplicate the failure reason string, so that it outlives ciEnv
2368       failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2369       failure_reason_on_C_heap = true;
2370       retry_message = ci_env.retry_message();
2371       ci_env.report_failure(failure_reason);
2372     }
2373 
2374     if (ci_env.failing()) {
2375       handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2376     }
2377     if (event.should_commit()) {
2378       post_compilation_event(event, task);
2379     }
2380   }
2381 
2382   if (failure_reason != nullptr) {
2383     task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2384     if (CompilationLog::log() != nullptr) {
2385       CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2386     }
2387     if (PrintCompilation || directive->PrintCompilationOption) {
2388       FormatBufferResource msg = retry_message != nullptr ?
2389         FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2390         FormatBufferResource("COMPILE SKIPPED: %s",      failure_reason);
2391       task->print(tty, msg);
2392     }
2393   }
2394 
2395   DirectivesStack::release(directive);
2396 
2397   methodHandle method(thread, task->method());
2398 
2399   DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2400 
2401   collect_statistics(thread, time, task);
2402 
2403   if (PrintCompilation && PrintCompilation2) {
2404     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
2405     tty->print("%4d ", compile_id);    // print compilation number
2406     tty->print("%s ", (is_osr ? "%" : " "));
2407     if (task->is_success()) {
2408       tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2409     }
2410     tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2411   }
2412 
2413   Log(compilation, codecache) log;
2414   if (log.is_debug()) {
2415     LogStream ls(log.debug());
2416     codecache_print(&ls, /* detailed= */ false);
2417   }
2418   if (PrintCodeCacheOnCompilation) {
2419     codecache_print(/* detailed= */ false);
2420   }
2421   // Disable compilation, if required.
2422   switch (compilable) {
2423   case ciEnv::MethodCompilable_never:
2424     if (is_osr)
2425       method->set_not_osr_compilable_quietly("MethodCompilable_never");
2426     else
2427       method->set_not_compilable_quietly("MethodCompilable_never");
2428     break;
2429   case ciEnv::MethodCompilable_not_at_tier:
2430     if (is_osr)
2431       method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2432     else
2433       method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2434     break;
2435   }
2436 
2437   // Note that the queued_for_compilation bits are cleared without
2438   // protection of a mutex. [They were set by the requester thread,
2439   // when adding the task to the compile queue -- at which time the
2440   // compile queue lock was held. Subsequently, we acquired the compile
2441   // queue lock to get this task off the compile queue; thus (to belabour
2442   // the point somewhat) our clearing of the bits must be occurring
2443   // only after the setting of the bits. See also 14012000 above.
2444   method->clear_queued_for_compilation();
2445 }
2446 
2447 /**
2448  * The CodeCache is full. Print warning and disable compilation.
2449  * Schedule code cache cleaning so compilation can continue later.
2450  * This function needs to be called only from CodeCache::allocate(),
2451  * since we currently handle a full code cache uniformly.
2452  */
2453 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2454   UseInterpreter = true;
2455   if (UseCompiler || AlwaysCompileLoopMethods ) {
2456     if (xtty != nullptr) {
2457       stringStream s;
2458       // Dump code cache state into a buffer before locking the tty,
2459       // because log_state() will use locks causing lock conflicts.
2460       CodeCache::log_state(&s);
2461       // Lock to prevent tearing
2462       ttyLocker ttyl;
2463       xtty->begin_elem("code_cache_full");
2464       xtty->print("%s", s.freeze());
2465       xtty->stamp();
2466       xtty->end_elem();
2467     }
2468 
2469 #ifndef PRODUCT
2470     if (ExitOnFullCodeCache) {
2471       codecache_print(/* detailed= */ true);
2472       before_exit(JavaThread::current());
2473       exit_globals(); // will delete tty
2474       vm_direct_exit(1);
2475     }
2476 #endif
2477     if (UseCodeCacheFlushing) {
2478       // Since code cache is full, immediately stop new compiles
2479       if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) {
2480         log_info(codecache)("Code cache is full - disabling compilation");
2481       }
2482     } else {
2483       disable_compilation_forever();
2484     }
2485 
2486     CodeCache::report_codemem_full(code_blob_type, should_print_compiler_warning());
2487   }
2488 }
2489 
2490 // ------------------------------------------------------------------
2491 // CompileBroker::update_compile_perf_data
2492 //
2493 // Record this compilation for debugging purposes.
2494 void CompileBroker::update_compile_perf_data(CompilerThread* thread, const methodHandle& method, bool is_osr) {
2495   ResourceMark rm;
2496   char* method_name = method->name()->as_C_string();
2497   char current_method[CompilerCounters::cmname_buffer_length];
2498   size_t maxLen = CompilerCounters::cmname_buffer_length;
2499 
2500   const char* class_name = method->method_holder()->name()->as_C_string();
2501 
2502   size_t s1len = strlen(class_name);
2503   size_t s2len = strlen(method_name);
2504 
2505   // check if we need to truncate the string
2506   if (s1len + s2len + 2 > maxLen) {
2507 
2508     // the strategy is to lop off the leading characters of the
2509     // class name and the trailing characters of the method name.
2510 
2511     if (s2len + 2 > maxLen) {
2512       // lop of the entire class name string, let snprintf handle
2513       // truncation of the method name.
2514       class_name += s1len; // null string
2515     }
2516     else {
2517       // lop off the extra characters from the front of the class name
2518       class_name += ((s1len + s2len + 2) - maxLen);
2519     }
2520   }
2521 
2522   jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
2523 
2524   int last_compile_type = normal_compile;
2525   if (CICountOSR && is_osr) {
2526     last_compile_type = osr_compile;
2527   } else if (CICountNative && method->is_native()) {
2528     last_compile_type = native_compile;
2529   }
2530 
2531   CompilerCounters* counters = thread->counters();
2532   counters->set_current_method(current_method);
2533   counters->set_compile_type((jlong) last_compile_type);
2534 }
2535 
2536 // ------------------------------------------------------------------
2537 // CompileBroker::collect_statistics
2538 //
2539 // Collect statistics about the compilation.
2540 
2541 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2542   bool success = task->is_success();
2543   methodHandle method (thread, task->method());
2544   int compile_id = task->compile_id();
2545   bool is_osr = (task->osr_bci() != standard_entry_bci);
2546   const int comp_level = task->comp_level();
2547   CompilerCounters* counters = thread->counters();
2548 
2549   MutexLocker locker(CompileStatistics_lock);
2550 
2551   // _perf variables are production performance counters which are
2552   // updated regardless of the setting of the CITime and CITimeEach flags
2553   //
2554 
2555   // account all time, including bailouts and failures in this counter;
2556   // C1 and C2 counters are counting both successful and unsuccessful compiles
2557   _t_total_compilation.add(time);
2558 
2559   // Update compilation times. Used by the implementation of JFR CompilerStatistics
2560   // and java.lang.management.CompilationMXBean.
2561   _perf_total_compilation->inc(time.ticks());
2562   _peak_compilation_time = MAX2(time.milliseconds(), _peak_compilation_time);
2563 
2564   if (!success) {
2565     _total_bailout_count++;
2566     if (UsePerfData) {
2567       _perf_last_failed_method->set_value(counters->current_method());
2568       _perf_last_failed_type->set_value(counters->compile_type());
2569       _perf_total_bailout_count->inc();
2570     }
2571     _t_bailedout_compilation.add(time);
2572   } else if (!task->is_success()) {
2573     if (UsePerfData) {
2574       _perf_last_invalidated_method->set_value(counters->current_method());
2575       _perf_last_invalidated_type->set_value(counters->compile_type());
2576       _perf_total_invalidated_count->inc();
2577     }
2578     _total_invalidated_count++;
2579     _t_invalidated_compilation.add(time);
2580   } else {
2581     // Compilation succeeded
2582     if (CITime) {
2583       int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2584       if (is_osr) {
2585         _t_osr_compilation.add(time);
2586         _sum_osr_bytes_compiled += bytes_compiled;
2587       } else {
2588         _t_standard_compilation.add(time);
2589         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2590       }
2591 
2592       // Collect statistic per compilation level
2593       if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2594         CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2595         if (is_osr) {
2596           stats->_osr.update(time, bytes_compiled);
2597         } else {
2598           stats->_standard.update(time, bytes_compiled);
2599         }
2600         stats->_nmethods_size += task->nm_total_size();
2601         stats->_nmethods_code_size += task->nm_insts_size();
2602       } else {
2603         assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2604       }
2605 
2606       // Collect statistic per compiler
2607       AbstractCompiler* comp = compiler(comp_level);
2608       if (comp) {
2609         CompilerStatistics* stats = comp->stats();
2610         if (is_osr) {
2611           stats->_osr.update(time, bytes_compiled);
2612         } else {
2613           stats->_standard.update(time, bytes_compiled);
2614         }
2615         stats->_nmethods_size += task->nm_total_size();
2616         stats->_nmethods_code_size += task->nm_insts_size();
2617       } else { // if (!comp)
2618         assert(false, "Compiler object must exist");
2619       }
2620     }
2621 
2622     if (UsePerfData) {
2623       // save the name of the last method compiled
2624       _perf_last_method->set_value(counters->current_method());
2625       _perf_last_compile_type->set_value(counters->compile_type());
2626       _perf_last_compile_size->set_value(method->code_size() +
2627                                          task->num_inlined_bytecodes());
2628       if (is_osr) {
2629         _perf_osr_compilation->inc(time.ticks());
2630         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2631       } else {
2632         _perf_standard_compilation->inc(time.ticks());
2633         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2634       }
2635     }
2636 
2637     if (CITimeEach) {
2638       double compile_time = time.seconds();
2639       double bytes_per_sec = compile_time == 0.0 ? 0.0 : (double)(method->code_size() + task->num_inlined_bytecodes()) / compile_time;
2640       tty->print_cr("%3d   seconds: %6.3f bytes/sec : %f (bytes %d + %d inlined)",
2641                     compile_id, compile_time, bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
2642     }
2643 
2644     // Collect counts of successful compilations
2645     _sum_nmethod_size      += task->nm_total_size();
2646     _sum_nmethod_code_size += task->nm_insts_size();
2647     _total_compile_count++;
2648 
2649     if (UsePerfData) {
2650       _perf_sum_nmethod_size->inc(     task->nm_total_size());
2651       _perf_sum_nmethod_code_size->inc(task->nm_insts_size());
2652       _perf_total_compile_count->inc();
2653     }
2654 
2655     if (is_osr) {
2656       if (UsePerfData) _perf_total_osr_compile_count->inc();
2657       _total_osr_compile_count++;
2658     } else {
2659       if (UsePerfData) _perf_total_standard_compile_count->inc();
2660       _total_standard_compile_count++;
2661     }
2662   }
2663   // set the current method for the thread to null
2664   if (UsePerfData) counters->set_current_method("");
2665 }
2666 
2667 const char* CompileBroker::compiler_name(int comp_level) {
2668   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2669   if (comp == nullptr) {
2670     return "no compiler";
2671   } else {
2672     return (comp->name());
2673   }
2674 }
2675 
2676 jlong CompileBroker::total_compilation_ticks() {
2677   return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2678 }
2679 
2680 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2681   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}",
2682                 name, stats->bytes_per_second(),
2683                 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2684                 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2685                 stats->_nmethods_size, stats->_nmethods_code_size);
2686 }
2687 
2688 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
2689   if (per_compiler) {
2690     if (aggregate) {
2691       tty->cr();
2692       tty->print_cr("Individual compiler times (for compiled methods only)");
2693       tty->print_cr("------------------------------------------------");
2694       tty->cr();
2695     }
2696     for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
2697       AbstractCompiler* comp = _compilers[i];
2698       if (comp != nullptr) {
2699         print_times(comp->name(), comp->stats());
2700       }
2701     }
2702     if (aggregate) {
2703       tty->cr();
2704       tty->print_cr("Individual compilation Tier times (for compiled methods only)");
2705       tty->print_cr("------------------------------------------------");
2706       tty->cr();
2707     }
2708     char tier_name[256];
2709     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
2710       CompilerStatistics* stats = &_stats_per_level[tier-1];
2711       os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
2712       print_times(tier_name, stats);
2713     }
2714   }
2715 
2716   if (!aggregate) {
2717     return;
2718   }
2719 
2720   elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
2721   elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
2722   elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
2723 
2724   uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
2725   uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
2726 
2727   uint standard_compile_count = CompileBroker::_total_standard_compile_count;
2728   uint osr_compile_count = CompileBroker::_total_osr_compile_count;
2729   uint total_compile_count = CompileBroker::_total_compile_count;
2730   uint total_bailout_count = CompileBroker::_total_bailout_count;
2731   uint total_invalidated_count = CompileBroker::_total_invalidated_count;
2732 
2733   uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;
2734   uint nmethods_size = CompileBroker::_sum_nmethod_size;
2735 
2736   tty->cr();
2737   tty->print_cr("Accumulated compiler times");
2738   tty->print_cr("----------------------------------------------------------");
2739                //0000000000111111111122222222223333333333444444444455555555556666666666
2740                //0123456789012345678901234567890123456789012345678901234567890123456789
2741   tty->print_cr("  Total compilation time   : %7.3f s", total_compilation.seconds());
2742   tty->print_cr("    Standard compilation   : %7.3f s, Average : %2.3f s",
2743                 standard_compilation.seconds(),
2744                 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
2745   tty->print_cr("    Bailed out compilation : %7.3f s, Average : %2.3f s",
2746                 CompileBroker::_t_bailedout_compilation.seconds(),
2747                 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
2748   tty->print_cr("    On stack replacement   : %7.3f s, Average : %2.3f s",
2749                 osr_compilation.seconds(),
2750                 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
2751   tty->print_cr("    Invalidated            : %7.3f s, Average : %2.3f s",
2752                 CompileBroker::_t_invalidated_compilation.seconds(),
2753                 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
2754 
2755   AbstractCompiler *comp = compiler(CompLevel_simple);
2756   if (comp != nullptr) {
2757     tty->cr();
2758     comp->print_timers();
2759   }
2760   comp = compiler(CompLevel_full_optimization);
2761   if (comp != nullptr) {
2762     tty->cr();
2763     comp->print_timers();
2764   }
2765 #if INCLUDE_JVMCI
2766   if (EnableJVMCI) {
2767     JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
2768     if (jvmci_comp != nullptr && jvmci_comp != comp) {
2769       tty->cr();
2770       jvmci_comp->print_timers();
2771     }
2772   }
2773 #endif
2774 
2775   tty->cr();
2776   tty->print_cr("  Total compiled methods    : %8u methods", total_compile_count);
2777   tty->print_cr("    Standard compilation    : %8u methods", standard_compile_count);
2778   tty->print_cr("    On stack replacement    : %8u methods", osr_compile_count);
2779   uint tcb = osr_bytes_compiled + standard_bytes_compiled;
2780   tty->print_cr("  Total compiled bytecodes  : %8u bytes", tcb);
2781   tty->print_cr("    Standard compilation    : %8u bytes", standard_bytes_compiled);
2782   tty->print_cr("    On stack replacement    : %8u bytes", osr_bytes_compiled);
2783   double tcs = total_compilation.seconds();
2784   uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);
2785   tty->print_cr("  Average compilation speed : %8u bytes/s", bps);
2786   tty->cr();
2787   tty->print_cr("  nmethod code size         : %8u bytes", nmethods_code_size);
2788   tty->print_cr("  nmethod total size        : %8u bytes", nmethods_size);
2789 }
2790 
2791 // Print general/accumulated JIT information.
2792 void CompileBroker::print_info(outputStream *out) {
2793   if (out == nullptr) out = tty;
2794   out->cr();
2795   out->print_cr("======================");
2796   out->print_cr("   General JIT info   ");
2797   out->print_cr("======================");
2798   out->cr();
2799   out->print_cr("            JIT is : %7s",     should_compile_new_jobs() ? "on" : "off");
2800   out->print_cr("  Compiler threads : %7d",     (int)CICompilerCount);
2801   out->cr();
2802   out->print_cr("CodeCache overview");
2803   out->print_cr("--------------------------------------------------------");
2804   out->cr();
2805   out->print_cr("         Reserved size : %7zu KB", CodeCache::max_capacity() / K);
2806   out->print_cr("        Committed size : %7zu KB", CodeCache::capacity() / K);
2807   out->print_cr("  Unallocated capacity : %7zu KB", CodeCache::unallocated_capacity() / K);
2808   out->cr();
2809 }
2810 
2811 // Note: tty_lock must not be held upon entry to this function.
2812 //       Print functions called from herein do "micro-locking" on tty_lock.
2813 //       That's a tradeoff which keeps together important blocks of output.
2814 //       At the same time, continuous tty_lock hold time is kept in check,
2815 //       preventing concurrently printing threads from stalling a long time.
2816 void CompileBroker::print_heapinfo(outputStream* out, const char* function, size_t granularity) {
2817   TimeStamp ts_total;
2818   TimeStamp ts_global;
2819   TimeStamp ts;
2820 
2821   bool allFun = !strcmp(function, "all");
2822   bool aggregate = !strcmp(function, "aggregate") || !strcmp(function, "analyze") || allFun;
2823   bool usedSpace = !strcmp(function, "UsedSpace") || allFun;
2824   bool freeSpace = !strcmp(function, "FreeSpace") || allFun;
2825   bool methodCount = !strcmp(function, "MethodCount") || allFun;
2826   bool methodSpace = !strcmp(function, "MethodSpace") || allFun;
2827   bool methodAge = !strcmp(function, "MethodAge") || allFun;
2828   bool methodNames = !strcmp(function, "MethodNames") || allFun;
2829   bool discard = !strcmp(function, "discard") || allFun;
2830 
2831   if (out == nullptr) {
2832     out = tty;
2833   }
2834 
2835   if (!(aggregate || usedSpace || freeSpace || methodCount || methodSpace || methodAge || methodNames || discard)) {
2836     out->print_cr("\n__ CodeHeapStateAnalytics: Function %s is not supported", function);
2837     out->cr();
2838     return;
2839   }
2840 
2841   ts_total.update(); // record starting point
2842 
2843   if (aggregate) {
2844     print_info(out);
2845   }
2846 
2847   // We hold the CodeHeapStateAnalytics_lock all the time, from here until we leave this function.
2848   // That prevents other threads from destroying (making inconsistent) our view on the CodeHeap.
2849   // When we request individual parts of the analysis via the jcmd interface, it is possible
2850   // that in between another thread (another jcmd user or the vm running into CodeCache OOM)
2851   // updated the aggregated data. We will then see a modified, but again consistent, view
2852   // on the CodeHeap. That's a tolerable tradeoff we have to accept because we can't hold
2853   // a lock across user interaction.
2854 
2855   // We should definitely acquire this lock before acquiring Compile_lock and CodeCache_lock.
2856   // CodeHeapStateAnalytics_lock may be held by a concurrent thread for a long time,
2857   // leading to an unnecessarily long hold time of the other locks we acquired before.
2858   ts.update(); // record starting point
2859   MutexLocker mu0(CodeHeapStateAnalytics_lock, Mutex::_safepoint_check_flag);
2860   out->print_cr("\n__ CodeHeapStateAnalytics lock wait took %10.3f seconds _________\n", ts.seconds());
2861 
2862   // Holding the CodeCache_lock protects from concurrent alterations of the CodeCache.
2863   // Unfortunately, such protection is not sufficient:
2864   // When a new nmethod is created via ciEnv::register_method(), the
2865   // Compile_lock is taken first. After some initializations,
2866   // nmethod::new_nmethod() takes over, grabbing the CodeCache_lock
2867   // immediately (after finalizing the oop references). To lock out concurrent
2868   // modifiers, we have to grab both locks as well in the described sequence.
2869   //
2870   // If we serve an "allFun" call, it is beneficial to hold CodeCache_lock and Compile_lock
2871   // for the entire duration of aggregation and printing. That makes sure we see
2872   // a consistent picture and do not run into issues caused by concurrent alterations.
2873   bool should_take_Compile_lock   = !SafepointSynchronize::is_at_safepoint() &&
2874                                     !Compile_lock->owned_by_self();
2875   bool should_take_CodeCache_lock = !SafepointSynchronize::is_at_safepoint() &&
2876                                     !CodeCache_lock->owned_by_self();
2877   bool take_global_lock_1   =  allFun && should_take_Compile_lock;
2878   bool take_global_lock_2   =  allFun && should_take_CodeCache_lock;
2879   bool take_function_lock_1 = !allFun && should_take_Compile_lock;
2880   bool take_function_lock_2 = !allFun && should_take_CodeCache_lock;
2881   bool take_global_locks    = take_global_lock_1 || take_global_lock_2;
2882   bool take_function_locks  = take_function_lock_1 || take_function_lock_2;
2883 
2884   ts_global.update(); // record starting point
2885 
2886   ConditionalMutexLocker mu1(Compile_lock, take_global_lock_1, Mutex::_safepoint_check_flag);
2887   ConditionalMutexLocker mu2(CodeCache_lock, take_global_lock_2, Mutex::_no_safepoint_check_flag);
2888   if (take_global_locks) {
2889     out->print_cr("\n__ Compile & CodeCache (global) lock wait took %10.3f seconds _________\n", ts_global.seconds());
2890     ts_global.update(); // record starting point
2891   }
2892 
2893   if (aggregate) {
2894     ts.update(); // record starting point
2895     ConditionalMutexLocker mu11(Compile_lock, take_function_lock_1,  Mutex::_safepoint_check_flag);
2896     ConditionalMutexLocker mu22(CodeCache_lock, take_function_lock_2, Mutex::_no_safepoint_check_flag);
2897     if (take_function_locks) {
2898       out->print_cr("\n__ Compile & CodeCache (function) lock wait took %10.3f seconds _________\n", ts.seconds());
2899     }
2900 
2901     ts.update(); // record starting point
2902     CodeCache::aggregate(out, granularity);
2903     if (take_function_locks) {
2904       out->print_cr("\n__ Compile & CodeCache (function) lock hold took %10.3f seconds _________\n", ts.seconds());
2905     }
2906   }
2907 
2908   if (usedSpace) CodeCache::print_usedSpace(out);
2909   if (freeSpace) CodeCache::print_freeSpace(out);
2910   if (methodCount) CodeCache::print_count(out);
2911   if (methodSpace) CodeCache::print_space(out);
2912   if (methodAge) CodeCache::print_age(out);
2913   if (methodNames) {
2914     if (allFun) {
2915       // print_names() can only be used safely if the locks have been continuously held
2916       // since aggregation begin. That is true only for function "all".
2917       CodeCache::print_names(out);
2918     } else {
2919       out->print_cr("\nCodeHeapStateAnalytics: Function 'MethodNames' is only available as part of function 'all'");
2920     }
2921   }
2922   if (discard) CodeCache::discard(out);
2923 
2924   if (take_global_locks) {
2925     out->print_cr("\n__ Compile & CodeCache (global) lock hold took %10.3f seconds _________\n", ts_global.seconds());
2926   }
2927   out->print_cr("\n__ CodeHeapStateAnalytics total duration %10.3f seconds _________\n", ts_total.seconds());
2928 }