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