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