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