< prev index next >

src/hotspot/share/compiler/compileBroker.cpp

Print this page

   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 

  25 #include "cds/cdsConfig.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "classfile/symbolTable.hpp"
  28 #include "classfile/vmClasses.hpp"
  29 #include "classfile/vmSymbols.hpp"

  30 #include "code/codeCache.hpp"
  31 #include "code/codeHeapState.hpp"
  32 #include "code/dependencyContext.hpp"
  33 #include "compiler/compilationLog.hpp"
  34 #include "compiler/compilationMemoryStatistic.hpp"
  35 #include "compiler/compilationPolicy.hpp"
  36 #include "compiler/compileBroker.hpp"
  37 #include "compiler/compileLog.hpp"

  38 #include "compiler/compilerEvent.hpp"
  39 #include "compiler/compilerOracle.hpp"
  40 #include "compiler/directivesParser.hpp"

  41 #include "gc/shared/memAllocator.hpp"
  42 #include "interpreter/linkResolver.hpp"
  43 #include "jfr/jfrEvents.hpp"
  44 #include "jvm.h"
  45 #include "logging/log.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/allocation.inline.hpp"
  48 #include "memory/resourceArea.hpp"
  49 #include "memory/universe.hpp"
  50 #include "oops/method.inline.hpp"
  51 #include "oops/methodData.hpp"
  52 #include "oops/oop.inline.hpp"
  53 #include "prims/jvmtiExport.hpp"
  54 #include "prims/nativeLookup.hpp"
  55 #include "prims/whitebox.hpp"
  56 #include "runtime/atomicAccess.hpp"
  57 #include "runtime/escapeBarrier.hpp"
  58 #include "runtime/globals_extension.hpp"
  59 #include "runtime/handles.inline.hpp"
  60 #include "runtime/init.hpp"
  61 #include "runtime/interfaceSupport.inline.hpp"
  62 #include "runtime/java.hpp"
  63 #include "runtime/javaCalls.hpp"
  64 #include "runtime/jniHandles.inline.hpp"
  65 #include "runtime/os.hpp"
  66 #include "runtime/perfData.hpp"
  67 #include "runtime/safepointVerifiers.hpp"
  68 #include "runtime/sharedRuntime.hpp"
  69 #include "runtime/threads.hpp"
  70 #include "runtime/threadSMR.hpp"
  71 #include "runtime/timerTrace.hpp"
  72 #include "runtime/vframe.inline.hpp"

  73 #include "utilities/debug.hpp"
  74 #include "utilities/dtrace.hpp"
  75 #include "utilities/events.hpp"
  76 #include "utilities/formatBuffer.hpp"
  77 #include "utilities/macros.hpp"

  78 #ifdef COMPILER1
  79 #include "c1/c1_Compiler.hpp"
  80 #endif
  81 #ifdef COMPILER2
  82 #include "opto/c2compiler.hpp"
  83 #endif
  84 #if INCLUDE_JVMCI
  85 #include "jvmci/jvmciEnv.hpp"
  86 #include "jvmci/jvmciRuntime.hpp"
  87 #endif
  88 
  89 #ifdef DTRACE_ENABLED
  90 
  91 // Only bother with this argument setup if dtrace is available
  92 
  93 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
  94   {                                                                      \
  95     Symbol* klass_name = (method)->klass_name();                         \
  96     Symbol* name = (method)->name();                                     \
  97     Symbol* signature = (method)->signature();                           \

 115   }
 116 
 117 #else //  ndef DTRACE_ENABLED
 118 
 119 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
 120 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
 121 
 122 #endif // ndef DTRACE_ENABLED
 123 
 124 bool CompileBroker::_initialized = false;
 125 volatile bool CompileBroker::_should_block = false;
 126 volatile int  CompileBroker::_print_compilation_warning = 0;
 127 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
 128 
 129 // The installed compiler(s)
 130 AbstractCompiler* CompileBroker::_compilers[2];
 131 
 132 // The maximum numbers of compiler threads to be determined during startup.
 133 int CompileBroker::_c1_count = 0;
 134 int CompileBroker::_c2_count = 0;

 135 
 136 // An array of compiler names as Java String objects
 137 jobject* CompileBroker::_compiler1_objects = nullptr;
 138 jobject* CompileBroker::_compiler2_objects = nullptr;

 139 
 140 CompileLog** CompileBroker::_compiler1_logs = nullptr;
 141 CompileLog** CompileBroker::_compiler2_logs = nullptr;

 142 
 143 // These counters are used to assign an unique ID to each compilation.
 144 volatile jint CompileBroker::_compilation_id     = 0;
 145 volatile jint CompileBroker::_osr_compilation_id = 0;
 146 volatile jint CompileBroker::_native_compilation_id = 0;
 147 
 148 // Performance counters
 149 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
 150 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
 151 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
 152 
 153 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
 154 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
 155 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
 156 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
 157 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
 158 
 159 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
 160 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
 161 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
 162 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
 163 
 164 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
 165 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
 166 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
 167 PerfVariable*       CompileBroker::_perf_last_compile_type = nullptr;
 168 PerfVariable*       CompileBroker::_perf_last_compile_size = nullptr;
 169 PerfVariable*       CompileBroker::_perf_last_failed_type = nullptr;
 170 PerfVariable*       CompileBroker::_perf_last_invalidated_type = nullptr;
 171 
 172 // Timers and counters for generating statistics
 173 elapsedTimer CompileBroker::_t_total_compilation;
 174 elapsedTimer CompileBroker::_t_osr_compilation;
 175 elapsedTimer CompileBroker::_t_standard_compilation;
 176 elapsedTimer CompileBroker::_t_invalidated_compilation;
 177 elapsedTimer CompileBroker::_t_bailedout_compilation;
 178 
 179 uint CompileBroker::_total_bailout_count            = 0;
 180 uint CompileBroker::_total_invalidated_count        = 0;

 181 uint CompileBroker::_total_compile_count            = 0;
 182 uint CompileBroker::_total_osr_compile_count        = 0;
 183 uint CompileBroker::_total_standard_compile_count   = 0;
 184 uint CompileBroker::_total_compiler_stopped_count   = 0;
 185 uint CompileBroker::_total_compiler_restarted_count = 0;
 186 
 187 uint CompileBroker::_sum_osr_bytes_compiled         = 0;
 188 uint CompileBroker::_sum_standard_bytes_compiled    = 0;
 189 uint CompileBroker::_sum_nmethod_size               = 0;
 190 uint CompileBroker::_sum_nmethod_code_size          = 0;
 191 
 192 jlong CompileBroker::_peak_compilation_time        = 0;
 193 
 194 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];


 195 
 196 CompileQueue* CompileBroker::_c2_compile_queue     = nullptr;
 197 CompileQueue* CompileBroker::_c1_compile_queue     = nullptr;


 198 
 199 bool compileBroker_init() {
 200   if (LogEvents) {
 201     CompilationLog::init();
 202   }
 203 
 204   // init directives stack, adding default directive
 205   DirectivesStack::init();
 206 
 207   if (DirectivesParser::has_file()) {
 208     return DirectivesParser::parse_from_flag();
 209   } else if (CompilerDirectivesPrint) {
 210     // Print default directive even when no other was added
 211     DirectivesStack::print(tty);
 212   }
 213 
 214   return true;
 215 }
 216 
 217 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
 218   CompilerThread* thread = CompilerThread::current();
 219   thread->set_task(task);
 220   CompileLog*     log  = thread->log();
 221   thread->timeout()->arm();
 222   if (log != nullptr && !task->is_unloaded())  task->log_task_start(log);
 223 }
 224 
 225 CompileTaskWrapper::~CompileTaskWrapper() {
 226   CompilerThread* thread = CompilerThread::current();
 227 
 228   // First, disarm the timeout. This still relies on the underlying task.
 229   thread->timeout()->disarm();
 230 
 231   CompileTask* task = thread->task();
 232   CompileLog*  log  = thread->log();

 233   if (log != nullptr && !task->is_unloaded())  task->log_task_done(log);
 234   thread->set_task(nullptr);
 235   thread->set_env(nullptr);
 236   if (task->is_blocking()) {
 237     bool free_task = false;
 238     {
 239       MutexLocker notifier(thread, CompileTaskWait_lock);
 240       task->mark_complete();
 241 #if INCLUDE_JVMCI
 242       if (CompileBroker::compiler(task->comp_level())->is_jvmci()) {
 243         if (!task->has_waiter()) {
 244           // The waiting thread timed out and thus did not delete the task.
 245           free_task = true;
 246         }
 247         task->set_blocking_jvmci_compile_state(nullptr);
 248       }
 249 #endif
 250       if (!free_task) {
 251         // Notify the waiting thread that the compilation has completed
 252         // so that it can free the task.
 253         CompileTaskWait_lock->notify_all();
 254       }
 255     }
 256     if (free_task) {
 257       // The task can only be deleted once the task lock is released.
 258       delete task;
 259     }
 260   } else {
 261     task->mark_complete();
 262 
 263     // By convention, the compiling thread is responsible for deleting
 264     // a non-blocking CompileTask.
 265     delete task;
 266   }
 267 }
 268 
 269 /**
 270  * Check if a CompilerThread can be removed and update count if requested.
 271  */
 272 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
 273   assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
 274   if (!ReduceNumberOfCompilerThreads) return false;
 275 


 276   AbstractCompiler *compiler = ct->compiler();
 277   int compiler_count = compiler->num_compiler_threads();
 278   bool c1 = compiler->is_c1();
 279 
 280   // Keep at least 1 compiler thread of each type.
 281   if (compiler_count < 2) return false;
 282 
 283   // Keep thread alive for at least some time.
 284   if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
 285 
 286 #if INCLUDE_JVMCI
 287   if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 288     // Handles for JVMCI thread objects may get released concurrently.
 289     if (do_it) {
 290       assert(CompileThread_lock->owner() == ct, "must be holding lock");
 291     } else {
 292       // Skip check if it's the last thread and let caller check again.
 293       return true;
 294     }
 295   }

 302     if (do_it) {
 303       assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
 304       compiler->set_num_compiler_threads(compiler_count - 1);
 305 #if INCLUDE_JVMCI
 306       if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 307         // Old j.l.Thread object can die when no longer referenced elsewhere.
 308         JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
 309         _compiler2_objects[compiler_count - 1] = nullptr;
 310       }
 311 #endif
 312     }
 313     return true;
 314   }
 315   return false;
 316 }
 317 
 318 /**
 319  * Add a CompileTask to a CompileQueue.
 320  */
 321 void CompileQueue::add(CompileTask* task) {
 322   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 323 
 324   task->set_next(nullptr);
 325   task->set_prev(nullptr);
 326 
 327   if (_last == nullptr) {
 328     // The compile queue is empty.
 329     assert(_first == nullptr, "queue is empty");
 330     _first = task;
 331     _last = task;
 332   } else {
 333     // Append the task to the queue.
 334     assert(_last->next() == nullptr, "not last");
 335     _last->set_next(task);
 336     task->set_prev(_last);
 337     _last = task;
 338   }
 339   ++_size;
 340   ++_total_added;
 341   if (_size > _peak_size) {
 342     _peak_size = _size;
 343   }
 344 
 345   // Mark the method as being in the compile queue.
 346   task->method()->set_queued_for_compilation();
 347 


 348   if (CIPrintCompileQueue) {
 349     print_tty();
 350   }
 351 
 352   if (LogCompilation && xtty != nullptr) {
 353     task->log_task_queued();
 354   }
 355 
 356   if (TrainingData::need_data() && !CDSConfig::is_dumping_final_static_archive()) {
 357     CompileTrainingData* ctd = CompileTrainingData::make(task);
 358     if (ctd != nullptr) {
 359       task->set_training_data(ctd);
 360     }
 361   }
 362 
 363   // Notify CompilerThreads that a task is available.
 364   MethodCompileQueue_lock->notify_all();














































 365 }
 366 
 367 /**
 368  * Empties compilation queue by deleting all compilation tasks.
 369  * Furthermore, the method wakes up all threads that are waiting
 370  * on a compilation task to finish. This can happen if background
 371  * compilation is disabled.
 372  */
 373 void CompileQueue::delete_all() {
 374   MutexLocker mu(MethodCompileQueue_lock);


 375   CompileTask* current = _first;
 376 
 377   // Iterate over all tasks in the compile queue
 378   while (current != nullptr) {
 379     CompileTask* next = current->next();
 380     if (!current->is_blocking()) {
 381       // Non-blocking task. No one is waiting for it, delete it now.
 382       delete current;
 383     } else {
 384       // Blocking task. By convention, it is the waiters responsibility
 385       // to delete the task. We cannot delete it here, because we do not
 386       // coordinate with waiters. We will notify the waiters later.
 387     }
 388     current = next;
 389   }
 390   _first = nullptr;
 391   _last = nullptr;
 392 
 393   // Wake up all blocking task waiters to deal with remaining blocking
 394   // tasks. This is not a performance sensitive path, so we do this
 395   // unconditionally to simplify coding/testing.
 396   {
 397     MonitorLocker ml(Thread::current(), CompileTaskWait_lock);
 398     ml.notify_all();
 399   }
 400 
 401   // Wake up all threads that block on the queue.
 402   MethodCompileQueue_lock->notify_all();
 403 }
 404 
 405 /**
 406  * Get the next CompileTask from a CompileQueue
 407  */
 408 CompileTask* CompileQueue::get(CompilerThread* thread) {
 409   // save methods from RedefineClasses across safepoint
 410   // across MethodCompileQueue_lock below.
 411   methodHandle save_method;
 412 
 413   MonitorLocker locker(MethodCompileQueue_lock);




 414   // If _first is null we have no more compile jobs. There are two reasons for
 415   // having no compile jobs: First, we compiled everything we wanted. Second,
 416   // we ran out of code cache so compilation has been disabled. In the latter
 417   // case we perform code cache sweeps to free memory such that we can re-enable
 418   // compilation.
 419   while (_first == nullptr) {
 420     // Exit loop if compilation is disabled forever
 421     if (CompileBroker::is_compilation_disabled_forever()) {
 422       return nullptr;
 423     }
 424 
 425     AbstractCompiler* compiler = thread->compiler();
 426     guarantee(compiler != nullptr, "Compiler object must exist");
 427     compiler->on_empty_queue(this, thread);
 428     if (_first != nullptr) {
 429       // The call to on_empty_queue may have temporarily unlocked the MCQ lock
 430       // so check again whether any tasks were added to the queue.
 431       break;
 432     }
 433 
















 434     // If there are no compilation tasks and we can compile new jobs
 435     // (i.e., there is enough free space in the code cache) there is
 436     // no need to invoke the GC.
 437     // We need a timed wait here, since compiler threads can exit if compilation
 438     // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
 439     // is not critical and we do not want idle compiler threads to wake up too often.
 440     locker.wait(5*1000);
 441 




 442     if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
 443       // Still nothing to compile. Give caller a chance to stop this thread.
 444       if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
 445     }
 446   }
 447 
 448   if (CompileBroker::is_compilation_disabled_forever()) {
 449     return nullptr;
 450   }
 451 
 452   CompileTask* task;
 453   {
 454     NoSafepointVerifier nsv;
 455     task = CompilationPolicy::select_task(this, thread);
 456     if (task != nullptr) {
 457       task = task->select_for_compilation();
 458     }
 459   }
 460 
 461   if (task != nullptr) {
 462     // Save method pointers across unlock safepoint.  The task is removed from
 463     // the compilation queue, which is walked during RedefineClasses.
 464     Thread* thread = Thread::current();
 465     save_method = methodHandle(thread, task->method());
 466 
 467     remove(task);
 468   }
 469   purge_stale_tasks(); // may temporarily release MCQ lock
 470   return task;
 471 }
 472 
 473 // Clean & deallocate stale compile tasks.
 474 // Temporarily releases MethodCompileQueue lock.
 475 void CompileQueue::purge_stale_tasks() {
 476   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 477   if (_first_stale != nullptr) {
 478     // Stale tasks are purged when MCQ lock is released,
 479     // but _first_stale updates are protected by MCQ lock.
 480     // Once task processing starts and MCQ lock is released,
 481     // other compiler threads can reuse _first_stale.
 482     CompileTask* head = _first_stale;
 483     _first_stale = nullptr;
 484     {
 485       MutexUnlocker ul(MethodCompileQueue_lock);
 486       for (CompileTask* task = head; task != nullptr; ) {
 487         CompileTask* next_task = task->next();
 488         task->set_next(nullptr);
 489         CompileTaskWrapper ctw(task); // Frees the task
 490         task->set_failure_reason("stale task");
 491         task = next_task;
 492       }
 493     }

 494   }
 495 }
 496 
 497 void CompileQueue::remove(CompileTask* task) {
 498   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 499   if (task->prev() != nullptr) {
 500     task->prev()->set_next(task->next());
 501   } else {
 502     // max is the first element
 503     assert(task == _first, "Sanity");
 504     _first = task->next();
 505   }
 506 
 507   if (task->next() != nullptr) {
 508     task->next()->set_prev(task->prev());
 509   } else {
 510     // max is the last element
 511     assert(task == _last, "Sanity");
 512     _last = task->prev();
 513   }
 514   task->set_next(nullptr);
 515   task->set_prev(nullptr);
 516   --_size;
 517   ++_total_removed;
 518 }
 519 
 520 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
 521   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 522   remove(task);
 523 
 524   // Enqueue the task for reclamation (should be done outside MCQ lock)
 525   task->set_next(_first_stale);
 526   task->set_prev(nullptr);
 527   _first_stale = task;
 528 }
 529 
 530 // methods in the compile queue need to be marked as used on the stack
 531 // so that they don't get reclaimed by Redefine Classes
 532 void CompileQueue::mark_on_stack() {
 533   CompileTask* task = _first;
 534   while (task != nullptr) {



 535     task->mark_on_stack();
 536     task = task->next();
 537   }
 538 }
 539 
 540 
 541 CompileQueue* CompileBroker::compile_queue(int comp_level) {
 542   if (is_c2_compile(comp_level)) return _c2_compile_queue;
 543   if (is_c1_compile(comp_level)) return _c1_compile_queue;
 544   return nullptr;
 545 }
 546 
 547 CompileQueue* CompileBroker::c1_compile_queue() {
 548   return _c1_compile_queue;
 549 }
 550 
 551 CompileQueue* CompileBroker::c2_compile_queue() {
 552   return _c2_compile_queue;
 553 }
 554 
 555 void CompileBroker::print_compile_queues(outputStream* st) {
 556   st->print_cr("Current compiles: ");
 557 
 558   char buf[2000];
 559   int buflen = sizeof(buf);
 560   Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
 561 
 562   st->cr();
 563   if (_c1_compile_queue != nullptr) {
 564     _c1_compile_queue->print(st);
 565   }
 566   if (_c2_compile_queue != nullptr) {
 567     _c2_compile_queue->print(st);
 568   }






 569 }
 570 
 571 void CompileQueue::print(outputStream* st) {
 572   assert_locked_or_safepoint(MethodCompileQueue_lock);
 573   st->print_cr("%s:", name());
 574   CompileTask* task = _first;
 575   if (task == nullptr) {
 576     st->print_cr("Empty");
 577   } else {
 578     while (task != nullptr) {
 579       task->print(st, nullptr, true, true);
 580       task = task->next();
 581     }
 582   }
 583   st->cr();
 584 }
 585 
 586 void CompileQueue::print_tty() {
 587   stringStream ss;
 588   // Dump the compile queue into a buffer before locking the tty
 589   print(&ss);
 590   {
 591     ttyLocker ttyl;
 592     tty->print("%s", ss.freeze());

 619       CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
 620     }
 621     first_registration = false;
 622 #endif // COMPILER2
 623   }
 624 }
 625 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
 626 
 627 // ------------------------------------------------------------------
 628 // CompileBroker::compilation_init
 629 //
 630 // Initialize the Compilation object
 631 void CompileBroker::compilation_init(JavaThread* THREAD) {
 632   // No need to initialize compilation system if we do not use it.
 633   if (!UseCompiler) {
 634     return;
 635   }
 636   // Set the interface to the current compiler(s).
 637   _c1_count = CompilationPolicy::c1_count();
 638   _c2_count = CompilationPolicy::c2_count();

 639 
 640 #if INCLUDE_JVMCI
 641   if (EnableJVMCI) {
 642     // This is creating a JVMCICompiler singleton.
 643     JVMCICompiler* jvmci = new JVMCICompiler();
 644 
 645     if (UseJVMCICompiler) {
 646       _compilers[1] = jvmci;
 647       if (FLAG_IS_DEFAULT(JVMCIThreads)) {
 648         if (BootstrapJVMCI) {
 649           // JVMCI will bootstrap so give it more threads
 650           _c2_count = MIN2(32, os::active_processor_count());
 651         }
 652       } else {
 653         _c2_count = JVMCIThreads;
 654       }
 655       if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
 656       } else {
 657 #ifdef COMPILER1
 658         _c1_count = JVMCIHostThreads;

 775     _perf_last_compile_size =
 776              PerfDataManager::create_variable(SUN_CI, "lastSize",
 777                                               PerfData::U_Bytes,
 778                                               (jlong)CompileBroker::no_compile,
 779                                               CHECK);
 780 
 781 
 782     _perf_last_failed_type =
 783              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 784                                               PerfData::U_None,
 785                                               (jlong)CompileBroker::no_compile,
 786                                               CHECK);
 787 
 788     _perf_last_invalidated_type =
 789          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 790                                           PerfData::U_None,
 791                                           (jlong)CompileBroker::no_compile,
 792                                           CHECK);
 793   }
 794 

 795   _initialized = true;
 796 }
 797 





 798 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
 799   CompilationPolicy::replay_training_at_init_loop(thread);
 800 }
 801 
 802 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 803 // Entry for DeoptimizeObjectsALotThread. The threads are started in
 804 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
 805 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
 806     DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
 807     bool enter_single_loop;
 808     {
 809       MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
 810       static int single_thread_count = 0;
 811       enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
 812     }
 813     if (enter_single_loop) {
 814       dt->deoptimize_objects_alot_loop_single();
 815     } else {
 816       dt->deoptimize_objects_alot_loop_all();
 817     }

 941 }
 942 
 943 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
 944   char name_buffer[256];
 945   os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
 946   Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
 947   return JNIHandles::make_global(thread_oop);
 948 }
 949 
 950 static void print_compiler_threads(stringStream& msg) {
 951   if (TraceCompilerThreads) {
 952     tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
 953   }
 954   LogTarget(Debug, jit, thread) lt;
 955   if (lt.is_enabled()) {
 956     LogStream ls(lt);
 957     ls.print_cr("%s", msg.as_string());
 958   }
 959 }
 960 











 961 void CompileBroker::init_compiler_threads() {
 962   // Ensure any exceptions lead to vm_exit_during_initialization.
 963   EXCEPTION_MARK;
 964 #if !defined(ZERO)
 965   assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
 966 #endif // !ZERO
 967   // Initialize the compilation queue
 968   if (_c2_count > 0) {
 969     const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
 970     _c2_compile_queue  = new CompileQueue(name);
 971     _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
 972     _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
 973   }
 974   if (_c1_count > 0) {
 975     _c1_compile_queue  = new CompileQueue("C1 compile queue");
 976     _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
 977     _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
 978   }
 979 












 980   for (int i = 0; i < _c2_count; i++) {
 981     // Create a name for our thread.
 982     jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
 983     _compiler2_objects[i] = thread_handle;
 984     _compiler2_logs[i] = nullptr;
 985 
 986     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
 987       JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
 988       assert(ct != nullptr, "should have been handled for initial thread");
 989       _compilers[1]->set_num_compiler_threads(i + 1);
 990       if (trace_compiler_threads()) {
 991         ResourceMark rm;
 992         ThreadsListHandle tlh;  // name() depends on the TLH.
 993         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
 994         stringStream msg;
 995         msg.print("Added initial compiler thread %s", ct->name());
 996         print_compiler_threads(msg);
 997       }
 998     }
 999   }
1000 
1001   for (int i = 0; i < _c1_count; i++) {
1002     // Create a name for our thread.
1003     jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
1004     _compiler1_objects[i] = thread_handle;
1005     _compiler1_logs[i] = nullptr;
1006 
1007     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1008       JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1009       assert(ct != nullptr, "should have been handled for initial thread");
1010       _compilers[0]->set_num_compiler_threads(i + 1);
1011       if (trace_compiler_threads()) {
1012         ResourceMark rm;
1013         ThreadsListHandle tlh;  // name() depends on the TLH.
1014         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1015         stringStream msg;
1016         msg.print("Added initial compiler thread %s", ct->name());
1017         print_compiler_threads(msg);
1018       }




















1019     }
1020   }
1021 
1022   if (UsePerfData) {
1023     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK);
1024   }
1025 
1026 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1027   if (DeoptimizeObjectsALot) {
1028     // Initialize and start the object deoptimizer threads
1029     const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1030     for (int count = 0; count < total_count; count++) {
1031       Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1032       jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1033       make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1034     }
1035   }
1036 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1037 }
1038 
1039 void CompileBroker::init_training_replay() {
1040   // Ensure any exceptions lead to vm_exit_during_initialization.
1041   EXCEPTION_MARK;
1042   if (TrainingData::have_data()) {
1043     Handle thread_oop = JavaThread::create_system_thread_object("Training replay thread", CHECK);
1044     jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1045     make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1046   }
1047 }
1048 
1049 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1050 
1051   int old_c2_count = 0, new_c2_count = 0, old_c1_count = 0, new_c1_count = 0;
1052   const int c2_tasks_per_thread = 2, c1_tasks_per_thread = 4;
1053 
1054   // Quick check if we already have enough compiler threads without taking the lock.
1055   // Numbers may change concurrently, so we read them again after we have the lock.
1056   if (_c2_compile_queue != nullptr) {
1057     old_c2_count = get_c2_thread_count();
1058     new_c2_count = MIN2(_c2_count, _c2_compile_queue->size() / c2_tasks_per_thread);
1059   }
1060   if (_c1_compile_queue != nullptr) {
1061     old_c1_count = get_c1_thread_count();
1062     new_c1_count = MIN2(_c1_count, _c1_compile_queue->size() / c1_tasks_per_thread);
1063   }

1159   }
1160 
1161   CompileThread_lock->unlock();
1162 }
1163 
1164 
1165 /**
1166  * Set the methods on the stack as on_stack so that redefine classes doesn't
1167  * reclaim them. This method is executed at a safepoint.
1168  */
1169 void CompileBroker::mark_on_stack() {
1170   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1171   // Since we are at a safepoint, we do not need a lock to access
1172   // the compile queues.
1173   if (_c2_compile_queue != nullptr) {
1174     _c2_compile_queue->mark_on_stack();
1175   }
1176   if (_c1_compile_queue != nullptr) {
1177     _c1_compile_queue->mark_on_stack();
1178   }






1179 }
1180 
1181 // ------------------------------------------------------------------
1182 // CompileBroker::compile_method
1183 //
1184 // Request compilation of a method.
1185 void CompileBroker::compile_method_base(const methodHandle& method,
1186                                         int osr_bci,
1187                                         int comp_level,
1188                                         int hot_count,
1189                                         CompileTask::CompileReason compile_reason,

1190                                         bool blocking,
1191                                         Thread* thread) {
1192   guarantee(!method->is_abstract(), "cannot compile abstract methods");
1193   assert(method->method_holder()->is_instance_klass(),
1194          "sanity check");
1195   assert(!method->method_holder()->is_not_initialized(),
1196          "method holder must be initialized");


1197   assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1198 
1199   if (CIPrintRequests) {
1200     tty->print("request: ");
1201     method->print_short_name(tty);
1202     if (osr_bci != InvocationEntryBci) {
1203       tty->print(" osr_bci: %d", osr_bci);
1204     }
1205     tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1206     if (hot_count > 0) {
1207       tty->print(" hot: yes");
1208     }
1209     tty->cr();
1210   }
1211 
1212   // A request has been made for compilation.  Before we do any
1213   // real work, check to see if the method has been compiled
1214   // in the meantime with a definitive result.
1215   if (compilation_is_complete(method, osr_bci, comp_level)) {
1216     return;
1217   }
1218 
1219 #ifndef PRODUCT
1220   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1221     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1222       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
1223       return;
1224     }
1225   }
1226 #endif
1227 
1228   // If this method is already in the compile queue, then
1229   // we do not block the current thread.
1230   if (compilation_is_in_queue(method)) {
1231     // We may want to decay our counter a bit here to prevent
1232     // multiple denied requests for compilation.  This is an
1233     // open compilation policy issue. Note: The other possibility,
1234     // in the case that this is a blocking compile request, is to have
1235     // all subsequent blocking requesters wait for completion of
1236     // ongoing compiles. Note that in this case we'll need a protocol
1237     // for freeing the associated compile tasks. [Or we could have
1238     // a single static monitor on which all these waiters sleep.]
1239     return;
1240   }
1241 
1242   // Tiered policy requires MethodCounters to exist before adding a method to
1243   // the queue. Create if we don't have them yet.
1244   method->get_method_counters(thread);
1245 




1246   // Outputs from the following MutexLocker block:
1247   CompileTask* task     = nullptr;
1248   CompileQueue* queue  = compile_queue(comp_level);
1249 
1250   // Acquire our lock.
1251   {
1252     MutexLocker locker(thread, MethodCompileQueue_lock);
1253 
1254     // Make sure the method has not slipped into the queues since
1255     // last we checked; note that those checks were "fast bail-outs".
1256     // Here we need to be more careful, see 14012000 below.
1257     if (compilation_is_in_queue(method)) {
1258       return;
1259     }
1260 
1261     // We need to check again to see if the compilation has
1262     // completed.  A previous compilation may have registered
1263     // some result.
1264     if (compilation_is_complete(method, osr_bci, comp_level)) {
1265       return;
1266     }
1267 
1268     // We now know that this compilation is not pending, complete,
1269     // or prohibited.  Assign a compile_id to this compilation
1270     // and check to see if it is in our [Start..Stop) range.
1271     int compile_id = assign_compile_id(method, osr_bci);
1272     if (compile_id == 0) {
1273       // The compilation falls outside the allowed range.
1274       return;
1275     }
1276 
1277 #if INCLUDE_JVMCI
1278     if (UseJVMCICompiler && blocking) {
1279       // Don't allow blocking compiles for requests triggered by JVMCI.
1280       if (thread->is_Compiler_thread()) {
1281         blocking = false;
1282       }
1283 
1284       // In libjvmci, JVMCI initialization should not deadlock with other threads

1334     // <RESULT, QUEUE> :
1335     //     <0, 1> : in compile queue, but not yet compiled
1336     //     <1, 1> : compiled but queue bit not cleared
1337     //     <1, 0> : compiled and queue bit cleared
1338     // Because we first check the queue bits then check the result bits,
1339     // we are assured that we cannot introduce a duplicate task.
1340     // Note that if we did the tests in the reverse order (i.e. check
1341     // result then check queued bit), we could get the result bit before
1342     // the compilation completed, and the queue bit after the compilation
1343     // completed, and end up introducing a "duplicate" (redundant) task.
1344     // In that case, the compiler thread should first check if a method
1345     // has already been compiled before trying to compile it.
1346     // NOTE: in the event that there are multiple compiler threads and
1347     // there is de-optimization/recompilation, things will get hairy,
1348     // and in that case it's best to protect both the testing (here) of
1349     // these bits, and their updating (here and elsewhere) under a
1350     // common lock.
1351     task = create_compile_task(queue,
1352                                compile_id, method,
1353                                osr_bci, comp_level,
1354                                hot_count, compile_reason,
1355                                blocking);












1356   }
1357 
1358   if (blocking) {
1359     wait_for_completion(task);
1360   }
1361 }
1362 



















1363 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1364                                        int comp_level,
1365                                        int hot_count,

1366                                        CompileTask::CompileReason compile_reason,
1367                                        TRAPS) {
1368   // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1369   if (!_initialized || comp_level == CompLevel_none) {
1370     return nullptr;
1371   }
1372 
1373   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1374   assert(comp != nullptr, "Ensure we have a compiler");
1375 
1376 #if INCLUDE_JVMCI
1377   if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1378     // JVMCI compilation is not yet initializable.
1379     return nullptr;
1380   }
1381 #endif
1382 
1383   DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1384   // CompileBroker::compile_method can trap and can have pending async exception.
1385   nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_count, compile_reason, directive, THREAD);
1386   DirectivesStack::release(directive);
1387   return nm;
1388 }
1389 
1390 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1391                                          int comp_level,
1392                                          int hot_count,

1393                                          CompileTask::CompileReason compile_reason,
1394                                          DirectiveSet* directive,
1395                                          TRAPS) {
1396 
1397   // make sure arguments make sense
1398   assert(method->method_holder()->is_instance_klass(), "not an instance method");
1399   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1400   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1401   assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");



1402   // return quickly if possible






1403 
1404   // lock, make sure that the compilation
1405   // isn't prohibited in a straightforward way.
1406   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1407   if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1408     return nullptr;
1409   }
1410 
1411   if (osr_bci == InvocationEntryBci) {
1412     // standard compilation
1413     nmethod* method_code = method->code();
1414     if (method_code != nullptr) {
1415       if (compilation_is_complete(method, osr_bci, comp_level)) {
1416         return method_code;
1417       }
1418     }
1419     if (method->is_not_compilable(comp_level)) {
1420       return nullptr;
1421     }
1422   } else {
1423     // osr compilation
1424     // We accept a higher level osr method
1425     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1426     if (nm != nullptr) return nm;
1427     if (method->is_not_osr_compilable(comp_level)) return nullptr;
1428   }
1429 
1430   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1431   // some prerequisites that are compiler specific
1432   if (comp->is_c2() || comp->is_jvmci()) {


1433     InternalOOMEMark iom(THREAD);
1434     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1435     // Resolve all classes seen in the signature of the method
1436     // we are compiling.
1437     Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1438   }
1439 
1440   // If the method is native, do the lookup in the thread requesting
1441   // the compilation. Native lookups can load code, which is not
1442   // permitted during compilation.
1443   //
1444   // Note: A native method implies non-osr compilation which is
1445   //       checked with an assertion at the entry of this method.
1446   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1447     address adr = NativeLookup::lookup(method, THREAD);
1448     if (HAS_PENDING_EXCEPTION) {
1449       // In case of an exception looking up the method, we just forget
1450       // about it. The interpreter will kick-in and throw the exception.
1451       method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1452       CLEAR_PENDING_EXCEPTION;

1467   }
1468 
1469   // do the compilation
1470   if (method->is_native()) {
1471     if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1472       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1473       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1474       //
1475       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1476       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1477       AdapterHandlerLibrary::create_native_wrapper(method);
1478     } else {
1479       return nullptr;
1480     }
1481   } else {
1482     // If the compiler is shut off due to code cache getting full
1483     // fail out now so blocking compiles dont hang the java thread
1484     if (!should_compile_new_jobs()) {
1485       return nullptr;
1486     }
1487     bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles;
1488     compile_method_base(method, osr_bci, comp_level, hot_count, compile_reason, is_blocking, THREAD);


1489   }
1490 
1491   // return requested nmethod
1492   // We accept a higher level osr method
1493   if (osr_bci == InvocationEntryBci) {
1494     return method->code();
1495   }
1496   return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1497 }
1498 
1499 
1500 // ------------------------------------------------------------------
1501 // CompileBroker::compilation_is_complete
1502 //
1503 // See if compilation of this method is already complete.
1504 bool CompileBroker::compilation_is_complete(const methodHandle& method,
1505                                             int                 osr_bci,
1506                                             int                 comp_level) {






1507   bool is_osr = (osr_bci != standard_entry_bci);
1508   if (is_osr) {
1509     if (method->is_not_osr_compilable(comp_level)) {
1510       return true;
1511     } else {
1512       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1513       return (result != nullptr);
1514     }
1515   } else {
1516     if (method->is_not_compilable(comp_level)) {
1517       return true;
1518     } else {
1519       nmethod* result = method->code();
1520       if (result == nullptr) return false;
1521       return comp_level == result->comp_level();









1522     }
1523   }
1524 }
1525 
1526 
1527 /**
1528  * See if this compilation is already requested.
1529  *
1530  * Implementation note: there is only a single "is in queue" bit
1531  * for each method.  This means that the check below is overly
1532  * conservative in the sense that an osr compilation in the queue
1533  * will block a normal compilation from entering the queue (and vice
1534  * versa).  This can be remedied by a full queue search to disambiguate
1535  * cases.  If it is deemed profitable, this may be done.
1536  */
1537 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1538   return method->queued_for_compilation();
1539 }
1540 
1541 // ------------------------------------------------------------------

1601     if (CIStart <= id && id < CIStop) {
1602       return id;
1603     }
1604   }
1605 
1606   // Method was not in the appropriate compilation range.
1607   method->set_not_compilable_quietly("Not in requested compile id range");
1608   return 0;
1609 #else
1610   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1611   // only _compilation_id is incremented.
1612   return AtomicAccess::add(&_compilation_id, 1);
1613 #endif
1614 }
1615 
1616 // ------------------------------------------------------------------
1617 // CompileBroker::assign_compile_id_unlocked
1618 //
1619 // Public wrapper for assign_compile_id that acquires the needed locks
1620 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1621   MutexLocker locker(thread, MethodCompileQueue_lock);
1622   return assign_compile_id(method, osr_bci);
1623 }
1624 
1625 // ------------------------------------------------------------------
1626 // CompileBroker::create_compile_task
1627 //
1628 // Create a CompileTask object representing the current request for
1629 // compilation.  Add this task to the queue.
1630 CompileTask* CompileBroker::create_compile_task(CompileQueue*       queue,
1631                                                 int                 compile_id,
1632                                                 const methodHandle& method,
1633                                                 int                 osr_bci,
1634                                                 int                 comp_level,
1635                                                 int                 hot_count,

1636                                                 CompileTask::CompileReason compile_reason,

1637                                                 bool                blocking) {
1638   CompileTask* new_task = new CompileTask(compile_id, method, osr_bci, comp_level,
1639                                           hot_count, compile_reason, blocking);
1640   queue->add(new_task);
1641   return new_task;
1642 }
1643 
1644 #if INCLUDE_JVMCI
1645 // The number of milliseconds to wait before checking if
1646 // JVMCI compilation has made progress.
1647 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1648 
1649 // The number of JVMCI compilation progress checks that must fail
1650 // before unblocking a thread waiting for a blocking compilation.
1651 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1652 
1653 /**
1654  * Waits for a JVMCI compiler to complete a given task. This thread
1655  * waits until either the task completes or it sees no JVMCI compilation
1656  * progress for N consecutive milliseconds where N is
1657  * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1658  * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1659  *
1660  * @return true if this thread needs to delete the task

1774  * compiler threads can start compiling.
1775  */
1776 bool CompileBroker::init_compiler_runtime() {
1777   CompilerThread* thread = CompilerThread::current();
1778   AbstractCompiler* comp = thread->compiler();
1779   // Final sanity check - the compiler object must exist
1780   guarantee(comp != nullptr, "Compiler object must exist");
1781 
1782   {
1783     // Must switch to native to allocate ci_env
1784     ThreadToNativeFromVM ttn(thread);
1785     ciEnv ci_env((CompileTask*)nullptr);
1786     // Cache Jvmti state
1787     ci_env.cache_jvmti_state();
1788     // Cache DTrace flags
1789     ci_env.cache_dtrace_flags();
1790 
1791     // Switch back to VM state to do compiler initialization
1792     ThreadInVMfromNative tv(thread);
1793 
1794     // Perform per-thread and global initializations
1795     comp->initialize();
1796   }
1797 
1798   if (comp->is_failed()) {
1799     disable_compilation_forever();
1800     // If compiler initialization failed, no compiler thread that is specific to a
1801     // particular compiler runtime will ever start to compile methods.
1802     shutdown_compiler_runtime(comp, thread);
1803     return false;
1804   }
1805 
1806   // C1 specific check
1807   if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
1808     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
1809     return false;
1810   }
1811 
1812   return true;
1813 }
1814 
1815 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
1816   BufferBlob* blob = thread->get_buffer_blob();
1817   if (blob != nullptr) {
1818     blob->purge();
1819     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1820     CodeCache::free(blob);
1821   }
1822 }
1823 
1824 /**
1825  * If C1 and/or C2 initialization failed, we shut down all compilation.
1826  * We do this to keep things simple. This can be changed if it ever turns
1827  * out to be a problem.
1828  */
1829 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
1830   free_buffer_blob_if_allocated(thread);
1831 


1832   if (comp->should_perform_shutdown()) {
1833     // There are two reasons for shutting down the compiler
1834     // 1) compiler runtime initialization failed
1835     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
1836     warning("%s initialization failed. Shutting down all compilers", comp->name());
1837 
1838     // Only one thread per compiler runtime object enters here
1839     // Set state to shut down
1840     comp->set_shut_down();
1841 
1842     // Delete all queued compilation tasks to make compiler threads exit faster.
1843     if (_c1_compile_queue != nullptr) {
1844       _c1_compile_queue->delete_all();
1845     }
1846 
1847     if (_c2_compile_queue != nullptr) {
1848       _c2_compile_queue->delete_all();
1849     }
1850 
1851     // Set flags so that we continue execution with using interpreter only.

1855     // We could delete compiler runtimes also. However, there are references to
1856     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
1857     // fail. This can be done later if necessary.
1858   }
1859 }
1860 
1861 /**
1862  * Helper function to create new or reuse old CompileLog.
1863  */
1864 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
1865   if (!LogCompilation) return nullptr;
1866 
1867   AbstractCompiler *compiler = ct->compiler();
1868   bool c1 = compiler->is_c1();
1869   jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;
1870   assert(compiler_objects != nullptr, "must be initialized at this point");
1871   CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;
1872   assert(logs != nullptr, "must be initialized at this point");
1873   int count = c1 ? _c1_count : _c2_count;
1874 





1875   // Find Compiler number by its threadObj.
1876   oop compiler_obj = ct->threadObj();
1877   int compiler_number = 0;
1878   bool found = false;
1879   for (; compiler_number < count; compiler_number++) {
1880     if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
1881       found = true;
1882       break;
1883     }
1884   }
1885   assert(found, "Compiler must exist at this point");
1886 
1887   // Determine pointer for this thread's log.
1888   CompileLog** log_ptr = &logs[compiler_number];
1889 
1890   // Return old one if it exists.
1891   CompileLog* log = *log_ptr;
1892   if (log != nullptr) {
1893     ct->init_log(log);
1894     return log;

1936   if (!thread->init_compilation_timeout()) {
1937     return;
1938   }
1939 
1940   // If compiler thread/runtime initialization fails, exit the compiler thread
1941   if (!init_compiler_runtime()) {
1942     return;
1943   }
1944 
1945   thread->start_idle_timer();
1946 
1947   // Poll for new compilation tasks as long as the JVM runs. Compilation
1948   // should only be disabled if something went wrong while initializing the
1949   // compiler runtimes. This, in turn, should not happen. The only known case
1950   // when compiler runtime initialization fails is if there is not enough free
1951   // space in the code cache to generate the necessary stubs, etc.
1952   while (!is_compilation_disabled_forever()) {
1953     // We need this HandleMark to avoid leaking VM handles.
1954     HandleMark hm(thread);
1955 


1956     CompileTask* task = queue->get(thread);
1957     if (task == nullptr) {
1958       if (UseDynamicNumberOfCompilerThreads) {
1959         // Access compiler_count under lock to enforce consistency.
1960         MutexLocker only_one(CompileThread_lock);
1961         if (can_remove(thread, true)) {
1962           if (trace_compiler_threads()) {
1963             ResourceMark rm;
1964             stringStream msg;
1965             msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
1966                       thread->name(), thread->idle_time_millis());
1967             print_compiler_threads(msg);
1968           }
1969 
1970           // Notify compiler that the compiler thread is about to stop
1971           thread->compiler()->stopping_compiler_thread(thread);
1972 
1973           free_buffer_blob_if_allocated(thread);
1974           return; // Stop this thread.
1975         }
1976       }
1977     } else {
1978       // Assign the task to the current thread.  Mark this compilation
1979       // thread as active for the profiler.
1980       // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
1981       // occurs after fetching the compile task off the queue.
1982       CompileTaskWrapper ctw(task);
1983       methodHandle method(thread, task->method());
1984 
1985       // Never compile a method if breakpoints are present in it
1986       if (method()->number_of_breakpoints() == 0) {
1987         // Compile the method.
1988         if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1989           invoke_compiler_on_method(task);
1990           thread->start_idle_timer();
1991         } else {
1992           // After compilation is disabled, remove remaining methods from queue
1993           method->clear_queued_for_compilation();

1994           task->set_failure_reason("compilation is disabled");
1995         }
1996       } else {
1997         task->set_failure_reason("breakpoints are present");
1998       }
1999 
2000       if (UseDynamicNumberOfCompilerThreads) {


2001         possibly_add_compiler_threads(thread);
2002         assert(!thread->has_pending_exception(), "should have been handled");
2003       }
2004     }
2005   }
2006 
2007   // Shut down compiler runtime
2008   shutdown_compiler_runtime(thread->compiler(), thread);
2009 }
2010 
2011 // ------------------------------------------------------------------
2012 // CompileBroker::init_compiler_thread_log
2013 //
2014 // Set up state required by +LogCompilation.
2015 void CompileBroker::init_compiler_thread_log() {
2016     CompilerThread* thread = CompilerThread::current();
2017     char  file_name[4*K];
2018     FILE* fp = nullptr;
2019     intx thread_id = os::current_thread_id();
2020     for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {

2176 
2177 // Acquires Compilation_lock and waits for it to be notified
2178 // as long as WhiteBox::compilation_locked is true.
2179 static void whitebox_lock_compilation() {
2180   MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2181   while (WhiteBox::compilation_locked) {
2182     locker.wait();
2183   }
2184 }
2185 
2186 // ------------------------------------------------------------------
2187 // CompileBroker::invoke_compiler_on_method
2188 //
2189 // Compile a method.
2190 //
2191 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2192   task->print_ul();
2193   elapsedTimer time;
2194 
2195   DirectiveSet* directive = task->directive();
2196   if (directive->PrintCompilationOption) {
2197     ResourceMark rm;
2198     task->print_tty();
2199   }
2200 
2201   CompilerThread* thread = CompilerThread::current();
2202   ResourceMark rm(thread);
2203 
2204   if (CompilationLog::log() != nullptr) {
2205     CompilationLog::log()->log_compile(thread, task);
2206   }
2207 
2208   // Common flags.
2209   int compile_id = task->compile_id();
2210   int osr_bci = task->osr_bci();
2211   bool is_osr = (osr_bci != standard_entry_bci);
2212   bool should_log = (thread->log() != nullptr);
2213   bool should_break = false;

2214   const int task_level = task->comp_level();
2215   AbstractCompiler* comp = task->compiler();
2216   {
2217     // create the handle inside it's own block so it can't
2218     // accidentally be referenced once the thread transitions to
2219     // native.  The NoHandleMark before the transition should catch
2220     // any cases where this occurs in the future.
2221     methodHandle method(thread, task->method());
2222 
2223     assert(!method->is_native(), "no longer compile natives");
2224 
2225     // Update compile information when using perfdata.
2226     if (UsePerfData) {
2227       update_compile_perf_data(thread, method, is_osr);
2228     }
2229 
2230     DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2231   }
2232 
2233   should_break = directive->BreakAtCompileOption || task->check_break_at_flags();

2328       ci_env.record_method_not_compilable("redefined method", true);
2329     }
2330 
2331     // Cache DTrace flags
2332     ci_env.cache_dtrace_flags();
2333 
2334     ciMethod* target = ci_env.get_method_from_handle(target_handle);
2335 
2336     TraceTime t1("compilation", &time);
2337     EventCompilation event;
2338 
2339     if (comp == nullptr) {
2340       ci_env.record_method_not_compilable("no compiler");
2341     } else if (!ci_env.failing()) {
2342       if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2343         whitebox_lock_compilation();
2344       }
2345       comp->compile_method(&ci_env, target, osr_bci, true, directive);
2346 
2347       /* Repeat compilation without installing code for profiling purposes */
2348       int repeat_compilation_count = directive->RepeatCompilationOption;
2349       if (repeat_compilation_count > 0) {
2350         CHeapStringHolder failure_reason;
2351         failure_reason.set(ci_env._failure_reason.get());
2352         while (repeat_compilation_count > 0) {
2353           ResourceMark rm(thread);
2354           task->print_ul("NO CODE INSTALLED");
2355           thread->timeout()->reset();
2356           ci_env._failure_reason.clear();
2357           comp->compile_method(&ci_env, target, osr_bci, false, directive);
2358           repeat_compilation_count--;
2359         }
2360         ci_env._failure_reason.set(failure_reason.get());
2361       }
2362     }
2363 
2364 
2365     if (!ci_env.failing() && !task->is_success()) {
2366       assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2367       assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2368       // The compiler elected, without comment, not to register a result.
2369       // Do not attempt further compilations of this method.
2370       ci_env.record_method_not_compilable("compile failed");
2371     }
2372 
2373     // Copy this bit to the enclosing block:
2374     compilable = ci_env.compilable();
2375 
2376     if (ci_env.failing()) {
2377       // Duplicate the failure reason string, so that it outlives ciEnv
2378       failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2379       failure_reason_on_C_heap = true;
2380       retry_message = ci_env.retry_message();
2381       ci_env.report_failure(failure_reason);
2382     }
2383 
2384     if (ci_env.failing()) {
2385       handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2386     }
2387     if (event.should_commit()) {
2388       post_compilation_event(event, task);
2389     }
2390   }
2391 
2392   if (failure_reason != nullptr) {
2393     task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2394     if (CompilationLog::log() != nullptr) {
2395       CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2396     }
2397     if (PrintCompilation || directive->PrintCompilationOption) {
2398       FormatBufferResource msg = retry_message != nullptr ?
2399         FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2400         FormatBufferResource("COMPILE SKIPPED: %s",      failure_reason);
2401       task->print(tty, msg);
2402     }
2403   }
2404 

2405   DirectivesStack::release(directive);
2406 
2407   methodHandle method(thread, task->method());
2408 
2409   DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2410 
2411   collect_statistics(thread, time, task);
2412 
2413   if (PrintCompilation && PrintCompilation2) {
2414     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
2415     tty->print("%4d ", compile_id);    // print compilation number
2416     tty->print("%s ", (is_osr ? "%" : " "));
2417     if (task->is_success()) {
2418       tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2419     }
2420     tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2421   }
2422 
2423   Log(compilation, codecache) log;
2424   if (log.is_debug()) {
2425     LogStream ls(log.debug());
2426     codecache_print(&ls, /* detailed= */ false);
2427   }
2428   if (PrintCodeCacheOnCompilation) {
2429     codecache_print(/* detailed= */ false);
2430   }
2431   // Disable compilation, if required.
2432   switch (compilable) {
2433   case ciEnv::MethodCompilable_never:
2434     if (is_osr)
2435       method->set_not_osr_compilable_quietly("MethodCompilable_never");
2436     else
2437       method->set_not_compilable_quietly("MethodCompilable_never");
2438     break;
2439   case ciEnv::MethodCompilable_not_at_tier:
2440     if (is_osr)
2441       method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2442     else
2443       method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2444     break;
2445   }
2446 
2447   // Note that the queued_for_compilation bits are cleared without
2448   // protection of a mutex. [They were set by the requester thread,
2449   // when adding the task to the compile queue -- at which time the
2450   // compile queue lock was held. Subsequently, we acquired the compile
2451   // queue lock to get this task off the compile queue; thus (to belabour
2452   // the point somewhat) our clearing of the bits must be occurring
2453   // only after the setting of the bits. See also 14012000 above.
2454   method->clear_queued_for_compilation();






2455 }
2456 
2457 /**
2458  * The CodeCache is full. Print warning and disable compilation.
2459  * Schedule code cache cleaning so compilation can continue later.
2460  * This function needs to be called only from CodeCache::allocate(),
2461  * since we currently handle a full code cache uniformly.
2462  */
2463 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2464   UseInterpreter = true;
2465   if (UseCompiler || AlwaysCompileLoopMethods ) {
2466     if (xtty != nullptr) {
2467       stringStream s;
2468       // Dump code cache state into a buffer before locking the tty,
2469       // because log_state() will use locks causing lock conflicts.
2470       CodeCache::log_state(&s);
2471       // Lock to prevent tearing
2472       ttyLocker ttyl;
2473       xtty->begin_elem("code_cache_full");
2474       xtty->print("%s", s.freeze());

2547 // CompileBroker::collect_statistics
2548 //
2549 // Collect statistics about the compilation.
2550 
2551 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2552   bool success = task->is_success();
2553   methodHandle method (thread, task->method());
2554   int compile_id = task->compile_id();
2555   bool is_osr = (task->osr_bci() != standard_entry_bci);
2556   const int comp_level = task->comp_level();
2557   CompilerCounters* counters = thread->counters();
2558 
2559   MutexLocker locker(CompileStatistics_lock);
2560 
2561   // _perf variables are production performance counters which are
2562   // updated regardless of the setting of the CITime and CITimeEach flags
2563   //
2564 
2565   // account all time, including bailouts and failures in this counter;
2566   // C1 and C2 counters are counting both successful and unsuccessful compiles
2567   _t_total_compilation.add(time);
2568 
2569   // Update compilation times. Used by the implementation of JFR CompilerStatistics
2570   // and java.lang.management.CompilationMXBean.
2571   _perf_total_compilation->inc(time.ticks());
2572   _peak_compilation_time = MAX2(time.milliseconds(), _peak_compilation_time);
2573 
2574   if (!success) {
2575     _total_bailout_count++;
2576     if (UsePerfData) {
2577       _perf_last_failed_method->set_value(counters->current_method());
2578       _perf_last_failed_type->set_value(counters->compile_type());
2579       _perf_total_bailout_count->inc();
2580     }
2581     _t_bailedout_compilation.add(time);











2582   } else if (!task->is_success()) {
2583     if (UsePerfData) {
2584       _perf_last_invalidated_method->set_value(counters->current_method());
2585       _perf_last_invalidated_type->set_value(counters->compile_type());
2586       _perf_total_invalidated_count->inc();
2587     }
2588     _total_invalidated_count++;
2589     _t_invalidated_compilation.add(time);











2590   } else {
2591     // Compilation succeeded
2592     if (CITime) {
2593       int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2594       if (is_osr) {
2595         _t_osr_compilation.add(time);
2596         _sum_osr_bytes_compiled += bytes_compiled;
2597       } else {
2598         _t_standard_compilation.add(time);
2599         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2600       }
2601 
2602       // Collect statistic per compilation level
2603       if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {









2604         CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2605         if (is_osr) {
2606           stats->_osr.update(time, bytes_compiled);
2607         } else {
2608           stats->_standard.update(time, bytes_compiled);
2609         }
2610         stats->_nmethods_size += task->nm_total_size();
2611         stats->_nmethods_code_size += task->nm_insts_size();
2612       } else {
2613         assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2614       }
2615 
2616       // Collect statistic per compiler
2617       AbstractCompiler* comp = compiler(comp_level);
2618       if (comp) {
2619         CompilerStatistics* stats = comp->stats();
2620         if (is_osr) {
2621           stats->_osr.update(time, bytes_compiled);
2622         } else {
2623           stats->_standard.update(time, bytes_compiled);
2624         }
2625         stats->_nmethods_size += task->nm_total_size();
2626         stats->_nmethods_code_size += task->nm_insts_size();
2627       } else { // if (!comp)
2628         assert(false, "Compiler object must exist");
2629       }
2630     }
2631 
2632     if (UsePerfData) {
2633       // save the name of the last method compiled
2634       _perf_last_method->set_value(counters->current_method());
2635       _perf_last_compile_type->set_value(counters->compile_type());
2636       _perf_last_compile_size->set_value(method->code_size() +
2637                                          task->num_inlined_bytecodes());
2638       if (is_osr) {
2639         _perf_osr_compilation->inc(time.ticks());
2640         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2641       } else {
2642         _perf_standard_compilation->inc(time.ticks());
2643         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2644       }
2645     }
2646 
2647     if (CITimeEach) {

2670       _total_standard_compile_count++;
2671     }
2672   }
2673   // set the current method for the thread to null
2674   if (UsePerfData) counters->set_current_method("");
2675 }
2676 
2677 const char* CompileBroker::compiler_name(int comp_level) {
2678   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2679   if (comp == nullptr) {
2680     return "no compiler";
2681   } else {
2682     return (comp->name());
2683   }
2684 }
2685 
2686 jlong CompileBroker::total_compilation_ticks() {
2687   return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2688 }
2689 


















2690 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2691   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}",
2692                 name, stats->bytes_per_second(),
2693                 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2694                 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2695                 stats->_nmethods_size, stats->_nmethods_code_size);
2696 }
2697 











































































































2698 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
2699   if (per_compiler) {
2700     if (aggregate) {
2701       tty->cr();
2702       tty->print_cr("Individual compiler times (for compiled methods only)");
2703       tty->print_cr("------------------------------------------------");
2704       tty->cr();
2705     }
2706     for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
2707       AbstractCompiler* comp = _compilers[i];
2708       if (comp != nullptr) {
2709         print_times(comp->name(), comp->stats());
2710       }
2711     }



2712     if (aggregate) {
2713       tty->cr();
2714       tty->print_cr("Individual compilation Tier times (for compiled methods only)");
2715       tty->print_cr("------------------------------------------------");
2716       tty->cr();
2717     }
2718     char tier_name[256];
2719     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
2720       CompilerStatistics* stats = &_stats_per_level[tier-1];
2721       os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
2722       print_times(tier_name, stats);
2723     }







2724   }
2725 
2726   if (!aggregate) {
2727     return;
2728   }
2729 
2730   elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
2731   elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
2732   elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
2733 
2734   uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
2735   uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
2736 
2737   uint standard_compile_count = CompileBroker::_total_standard_compile_count;
2738   uint osr_compile_count = CompileBroker::_total_osr_compile_count;
2739   uint total_compile_count = CompileBroker::_total_compile_count;
2740   uint total_bailout_count = CompileBroker::_total_bailout_count;
2741   uint total_invalidated_count = CompileBroker::_total_invalidated_count;
2742 
2743   uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;

2745 
2746   tty->cr();
2747   tty->print_cr("Accumulated compiler times");
2748   tty->print_cr("----------------------------------------------------------");
2749                //0000000000111111111122222222223333333333444444444455555555556666666666
2750                //0123456789012345678901234567890123456789012345678901234567890123456789
2751   tty->print_cr("  Total compilation time   : %7.3f s", total_compilation.seconds());
2752   tty->print_cr("    Standard compilation   : %7.3f s, Average : %2.3f s",
2753                 standard_compilation.seconds(),
2754                 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
2755   tty->print_cr("    Bailed out compilation : %7.3f s, Average : %2.3f s",
2756                 CompileBroker::_t_bailedout_compilation.seconds(),
2757                 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
2758   tty->print_cr("    On stack replacement   : %7.3f s, Average : %2.3f s",
2759                 osr_compilation.seconds(),
2760                 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
2761   tty->print_cr("    Invalidated            : %7.3f s, Average : %2.3f s",
2762                 CompileBroker::_t_invalidated_compilation.seconds(),
2763                 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
2764 




2765   AbstractCompiler *comp = compiler(CompLevel_simple);
2766   if (comp != nullptr) {
2767     tty->cr();
2768     comp->print_timers();
2769   }
2770   comp = compiler(CompLevel_full_optimization);
2771   if (comp != nullptr) {
2772     tty->cr();
2773     comp->print_timers();
2774   }
2775 #if INCLUDE_JVMCI
2776   if (EnableJVMCI) {
2777     JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
2778     if (jvmci_comp != nullptr && jvmci_comp != comp) {
2779       tty->cr();
2780       jvmci_comp->print_timers();
2781     }
2782   }
2783 #endif
2784 

   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "cds/aotLinkedClassBulkLoader.hpp"
  26 #include "cds/cdsConfig.hpp"
  27 #include "classfile/javaClasses.inline.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/vmClasses.hpp"
  30 #include "classfile/vmSymbols.hpp"
  31 #include "code/aotCodeCache.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "code/codeHeapState.hpp"
  34 #include "code/dependencyContext.hpp"
  35 #include "compiler/compilationLog.hpp"
  36 #include "compiler/compilationMemoryStatistic.hpp"
  37 #include "compiler/compilationPolicy.hpp"
  38 #include "compiler/compileBroker.hpp"
  39 #include "compiler/compileLog.hpp"
  40 #include "compiler/compilerDefinitions.inline.hpp"
  41 #include "compiler/compilerEvent.hpp"
  42 #include "compiler/compilerOracle.hpp"
  43 #include "compiler/directivesParser.hpp"
  44 #include "compiler/recompilationPolicy.hpp"
  45 #include "gc/shared/memAllocator.hpp"
  46 #include "interpreter/linkResolver.hpp"
  47 #include "jfr/jfrEvents.hpp"
  48 #include "jvm.h"
  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/method.inline.hpp"
  55 #include "oops/methodData.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/atomicAccess.hpp"
  61 #include "runtime/escapeBarrier.hpp"
  62 #include "runtime/globals_extension.hpp"
  63 #include "runtime/handles.inline.hpp"
  64 #include "runtime/init.hpp"
  65 #include "runtime/interfaceSupport.inline.hpp"
  66 #include "runtime/java.hpp"
  67 #include "runtime/javaCalls.hpp"
  68 #include "runtime/jniHandles.inline.hpp"
  69 #include "runtime/os.hpp"
  70 #include "runtime/perfData.hpp"
  71 #include "runtime/safepointVerifiers.hpp"
  72 #include "runtime/sharedRuntime.hpp"
  73 #include "runtime/threads.hpp"
  74 #include "runtime/threadSMR.inline.hpp"
  75 #include "runtime/timerTrace.hpp"
  76 #include "runtime/vframe.inline.hpp"
  77 #include "services/management.hpp"
  78 #include "utilities/debug.hpp"
  79 #include "utilities/dtrace.hpp"
  80 #include "utilities/events.hpp"
  81 #include "utilities/formatBuffer.hpp"
  82 #include "utilities/macros.hpp"
  83 #include "utilities/nonblockingQueue.inline.hpp"
  84 #ifdef COMPILER1
  85 #include "c1/c1_Compiler.hpp"
  86 #endif
  87 #ifdef COMPILER2
  88 #include "opto/c2compiler.hpp"
  89 #endif
  90 #if INCLUDE_JVMCI
  91 #include "jvmci/jvmciEnv.hpp"
  92 #include "jvmci/jvmciRuntime.hpp"
  93 #endif
  94 
  95 #ifdef DTRACE_ENABLED
  96 
  97 // Only bother with this argument setup if dtrace is available
  98 
  99 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
 100   {                                                                      \
 101     Symbol* klass_name = (method)->klass_name();                         \
 102     Symbol* name = (method)->name();                                     \
 103     Symbol* signature = (method)->signature();                           \

 121   }
 122 
 123 #else //  ndef DTRACE_ENABLED
 124 
 125 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
 126 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
 127 
 128 #endif // ndef DTRACE_ENABLED
 129 
 130 bool CompileBroker::_initialized = false;
 131 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[2];
 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::_ac_count = 0;
 142 
 143 // An array of compiler names as Java String objects
 144 jobject* CompileBroker::_compiler1_objects = nullptr;
 145 jobject* CompileBroker::_compiler2_objects = nullptr;
 146 jobject* CompileBroker::_ac_objects = nullptr;
 147 
 148 CompileLog** CompileBroker::_compiler1_logs = nullptr;
 149 CompileLog** CompileBroker::_compiler2_logs = nullptr;
 150 CompileLog** CompileBroker::_ac_logs = nullptr;
 151 
 152 // These counters are used to assign an unique ID to each compilation.
 153 volatile jint CompileBroker::_compilation_id     = 0;
 154 volatile jint CompileBroker::_osr_compilation_id = 0;
 155 volatile jint CompileBroker::_native_compilation_id = 0;
 156 
 157 // Performance counters
 158 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
 159 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
 160 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
 161 
 162 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
 163 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
 164 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
 165 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
 166 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
 167 
 168 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
 169 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
 170 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
 171 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
 172 
 173 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
 174 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
 175 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
 176 PerfVariable*       CompileBroker::_perf_last_compile_type = nullptr;
 177 PerfVariable*       CompileBroker::_perf_last_compile_size = nullptr;
 178 PerfVariable*       CompileBroker::_perf_last_failed_type = nullptr;
 179 PerfVariable*       CompileBroker::_perf_last_invalidated_type = nullptr;
 180 
 181 // Timers and counters for generating statistics
 182 elapsedTimer CompileBroker::_t_total_compilation;
 183 elapsedTimer CompileBroker::_t_osr_compilation;
 184 elapsedTimer CompileBroker::_t_standard_compilation;
 185 elapsedTimer CompileBroker::_t_invalidated_compilation;
 186 elapsedTimer CompileBroker::_t_bailedout_compilation;
 187 
 188 uint CompileBroker::_total_bailout_count            = 0;
 189 uint CompileBroker::_total_invalidated_count        = 0;
 190 uint CompileBroker::_total_not_entrant_count        = 0;
 191 uint CompileBroker::_total_compile_count            = 0;
 192 uint CompileBroker::_total_osr_compile_count        = 0;
 193 uint CompileBroker::_total_standard_compile_count   = 0;
 194 uint CompileBroker::_total_compiler_stopped_count   = 0;
 195 uint CompileBroker::_total_compiler_restarted_count = 0;
 196 
 197 uint CompileBroker::_sum_osr_bytes_compiled         = 0;
 198 uint CompileBroker::_sum_standard_bytes_compiled    = 0;
 199 uint CompileBroker::_sum_nmethod_size               = 0;
 200 uint CompileBroker::_sum_nmethod_code_size          = 0;
 201 
 202 jlong CompileBroker::_peak_compilation_time        = 0;
 203 
 204 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];
 205 CompilerStatistics CompileBroker::_aot_stats;
 206 CompilerStatistics CompileBroker::_aot_stats_per_level[CompLevel_full_optimization + 1];
 207 
 208 CompileQueue* CompileBroker::_c2_compile_queue     = nullptr;
 209 CompileQueue* CompileBroker::_c1_compile_queue     = nullptr;
 210 CompileQueue* CompileBroker::_ac1_compile_queue    = nullptr;
 211 CompileQueue* CompileBroker::_ac2_compile_queue    = nullptr;
 212 
 213 bool compileBroker_init() {
 214   if (LogEvents) {
 215     CompilationLog::init();
 216   }
 217 
 218   // init directives stack, adding default directive
 219   DirectivesStack::init();
 220 
 221   if (DirectivesParser::has_file()) {
 222     return DirectivesParser::parse_from_flag();
 223   } else if (CompilerDirectivesPrint) {
 224     // Print default directive even when no other was added
 225     DirectivesStack::print(tty);
 226   }
 227 
 228   return true;
 229 }
 230 
 231 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
 232   CompilerThread* thread = CompilerThread::current();
 233   thread->set_task(task);
 234   CompileLog*     log  = thread->log();
 235   thread->timeout()->arm();
 236   if (log != nullptr && !task->is_unloaded())  task->log_task_start(log);
 237 }
 238 
 239 CompileTaskWrapper::~CompileTaskWrapper() {
 240   CompilerThread* thread = CompilerThread::current();
 241 
 242   // First, disarm the timeout. This still relies on the underlying task.
 243   thread->timeout()->disarm();
 244 
 245   CompileTask* task = thread->task();
 246   CompileLog*  log  = thread->log();
 247   AbstractCompiler* comp = thread->compiler();
 248   if (log != nullptr && !task->is_unloaded())  task->log_task_done(log);
 249   thread->set_task(nullptr);
 250   thread->set_env(nullptr);
 251   if (task->is_blocking()) {
 252     bool free_task = false;
 253     {
 254       MutexLocker notifier(thread, CompileTaskWait_lock);
 255       task->mark_complete();
 256 #if INCLUDE_JVMCI
 257       if (comp->is_jvmci()) {
 258         if (!task->has_waiter()) {
 259           // The waiting thread timed out and thus did not delete the task.
 260           free_task = true;
 261         }
 262         task->set_blocking_jvmci_compile_state(nullptr);
 263       }
 264 #endif
 265       if (!free_task) {
 266         // Notify the waiting thread that the compilation has completed
 267         // so that it can free the task.
 268         CompileTaskWait_lock->notify_all();
 269       }
 270     }
 271     if (free_task) {
 272       // The task can only be deleted once the task lock is released.
 273       delete task;
 274     }
 275   } else {
 276     task->mark_complete();
 277 
 278     // By convention, the compiling thread is responsible for deleting
 279     // a non-blocking CompileTask.
 280     delete task;
 281   }
 282 }
 283 
 284 /**
 285  * Check if a CompilerThread can be removed and update count if requested.
 286  */
 287 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
 288   assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
 289   if (!ReduceNumberOfCompilerThreads) return false;
 290 
 291   if (RecompilationPolicy::have_recompilation_work()) return false;
 292 
 293   AbstractCompiler *compiler = ct->compiler();
 294   int compiler_count = compiler->num_compiler_threads();
 295   bool c1 = compiler->is_c1();
 296 
 297   // Keep at least 1 compiler thread of each type.
 298   if (compiler_count < 2) return false;
 299 
 300   // Keep thread alive for at least some time.
 301   if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
 302 
 303 #if INCLUDE_JVMCI
 304   if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 305     // Handles for JVMCI thread objects may get released concurrently.
 306     if (do_it) {
 307       assert(CompileThread_lock->owner() == ct, "must be holding lock");
 308     } else {
 309       // Skip check if it's the last thread and let caller check again.
 310       return true;
 311     }
 312   }

 319     if (do_it) {
 320       assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
 321       compiler->set_num_compiler_threads(compiler_count - 1);
 322 #if INCLUDE_JVMCI
 323       if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 324         // Old j.l.Thread object can die when no longer referenced elsewhere.
 325         JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
 326         _compiler2_objects[compiler_count - 1] = nullptr;
 327       }
 328 #endif
 329     }
 330     return true;
 331   }
 332   return false;
 333 }
 334 
 335 /**
 336  * Add a CompileTask to a CompileQueue.
 337  */
 338 void CompileQueue::add(CompileTask* task) {
 339   assert(_lock->owned_by_self(), "must own lock");
 340 
 341   task->set_next(nullptr);
 342   task->set_prev(nullptr);
 343 
 344   if (_last == nullptr) {
 345     // The compile queue is empty.
 346     assert(_first == nullptr, "queue is empty");
 347     _first = task;
 348     _last = task;
 349   } else {
 350     // Append the task to the queue.
 351     assert(_last->next() == nullptr, "not last");
 352     _last->set_next(task);
 353     task->set_prev(_last);
 354     _last = task;
 355   }
 356   ++_size;
 357   ++_total_added;
 358   if (_size > _peak_size) {
 359     _peak_size = _size;
 360   }
 361 
 362   // Mark the method as being in the compile queue.
 363   task->method()->set_queued_for_compilation();
 364 
 365   task->mark_queued(os::elapsed_counter());
 366 
 367   if (CIPrintCompileQueue) {
 368     print_tty();
 369   }
 370 
 371   if (LogCompilation && xtty != nullptr) {
 372     task->log_task_queued();
 373   }
 374 
 375   if (TrainingData::need_data() && !CDSConfig::is_dumping_final_static_archive()) {
 376     CompileTrainingData* ctd = CompileTrainingData::make(task);
 377     if (ctd != nullptr) {
 378       task->set_training_data(ctd);
 379     }
 380   }
 381 
 382   // Notify CompilerThreads that a task is available.
 383   _lock->notify_all();
 384 }
 385 
 386 void CompileQueue::add_pending(CompileTask* task) {
 387   assert(_lock->owned_by_self() == false, "must NOT own lock");
 388   assert(UseLockFreeCompileQueues, "");
 389   task->method()->set_queued_for_compilation();
 390   _queue.push(*task);
 391   // FIXME: additional coordination needed? e.g., is it possible for compiler thread to block w/o processing pending tasks?
 392   if (is_empty()) {
 393     MutexLocker ml(_lock);
 394     _lock->notify_all();
 395   }
 396 }
 397 
 398 static bool process_pending(CompileTask* task) {
 399 //  guarantee(task->method()->queued_for_compilation(), "");
 400   if (task->is_unloaded()) {
 401     return true; // unloaded
 402   }
 403   task->method()->set_queued_for_compilation(); // FIXME
 404   if (task->method()->pending_queue_processed()) {
 405     return true; // already queued
 406   }
 407   // Mark the method as being in the compile queue.
 408   task->method()->set_pending_queue_processed();
 409   if (CompileBroker::compilation_is_complete(task->method(), task->osr_bci(), task->comp_level(),
 410                                              task->requires_online_compilation(), task->compile_reason())) {
 411     return true; // already compiled
 412   }
 413   return false; // active
 414 }
 415 
 416 void CompileQueue::transfer_pending() {
 417   assert(_lock->owned_by_self(), "must own lock");
 418 
 419   CompileTask* task;
 420   while ((task = _queue.pop()) != nullptr) {
 421     bool is_stale = process_pending(task);
 422     if (is_stale) {
 423       task->set_next(_first_stale);
 424       task->set_prev(nullptr);
 425       _first_stale = task;
 426     } else {
 427       add(task);
 428     }
 429   }
 430 }
 431 
 432 /**
 433  * Empties compilation queue by deleting all compilation tasks.
 434  * Furthermore, the method wakes up all threads that are waiting
 435  * on a compilation task to finish. This can happen if background
 436  * compilation is disabled.
 437  */
 438 void CompileQueue::delete_all() {
 439   MutexLocker mu(_lock);
 440   transfer_pending();
 441 
 442   CompileTask* current = _first;
 443 
 444   // Iterate over all tasks in the compile queue
 445   while (current != nullptr) {
 446     CompileTask* next = current->next();
 447     if (!current->is_blocking()) {
 448       // Non-blocking task. No one is waiting for it, delete it now.
 449       delete current;
 450     } else {
 451       // Blocking task. By convention, it is the waiters responsibility
 452       // to delete the task. We cannot delete it here, because we do not
 453       // coordinate with waiters. We will notify the waiters later.
 454     }
 455     current = next;
 456   }
 457   _first = nullptr;
 458   _last = nullptr;
 459 
 460   // Wake up all blocking task waiters to deal with remaining blocking
 461   // tasks. This is not a performance sensitive path, so we do this
 462   // unconditionally to simplify coding/testing.
 463   {
 464     MonitorLocker ml(Thread::current(), CompileTaskWait_lock);
 465     ml.notify_all();
 466   }
 467 
 468   // Wake up all threads that block on the queue.
 469   _lock->notify_all();
 470 }
 471 
 472 /**
 473  * Get the next CompileTask from a CompileQueue
 474  */
 475 CompileTask* CompileQueue::get(CompilerThread* thread) {
 476   // save methods from RedefineClasses across safepoint
 477   // across compile queue lock below.
 478   methodHandle save_method;
 479 
 480   MonitorLocker locker(_lock);
 481   transfer_pending();
 482 
 483   RecompilationPolicy::sample_load_average();
 484 
 485   // If _first is null we have no more compile jobs. There are two reasons for
 486   // having no compile jobs: First, we compiled everything we wanted. Second,
 487   // we ran out of code cache so compilation has been disabled. In the latter
 488   // case we perform code cache sweeps to free memory such that we can re-enable
 489   // compilation.
 490   while (_first == nullptr) {
 491     // Exit loop if compilation is disabled forever
 492     if (CompileBroker::is_compilation_disabled_forever()) {
 493       return nullptr;
 494     }
 495 
 496     AbstractCompiler* compiler = thread->compiler();
 497     guarantee(compiler != nullptr, "Compiler object must exist");
 498     compiler->on_empty_queue(this, thread);
 499     if (_first != nullptr) {
 500       // The call to on_empty_queue may have temporarily unlocked the MCQ lock
 501       // so check again whether any tasks were added to the queue.
 502       break;
 503     }
 504 
 505     // If we have added stale tasks, there might be waiters that want
 506     // the notification these tasks have failed. Normally, this would
 507     // be done by a compiler thread that would perform the purge at
 508     // the end of some compilation. But, if compile queue is empty,
 509     // there is no guarantee compilers would run and do the purge.
 510     // Do the purge here and now to unblock the waiters.
 511     // Perform this until we run out of stale tasks.
 512     while (_first_stale != nullptr) {
 513       purge_stale_tasks();
 514     }
 515     if (_first != nullptr) {
 516       // Purge stale tasks may have transferred some new tasks,
 517       // so check again.
 518       break;
 519     }
 520 
 521     // If there are no compilation tasks and we can compile new jobs
 522     // (i.e., there is enough free space in the code cache) there is
 523     // no need to invoke the GC.
 524     // We need a timed wait here, since compiler threads can exit if compilation
 525     // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
 526     // is not critical and we do not want idle compiler threads to wake up too often.
 527     locker.wait(5*1000);
 528 
 529     transfer_pending(); // reacquired lock
 530 
 531     if (RecompilationPolicy::have_recompilation_work()) return nullptr;
 532 
 533     if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
 534       // Still nothing to compile. Give caller a chance to stop this thread.
 535       if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
 536     }
 537   }
 538 
 539   if (CompileBroker::is_compilation_disabled_forever()) {
 540     return nullptr;
 541   }
 542 
 543   CompileTask* task;
 544   {
 545     NoSafepointVerifier nsv;
 546     task = CompilationPolicy::select_task(this, thread);
 547     if (task != nullptr) {
 548       task = task->select_for_compilation();
 549     }
 550   }
 551 
 552   if (task != nullptr) {
 553     // Save method pointers across unlock safepoint.  The task is removed from
 554     // the compilation queue, which is walked during RedefineClasses.
 555     Thread* thread = Thread::current();
 556     save_method = methodHandle(thread, task->method());
 557 
 558     remove(task);
 559   }
 560   purge_stale_tasks(); // may temporarily release MCQ lock
 561   return task;
 562 }
 563 
 564 // Clean & deallocate stale compile tasks.
 565 // Temporarily releases MethodCompileQueue lock.
 566 void CompileQueue::purge_stale_tasks() {
 567   assert(_lock->owned_by_self(), "must own lock");
 568   if (_first_stale != nullptr) {
 569     // Stale tasks are purged when MCQ lock is released,
 570     // but _first_stale updates are protected by MCQ lock.
 571     // Once task processing starts and MCQ lock is released,
 572     // other compiler threads can reuse _first_stale.
 573     CompileTask* head = _first_stale;
 574     _first_stale = nullptr;
 575     {
 576       MutexUnlocker ul(_lock);
 577       for (CompileTask* task = head; task != nullptr; ) {
 578         CompileTask* next_task = task->next();
 579         task->set_next(nullptr);
 580         CompileTaskWrapper ctw(task); // Frees the task
 581         task->set_failure_reason("stale task");
 582         task = next_task;
 583       }
 584     }
 585     transfer_pending(); // transfer pending after reacquiring MCQ lock
 586   }
 587 }
 588 
 589 void CompileQueue::remove(CompileTask* task) {
 590   assert(_lock->owned_by_self(), "must own lock");
 591   if (task->prev() != nullptr) {
 592     task->prev()->set_next(task->next());
 593   } else {
 594     // max is the first element
 595     assert(task == _first, "Sanity");
 596     _first = task->next();
 597   }
 598 
 599   if (task->next() != nullptr) {
 600     task->next()->set_prev(task->prev());
 601   } else {
 602     // max is the last element
 603     assert(task == _last, "Sanity");
 604     _last = task->prev();
 605   }
 606   task->set_next(nullptr);
 607   task->set_prev(nullptr);
 608   --_size;
 609   ++_total_removed;
 610 }
 611 
 612 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
 613   assert(_lock->owned_by_self(), "must own lock");
 614   remove(task);
 615 
 616   // Enqueue the task for reclamation (should be done outside MCQ lock)
 617   task->set_next(_first_stale);
 618   task->set_prev(nullptr);
 619   _first_stale = task;
 620 }
 621 
 622 // methods in the compile queue need to be marked as used on the stack
 623 // so that they don't get reclaimed by Redefine Classes
 624 void CompileQueue::mark_on_stack() {
 625   for (CompileTask* task = _first; task != nullptr; task = task->next()) {
 626     task->mark_on_stack();
 627   }
 628   for (CompileTask* task = _queue.first(); !_queue.is_end(task); task = task->next()) {
 629     assert(task != nullptr, "");
 630     task->mark_on_stack();

 631   }
 632 }
 633 
 634 
 635 CompileQueue* CompileBroker::compile_queue(int comp_level, bool is_aot) {
 636   if (is_c2_compile(comp_level)) return ((is_aot  && (_ac_count > 0)) ? _ac2_compile_queue : _c2_compile_queue);
 637   if (is_c1_compile(comp_level)) return ((is_aot && (_ac_count > 0)) ? _ac1_compile_queue : _c1_compile_queue);
 638   return nullptr;
 639 }
 640 
 641 CompileQueue* CompileBroker::c1_compile_queue() {
 642   return _c1_compile_queue;
 643 }
 644 
 645 CompileQueue* CompileBroker::c2_compile_queue() {
 646   return _c2_compile_queue;
 647 }
 648 
 649 void CompileBroker::print_compile_queues(outputStream* st) {
 650   st->print_cr("Current compiles: ");
 651 
 652   char buf[2000];
 653   int buflen = sizeof(buf);
 654   Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
 655 
 656   st->cr();
 657   if (_c1_compile_queue != nullptr) {
 658     _c1_compile_queue->print(st);
 659   }
 660   if (_c2_compile_queue != nullptr) {
 661     _c2_compile_queue->print(st);
 662   }
 663   if (_ac1_compile_queue != nullptr) {
 664     _ac1_compile_queue->print(st);
 665   }
 666   if (_ac2_compile_queue != nullptr) {
 667     _ac2_compile_queue->print(st);
 668   }
 669 }
 670 
 671 void CompileQueue::print(outputStream* st) {
 672   assert_locked_or_safepoint(_lock);
 673   st->print_cr("%s:", name());
 674   CompileTask* task = _first;
 675   if (task == nullptr) {
 676     st->print_cr("Empty");
 677   } else {
 678     while (task != nullptr) {
 679       task->print(st, nullptr, true, true);
 680       task = task->next();
 681     }
 682   }
 683   st->cr();
 684 }
 685 
 686 void CompileQueue::print_tty() {
 687   stringStream ss;
 688   // Dump the compile queue into a buffer before locking the tty
 689   print(&ss);
 690   {
 691     ttyLocker ttyl;
 692     tty->print("%s", ss.freeze());

 719       CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
 720     }
 721     first_registration = false;
 722 #endif // COMPILER2
 723   }
 724 }
 725 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
 726 
 727 // ------------------------------------------------------------------
 728 // CompileBroker::compilation_init
 729 //
 730 // Initialize the Compilation object
 731 void CompileBroker::compilation_init(JavaThread* THREAD) {
 732   // No need to initialize compilation system if we do not use it.
 733   if (!UseCompiler) {
 734     return;
 735   }
 736   // Set the interface to the current compiler(s).
 737   _c1_count = CompilationPolicy::c1_count();
 738   _c2_count = CompilationPolicy::c2_count();
 739   _ac_count = CompilationPolicy::ac_count();
 740 
 741 #if INCLUDE_JVMCI
 742   if (EnableJVMCI) {
 743     // This is creating a JVMCICompiler singleton.
 744     JVMCICompiler* jvmci = new JVMCICompiler();
 745 
 746     if (UseJVMCICompiler) {
 747       _compilers[1] = jvmci;
 748       if (FLAG_IS_DEFAULT(JVMCIThreads)) {
 749         if (BootstrapJVMCI) {
 750           // JVMCI will bootstrap so give it more threads
 751           _c2_count = MIN2(32, os::active_processor_count());
 752         }
 753       } else {
 754         _c2_count = JVMCIThreads;
 755       }
 756       if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
 757       } else {
 758 #ifdef COMPILER1
 759         _c1_count = JVMCIHostThreads;

 876     _perf_last_compile_size =
 877              PerfDataManager::create_variable(SUN_CI, "lastSize",
 878                                               PerfData::U_Bytes,
 879                                               (jlong)CompileBroker::no_compile,
 880                                               CHECK);
 881 
 882 
 883     _perf_last_failed_type =
 884              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 885                                               PerfData::U_None,
 886                                               (jlong)CompileBroker::no_compile,
 887                                               CHECK);
 888 
 889     _perf_last_invalidated_type =
 890          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 891                                           PerfData::U_None,
 892                                           (jlong)CompileBroker::no_compile,
 893                                           CHECK);
 894   }
 895 
 896   log_info(aot, codecache, init)("CompileBroker is initialized");
 897   _initialized = true;
 898 }
 899 
 900 Handle CompileBroker::create_thread_oop(const char* name, TRAPS) {
 901   Handle thread_oop = JavaThread::create_system_thread_object(name, CHECK_NH);
 902   return thread_oop;
 903 }
 904 
 905 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
 906   CompilationPolicy::replay_training_at_init_loop(thread);
 907 }
 908 
 909 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 910 // Entry for DeoptimizeObjectsALotThread. The threads are started in
 911 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
 912 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
 913     DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
 914     bool enter_single_loop;
 915     {
 916       MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
 917       static int single_thread_count = 0;
 918       enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
 919     }
 920     if (enter_single_loop) {
 921       dt->deoptimize_objects_alot_loop_single();
 922     } else {
 923       dt->deoptimize_objects_alot_loop_all();
 924     }

1048 }
1049 
1050 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
1051   char name_buffer[256];
1052   os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
1053   Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
1054   return JNIHandles::make_global(thread_oop);
1055 }
1056 
1057 static void print_compiler_threads(stringStream& msg) {
1058   if (TraceCompilerThreads) {
1059     tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
1060   }
1061   LogTarget(Debug, jit, thread) lt;
1062   if (lt.is_enabled()) {
1063     LogStream ls(lt);
1064     ls.print_cr("%s", msg.as_string());
1065   }
1066 }
1067 
1068 static void print_compiler_thread(JavaThread *ct) {
1069   if (trace_compiler_threads()) {
1070     ResourceMark rm;
1071     ThreadsListHandle tlh;  // name() depends on the TLH.
1072     assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1073     stringStream msg;
1074     msg.print("Added initial compiler thread %s", ct->name());
1075     print_compiler_threads(msg);
1076   }
1077 }
1078 
1079 void CompileBroker::init_compiler_threads() {
1080   // Ensure any exceptions lead to vm_exit_during_initialization.
1081   EXCEPTION_MARK;
1082 #if !defined(ZERO)
1083   assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
1084 #endif // !ZERO
1085   // Initialize the compilation queue
1086   if (_c2_count > 0) {
1087     const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
1088     _c2_compile_queue  = new CompileQueue(name, MethodCompileQueueC2_lock);
1089     _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
1090     _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
1091   }
1092   if (_c1_count > 0) {
1093     _c1_compile_queue  = new CompileQueue("C1 compile queue", MethodCompileQueueC1_lock);
1094     _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
1095     _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
1096   }
1097 
1098   if (_ac_count > 0) {
1099     if (_c1_count > 0) { // C1 is present
1100       _ac1_compile_queue  = new CompileQueue("C1 AOT code compile queue", MethodCompileQueueSC1_lock);
1101     }
1102     if (_c2_count > 0) { // C2 is present
1103       _ac2_compile_queue  = new CompileQueue("C2 AOT code compile queue", MethodCompileQueueSC2_lock);
1104     }
1105     _ac_objects = NEW_C_HEAP_ARRAY(jobject, _ac_count, mtCompiler);
1106     _ac_logs = NEW_C_HEAP_ARRAY(CompileLog*, _ac_count, mtCompiler);
1107   }
1108   char name_buffer[256];
1109 
1110   for (int i = 0; i < _c2_count; i++) {
1111     // Create a name for our thread.
1112     jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
1113     _compiler2_objects[i] = thread_handle;
1114     _compiler2_logs[i] = nullptr;
1115 
1116     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1117       JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
1118       assert(ct != nullptr, "should have been handled for initial thread");
1119       _compilers[1]->set_num_compiler_threads(i + 1);
1120       print_compiler_thread(ct);







1121     }
1122   }
1123 
1124   for (int i = 0; i < _c1_count; i++) {
1125     // Create a name for our thread.
1126     jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
1127     _compiler1_objects[i] = thread_handle;
1128     _compiler1_logs[i] = nullptr;
1129 
1130     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1131       JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1132       assert(ct != nullptr, "should have been handled for initial thread");
1133       _compilers[0]->set_num_compiler_threads(i + 1);
1134       print_compiler_thread(ct);
1135     }
1136   }
1137 
1138   if (_ac_count > 0) {
1139     int i = 0;
1140     if (_c1_count > 0) { // C1 is present
1141       os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d AOT code caching CompilerThread", 1);
1142       Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1143       jobject thread_handle = JNIHandles::make_global(thread_oop);
1144       _ac_objects[i] = thread_handle;
1145       _ac_logs[i] = nullptr;
1146       i++;
1147 
1148       JavaThread *ct = make_thread(compiler_t, thread_handle, _ac1_compile_queue, _compilers[0], THREAD);
1149       assert(ct != nullptr, "should have been handled for initial thread");
1150       print_compiler_thread(ct);
1151     }
1152     if (_c2_count > 0) { // C2 is present
1153       os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d AOT code caching CompilerThread", 2);
1154       Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1155       jobject thread_handle = JNIHandles::make_global(thread_oop);
1156       _ac_objects[i] = thread_handle;
1157       _ac_logs[i] = nullptr;
1158 
1159       JavaThread *ct = make_thread(compiler_t, thread_handle, _ac2_compile_queue, _compilers[1], THREAD);
1160       assert(ct != nullptr, "should have been handled for initial thread");
1161       print_compiler_thread(ct);
1162     }
1163   }
1164 
1165   if (UsePerfData) {
1166     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK);
1167   }
1168 
1169 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1170   if (DeoptimizeObjectsALot) {
1171     // Initialize and start the object deoptimizer threads
1172     const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1173     for (int count = 0; count < total_count; count++) {
1174       Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1175       jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1176       make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1177     }
1178   }
1179 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1180 }
1181 
1182 void CompileBroker::init_training_replay() {
1183   // Ensure any exceptions lead to vm_exit_during_initialization.
1184   EXCEPTION_MARK;
1185   if (TrainingData::have_data()) {
1186     Handle thread_oop = create_thread_oop("Training replay thread", CHECK);
1187     jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1188     make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1189   }
1190 }
1191 
1192 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1193 
1194   int old_c2_count = 0, new_c2_count = 0, old_c1_count = 0, new_c1_count = 0;
1195   const int c2_tasks_per_thread = 2, c1_tasks_per_thread = 4;
1196 
1197   // Quick check if we already have enough compiler threads without taking the lock.
1198   // Numbers may change concurrently, so we read them again after we have the lock.
1199   if (_c2_compile_queue != nullptr) {
1200     old_c2_count = get_c2_thread_count();
1201     new_c2_count = MIN2(_c2_count, _c2_compile_queue->size() / c2_tasks_per_thread);
1202   }
1203   if (_c1_compile_queue != nullptr) {
1204     old_c1_count = get_c1_thread_count();
1205     new_c1_count = MIN2(_c1_count, _c1_compile_queue->size() / c1_tasks_per_thread);
1206   }

1302   }
1303 
1304   CompileThread_lock->unlock();
1305 }
1306 
1307 
1308 /**
1309  * Set the methods on the stack as on_stack so that redefine classes doesn't
1310  * reclaim them. This method is executed at a safepoint.
1311  */
1312 void CompileBroker::mark_on_stack() {
1313   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1314   // Since we are at a safepoint, we do not need a lock to access
1315   // the compile queues.
1316   if (_c2_compile_queue != nullptr) {
1317     _c2_compile_queue->mark_on_stack();
1318   }
1319   if (_c1_compile_queue != nullptr) {
1320     _c1_compile_queue->mark_on_stack();
1321   }
1322   if (_ac1_compile_queue != nullptr) {
1323     _ac1_compile_queue->mark_on_stack();
1324   }
1325   if (_ac2_compile_queue != nullptr) {
1326     _ac2_compile_queue->mark_on_stack();
1327   }
1328 }
1329 
1330 // ------------------------------------------------------------------
1331 // CompileBroker::compile_method
1332 //
1333 // Request compilation of a method.
1334 void CompileBroker::compile_method_base(const methodHandle& method,
1335                                         int osr_bci,
1336                                         int comp_level,
1337                                         int hot_count,
1338                                         CompileTask::CompileReason compile_reason,
1339                                         bool requires_online_compilation,
1340                                         bool blocking,
1341                                         Thread* thread) {
1342   guarantee(!method->is_abstract(), "cannot compile abstract methods");
1343   assert(method->method_holder()->is_instance_klass(),
1344          "sanity check");
1345   assert(!method->method_holder()->is_not_initialized()   ||
1346          compile_reason == CompileTask::Reason_Preload    ||
1347          compile_reason == CompileTask::Reason_Precompile ||
1348          compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1349   assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1350 
1351   if (CIPrintRequests) {
1352     tty->print("request: ");
1353     method->print_short_name(tty);
1354     if (osr_bci != InvocationEntryBci) {
1355       tty->print(" osr_bci: %d", osr_bci);
1356     }
1357     tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1358     if (hot_count > 0) {
1359       tty->print(" hot: yes");
1360     }
1361     tty->cr();
1362   }
1363 
1364   // A request has been made for compilation.  Before we do any
1365   // real work, check to see if the method has been compiled
1366   // in the meantime with a definitive result.
1367   if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1368     return;
1369   }
1370 
1371 #ifndef PRODUCT
1372   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1373     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1374       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
1375       return;
1376     }
1377   }
1378 #endif
1379 
1380   // If this method is already in the compile queue, then
1381   // we do not block the current thread.
1382   if (compilation_is_in_queue(method)) {
1383     // We may want to decay our counter a bit here to prevent
1384     // multiple denied requests for compilation.  This is an
1385     // open compilation policy issue. Note: The other possibility,
1386     // in the case that this is a blocking compile request, is to have
1387     // all subsequent blocking requesters wait for completion of
1388     // ongoing compiles. Note that in this case we'll need a protocol
1389     // for freeing the associated compile tasks. [Or we could have
1390     // a single static monitor on which all these waiters sleep.]
1391     return;
1392   }
1393 
1394   // Tiered policy requires MethodCounters to exist before adding a method to
1395   // the queue. Create if we don't have them yet.
1396   method->get_method_counters(thread);
1397 
1398   AOTCodeEntry* aot_code_entry = find_aot_code_entry(method, osr_bci, comp_level, compile_reason, requires_online_compilation);
1399   bool is_aot = (aot_code_entry != nullptr);
1400   requires_online_compilation = !is_aot; // Request JIT compilation
1401 
1402   // Outputs from the following MutexLocker block:
1403   CompileTask* task = nullptr;
1404   CompileQueue* queue = compile_queue(comp_level, is_aot);
1405 
1406   // Acquire our lock.
1407   {
1408     ConditionalMutexLocker locker(thread, queue->lock(), !UseLockFreeCompileQueues);
1409 
1410     // Make sure the method has not slipped into the queues since
1411     // last we checked; note that those checks were "fast bail-outs".
1412     // Here we need to be more careful, see 14012000 below.
1413     if (compilation_is_in_queue(method)) {
1414       return;
1415     }
1416 
1417     // We need to check again to see if the compilation has
1418     // completed.  A previous compilation may have registered
1419     // some result.
1420     if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1421       return;
1422     }
1423 
1424     // We now know that this compilation is not pending, complete,
1425     // or prohibited.  Assign a compile_id to this compilation
1426     // and check to see if it is in our [Start..Stop) range.
1427     int compile_id = assign_compile_id(method, osr_bci);
1428     if (compile_id == 0) {
1429       // The compilation falls outside the allowed range.
1430       return;
1431     }
1432 
1433 #if INCLUDE_JVMCI
1434     if (UseJVMCICompiler && blocking) {
1435       // Don't allow blocking compiles for requests triggered by JVMCI.
1436       if (thread->is_Compiler_thread()) {
1437         blocking = false;
1438       }
1439 
1440       // In libjvmci, JVMCI initialization should not deadlock with other threads

1490     // <RESULT, QUEUE> :
1491     //     <0, 1> : in compile queue, but not yet compiled
1492     //     <1, 1> : compiled but queue bit not cleared
1493     //     <1, 0> : compiled and queue bit cleared
1494     // Because we first check the queue bits then check the result bits,
1495     // we are assured that we cannot introduce a duplicate task.
1496     // Note that if we did the tests in the reverse order (i.e. check
1497     // result then check queued bit), we could get the result bit before
1498     // the compilation completed, and the queue bit after the compilation
1499     // completed, and end up introducing a "duplicate" (redundant) task.
1500     // In that case, the compiler thread should first check if a method
1501     // has already been compiled before trying to compile it.
1502     // NOTE: in the event that there are multiple compiler threads and
1503     // there is de-optimization/recompilation, things will get hairy,
1504     // and in that case it's best to protect both the testing (here) of
1505     // these bits, and their updating (here and elsewhere) under a
1506     // common lock.
1507     task = create_compile_task(queue,
1508                                compile_id, method,
1509                                osr_bci, comp_level,
1510                                hot_count, aot_code_entry, compile_reason,
1511                                requires_online_compilation, blocking);
1512 
1513     if (task->is_aot_load() && (_ac_count > 0)) {
1514       // Put it on AOT code caching queue
1515       queue = is_c1_compile(comp_level) ? _ac1_compile_queue : _ac2_compile_queue;
1516     }
1517 
1518     if (UseLockFreeCompileQueues) {
1519       assert(queue->lock()->owned_by_self() == false, "");
1520       queue->add_pending(task);
1521     } else {
1522       queue->add(task);
1523     }
1524   }
1525 
1526   if (blocking) {
1527     wait_for_completion(task);
1528   }
1529 }
1530 
1531 AOTCodeEntry* CompileBroker::find_aot_code_entry(const methodHandle& method, int osr_bci, int comp_level,
1532                                         CompileTask::CompileReason compile_reason,
1533                                         bool requires_online_compilation) {
1534   if (requires_online_compilation || compile_reason == CompileTask::Reason_Whitebox) {
1535     return nullptr; // Need normal JIT compilation
1536   }
1537   AOTCodeEntry* aot_code_entry = nullptr;
1538   if (osr_bci == InvocationEntryBci && AOTCodeCache::is_using_code()) {
1539     // Check for AOT preload code first.
1540     if (compile_reason == CompileTask::Reason_Preload) {
1541       aot_code_entry = method->aot_code_entry();
1542       assert(aot_code_entry != nullptr && aot_code_entry->for_preload(), "sanity");
1543     } else {
1544       aot_code_entry = AOTCodeCache::find_code_entry(method, comp_level);
1545     }
1546   }
1547   return aot_code_entry;
1548 }
1549 
1550 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1551                                        int comp_level,
1552                                        int hot_count,
1553                                        bool requires_online_compilation,
1554                                        CompileTask::CompileReason compile_reason,
1555                                        TRAPS) {
1556   // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1557   if (!_initialized || comp_level == CompLevel_none) {
1558     return nullptr;
1559   }
1560 
1561   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1562   assert(comp != nullptr, "Ensure we have a compiler");
1563 
1564 #if INCLUDE_JVMCI
1565   if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1566     // JVMCI compilation is not yet initializable.
1567     return nullptr;
1568   }
1569 #endif
1570 
1571   DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1572   // CompileBroker::compile_method can trap and can have pending async exception.
1573   nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_count, requires_online_compilation, compile_reason, directive, THREAD);
1574   DirectivesStack::release(directive);
1575   return nm;
1576 }
1577 
1578 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1579                                          int comp_level,
1580                                          int hot_count,
1581                                          bool requires_online_compilation,
1582                                          CompileTask::CompileReason compile_reason,
1583                                          DirectiveSet* directive,
1584                                          TRAPS) {
1585 
1586   // make sure arguments make sense
1587   assert(method->method_holder()->is_instance_klass(), "not an instance method");
1588   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1589   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1590   assert(!method->method_holder()->is_not_initialized()   ||
1591          compile_reason == CompileTask::Reason_Preload    ||
1592          compile_reason == CompileTask::Reason_Precompile ||
1593          compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1594   // return quickly if possible
1595   bool aot_compilation = (PrecompileCode && PrecompileOnlyAndExit) ||
1596                          CDSConfig::is_dumping_aot_code();
1597   if (aot_compilation && !CompileTask::reason_is_precompile(compile_reason)) {
1598     // Skip normal compilations when compiling AOT code
1599     return nullptr;
1600   }
1601 
1602   // lock, make sure that the compilation
1603   // isn't prohibited in a straightforward way.
1604   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1605   if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1606     return nullptr;
1607   }
1608 
1609   if (osr_bci == InvocationEntryBci) {
1610     // standard compilation
1611     nmethod* method_code = method->code();
1612     if (method_code != nullptr) {
1613       if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1614         return method_code;
1615       }
1616     }
1617     if (method->is_not_compilable(comp_level)) {
1618       return nullptr;
1619     }
1620   } else {
1621     // osr compilation
1622     // We accept a higher level osr method
1623     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1624     if (nm != nullptr) return nm;
1625     if (method->is_not_osr_compilable(comp_level)) return nullptr;
1626   }
1627 
1628   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1629   // some prerequisites that are compiler specific
1630   if (compile_reason != CompileTask::Reason_Preload &&
1631       !CompileTask::reason_is_precompile(compile_reason) &&
1632      (comp->is_c2() || comp->is_jvmci())) {
1633     InternalOOMEMark iom(THREAD);
1634     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1635     // Resolve all classes seen in the signature of the method
1636     // we are compiling.
1637     Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1638   }
1639 
1640   // If the method is native, do the lookup in the thread requesting
1641   // the compilation. Native lookups can load code, which is not
1642   // permitted during compilation.
1643   //
1644   // Note: A native method implies non-osr compilation which is
1645   //       checked with an assertion at the entry of this method.
1646   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1647     address adr = NativeLookup::lookup(method, THREAD);
1648     if (HAS_PENDING_EXCEPTION) {
1649       // In case of an exception looking up the method, we just forget
1650       // about it. The interpreter will kick-in and throw the exception.
1651       method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1652       CLEAR_PENDING_EXCEPTION;

1667   }
1668 
1669   // do the compilation
1670   if (method->is_native()) {
1671     if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1672       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1673       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1674       //
1675       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1676       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1677       AdapterHandlerLibrary::create_native_wrapper(method);
1678     } else {
1679       return nullptr;
1680     }
1681   } else {
1682     // If the compiler is shut off due to code cache getting full
1683     // fail out now so blocking compiles dont hang the java thread
1684     if (!should_compile_new_jobs()) {
1685       return nullptr;
1686     }
1687     bool is_blocking = ReplayCompiles                                             ||
1688                        !directive->BackgroundCompilationOption                    ||
1689                        (PreloadBlocking && (compile_reason == CompileTask::Reason_Preload));
1690     compile_method_base(method, osr_bci, comp_level, hot_count, compile_reason, requires_online_compilation, is_blocking, THREAD);
1691   }
1692 
1693   // return requested nmethod
1694   // We accept a higher level osr method
1695   if (osr_bci == InvocationEntryBci) {
1696     return method->code();
1697   }
1698   return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1699 }
1700 
1701 
1702 // ------------------------------------------------------------------
1703 // CompileBroker::compilation_is_complete
1704 //
1705 // See if compilation of this method is already complete.
1706 bool CompileBroker::compilation_is_complete(Method*                    method,
1707                                             int                        osr_bci,
1708                                             int                        comp_level,
1709                                             bool                       online_only,
1710                                             CompileTask::CompileReason compile_reason) {
1711   if (compile_reason == CompileTask::Reason_Precompile ||
1712       compile_reason == CompileTask::Reason_PrecompileForPreload) {
1713     return false; // FIXME: any restrictions?
1714   }
1715   bool is_osr = (osr_bci != standard_entry_bci);
1716   if (is_osr) {
1717     if (method->is_not_osr_compilable(comp_level)) {
1718       return true;
1719     } else {
1720       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1721       return (result != nullptr);
1722     }
1723   } else {
1724     if (method->is_not_compilable(comp_level)) {
1725       return true;
1726     } else {
1727       nmethod* result = method->code();
1728       if (result == nullptr) {
1729         return false;
1730       }
1731       if (online_only && result->is_aot()) {
1732         return false;
1733       }
1734       bool same_level = (comp_level == result->comp_level());
1735       if (result->preloaded() || result->has_clinit_barriers()) {
1736         return !same_level; // Allow replace preloaded code with new code of the same level
1737       }
1738       return same_level;
1739     }
1740   }
1741 }
1742 
1743 
1744 /**
1745  * See if this compilation is already requested.
1746  *
1747  * Implementation note: there is only a single "is in queue" bit
1748  * for each method.  This means that the check below is overly
1749  * conservative in the sense that an osr compilation in the queue
1750  * will block a normal compilation from entering the queue (and vice
1751  * versa).  This can be remedied by a full queue search to disambiguate
1752  * cases.  If it is deemed profitable, this may be done.
1753  */
1754 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1755   return method->queued_for_compilation();
1756 }
1757 
1758 // ------------------------------------------------------------------

1818     if (CIStart <= id && id < CIStop) {
1819       return id;
1820     }
1821   }
1822 
1823   // Method was not in the appropriate compilation range.
1824   method->set_not_compilable_quietly("Not in requested compile id range");
1825   return 0;
1826 #else
1827   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1828   // only _compilation_id is incremented.
1829   return AtomicAccess::add(&_compilation_id, 1);
1830 #endif
1831 }
1832 
1833 // ------------------------------------------------------------------
1834 // CompileBroker::assign_compile_id_unlocked
1835 //
1836 // Public wrapper for assign_compile_id that acquires the needed locks
1837 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {

1838   return assign_compile_id(method, osr_bci);
1839 }
1840 
1841 // ------------------------------------------------------------------
1842 // CompileBroker::create_compile_task
1843 //
1844 // Create a CompileTask object representing the current request for
1845 // compilation.  Add this task to the queue.
1846 CompileTask* CompileBroker::create_compile_task(CompileQueue*       queue,
1847                                                 int                 compile_id,
1848                                                 const methodHandle& method,
1849                                                 int                 osr_bci,
1850                                                 int                 comp_level,
1851                                                 int                 hot_count,
1852                                                 AOTCodeEntry*       aot_code_entry,
1853                                                 CompileTask::CompileReason compile_reason,
1854                                                 bool                requires_online_compilation,
1855                                                 bool                blocking) {
1856   CompileTask* new_task = new CompileTask(compile_id, method, osr_bci, comp_level,
1857                        hot_count, aot_code_entry, compile_reason, queue,
1858                        requires_online_compilation, blocking);
1859   return new_task;
1860 }
1861 
1862 #if INCLUDE_JVMCI
1863 // The number of milliseconds to wait before checking if
1864 // JVMCI compilation has made progress.
1865 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1866 
1867 // The number of JVMCI compilation progress checks that must fail
1868 // before unblocking a thread waiting for a blocking compilation.
1869 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1870 
1871 /**
1872  * Waits for a JVMCI compiler to complete a given task. This thread
1873  * waits until either the task completes or it sees no JVMCI compilation
1874  * progress for N consecutive milliseconds where N is
1875  * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1876  * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1877  *
1878  * @return true if this thread needs to delete the task

1992  * compiler threads can start compiling.
1993  */
1994 bool CompileBroker::init_compiler_runtime() {
1995   CompilerThread* thread = CompilerThread::current();
1996   AbstractCompiler* comp = thread->compiler();
1997   // Final sanity check - the compiler object must exist
1998   guarantee(comp != nullptr, "Compiler object must exist");
1999 
2000   {
2001     // Must switch to native to allocate ci_env
2002     ThreadToNativeFromVM ttn(thread);
2003     ciEnv ci_env((CompileTask*)nullptr);
2004     // Cache Jvmti state
2005     ci_env.cache_jvmti_state();
2006     // Cache DTrace flags
2007     ci_env.cache_dtrace_flags();
2008 
2009     // Switch back to VM state to do compiler initialization
2010     ThreadInVMfromNative tv(thread);
2011 

2012     comp->initialize();
2013   }
2014 
2015   if (comp->is_failed()) {
2016     disable_compilation_forever();
2017     // If compiler initialization failed, no compiler thread that is specific to a
2018     // particular compiler runtime will ever start to compile methods.
2019     shutdown_compiler_runtime(comp, thread);
2020     return false;
2021   }
2022 
2023   // C1 specific check
2024   if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
2025     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
2026     return false;
2027   }
2028 
2029   return true;
2030 }
2031 
2032 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
2033   BufferBlob* blob = thread->get_buffer_blob();
2034   if (blob != nullptr) {
2035     blob->purge();
2036     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2037     CodeCache::free(blob);
2038   }
2039 }
2040 
2041 /**
2042  * If C1 and/or C2 initialization failed, we shut down all compilation.
2043  * We do this to keep things simple. This can be changed if it ever turns
2044  * out to be a problem.
2045  */
2046 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
2047   free_buffer_blob_if_allocated(thread);
2048 
2049   log_info(compilation)("shutdown_compiler_runtime: " INTPTR_FORMAT, p2i(thread));
2050 
2051   if (comp->should_perform_shutdown()) {
2052     // There are two reasons for shutting down the compiler
2053     // 1) compiler runtime initialization failed
2054     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
2055     warning("%s initialization failed. Shutting down all compilers", comp->name());
2056 
2057     // Only one thread per compiler runtime object enters here
2058     // Set state to shut down
2059     comp->set_shut_down();
2060 
2061     // Delete all queued compilation tasks to make compiler threads exit faster.
2062     if (_c1_compile_queue != nullptr) {
2063       _c1_compile_queue->delete_all();
2064     }
2065 
2066     if (_c2_compile_queue != nullptr) {
2067       _c2_compile_queue->delete_all();
2068     }
2069 
2070     // Set flags so that we continue execution with using interpreter only.

2074     // We could delete compiler runtimes also. However, there are references to
2075     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
2076     // fail. This can be done later if necessary.
2077   }
2078 }
2079 
2080 /**
2081  * Helper function to create new or reuse old CompileLog.
2082  */
2083 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
2084   if (!LogCompilation) return nullptr;
2085 
2086   AbstractCompiler *compiler = ct->compiler();
2087   bool c1 = compiler->is_c1();
2088   jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;
2089   assert(compiler_objects != nullptr, "must be initialized at this point");
2090   CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;
2091   assert(logs != nullptr, "must be initialized at this point");
2092   int count = c1 ? _c1_count : _c2_count;
2093 
2094   if (ct->queue() == _ac1_compile_queue || ct->queue() == _ac2_compile_queue) {
2095     compiler_objects = _ac_objects;
2096     logs  = _ac_logs;
2097     count = _ac_count;
2098   }
2099   // Find Compiler number by its threadObj.
2100   oop compiler_obj = ct->threadObj();
2101   int compiler_number = 0;
2102   bool found = false;
2103   for (; compiler_number < count; compiler_number++) {
2104     if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
2105       found = true;
2106       break;
2107     }
2108   }
2109   assert(found, "Compiler must exist at this point");
2110 
2111   // Determine pointer for this thread's log.
2112   CompileLog** log_ptr = &logs[compiler_number];
2113 
2114   // Return old one if it exists.
2115   CompileLog* log = *log_ptr;
2116   if (log != nullptr) {
2117     ct->init_log(log);
2118     return log;

2160   if (!thread->init_compilation_timeout()) {
2161     return;
2162   }
2163 
2164   // If compiler thread/runtime initialization fails, exit the compiler thread
2165   if (!init_compiler_runtime()) {
2166     return;
2167   }
2168 
2169   thread->start_idle_timer();
2170 
2171   // Poll for new compilation tasks as long as the JVM runs. Compilation
2172   // should only be disabled if something went wrong while initializing the
2173   // compiler runtimes. This, in turn, should not happen. The only known case
2174   // when compiler runtime initialization fails is if there is not enough free
2175   // space in the code cache to generate the necessary stubs, etc.
2176   while (!is_compilation_disabled_forever()) {
2177     // We need this HandleMark to avoid leaking VM handles.
2178     HandleMark hm(thread);
2179 
2180     RecompilationPolicy::recompilation_step(AOTRecompilationWorkUnitSize, thread);
2181 
2182     CompileTask* task = queue->get(thread);
2183     if (task == nullptr) {
2184       if (UseDynamicNumberOfCompilerThreads) {
2185         // Access compiler_count under lock to enforce consistency.
2186         MutexLocker only_one(CompileThread_lock);
2187         if (can_remove(thread, true)) {
2188           if (trace_compiler_threads()) {
2189             ResourceMark rm;
2190             stringStream msg;
2191             msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
2192                       thread->name(), thread->idle_time_millis());
2193             print_compiler_threads(msg);
2194           }
2195 
2196           // Notify compiler that the compiler thread is about to stop
2197           thread->compiler()->stopping_compiler_thread(thread);
2198 
2199           free_buffer_blob_if_allocated(thread);
2200           return; // Stop this thread.
2201         }
2202       }
2203     } else {
2204       // Assign the task to the current thread.  Mark this compilation
2205       // thread as active for the profiler.
2206       // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
2207       // occurs after fetching the compile task off the queue.
2208       CompileTaskWrapper ctw(task);
2209       methodHandle method(thread, task->method());
2210 
2211       // Never compile a method if breakpoints are present in it
2212       if (method()->number_of_breakpoints() == 0) {
2213         // Compile the method.
2214         if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
2215           invoke_compiler_on_method(task);
2216           thread->start_idle_timer();
2217         } else {
2218           // After compilation is disabled, remove remaining methods from queue
2219           method->clear_queued_for_compilation();
2220           method->set_pending_queue_processed(false);
2221           task->set_failure_reason("compilation is disabled");
2222         }
2223       } else {
2224         task->set_failure_reason("breakpoints are present");
2225       }
2226 
2227       // Don't use AOT compielr threads for dynamic C1 and C2 threads creation.
2228       if (UseDynamicNumberOfCompilerThreads &&
2229           (queue == _c1_compile_queue || queue == _c2_compile_queue)) {
2230         possibly_add_compiler_threads(thread);
2231         assert(!thread->has_pending_exception(), "should have been handled");
2232       }
2233     }
2234   }
2235 
2236   // Shut down compiler runtime
2237   shutdown_compiler_runtime(thread->compiler(), thread);
2238 }
2239 
2240 // ------------------------------------------------------------------
2241 // CompileBroker::init_compiler_thread_log
2242 //
2243 // Set up state required by +LogCompilation.
2244 void CompileBroker::init_compiler_thread_log() {
2245     CompilerThread* thread = CompilerThread::current();
2246     char  file_name[4*K];
2247     FILE* fp = nullptr;
2248     intx thread_id = os::current_thread_id();
2249     for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {

2405 
2406 // Acquires Compilation_lock and waits for it to be notified
2407 // as long as WhiteBox::compilation_locked is true.
2408 static void whitebox_lock_compilation() {
2409   MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2410   while (WhiteBox::compilation_locked) {
2411     locker.wait();
2412   }
2413 }
2414 
2415 // ------------------------------------------------------------------
2416 // CompileBroker::invoke_compiler_on_method
2417 //
2418 // Compile a method.
2419 //
2420 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2421   task->print_ul();
2422   elapsedTimer time;
2423 
2424   DirectiveSet* directive = task->directive();




2425 
2426   CompilerThread* thread = CompilerThread::current();
2427   ResourceMark rm(thread);
2428 
2429   if (CompilationLog::log() != nullptr) {
2430     CompilationLog::log()->log_compile(thread, task);
2431   }
2432 
2433   // Common flags.
2434   int compile_id = task->compile_id();
2435   int osr_bci = task->osr_bci();
2436   bool is_osr = (osr_bci != standard_entry_bci);
2437   bool should_log = (thread->log() != nullptr);
2438   bool should_break = false;
2439   bool should_print_compilation = PrintCompilation || directive->PrintCompilationOption;
2440   const int task_level = task->comp_level();
2441   AbstractCompiler* comp = task->compiler();
2442   {
2443     // create the handle inside it's own block so it can't
2444     // accidentally be referenced once the thread transitions to
2445     // native.  The NoHandleMark before the transition should catch
2446     // any cases where this occurs in the future.
2447     methodHandle method(thread, task->method());
2448 
2449     assert(!method->is_native(), "no longer compile natives");
2450 
2451     // Update compile information when using perfdata.
2452     if (UsePerfData) {
2453       update_compile_perf_data(thread, method, is_osr);
2454     }
2455 
2456     DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2457   }
2458 
2459   should_break = directive->BreakAtCompileOption || task->check_break_at_flags();

2554       ci_env.record_method_not_compilable("redefined method", true);
2555     }
2556 
2557     // Cache DTrace flags
2558     ci_env.cache_dtrace_flags();
2559 
2560     ciMethod* target = ci_env.get_method_from_handle(target_handle);
2561 
2562     TraceTime t1("compilation", &time);
2563     EventCompilation event;
2564 
2565     if (comp == nullptr) {
2566       ci_env.record_method_not_compilable("no compiler");
2567     } else if (!ci_env.failing()) {
2568       if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2569         whitebox_lock_compilation();
2570       }
2571       comp->compile_method(&ci_env, target, osr_bci, true, directive);
2572 
2573       /* Repeat compilation without installing code for profiling purposes */
2574       int repeat_compilation_count = task->is_aot_load() ? 0 : directive->RepeatCompilationOption;
2575       if (repeat_compilation_count > 0) {
2576         CHeapStringHolder failure_reason;
2577         failure_reason.set(ci_env._failure_reason.get());
2578         while (repeat_compilation_count > 0) {
2579           ResourceMark rm(thread);
2580           task->print_ul("NO CODE INSTALLED");
2581           thread->timeout()->reset();
2582           ci_env._failure_reason.clear();
2583           comp->compile_method(&ci_env, target, osr_bci, false, directive);
2584           repeat_compilation_count--;
2585         }
2586         ci_env._failure_reason.set(failure_reason.get());
2587       }
2588     }
2589 
2590 
2591     if (!ci_env.failing() && !task->is_success() && !task->is_precompile()) {
2592       assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2593       assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2594       // The compiler elected, without comment, not to register a result.
2595       // Do not attempt further compilations of this method.
2596       ci_env.record_method_not_compilable("compile failed");
2597     }
2598 
2599     // Copy this bit to the enclosing block:
2600     compilable = ci_env.compilable();
2601 
2602     if (ci_env.failing()) {
2603       // Duplicate the failure reason string, so that it outlives ciEnv
2604       failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2605       failure_reason_on_C_heap = true;
2606       retry_message = ci_env.retry_message();
2607       ci_env.report_failure(failure_reason);
2608     }
2609 
2610     if (ci_env.failing()) {
2611       handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2612     }
2613     if (event.should_commit()) {
2614       post_compilation_event(event, task);
2615     }
2616   }
2617 
2618   if (failure_reason != nullptr) {
2619     task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2620     if (CompilationLog::log() != nullptr) {
2621       CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2622     }
2623     if (PrintCompilation || directive->PrintCompilationOption) {
2624       FormatBufferResource msg = retry_message != nullptr ?
2625         FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2626         FormatBufferResource("COMPILE SKIPPED: %s",      failure_reason);
2627       task->print(tty, msg);
2628     }
2629   }
2630 
2631   task->mark_finished(os::elapsed_counter());
2632   DirectivesStack::release(directive);
2633 
2634   methodHandle method(thread, task->method());
2635 
2636   DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2637 
2638   collect_statistics(thread, time, task);
2639 
2640   if (PrintCompilation && PrintCompilation2) {
2641     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
2642     tty->print("%4d ", compile_id);    // print compilation number
2643     tty->print("%s ", (is_osr ? "%" : (task->is_aot_load() ? (task->preload() ? "P" : "A") : " ")));
2644     if (task->is_success()) {
2645       tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2646     }
2647     tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2648   }
2649 
2650   Log(compilation, codecache) log;
2651   if (log.is_debug()) {
2652     LogStream ls(log.debug());
2653     codecache_print(&ls, /* detailed= */ false);
2654   }
2655   if (PrintCodeCacheOnCompilation) {
2656     codecache_print(/* detailed= */ false);
2657   }
2658   // Disable compilation, if required.
2659   switch (compilable) {
2660   case ciEnv::MethodCompilable_never:
2661     if (is_osr)
2662       method->set_not_osr_compilable_quietly("MethodCompilable_never");
2663     else
2664       method->set_not_compilable_quietly("MethodCompilable_never");
2665     break;
2666   case ciEnv::MethodCompilable_not_at_tier:
2667     if (is_osr)
2668       method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2669     else
2670       method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2671     break;
2672   }
2673 
2674   // Note that the queued_for_compilation bits are cleared without
2675   // protection of a mutex. [They were set by the requester thread,
2676   // when adding the task to the compile queue -- at which time the
2677   // compile queue lock was held. Subsequently, we acquired the compile
2678   // queue lock to get this task off the compile queue; thus (to belabour
2679   // the point somewhat) our clearing of the bits must be occurring
2680   // only after the setting of the bits. See also 14012000 above.
2681   method->clear_queued_for_compilation();
2682   method->set_pending_queue_processed(false);
2683 
2684   if (should_print_compilation) {
2685     ResourceMark rm;
2686     task->print_tty();
2687   }
2688 }
2689 
2690 /**
2691  * The CodeCache is full. Print warning and disable compilation.
2692  * Schedule code cache cleaning so compilation can continue later.
2693  * This function needs to be called only from CodeCache::allocate(),
2694  * since we currently handle a full code cache uniformly.
2695  */
2696 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2697   UseInterpreter = true;
2698   if (UseCompiler || AlwaysCompileLoopMethods ) {
2699     if (xtty != nullptr) {
2700       stringStream s;
2701       // Dump code cache state into a buffer before locking the tty,
2702       // because log_state() will use locks causing lock conflicts.
2703       CodeCache::log_state(&s);
2704       // Lock to prevent tearing
2705       ttyLocker ttyl;
2706       xtty->begin_elem("code_cache_full");
2707       xtty->print("%s", s.freeze());

2780 // CompileBroker::collect_statistics
2781 //
2782 // Collect statistics about the compilation.
2783 
2784 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2785   bool success = task->is_success();
2786   methodHandle method (thread, task->method());
2787   int compile_id = task->compile_id();
2788   bool is_osr = (task->osr_bci() != standard_entry_bci);
2789   const int comp_level = task->comp_level();
2790   CompilerCounters* counters = thread->counters();
2791 
2792   MutexLocker locker(CompileStatistics_lock);
2793 
2794   // _perf variables are production performance counters which are
2795   // updated regardless of the setting of the CITime and CITimeEach flags
2796   //
2797 
2798   // account all time, including bailouts and failures in this counter;
2799   // C1 and C2 counters are counting both successful and unsuccessful compiles
2800   _t_total_compilation.add(&time);
2801 
2802   // Update compilation times. Used by the implementation of JFR CompilerStatistics
2803   // and java.lang.management.CompilationMXBean.
2804   _perf_total_compilation->inc(time.ticks());
2805   _peak_compilation_time = MAX2(time.milliseconds(), _peak_compilation_time);
2806 
2807   if (!success) {
2808     _total_bailout_count++;
2809     if (UsePerfData) {
2810       _perf_last_failed_method->set_value(counters->current_method());
2811       _perf_last_failed_type->set_value(counters->compile_type());
2812       _perf_total_bailout_count->inc();
2813     }
2814     _t_bailedout_compilation.add(&time);
2815 
2816     if (CITime || log_is_enabled(Info, init)) {
2817       CompilerStatistics* stats = nullptr;
2818       if (task->is_aot_load()) {
2819         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2820         stats = &_aot_stats_per_level[level];
2821       } else {
2822         stats = &_stats_per_level[comp_level-1];
2823       }
2824       stats->_bailout.update(time, 0);
2825     }
2826   } else if (!task->is_success()) {
2827     if (UsePerfData) {
2828       _perf_last_invalidated_method->set_value(counters->current_method());
2829       _perf_last_invalidated_type->set_value(counters->compile_type());
2830       _perf_total_invalidated_count->inc();
2831     }
2832     _total_invalidated_count++;
2833     _t_invalidated_compilation.add(&time);
2834 
2835     if (CITime || log_is_enabled(Info, init)) {
2836       CompilerStatistics* stats = nullptr;
2837       if (task->is_aot_load()) {
2838         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2839         stats = &_aot_stats_per_level[level];
2840       } else {
2841         stats = &_stats_per_level[comp_level-1];
2842       }
2843       stats->_invalidated.update(time, 0);
2844     }
2845   } else {
2846     // Compilation succeeded
2847     if (CITime || log_is_enabled(Info, init)) {
2848       int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2849       if (is_osr) {
2850         _t_osr_compilation.add(&time);
2851         _sum_osr_bytes_compiled += bytes_compiled;
2852       } else {
2853         _t_standard_compilation.add(&time);
2854         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2855       }
2856 
2857       // Collect statistic per compilation level
2858       if (task->is_aot_load()) {
2859         _aot_stats._standard.update(time, bytes_compiled);
2860         _aot_stats._nmethods_size += task->nm_total_size();
2861         _aot_stats._nmethods_code_size += task->nm_insts_size();
2862         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2863         CompilerStatistics* stats = &_aot_stats_per_level[level];
2864         stats->_standard.update(time, bytes_compiled);
2865         stats->_nmethods_size += task->nm_total_size();
2866         stats->_nmethods_code_size += task->nm_insts_size();
2867       } else if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2868         CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2869         if (is_osr) {
2870           stats->_osr.update(time, bytes_compiled);
2871         } else {
2872           stats->_standard.update(time, bytes_compiled);
2873         }
2874         stats->_nmethods_size += task->nm_total_size();
2875         stats->_nmethods_code_size += task->nm_insts_size();
2876       } else {
2877         assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2878       }
2879 
2880       // Collect statistic per compiler
2881       AbstractCompiler* comp = task->compiler();
2882       if (comp && !task->is_aot_load()) {
2883         CompilerStatistics* stats = comp->stats();
2884         if (is_osr) {
2885           stats->_osr.update(time, bytes_compiled);
2886         } else {
2887           stats->_standard.update(time, bytes_compiled);
2888         }
2889         stats->_nmethods_size += task->nm_total_size();
2890         stats->_nmethods_code_size += task->nm_insts_size();
2891       } else if (!task->is_aot_load()) { // if (!comp)
2892         assert(false, "Compiler object must exist");
2893       }
2894     }
2895 
2896     if (UsePerfData) {
2897       // save the name of the last method compiled
2898       _perf_last_method->set_value(counters->current_method());
2899       _perf_last_compile_type->set_value(counters->compile_type());
2900       _perf_last_compile_size->set_value(method->code_size() +
2901                                          task->num_inlined_bytecodes());
2902       if (is_osr) {
2903         _perf_osr_compilation->inc(time.ticks());
2904         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2905       } else {
2906         _perf_standard_compilation->inc(time.ticks());
2907         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2908       }
2909     }
2910 
2911     if (CITimeEach) {

2934       _total_standard_compile_count++;
2935     }
2936   }
2937   // set the current method for the thread to null
2938   if (UsePerfData) counters->set_current_method("");
2939 }
2940 
2941 const char* CompileBroker::compiler_name(int comp_level) {
2942   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2943   if (comp == nullptr) {
2944     return "no compiler";
2945   } else {
2946     return (comp->name());
2947   }
2948 }
2949 
2950 jlong CompileBroker::total_compilation_ticks() {
2951   return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2952 }
2953 
2954 void CompileBroker::log_not_entrant(nmethod* nm) {
2955   _total_not_entrant_count++;
2956   if (CITime || log_is_enabled(Info, init)) {
2957     CompilerStatistics* stats = nullptr;
2958     int level = nm->comp_level();
2959     if (nm->is_aot()) {
2960       if (nm->preloaded()) {
2961         assert(level == CompLevel_full_optimization, "%d", level);
2962         level = CompLevel_full_optimization + 1;
2963       }
2964       stats = &_aot_stats_per_level[level - 1];
2965     } else {
2966       stats = &_stats_per_level[level - 1];
2967     }
2968     stats->_made_not_entrant._count++;
2969   }
2970 }
2971 
2972 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2973   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}",
2974                 name, stats->bytes_per_second(),
2975                 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2976                 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2977                 stats->_nmethods_size, stats->_nmethods_code_size);
2978 }
2979 
2980 static void print_helper(outputStream* st, const char* name, CompilerStatistics::Data data, bool print_time = true) {
2981   if (data._count > 0) {
2982     st->print("; %s: %4u methods", name, data._count);
2983     if (print_time) {
2984       st->print(" (in %.3fs)", data._time.seconds());
2985     }
2986   }
2987 }
2988 
2989 static void print_tier_helper(outputStream* st, const char* prefix, int tier, CompilerStatistics* stats) {
2990   st->print("    %s%d: %5u methods", prefix, tier, stats->_standard._count);
2991   if (stats->_standard._count > 0) {
2992     st->print(" (in %.3fs)", stats->_standard._time.seconds());
2993   }
2994   print_helper(st, "osr",     stats->_osr);
2995   print_helper(st, "bailout", stats->_bailout);
2996   print_helper(st, "invalid", stats->_invalidated);
2997   print_helper(st, "not_entrant", stats->_made_not_entrant, false);
2998   st->cr();
2999 }
3000 
3001 static void print_queue_info(outputStream* st, CompileQueue* queue) {
3002   if (queue != nullptr) {
3003     MutexLocker ml(queue->lock());
3004 
3005     uint  total_cnt = 0;
3006     uint active_cnt = 0;
3007     for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3008       guarantee(jt != nullptr, "");
3009       if (jt->is_Compiler_thread()) {
3010         CompilerThread* ct = (CompilerThread*)jt;
3011 
3012         guarantee(ct != nullptr, "");
3013         if (ct->queue() == queue) {
3014           ++total_cnt;
3015           CompileTask* task = ct->task();
3016           if (task != nullptr) {
3017             ++active_cnt;
3018           }
3019         }
3020       }
3021     }
3022 
3023     st->print("  %s (%d active / %d total threads): %u tasks",
3024               queue->name(), active_cnt, total_cnt, queue->size());
3025     if (queue->size() > 0) {
3026       uint counts[] = {0, 0, 0, 0, 0}; // T1 ... T5
3027       for (CompileTask* task = queue->first(); task != nullptr; task = task->next()) {
3028         int tier = task->comp_level();
3029         if (task->is_aot_load() && task->preload()) {
3030           assert(tier == CompLevel_full_optimization, "%d", tier);
3031           tier = CompLevel_full_optimization + 1;
3032         }
3033         counts[tier-1]++;
3034       }
3035       st->print(":");
3036       for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3037         uint cnt = counts[tier-1];
3038         if (cnt > 0) {
3039           st->print(" T%d: %u tasks;", tier, cnt);
3040         }
3041       }
3042     }
3043     st->cr();
3044 
3045 //    for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3046 //      guarantee(jt != nullptr, "");
3047 //      if (jt->is_Compiler_thread()) {
3048 //        CompilerThread* ct = (CompilerThread*)jt;
3049 //
3050 //        guarantee(ct != nullptr, "");
3051 //        if (ct->queue() == queue) {
3052 //          ResourceMark rm;
3053 //          CompileTask* task = ct->task();
3054 //          st->print("    %s: ", ct->name_raw());
3055 //          if (task != nullptr) {
3056 //            task->print(st, nullptr, true /*short_form*/, false /*cr*/);
3057 //          }
3058 //          st->cr();
3059 //        }
3060 //      }
3061 //    }
3062   }
3063 }
3064 void CompileBroker::print_statistics_on(outputStream* st) {
3065   st->print_cr("  Total: %u methods; %u bailouts, %u invalidated, %u non_entrant",
3066                _total_compile_count, _total_bailout_count, _total_invalidated_count, _total_not_entrant_count);
3067   for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3068     print_tier_helper(st, "Tier", tier, &_stats_per_level[tier-1]);
3069   }
3070   st->cr();
3071 
3072   if (AOTCodeCaching) {
3073     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3074       if (tier != CompLevel_full_profile) {
3075         print_tier_helper(st, "AOT Code T", tier, &_aot_stats_per_level[tier - 1]);
3076       }
3077     }
3078     st->cr();
3079   }
3080 
3081   print_queue_info(st, _c1_compile_queue);
3082   print_queue_info(st, _c2_compile_queue);
3083   print_queue_info(st, _ac1_compile_queue);
3084   print_queue_info(st, _ac2_compile_queue);
3085 }
3086 
3087 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
3088   if (per_compiler) {
3089     if (aggregate) {
3090       tty->cr();
3091       tty->print_cr("[%dms] Individual compiler times (for compiled methods only)", (int)tty->time_stamp().milliseconds());
3092       tty->print_cr("------------------------------------------------");
3093       tty->cr();
3094     }
3095     for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
3096       AbstractCompiler* comp = _compilers[i];
3097       if (comp != nullptr) {
3098         print_times(comp->name(), comp->stats());
3099       }
3100     }
3101     if (_aot_stats._standard._count > 0) {
3102       print_times("SC", &_aot_stats);
3103     }
3104     if (aggregate) {
3105       tty->cr();
3106       tty->print_cr("Individual compilation Tier times (for compiled methods only)");
3107       tty->print_cr("------------------------------------------------");
3108       tty->cr();
3109     }
3110     char tier_name[256];
3111     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3112       CompilerStatistics* stats = &_stats_per_level[tier-1];
3113       os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
3114       print_times(tier_name, stats);
3115     }
3116     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3117       CompilerStatistics* stats = &_aot_stats_per_level[tier-1];
3118       if (stats->_standard._bytes > 0) {
3119         os::snprintf_checked(tier_name, sizeof(tier_name), "AOT Code T%d", tier);
3120         print_times(tier_name, stats);
3121       }
3122     }
3123   }
3124 
3125   if (!aggregate) {
3126     return;
3127   }
3128 
3129   elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
3130   elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
3131   elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
3132 
3133   uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
3134   uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
3135 
3136   uint standard_compile_count = CompileBroker::_total_standard_compile_count;
3137   uint osr_compile_count = CompileBroker::_total_osr_compile_count;
3138   uint total_compile_count = CompileBroker::_total_compile_count;
3139   uint total_bailout_count = CompileBroker::_total_bailout_count;
3140   uint total_invalidated_count = CompileBroker::_total_invalidated_count;
3141 
3142   uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;

3144 
3145   tty->cr();
3146   tty->print_cr("Accumulated compiler times");
3147   tty->print_cr("----------------------------------------------------------");
3148                //0000000000111111111122222222223333333333444444444455555555556666666666
3149                //0123456789012345678901234567890123456789012345678901234567890123456789
3150   tty->print_cr("  Total compilation time   : %7.3f s", total_compilation.seconds());
3151   tty->print_cr("    Standard compilation   : %7.3f s, Average : %2.3f s",
3152                 standard_compilation.seconds(),
3153                 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
3154   tty->print_cr("    Bailed out compilation : %7.3f s, Average : %2.3f s",
3155                 CompileBroker::_t_bailedout_compilation.seconds(),
3156                 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
3157   tty->print_cr("    On stack replacement   : %7.3f s, Average : %2.3f s",
3158                 osr_compilation.seconds(),
3159                 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
3160   tty->print_cr("    Invalidated            : %7.3f s, Average : %2.3f s",
3161                 CompileBroker::_t_invalidated_compilation.seconds(),
3162                 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
3163 
3164   if (AOTCodeCaching) { // Check flags because AOT code cache could be closed already
3165     tty->cr();
3166     AOTCodeCache::print_timers_on(tty);
3167   }
3168   AbstractCompiler *comp = compiler(CompLevel_simple);
3169   if (comp != nullptr) {
3170     tty->cr();
3171     comp->print_timers();
3172   }
3173   comp = compiler(CompLevel_full_optimization);
3174   if (comp != nullptr) {
3175     tty->cr();
3176     comp->print_timers();
3177   }
3178 #if INCLUDE_JVMCI
3179   if (EnableJVMCI) {
3180     JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
3181     if (jvmci_comp != nullptr && jvmci_comp != comp) {
3182       tty->cr();
3183       jvmci_comp->print_timers();
3184     }
3185   }
3186 #endif
3187 
< prev index next >