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